修改
This commit is contained in:
@@ -14,7 +14,6 @@
|
||||
{ "id": "1002", "billNo": "2026083222P345", "projectId": "1", "projectNo": "20260813ZK2Q5f45", "projectName": "社区康养智能服务系统", "userId": "1", "amount": "20100.00", "contractId": null, "billType": "PROGRESS", "periodName": "第二期", "periodRatio": "33.00", "status": "PENDING", "payChannel": null, "transactionNo": null, "tradeName": null, "payTime": null, "dueDate": null },
|
||||
{ "id": "1003", "billNo": "2026083222P345", "projectId": "1", "projectNo": "20260813ZK2Q5f45", "projectName": "社区康养智能服务系统", "userId": "1", "amount": "20100.00", "contractId": null, "billType": "FINAL", "periodName": "第三期", "periodRatio": "33.00", "status": "UNSTARTED", "payChannel": null, "transactionNo": null, "tradeName": null, "payTime": null, "dueDate": null }
|
||||
],
|
||||
"billPlans": [],
|
||||
"invoices": [
|
||||
{ "id": "1", "billId": "1001", "invoiceTitle": "测试", "taxNo": null, "invoiceType": "电子普通发票", "amount": "20100.00", "status": "ISSUED", "invoiceNo": null, "invoiceFile": "https://example.com/inv.pdf", "applyTime": "2026-8-17 17:00", "invoiceDate": null, "createTime": "2026-8-17 17:00" },
|
||||
{ "id": "2", "billId": "1001", "invoiceTitle": "测试", "taxNo": null, "invoiceType": "电子普通发票", "amount": "20100.00", "status": "ISSUED", "invoiceNo": null, "invoiceFile": "https://example.com/inv2.pdf", "applyTime": "2026-8-17 17:00", "invoiceDate": null, "createTime": "2026-8-17 17:00" }
|
||||
|
||||
7
package-lock.json
generated
7
package-lock.json
generated
@@ -12,6 +12,7 @@
|
||||
"axios": "^1.20.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"pinia": "^4.0.3",
|
||||
"qrcode-generator": "^2.0.4",
|
||||
"vue": "^3.5.42",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
@@ -1836,6 +1837,12 @@
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/qrcode-generator": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
|
||||
"integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.2.10",
|
||||
"resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.10.tgz",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { request, serializeQuery } from '@/utils/request'
|
||||
import type {
|
||||
CaseSelectionModel,
|
||||
ProjectCaseAndCaseCountVo,
|
||||
ProjectCaseCountResultVo,
|
||||
ProjectCaseUserBo,
|
||||
ProjectCaseVo,
|
||||
} from '@/types/business/cases'
|
||||
@@ -42,6 +43,14 @@ export function getCaseCategories(): Promise<CaseSelectionModel> {
|
||||
})
|
||||
}
|
||||
|
||||
/** 案例总数与按业务类型统计(已按案例数倒序,无案例分类补 0)。 */
|
||||
export function getProjectCaseCount(): Promise<ProjectCaseCountResultVo> {
|
||||
return request<ProjectCaseCountResultVo>({
|
||||
url: '/web/projectCase/count',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function getFeaturedCases(type?: string): Promise<ProjectCaseVo[]> {
|
||||
return request<ProjectCaseVo[]>({
|
||||
url: '/web/projectCase/mostViewed',
|
||||
|
||||
@@ -1,102 +1,94 @@
|
||||
import type { FileInfo, PageResult } from '@/types/api'
|
||||
import type { Contract, ContractQuery } from '@/types/business/contract'
|
||||
import type {
|
||||
ContractPageResult,
|
||||
ContractPreviewVo,
|
||||
ContractQrTokenVo,
|
||||
ContractQuery,
|
||||
ContractSignProgressVo,
|
||||
ContractVo,
|
||||
} from '@/types/business/contract'
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
// TODO(api): 待接口文档到位后,将以下 mock 替换为 request<T> 调用
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/contract/page → 合同中心列表(表格分页)
|
||||
// pageNum/pageSize 分页;keyword 模糊匹配合同编号 / 标题 / 项目名
|
||||
// 返回 { total, rows: ContractVo[] }
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
function mockFile(name: string, size: number, uploadTime: string): FileInfo {
|
||||
return { name, size, uploadTime, url: '' }
|
||||
}
|
||||
|
||||
const DETAIL_ID = 'contract-001'
|
||||
|
||||
const MOCK_CONTRACTS: Contract[] = [
|
||||
{
|
||||
id: 'contract-001',
|
||||
contractNo: 'C8K2M202408001',
|
||||
contractName: '智慧城市建设项目技术服务合同',
|
||||
contractType: '互联网软件通用/app开发',
|
||||
contractAmount: 201000,
|
||||
relatedProjectName: '智慧城市大数据平台建设项目',
|
||||
projectNo: 'P8K2M202408001',
|
||||
signStatus: '履行中',
|
||||
signDate: '2026-8-17 14:00',
|
||||
effectiveDate: '2026-8-17 14:00',
|
||||
expiryDate: '2026-8-17 14:00',
|
||||
files: [mockFile('项目需求规格说明书.pdf', 2516582, '2026-8-17 14:00')],
|
||||
export function getContractList(query: ContractQuery): Promise<ContractPageResult> {
|
||||
return request<ContractPageResult>({
|
||||
url: '/web/contract/page',
|
||||
method: 'get',
|
||||
params: {
|
||||
keyword: query.keyword || undefined,
|
||||
pageNum: query.pageNum,
|
||||
pageSize: query.pageSize,
|
||||
},
|
||||
{
|
||||
id: 'contract-002',
|
||||
contractNo: 'C8K2M202408002',
|
||||
contractName: '智慧城市建设项目硬件电路设计合同',
|
||||
contractType: '硬件电路通用/电路版设计',
|
||||
contractAmount: 180000,
|
||||
relatedProjectName: '三甲医院指挥医疗信息化系统',
|
||||
projectNo: 'P8K2M202408001',
|
||||
signStatus: '已过期',
|
||||
signDate: '2026-8-17 14:00',
|
||||
effectiveDate: '2026-8-17 14:00',
|
||||
expiryDate: '2026-8-17 14:00',
|
||||
files: [mockFile('硬件电路设计合同.pdf', 1468006, '2026-8-17 14:00')],
|
||||
},
|
||||
{
|
||||
id: 'contract-003',
|
||||
contractNo: 'C8K2M202408003',
|
||||
contractName: '智慧城市建设项目物联网全案合同',
|
||||
contractType: '物联网全案通用/一套门禁卡',
|
||||
contractAmount: 96000,
|
||||
relatedProjectName: '社区康养智能服务系统',
|
||||
projectNo: 'P8K2M202408001',
|
||||
signStatus: '待签署',
|
||||
effectiveDate: '2026-8-17 14:00',
|
||||
expiryDate: '2026-8-17 14:00',
|
||||
files: [mockFile('物联网全案合同.pdf', 1258291, '2026-8-17 14:00')],
|
||||
},
|
||||
]
|
||||
|
||||
const CONTRACT_DETAIL: Contract = {
|
||||
id: DETAIL_ID,
|
||||
contractNo: 'C8K2M202408001',
|
||||
contractName: '社区康养智能服务系统开发合同',
|
||||
contractType: '互联网软件开发',
|
||||
contractAmount: 201000,
|
||||
relatedProjectName: '社区康养智能服务系统',
|
||||
projectNo: '20260813ZZ251245',
|
||||
signStatus: '履行中',
|
||||
signDate: '2024-10-15',
|
||||
effectiveDate: '2024-10-15',
|
||||
expiryDate: '2024-10-15',
|
||||
files: [mockFile('项目需求规格说明书.pdf', 2516582, '2024-10-15')],
|
||||
}
|
||||
|
||||
export function getContractList(query: ContractQuery): Promise<PageResult<Contract>> {
|
||||
const filtered = MOCK_CONTRACTS.filter((item) => {
|
||||
if (
|
||||
query.keyword
|
||||
&& !item.contractName.includes(query.keyword)
|
||||
&& !item.contractNo.includes(query.keyword)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
const pageSize = query.pageSize > 0 ? query.pageSize : 8
|
||||
const start = (query.page - 1) * pageSize
|
||||
return Promise.resolve({
|
||||
list: filtered.slice(start, start + pageSize),
|
||||
total: filtered.length,
|
||||
})
|
||||
}
|
||||
|
||||
export function getContractDetail(id: string): Promise<Contract | null> {
|
||||
if (id === DETAIL_ID) return Promise.resolve({ ...CONTRACT_DETAIL, files: [...CONTRACT_DETAIL.files] })
|
||||
const found = MOCK_CONTRACTS.find((item) => item.id === id) ?? null
|
||||
return Promise.resolve(found ? { ...found, files: [...found.files] } : null)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/contract/{id} → 合同详情 ContractVo
|
||||
// GET /web/contract/preview/{id} → ContractPreviewVo(合同 PDF 地址)
|
||||
// GET /web/contract/download/{id} → String(仅「已签署」合同可下载)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getContractDetail(id: string): Promise<ContractVo> {
|
||||
return request<ContractVo>({
|
||||
url: `/web/contract/${id}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function getSignQr(_id: string): Promise<{ expiresInSeconds: number }> {
|
||||
return Promise.resolve({ expiresInSeconds: 272 })
|
||||
export function getContractPreview(id: string): Promise<ContractPreviewVo> {
|
||||
return request<ContractPreviewVo>({
|
||||
url: `/web/contract/preview/${id}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function refreshSignQr(_id: string): Promise<{ expiresInSeconds: number }> {
|
||||
return Promise.resolve({ expiresInSeconds: 272 })
|
||||
export function getContractDownloadUrl(id: string): Promise<string> {
|
||||
return request<string>({
|
||||
url: `/web/contract/download/${id}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/contract/sign/progress/{id} → 签署进度 ContractSignProgressVo
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getContractSignProgress(id: string): Promise<ContractSignProgressVo> {
|
||||
return request<ContractSignProgressVo>({
|
||||
url: `/web/contract/sign/progress/${id}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// POST /web/contract/sign/qr-init/{contractId} → String(完整落地页 URL,Redis TTL 5 分钟)
|
||||
// GET /web/contract/sign/qr-status/{contractId} → Boolean(sign_status === SIGNED)
|
||||
// GET /web/contract/sign/qr-token/{token} → ContractQrTokenVo(扫码落地页数据)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function initContractSignQr(contractId: string): Promise<string> {
|
||||
return request<string>({
|
||||
url: `/web/contract/sign/qr-init/${contractId}`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
export function getContractSignQrStatus(contractId: string): Promise<boolean> {
|
||||
return request<boolean>({
|
||||
url: `/web/contract/sign/qr-status/${contractId}`,
|
||||
method: 'get',
|
||||
// 轮询接口:失败由调用方静默降级,避免每 3 秒弹一次错误提示
|
||||
silent: true,
|
||||
})
|
||||
}
|
||||
|
||||
export function getContractSignQrToken(token: string): Promise<ContractQrTokenVo> {
|
||||
return request<ContractQrTokenVo>({
|
||||
url: `/web/contract/sign/qr-token/${encodeURIComponent(token)}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,377 +1,328 @@
|
||||
import type { PageResult } from '@/types/api'
|
||||
import type {
|
||||
Bill,
|
||||
BillQuery,
|
||||
BillVo,
|
||||
FinanceStats,
|
||||
Invoice,
|
||||
InvoiceQuery,
|
||||
InvoiceTitle,
|
||||
InvoiceTitlePayload,
|
||||
PayMethod,
|
||||
PayOrderResponse,
|
||||
Payment,
|
||||
PaymentResult,
|
||||
DictOptionVo,
|
||||
FinanceBillStatisticsVo,
|
||||
FinanceBillVo,
|
||||
FinanceInvoiceApplyBo,
|
||||
FinanceInvoiceAvailableVo,
|
||||
FinanceInvoicePreviewVo,
|
||||
FinanceInvoiceQuery,
|
||||
FinanceInvoiceSendEmailBo,
|
||||
FinanceInvoiceTitleBo,
|
||||
FinanceInvoiceTitleVo,
|
||||
FinanceInvoiceVo,
|
||||
FinancePageResult,
|
||||
FinancePayQueryVo,
|
||||
FinancePayResultVo,
|
||||
FinanceRefundBo,
|
||||
FinanceRefundQuery,
|
||||
FinanceRefundVo,
|
||||
FinanceSummaryQuery,
|
||||
FinanceSummaryVo,
|
||||
PayChannelCode,
|
||||
PayChannelVo,
|
||||
} from '@/types/business/finance'
|
||||
import { toBills, toPlanBills, type PlanLike } from '@/utils/billVo'
|
||||
import { toPayMethod } from '@/utils/payMeta'
|
||||
import { request } from '@/utils/request'
|
||||
import { toBillStatusCode } from '@/utils/billVo'
|
||||
import service, { request } from '@/utils/request'
|
||||
|
||||
const MOCK_BILLS: Bill[] = [
|
||||
{
|
||||
id: 'bill-001',
|
||||
planName: '第一期·预付款 比例33%',
|
||||
billNo: '20260813ZZ251245',
|
||||
tradeNo: 'T20260819153035678K2M001',
|
||||
projectName: '某大型银行数字化转型方案',
|
||||
amount: 20000,
|
||||
status: '已支付',
|
||||
createTime: '2026-8-17 14:00',
|
||||
},
|
||||
{
|
||||
id: 'bill-002',
|
||||
planName: '第二期·进度款 比例30%',
|
||||
billNo: '20260813ZZ251246',
|
||||
projectName: '智慧城市大数据平台建设项目',
|
||||
amount: 20100,
|
||||
status: '待支付',
|
||||
createTime: '2026-8-17 14:00',
|
||||
},
|
||||
{
|
||||
id: 'bill-003',
|
||||
planName: '第三期·验收款 比例27%',
|
||||
billNo: '20260813ZZ251247',
|
||||
projectName: '三甲医院指挥医疗信息化系统',
|
||||
amount: 20000,
|
||||
status: '未到期',
|
||||
createTime: '2026-8-17 14:00',
|
||||
},
|
||||
{
|
||||
id: 'bill-004',
|
||||
planName: '第四期·尾款 比例10%',
|
||||
billNo: '20260813ZZ251248',
|
||||
projectName: '智慧城市大数据平台建设项目',
|
||||
amount: 20100,
|
||||
status: '未到期',
|
||||
createTime: '2026-8-17 14:00',
|
||||
},
|
||||
{
|
||||
id: 'bill-005',
|
||||
planName: '第二期·进度款 比例30%',
|
||||
billNo: '20260813ZZ251249',
|
||||
projectName: '三甲医院指挥医疗信息化系统',
|
||||
amount: 20100,
|
||||
status: '待支付',
|
||||
createTime: '2026-8-16 10:30',
|
||||
},
|
||||
{
|
||||
id: 'bill-006',
|
||||
planName: '第一期·预付款 比例33%',
|
||||
billNo: '20260813ZZ251250',
|
||||
tradeNo: 'T20260819153035678K2M002',
|
||||
projectName: '某大型银行数字化转型方案',
|
||||
amount: 20000,
|
||||
status: '已支付',
|
||||
createTime: '2026-8-15 09:12',
|
||||
},
|
||||
]
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/finance/summary → 财务中心首页统计(累计消费总额 + 业务类型分布)
|
||||
// year / dimension(YEAR|MONTH|QUARTER) / month(1-12) / quarter(1-4)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_INVOICES: Invoice[] = [
|
||||
{
|
||||
id: 'invoice-001',
|
||||
planName: '第一期·预付款 比例33%',
|
||||
billNo: '20260813ZZ251245',
|
||||
tradeNo: 'T20260819153035678K2M001',
|
||||
projectName: '某大型银行数字化转型方案',
|
||||
amount: 20000,
|
||||
status: '已开票',
|
||||
applyTime: '2026-8-17 14:00',
|
||||
export function getFinanceSummary(query: FinanceSummaryQuery = {}): Promise<FinanceSummaryVo> {
|
||||
const dimension = query.dimension ?? 'YEAR'
|
||||
return request<FinanceSummaryVo>({
|
||||
url: '/web/finance/summary',
|
||||
method: 'get',
|
||||
params: {
|
||||
year: query.year,
|
||||
dimension,
|
||||
month: dimension === 'MONTH' ? query.month : undefined,
|
||||
quarter: dimension === 'QUARTER' ? query.quarter : undefined,
|
||||
},
|
||||
{
|
||||
id: 'invoice-002',
|
||||
planName: '第一期·预付款 比例33%',
|
||||
billNo: '20260813ZZ251250',
|
||||
tradeNo: 'T20260819153035678K2M002',
|
||||
projectName: '某大型银行数字化转型方案',
|
||||
amount: 20000,
|
||||
status: '开票中',
|
||||
applyTime: '2026-8-17 14:00',
|
||||
},
|
||||
{
|
||||
id: 'invoice-003',
|
||||
planName: '第二期·进度款 比例30%',
|
||||
billNo: '20260813ZZ251249',
|
||||
projectName: '三甲医院指挥医疗信息化系统',
|
||||
amount: 20100,
|
||||
status: '未开票',
|
||||
applyTime: '2026-8-17 14:00',
|
||||
},
|
||||
]
|
||||
|
||||
const MOCK_TITLES: InvoiceTitle[] = [
|
||||
{
|
||||
id: 'title-001',
|
||||
type: '企业单位',
|
||||
title: '山东日照有限有限公司',
|
||||
taxNo: '344683434513543543545535',
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
id: 'title-002',
|
||||
type: '企业单位',
|
||||
title: '山东省一周练七次有限公司',
|
||||
taxNo: '6856754615216565476846',
|
||||
isDefault: false,
|
||||
},
|
||||
]
|
||||
|
||||
const MOCK_PAYMENTS = new Map<string, Payment>()
|
||||
|
||||
const MOCK_RESULTS = new Map<string, PaymentResult>()
|
||||
MOCK_RESULTS.set('bill-001', {
|
||||
method: 'wechat',
|
||||
amount: 20000,
|
||||
payTime: '2026-01-21 15:00:00',
|
||||
tradeNo: 'T20260819153035678K2M001',
|
||||
bills: [{ ...MOCK_BILLS[0] }],
|
||||
})
|
||||
MOCK_RESULTS.set('bill-006', {
|
||||
method: 'wechat',
|
||||
amount: 20000,
|
||||
payTime: '2026-01-21 15:00:00',
|
||||
tradeNo: 'T20260819153035678K2M002',
|
||||
bills: [{ ...MOCK_BILLS[5] }],
|
||||
})
|
||||
|
||||
const DEFAULT_STATS: FinanceStats = {
|
||||
totalExpense: 1726823900,
|
||||
month: '2026年1',
|
||||
pendingCount: 3,
|
||||
distribution: [
|
||||
{ name: '生产智造', value: 25, color: '#3370ff' },
|
||||
{ name: '物联网全案', value: 25, color: '#34c724' },
|
||||
{ name: '硬件电路', value: 25, color: '#ff8f1f' },
|
||||
{ name: '互联网软件', value: 25, color: '#f54a45' },
|
||||
],
|
||||
}
|
||||
|
||||
export function getFinanceStats(period?: string): Promise<FinanceStats> {
|
||||
void period
|
||||
return Promise.resolve(structuredClone(DEFAULT_STATS))
|
||||
}
|
||||
|
||||
function isRealBillId(id: string): boolean {
|
||||
return /^\d+$/.test(id)
|
||||
}
|
||||
|
||||
async function fetchOwnBills(): Promise<Bill[]> {
|
||||
const rows = await request<BillVo[]>({ url: '/web/bill/list', method: 'get' })
|
||||
return toBills(rows)
|
||||
}
|
||||
|
||||
function matchBillKeyword(item: Bill, keyword: string): boolean {
|
||||
if (!keyword) return true
|
||||
return (
|
||||
item.planName.includes(keyword) ||
|
||||
item.billNo.includes(keyword) ||
|
||||
item.projectName.includes(keyword) ||
|
||||
(item.tradeNo?.includes(keyword) ?? false)
|
||||
)
|
||||
}
|
||||
|
||||
export async function getBillList(query: BillQuery): Promise<PageResult<Bill>> {
|
||||
const all = await fetchOwnBills()
|
||||
const filtered = all.filter((item) => {
|
||||
if (query.status !== 'all' && item.status !== query.status) return false
|
||||
return matchBillKeyword(item, query.keyword)
|
||||
})
|
||||
const start = (query.page - 1) * query.pageSize
|
||||
return { list: filtered.slice(start, start + query.pageSize), total: filtered.length }
|
||||
}
|
||||
|
||||
export async function getBillDetail(id: string): Promise<Bill | null> {
|
||||
const rows = await request<BillVo[]>({ url: '/web/bill/list', method: 'get', params: { ids: id } })
|
||||
return toBills(rows)[0] ?? null
|
||||
}
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/bill/page → 账单分页列表 { total, rows }
|
||||
// GET /web/bill/statistics → 账单顶部统计(金额合计 / 总笔数 / 待支付笔数)
|
||||
// GET /web/bill/{id} → 账单详情
|
||||
// 查询参数:keyword / status(UNSTARTED/PENDING/PAID/CANCELLED) / bizType /
|
||||
// pageNum / pageSize / orderByColumn / isAsc
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// ---------------------------------------------------------------------
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
export function createPayment(billId: string, method: PayMethod): Promise<Payment> {
|
||||
const bill = MOCK_BILLS.find((item) => item.id === billId)
|
||||
if (!bill) return Promise.reject(new Error('账单不存在'))
|
||||
const payment: Payment = {
|
||||
billId,
|
||||
method,
|
||||
amount: bill.amount,
|
||||
qrExpiresInSeconds: 300,
|
||||
}
|
||||
MOCK_PAYMENTS.set(billId, payment)
|
||||
return Promise.resolve({ ...payment })
|
||||
}
|
||||
|
||||
export function switchPaymentMethod(billId: string, method: PayMethod): Promise<Payment> {
|
||||
return createPayment(billId, method)
|
||||
}
|
||||
|
||||
export async function getPayResult(billId: string): Promise<PaymentResult | null> {
|
||||
if (isRealBillId(billId)) {
|
||||
const bill = await getBillDetail(billId)
|
||||
if (!bill || bill.status !== '已支付') return null
|
||||
function toBillFilter(query: BillQuery): Record<string, unknown> {
|
||||
return {
|
||||
method: toPayMethod(bill.payChannel),
|
||||
amount: bill.amount,
|
||||
payTime: bill.payTime ?? '—',
|
||||
tradeNo: bill.tradeNo ?? '—',
|
||||
bills: [bill],
|
||||
keyword: query.keyword || undefined,
|
||||
status: toBillStatusCode(query.status),
|
||||
}
|
||||
}
|
||||
return getLegacyPayResult(billId)
|
||||
}
|
||||
|
||||
function getLegacyPayResult(billId: string): Promise<PaymentResult | null> {
|
||||
const existing = MOCK_RESULTS.get(billId)
|
||||
if (existing) return Promise.resolve(structuredClone(existing))
|
||||
|
||||
const payment = MOCK_PAYMENTS.get(billId)
|
||||
const bill = MOCK_BILLS.find((item) => item.id === billId)
|
||||
if (!payment || !bill) return Promise.resolve(null)
|
||||
|
||||
const tradeNo = bill.tradeNo ?? 'T20260819153035678K2M001'
|
||||
if (bill.status !== '已支付') {
|
||||
bill.status = '已支付'
|
||||
bill.tradeNo = tradeNo
|
||||
}
|
||||
const result: PaymentResult = {
|
||||
method: payment.method,
|
||||
amount: payment.amount,
|
||||
payTime: '2026-01-21 15:00:00',
|
||||
tradeNo,
|
||||
bills: [{ ...bill }],
|
||||
}
|
||||
MOCK_RESULTS.set(billId, result)
|
||||
return Promise.resolve(structuredClone(result))
|
||||
}
|
||||
|
||||
function matchInvoiceKeyword(item: Invoice, keyword: string): boolean {
|
||||
if (!keyword) return true
|
||||
return (
|
||||
item.planName.includes(keyword) ||
|
||||
item.billNo.includes(keyword) ||
|
||||
item.projectName.includes(keyword) ||
|
||||
(item.tradeNo?.includes(keyword) ?? false)
|
||||
)
|
||||
}
|
||||
|
||||
export function getInvoiceList(query: InvoiceQuery): Promise<PageResult<Invoice>> {
|
||||
const filtered = MOCK_INVOICES.filter((item) => {
|
||||
if (query.status !== 'all' && item.status !== query.status) return false
|
||||
return matchInvoiceKeyword(item, query.keyword)
|
||||
})
|
||||
const start = (query.page - 1) * query.pageSize
|
||||
return Promise.resolve({
|
||||
list: filtered.slice(start, start + query.pageSize).map((item) => ({ ...item })),
|
||||
total: filtered.length,
|
||||
export function getBillList(query: BillQuery): Promise<FinancePageResult<FinanceBillVo>> {
|
||||
return request<FinancePageResult<FinanceBillVo>>({
|
||||
url: '/web/bill/page',
|
||||
method: 'get',
|
||||
params: {
|
||||
...toBillFilter(query),
|
||||
pageNum: query.page,
|
||||
pageSize: query.pageSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function applyInvoice(id: string): Promise<Invoice> {
|
||||
const found = MOCK_INVOICES.find((item) => item.id === id)
|
||||
if (!found) return Promise.reject(new Error('发票记录不存在'))
|
||||
found.status = '开票中'
|
||||
return Promise.resolve({ ...found })
|
||||
export function getBillStatistics(query: BillQuery): Promise<FinanceBillStatisticsVo> {
|
||||
return request<FinanceBillStatisticsVo>({
|
||||
url: '/web/bill/statistics',
|
||||
method: 'get',
|
||||
params: toBillFilter(query),
|
||||
})
|
||||
}
|
||||
|
||||
export function getInvoiceTitles(): Promise<InvoiceTitle[]> {
|
||||
return Promise.resolve(MOCK_TITLES.map((item) => ({ ...item })))
|
||||
export function getBillDetail(id: string): Promise<FinanceBillVo> {
|
||||
return request<FinanceBillVo>({
|
||||
url: `/web/bill/${id}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function createInvoiceTitle(payload: InvoiceTitlePayload): Promise<InvoiceTitle> {
|
||||
const created: InvoiceTitle = {
|
||||
id: `title-${Date.now()}`,
|
||||
...payload,
|
||||
isDefault: false,
|
||||
}
|
||||
MOCK_TITLES.push(created)
|
||||
return Promise.resolve({ ...created })
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/bill/export?format=excel|pdf → 导出账单明细(二进制文件流)
|
||||
// 该接口不返回统一 JSON 包装,直接用 axios 实例取 Blob。
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type ExportFormat = 'excel' | 'pdf'
|
||||
|
||||
export async function exportBillReport(
|
||||
query: BillQuery,
|
||||
format: ExportFormat = 'excel',
|
||||
): Promise<Blob> {
|
||||
const resp = await service.get<Blob>('/web/bill/export', {
|
||||
params: {
|
||||
...toBillFilter(query),
|
||||
format,
|
||||
},
|
||||
responseType: 'blob',
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export function updateInvoiceTitle(id: string, payload: InvoiceTitlePayload): Promise<InvoiceTitle> {
|
||||
const found = MOCK_TITLES.find((item) => item.id === id)
|
||||
if (!found) return Promise.reject(new Error('抬头不存在'))
|
||||
found.type = payload.type
|
||||
found.title = payload.title
|
||||
found.taxNo = payload.taxNo
|
||||
return Promise.resolve({ ...found })
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/pay/channels → 可用支付通道
|
||||
// POST /web/pay/bill → 单笔支付 { id, payChannel } → { outTradeNo, qrCode }
|
||||
// POST /web/pay/bill/batch → 多账单合并支付 { ids, payChannel } → { outTradeNo, qrCode }
|
||||
// GET /web/pay/query/{outTradeNo} → 支付结果(status/transactionNo/payTime)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getPayChannels(): Promise<PayChannelVo[]> {
|
||||
return request<PayChannelVo[]>({
|
||||
url: '/web/pay/channels',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function payBill(id: string, payChannel: PayChannelCode): Promise<FinancePayResultVo> {
|
||||
return request<FinancePayResultVo>({
|
||||
url: '/web/pay/bill',
|
||||
method: 'post',
|
||||
data: { id, payChannel },
|
||||
})
|
||||
}
|
||||
|
||||
export function payBills(ids: string[], payChannel: PayChannelCode): Promise<FinancePayResultVo> {
|
||||
return request<FinancePayResultVo>({
|
||||
url: '/web/pay/bill/batch',
|
||||
method: 'post',
|
||||
data: { ids, payChannel },
|
||||
})
|
||||
}
|
||||
|
||||
/** silent:轮询时静默失败,避免瞬时网络异常反复弹提示。 */
|
||||
export function queryPayResult(outTradeNo: string, silent = false): Promise<FinancePayQueryVo> {
|
||||
return request<FinancePayQueryVo>({
|
||||
url: `/web/pay/query/${encodeURIComponent(outTradeNo)}`,
|
||||
method: 'get',
|
||||
silent,
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// POST /web/pay/refund → 申请退款,返回退款单 ID
|
||||
// GET /web/pay/refund/page → 我的退款分页列表
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function applyRefund(payload: FinanceRefundBo): Promise<number> {
|
||||
return request<number>({
|
||||
url: '/web/pay/refund',
|
||||
method: 'post',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
export function getRefundPage(query: FinanceRefundQuery): Promise<FinancePageResult<FinanceRefundVo>> {
|
||||
return request<FinancePageResult<FinanceRefundVo>>({
|
||||
url: '/web/pay/refund/page',
|
||||
method: 'get',
|
||||
params: {
|
||||
billId: query.billId,
|
||||
amount: query.amount,
|
||||
reason: query.reason || undefined,
|
||||
status: query.status || undefined,
|
||||
orderByColumn: query.orderByColumn,
|
||||
isAsc: query.isAsc,
|
||||
pageNum: query.page,
|
||||
pageSize: query.pageSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 发票抬头
|
||||
// GET /web/finance/invoice/title/list
|
||||
// POST /web/finance/invoice/title
|
||||
// PUT /web/finance/invoice/title
|
||||
// DELETE /web/finance/invoice/title/{id}
|
||||
// PUT /web/finance/invoice/title/default/{id}
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getInvoiceTitleList(): Promise<FinanceInvoiceTitleVo[]> {
|
||||
return request<FinanceInvoiceTitleVo[]>({
|
||||
url: '/web/finance/invoice/title/list',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function createInvoiceTitle(payload: FinanceInvoiceTitleBo): Promise<number> {
|
||||
return request<number>({
|
||||
url: '/web/finance/invoice/title',
|
||||
method: 'post',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
export function updateInvoiceTitle(payload: FinanceInvoiceTitleBo): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/finance/invoice/title',
|
||||
method: 'put',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteInvoiceTitle(id: string): Promise<void> {
|
||||
const index = MOCK_TITLES.findIndex((item) => item.id === id)
|
||||
if (index < 0) return Promise.reject(new Error('抬头不存在'))
|
||||
MOCK_TITLES.splice(index, 1)
|
||||
return Promise.resolve()
|
||||
return request<void>({
|
||||
url: `/web/finance/invoice/title/${encodeURIComponent(id)}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
export function setDefaultTitle(id: string): Promise<InvoiceTitle[]> {
|
||||
for (const item of MOCK_TITLES) {
|
||||
item.isDefault = item.id === id
|
||||
}
|
||||
return Promise.resolve(MOCK_TITLES.map((item) => ({ ...item })))
|
||||
export function setDefaultInvoiceTitle(id: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: `/web/finance/invoice/title/default/${encodeURIComponent(id)}`,
|
||||
method: 'put',
|
||||
})
|
||||
}
|
||||
|
||||
export function exportReport(): Promise<void> {
|
||||
return Promise.resolve()
|
||||
}
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 开票申请 / 发票记录
|
||||
// GET /web/finance/invoice/available → 可开票账单(已支付且尚无有效发票)
|
||||
// POST /web/finance/invoice/apply → 申请开票 { billId, titleId, invoiceType }
|
||||
// GET /web/finance/invoice/page → 发票记录分页
|
||||
// GET /web/finance/invoice/{id} → 发票记录详情
|
||||
// GET /web/finance/invoice/preview/{id} → 预览电子发票(仅已开票)
|
||||
// GET /web/finance/invoice/download/{id} → 下载电子发票(仅已开票)
|
||||
// POST /web/finance/invoice/send-email → 发送电子发票到邮箱(仅已开票)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/system/dict/data/type/invoice_status → 发票状态字典
|
||||
// 字典项:0 未开票 / 1 开票中 / 2 已开票(颜色取 listClass)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getCheckoutBills(requirementId: string, ids: string[] = []): Promise<Bill[]> {
|
||||
if (!/^\d+$/.test(requirementId)) return []
|
||||
const vo = await request<{ billPlans?: PlanLike[] }>({
|
||||
url: `/web/requirementPool/get/finance/${requirementId}`,
|
||||
export const INVOICE_STATUS_DICT = 'invoice_status'
|
||||
|
||||
export function getInvoiceStatusDict(): Promise<DictOptionVo[]> {
|
||||
return request<DictOptionVo[]>({
|
||||
url: `/web/system/dict/data/type/${INVOICE_STATUS_DICT}`,
|
||||
method: 'get',
|
||||
})
|
||||
const all = toPlanBills(vo?.billPlans)
|
||||
return ids.length > 0
|
||||
? all.filter((bill) => ids.includes(bill.id))
|
||||
: all.filter((bill) => bill.status === '待支付')
|
||||
}
|
||||
|
||||
export async function getPlanPayResult(requirementId: string, planId: string): Promise<PaymentResult | null> {
|
||||
const bills = await getCheckoutBills(requirementId, [planId])
|
||||
const bill = bills[0]
|
||||
if (!bill || bill.status !== '已支付') return null
|
||||
return {
|
||||
method: toPayMethod(bill.payChannel),
|
||||
amount: bill.amount,
|
||||
payTime: bill.payTime ?? '—',
|
||||
tradeNo: bill.tradeNo ?? '—',
|
||||
bills: [bill],
|
||||
export function getAvailableInvoiceBills(): Promise<FinanceInvoiceAvailableVo[]> {
|
||||
return request<FinanceInvoiceAvailableVo[]>({
|
||||
url: '/web/finance/invoice/available',
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function applyInvoice(payload: FinanceInvoiceApplyBo): Promise<number> {
|
||||
return request<number>({
|
||||
url: '/web/finance/invoice/apply',
|
||||
method: 'post',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
export function getInvoicePage(query: FinanceInvoiceQuery): Promise<FinancePageResult<FinanceInvoiceVo>> {
|
||||
return request<FinancePageResult<FinanceInvoiceVo>>({
|
||||
url: '/web/finance/invoice/page',
|
||||
method: 'get',
|
||||
params: {
|
||||
status: query.status,
|
||||
orderByColumn: query.orderByColumn,
|
||||
isAsc: query.isAsc,
|
||||
pageNum: query.page,
|
||||
pageSize: query.pageSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function getInvoiceDetail(id: string): Promise<FinanceInvoiceVo> {
|
||||
return request<FinanceInvoiceVo>({
|
||||
url: `/web/finance/invoice/${encodeURIComponent(id)}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export function previewInvoice(id: string): Promise<FinanceInvoicePreviewVo> {
|
||||
return request<FinanceInvoicePreviewVo>({
|
||||
url: `/web/finance/invoice/preview/${encodeURIComponent(id)}`,
|
||||
method: 'get',
|
||||
})
|
||||
}
|
||||
|
||||
export interface InvoiceDownloadFile {
|
||||
blob: Blob
|
||||
/** 服务器通过 download-filename 响应头下发的文件名 */
|
||||
fileName?: string
|
||||
}
|
||||
|
||||
/** 从 download-filename 响应头取文件名(可能经过 URL 编码)。 */
|
||||
function resolveDownloadFileName(value: unknown): string | undefined {
|
||||
const raw = Array.isArray(value) ? value[0] : value
|
||||
if (typeof raw !== 'string' || !raw) return undefined
|
||||
try {
|
||||
return decodeURIComponent(raw)
|
||||
}
|
||||
catch {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
|
||||
export function createWechatNativeOrder(
|
||||
orderNo: string,
|
||||
amount: number,
|
||||
billIds: string[] = [],
|
||||
): Promise<PayOrderResponse> {
|
||||
return request<PayOrderResponse>({
|
||||
url: '/pay/web/wechat/native',
|
||||
method: 'post',
|
||||
data: { orderNo, amount, billIds },
|
||||
/** 下载电子发票(PDF 文件流,不走统一 JSON 包装)。 */
|
||||
export async function downloadInvoice(id: string): Promise<InvoiceDownloadFile> {
|
||||
const resp = await service.get<Blob>(`/web/finance/invoice/download/${encodeURIComponent(id)}`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
return {
|
||||
blob: resp.data,
|
||||
fileName: resolveDownloadFileName(resp.headers['download-filename']),
|
||||
}
|
||||
}
|
||||
|
||||
export function createAlipayPageOrder(
|
||||
outTradeNo: string,
|
||||
amount: number,
|
||||
billIds: string[] = [],
|
||||
): Promise<PayOrderResponse> {
|
||||
return request<PayOrderResponse>({
|
||||
url: '/pay/web/alipay/page',
|
||||
export function sendInvoiceEmail(payload: FinanceInvoiceSendEmailBo): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/finance/invoice/send-email',
|
||||
method: 'post',
|
||||
data: { outTradeNo, amount, billIds },
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,146 +1,145 @@
|
||||
import type { PageResult } from '@/types/api'
|
||||
import type { Message, MessageQuery } from '@/types/business/message'
|
||||
import type {
|
||||
Message,
|
||||
MessageApiType,
|
||||
MessageCenterVo,
|
||||
MessagePageVo,
|
||||
MessageQuery,
|
||||
MessageType,
|
||||
MessageVo,
|
||||
} from '@/types/business/message'
|
||||
import { getChatCenterMessages, readAllChatMessages } from '@/api/service'
|
||||
import { request } from '@/utils/request'
|
||||
import {
|
||||
toCenterMessages,
|
||||
toMessage,
|
||||
toMessageApiType,
|
||||
toMessageApiTypes,
|
||||
toMessages,
|
||||
WEB_MESSAGE_TYPES,
|
||||
} from '@/utils/messageVo'
|
||||
|
||||
// TODO(api): 待接口文档到位后,将以下 mock 替换为 request<T> 调用
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// GET /web/message/center → 状态通知 / 系统通知入口未读数(cs 由客服模块提供)
|
||||
// GET /web/message/list → type + pageNum/pageSize,返回 { total, rows }
|
||||
// GET /web/message/detail → id + type
|
||||
// POST /web/message/readAll → type
|
||||
// GET /web/chat/message/centerList → 在线客服页签消息分页列表
|
||||
// POST /web/chat/message/readAll → 在线客服一键全部已读
|
||||
// 列表行字段见 SysMessageVo:messageId/title/message/content/createTime/path/data
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_MESSAGES: Message[] = [
|
||||
{
|
||||
id: 'msg-001',
|
||||
type: '系统通知',
|
||||
title: '【新功能】物联网全案"整机联调"看板正式上线',
|
||||
summary: '整机联调看板已上线,支持联调进度、问题闭环与交付物一览。',
|
||||
content: '尊敬的用户:\n\n为了提升物联网全案项目的交付透明度,平台已正式上线"整机联调"看板功能。\n\n一、功能亮点\n1、联调进度实时同步:设备接入、协议联调、场景验证各阶段进度一目了然;\n2、问题闭环跟踪:联调过程中产生的缺陷与阻塞项统一登记、分派、闭环;\n3、交付物一览:联调报告、测试记录、验收文档集中展示,随时查阅下载。\n\n二、使用方式\n进入「项目中心 → 项目详情 → 整机联调」即可查看对应看板。已有进行中的物联网全案项目将自动迁移历史数据,无需重新配置。\n\n三、温馨提示\n如在使用过程中遇到问题,可通过「在线客服」联系我们,或联系专属项目经理协助处理。\n\n智联智造平台产品团队\n2026年8月',
|
||||
publishTime: '2026-08-06 10:00',
|
||||
isRead: false,
|
||||
attachments: [
|
||||
{ name: '物联网全案服务介绍.pdf', size: 2.5 * 1024 * 1024, uploadTime: '2026-08-06 10:00', url: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'msg-002',
|
||||
type: '系统通知',
|
||||
title: '平台 v2.6 版本更新公告',
|
||||
summary: '新增需求提报模板、案例库对比功能,并优化了消息中心体验。',
|
||||
content: '尊敬的用户:\n\n平台 v2.6 版本已于近日发布,本次更新内容如下:\n\n一、新增功能\n1、需求提报模板:常用需求类型支持保存为模板,一键复用;\n2、案例库对比:最多选择 4 个案例进行横向对比,辅助决策;\n3、消息中心改版:分类标签、关键词搜索、全部已读一站式处理。\n\n二、体验优化\n1、列表页加载性能提升约 40%;\n2、移动端适配细节修复;\n3、附件上传支持 1GB 大文件。\n\n感谢您一直以来的支持,祝使用愉快!',
|
||||
publishTime: '2026-07-15 14:30',
|
||||
isRead: false,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-003',
|
||||
type: '系统通知',
|
||||
title: '关于平台服务时间调整的通知',
|
||||
summary: '自 2026-09-01 起,在线客服服务时间调整为 9:00-21:00。',
|
||||
content: '尊敬的用户:\n\n为进一步提升服务质量,自 2026 年 9 月 1 日起,在线客服服务时间调整如下:\n\n服务时间:每日 9:00 - 21:00(法定节假日照常服务)\n非服务时段提交的留言,我们将在下一个服务时段内尽快回复。\n\n紧急事务可通过专属项目经理电话联系。\n\n感谢您的理解与支持!',
|
||||
publishTime: '2026-08-28 09:00',
|
||||
isRead: true,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-004',
|
||||
type: '状态通知',
|
||||
title: '合同生效通知',
|
||||
summary: '您的合同已正式生效,合同编号 CZ-2026-0815 已开始生效。',
|
||||
content: '您好:\n\n您的合同已正式生效。\n\n合同编号:CZ-2026-0815\n合同名称:智能园区综合管理平台开发合同\n生效日期:2026-08-15\n\n合同已开始生效,可随时在「合同中心」查看详情及履约进度。\n\n如有疑问,请联系您的专属项目经理。',
|
||||
publishTime: '2026-08-15 16:42',
|
||||
isRead: false,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-005',
|
||||
type: '状态通知',
|
||||
title: '项目进度更新:需求确认阶段已完成',
|
||||
summary: '「智能工厂物联网整体解决方案」需求确认已完成,即将进入方案设计。',
|
||||
content: '您好:\n\n您的项目进度已更新:\n\n项目名称:智能工厂物联网整体解决方案\n当前阶段:需求确认 ✅ 已完成\n下一阶段:方案设计\n\n项目组将于 3 个工作日内提交初步方案,届时会再次通知您。您也可以前往「项目中心」查看详细进度与里程碑。\n\n感谢您的配合!',
|
||||
publishTime: '2026-08-20 11:05',
|
||||
isRead: false,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-006',
|
||||
type: '状态通知',
|
||||
title: '账单待办提醒',
|
||||
summary: '您有一笔待付款账单,账单编号 BILL-202608-023,请及时处理。',
|
||||
content: '您好:\n\n您有一笔待付款账单,请及时处理:\n\n账单编号:BILL-202608-023\n关联项目:电商中台系统定制开发\n账单金额:150,000.00 元\n到期日期:2026-09-10\n\n请前往「财务中心 → 账单管理」完成支付。如对账单有疑问,请通过在线客服联系我们。\n\n温馨提示:逾期支付可能影响项目排期,请留意处理时间。',
|
||||
publishTime: '2026-08-25 10:00',
|
||||
isRead: true,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-007',
|
||||
type: '在线客服',
|
||||
title: '您好,请问有什么可以帮您的?',
|
||||
summary: '专属客服小助手已收到您的咨询,将尽快为您答复。',
|
||||
content: '您好,欢迎咨询智联智造平台!\n\n我是您的专属客服小助手,请问有什么可以帮您的?\n\n您可以咨询:\n1、物联网全案开发的流程与周期\n2、项目进度查询\n3、合同与账单相关问题\n4、平台操作指引\n\n我们将在服务时间内尽快回复您。',
|
||||
publishTime: '2026-08-21 10:25',
|
||||
isRead: false,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-008',
|
||||
type: '在线客服',
|
||||
title: '您的咨询已有回复',
|
||||
summary: '关于"整机联调周期"的咨询已回复,点击查看详细内容。',
|
||||
content: '您好:\n\n关于您咨询的"整机联调周期"问题,客服回复如下:\n\n一般物联网全案项目的整机联调周期为 2-4 周,具体取决于设备数量、协议复杂度与场景验证范围。常规智能家居类项目约 2 周,工业场景多设备联调约 3-4 周。\n\n详细排期以项目计划为准,您可在「项目中心」查看最新里程碑。\n\n如还有其他问题,欢迎继续咨询!',
|
||||
publishTime: '2026-08-19 15:40',
|
||||
isRead: true,
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
id: 'msg-009',
|
||||
type: '在线客服',
|
||||
title: '会话满意度回访',
|
||||
summary: '您上次的会话已结束,欢迎对本次服务进行评价。',
|
||||
content: '您好:\n\n您于 2026-08-18 的会话已结束,感谢您的咨询!\n\n欢迎对本次服务进行评价,您的反馈将帮助我们持续改进。如问题未得到解决,可直接回复本条消息,我们将重新为您跟进。\n\n祝您使用愉快!',
|
||||
publishTime: '2026-08-18 17:00',
|
||||
isRead: false,
|
||||
attachments: [],
|
||||
},
|
||||
]
|
||||
|
||||
function applyFilters(query: MessageQuery): Message[] {
|
||||
return MOCK_MESSAGES.filter((item) => {
|
||||
if (query.type !== 'all' && item.type !== query.type) return false
|
||||
if (query.keyword && !item.title.includes(query.keyword) && !item.summary.includes(query.keyword)) return false
|
||||
return true
|
||||
/** silent:轮询未读数时静默失败,避免瞬时网络异常反复弹提示。 */
|
||||
export function getMessageCenter(silent = false): Promise<MessageCenterVo> {
|
||||
return request<MessageCenterVo>({
|
||||
url: '/web/message/center',
|
||||
method: 'get',
|
||||
silent,
|
||||
})
|
||||
}
|
||||
|
||||
export function getMessageList(query: MessageQuery): Promise<PageResult<Message>> {
|
||||
const filtered = applyFilters(query)
|
||||
function getMessagePage(
|
||||
type: MessageApiType,
|
||||
pageNum: number,
|
||||
pageSize: number,
|
||||
): Promise<MessagePageVo<MessageVo>> {
|
||||
return request<MessagePageVo<MessageVo>>({
|
||||
url: '/web/message/list',
|
||||
method: 'get',
|
||||
params: { type, pageNum, pageSize },
|
||||
})
|
||||
}
|
||||
|
||||
function filterByKeyword(list: Message[], keyword: string): Message[] {
|
||||
if (!keyword) return list
|
||||
return list.filter((item) => item.title.includes(keyword) || item.summary.includes(keyword))
|
||||
}
|
||||
|
||||
/**
|
||||
* 「全部」后端不支持一次查多个 type,按状态通知 + 系统通知 + 在线客服分别取到当前页并合并排序;
|
||||
* 单个 tab 直接按 pageNum/pageSize 分页,在线客服走独立接口 /web/chat/message/centerList。
|
||||
*/
|
||||
export async function getMessageList(query: MessageQuery): Promise<PageResult<Message>> {
|
||||
const keyword = query.keyword.trim()
|
||||
|
||||
if (query.type === '在线客服') {
|
||||
const page = await getChatCenterMessages({ pageNum: query.page, pageSize: query.pageSize })
|
||||
return {
|
||||
list: filterByKeyword(toCenterMessages(page.rows), keyword),
|
||||
total: Number(page.total ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
const types: MessageApiType[] = query.type === 'all' ? WEB_MESSAGE_TYPES : [toMessageApiType(query.type)]
|
||||
const fetchSize = query.type === 'all' ? query.page * query.pageSize : query.pageSize
|
||||
|
||||
const [pages, chatPage] = await Promise.all([
|
||||
Promise.all(
|
||||
types.map((type) =>
|
||||
query.type === 'all'
|
||||
// 单个入口失败不影响另一个入口展示
|
||||
? getMessagePage(type, 1, fetchSize).catch(() => null)
|
||||
: getMessagePage(type, query.page, fetchSize),
|
||||
),
|
||||
),
|
||||
query.type === 'all'
|
||||
? getChatCenterMessages({ pageNum: 1, pageSize: fetchSize }).catch(() => null)
|
||||
: null,
|
||||
])
|
||||
|
||||
let total = 0
|
||||
const rows: Message[] = []
|
||||
pages.forEach((page, index) => {
|
||||
if (!page) return
|
||||
total += Number(page.total ?? 0)
|
||||
rows.push(...toMessages(page.rows, types[index] ?? types[0]))
|
||||
})
|
||||
if (chatPage) {
|
||||
total += Number(chatPage.total ?? 0)
|
||||
rows.push(...toCenterMessages(chatPage.rows))
|
||||
}
|
||||
|
||||
const sorted = filterByKeyword(rows, keyword)
|
||||
.sort((a, b) => b.publishTime.localeCompare(a.publishTime))
|
||||
|
||||
if (query.type !== 'all') {
|
||||
return { list: sorted, total: Number(pages[0]?.total ?? 0) }
|
||||
}
|
||||
|
||||
const start = (query.page - 1) * query.pageSize
|
||||
return Promise.resolve({
|
||||
list: filtered.slice(start, start + query.pageSize),
|
||||
total: filtered.length,
|
||||
return { list: sorted.slice(start, start + query.pageSize), total }
|
||||
}
|
||||
|
||||
export async function getMessageDetail(
|
||||
id: string,
|
||||
type: MessageApiType,
|
||||
): Promise<Message | null> {
|
||||
const vo = await request<MessageVo | null>({
|
||||
url: '/web/message/detail',
|
||||
method: 'get',
|
||||
params: { id, type },
|
||||
})
|
||||
return vo ? toMessage(vo, type) : null
|
||||
}
|
||||
|
||||
export function getMessageDetail(id: string): Promise<Message | null> {
|
||||
const found = MOCK_MESSAGES.find((item) => item.id === id) ?? null
|
||||
return Promise.resolve(found ? { ...found } : null)
|
||||
}
|
||||
export async function markAllRead(type: MessageType | 'all'): Promise<void> {
|
||||
const requests: Promise<void>[] = []
|
||||
|
||||
export function markAllRead(): Promise<void> {
|
||||
for (const item of MOCK_MESSAGES) {
|
||||
item.isRead = true
|
||||
// 在线客服是独立接口且不区分 type,按范围分别调用
|
||||
if (type === 'all' || type === '在线客服') {
|
||||
requests.push(readAllChatMessages())
|
||||
}
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
export function markRead(id: string): Promise<void> {
|
||||
const found = MOCK_MESSAGES.find((item) => item.id === id)
|
||||
if (found) found.isRead = true
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
export function getTabCounts(): Promise<{ all: number; 在线客服: number; 状态通知: number; 系统通知: number }> {
|
||||
const counts = { all: MOCK_MESSAGES.length, 在线客服: 0, 状态通知: 0, 系统通知: 0 }
|
||||
for (const item of MOCK_MESSAGES) {
|
||||
counts[item.type] += 1
|
||||
if (type !== '在线客服') {
|
||||
toMessageApiTypes(type).forEach((item) => {
|
||||
requests.push(
|
||||
request<void>({
|
||||
url: '/web/message/readAll',
|
||||
method: 'post',
|
||||
params: { type: item },
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
return Promise.resolve(counts)
|
||||
}
|
||||
|
||||
export function getUnreadCount(): Promise<number> {
|
||||
return Promise.resolve(MOCK_MESSAGES.filter((item) => !item.isRead).length)
|
||||
await Promise.all(requests)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import service from '@/utils/request'
|
||||
import { readBlobErrorMessage } from '@/utils/download'
|
||||
|
||||
export async function fetchOssPreviewBlob(ossId: string | number): Promise<Blob> {
|
||||
const resp = await service.get(`/web/workOrderDraft/preview/${ossId}`, {
|
||||
@@ -6,3 +7,14 @@ export async function fetchOssPreviewBlob(ossId: string | number): Promise<Blob>
|
||||
})
|
||||
return resp.data as Blob
|
||||
}
|
||||
|
||||
/** 下载 OSS 文件(用于编辑弹窗里刚上传、尚未保存的附件)。 */
|
||||
export async function downloadOssFile(ossId: string | number): Promise<Blob> {
|
||||
const resp = await service.get<Blob>(`/web/resource/oss/download/${ossId}`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
if (resp.data.type.startsWith('application/json')) {
|
||||
throw new Error(await readBlobErrorMessage(resp.data))
|
||||
}
|
||||
return resp.data
|
||||
}
|
||||
|
||||
@@ -1,350 +1,350 @@
|
||||
import type { BusinessType, PageResult } from '@/types/api'
|
||||
import type { Case } from '@/types/business/cases'
|
||||
import type { BusinessType, FileInfo, PageResult } from '@/types/api'
|
||||
import type { Case, ProjectCaseVo } from '@/types/business/cases'
|
||||
import type {
|
||||
Address,
|
||||
ChangePasswordParams,
|
||||
Feedback,
|
||||
FeedbackVo,
|
||||
FavoritesQuery,
|
||||
HelpFaqGroup,
|
||||
ListQuery,
|
||||
Profile,
|
||||
ProfilePageVo,
|
||||
ProfileUploadVo,
|
||||
Qualification,
|
||||
QualificationInput,
|
||||
UserAddressVo,
|
||||
UserQualificationVo,
|
||||
} from '@/types/business/profile'
|
||||
import { getProjectCaseCount } from '@/api/cases'
|
||||
import {
|
||||
getAccountSecurity,
|
||||
getUserProfile,
|
||||
updateUserProfile as updateUserProfileApi,
|
||||
} from '@/api/user'
|
||||
import { formatDate, toBusinessType } from '@/utils/format'
|
||||
import { toCase } from '@/utils/caseVo'
|
||||
import { readBlobErrorMessage, resolveContentDispositionFileName } from '@/utils/download'
|
||||
import {
|
||||
toAddressBo,
|
||||
toAddresses,
|
||||
toFeedbackBo,
|
||||
toProfile,
|
||||
toQualificationBo,
|
||||
toQualifications,
|
||||
} from '@/utils/profileVo'
|
||||
import service, { request } from '@/utils/request'
|
||||
|
||||
// TODO(api): 待接口文档到位后,将以下 mock 替换为 request<T> 调用(页面 → store → api 数据流不变)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 个人资料 / 账号安全
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_PROFILE: Profile = {
|
||||
nickname: '王永志',
|
||||
phone: '186****618',
|
||||
email: 'yongzh******4@163.com',
|
||||
passwordModifiedAt: '15天前',
|
||||
export async function getProfile(): Promise<Profile> {
|
||||
const [user, security] = await Promise.all([
|
||||
getUserProfile(),
|
||||
// 账号安全接口异常不阻塞基本资料展示(老用户字段也可能为 null)
|
||||
getAccountSecurity().catch(() => null),
|
||||
])
|
||||
return toProfile(user, security)
|
||||
}
|
||||
|
||||
export function getProfile(): Promise<Profile> {
|
||||
return Promise.resolve({ ...MOCK_PROFILE })
|
||||
export async function updateNickname(name: string): Promise<Profile> {
|
||||
await updateUserProfileApi({ nickName: name })
|
||||
return getProfile()
|
||||
}
|
||||
|
||||
export function updateNickname(name: string): Promise<Profile> {
|
||||
MOCK_PROFILE.nickname = name
|
||||
return Promise.resolve({ ...MOCK_PROFILE })
|
||||
export async function updateAvatar(avatar: string): Promise<Profile> {
|
||||
await updateUserProfileApi({ avatar })
|
||||
return getProfile()
|
||||
}
|
||||
|
||||
/** 通用文件上传(POST /web/profile/upload,字段名固定 file)。 */
|
||||
export function uploadProfileFile(file: File): Promise<ProfileUploadVo> {
|
||||
const data = new FormData()
|
||||
data.append('file', file)
|
||||
return request<ProfileUploadVo>({
|
||||
url: '/web/profile/upload',
|
||||
method: 'post',
|
||||
data,
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
}
|
||||
|
||||
/** 上传并转成页面 FileInfo,便于附件列表统一展示。 */
|
||||
export async function uploadProfileAttachment(file: File): Promise<FileInfo> {
|
||||
const vo = await uploadProfileFile(file)
|
||||
return {
|
||||
ossId: vo.ossId,
|
||||
name: vo.originalName || file.name,
|
||||
size: file.size,
|
||||
uploadTime: formatDate(new Date()),
|
||||
url: vo.url,
|
||||
}
|
||||
}
|
||||
|
||||
export function changePassword(params: ChangePasswordParams): Promise<void> {
|
||||
MOCK_PROFILE.passwordModifiedAt = '刚刚'
|
||||
void params
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
export function bindPhone(phone: string, code: string): Promise<Profile> {
|
||||
void code
|
||||
MOCK_PROFILE.phone = phone
|
||||
return Promise.resolve({ ...MOCK_PROFILE })
|
||||
}
|
||||
|
||||
export function bindEmail(email: string, code: string): Promise<Profile> {
|
||||
void code
|
||||
MOCK_PROFILE.email = email
|
||||
return Promise.resolve({ ...MOCK_PROFILE })
|
||||
}
|
||||
|
||||
export function unbindEmail(): Promise<Profile> {
|
||||
MOCK_PROFILE.email = ''
|
||||
return Promise.resolve({ ...MOCK_PROFILE })
|
||||
}
|
||||
|
||||
export function verifyIdentity(phone: string, code: string): Promise<void> {
|
||||
void phone
|
||||
void code
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
export function deleteAccount(): Promise<void> {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
const MOCK_ADDRESSES: Address[] = [
|
||||
{
|
||||
id: 'addr-1',
|
||||
receiverName: '王永志',
|
||||
phone: '18556669516',
|
||||
region: '山东省日照市东港区',
|
||||
detailAddress: '凌云购物广场三楼',
|
||||
isDefault: true,
|
||||
return request<void>({
|
||||
url: '/web/profile/password/reset',
|
||||
method: 'post',
|
||||
data: {
|
||||
phoneNumber: params.phoneNumber ?? '',
|
||||
smsCode: params.code,
|
||||
newPassword: params.password,
|
||||
confirmPassword: params.password,
|
||||
},
|
||||
{
|
||||
id: 'addr-2',
|
||||
receiverName: '王永志',
|
||||
phone: '18556669516',
|
||||
region: '山东省日照市东港区',
|
||||
detailAddress: '海曲东路 12 号研发中心 A 座 8 层',
|
||||
isDefault: false,
|
||||
},
|
||||
{
|
||||
id: 'addr-3',
|
||||
receiverName: '李晓婷',
|
||||
phone: '13863331234',
|
||||
region: '山东省青岛市市南区',
|
||||
detailAddress: '香港中路 76 号 A 座 18 层',
|
||||
isDefault: false,
|
||||
},
|
||||
{
|
||||
id: 'addr-4',
|
||||
receiverName: '王永志',
|
||||
phone: '18556669516',
|
||||
region: '山东省济南市历下区',
|
||||
detailAddress: '经十路 9999 号舜耕大厦 12 层',
|
||||
isDefault: false,
|
||||
},
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
function paginate<T>(list: T[], query: ListQuery): PageResult<T> {
|
||||
/** 发送绑定手机号用的短信验证码。 */
|
||||
export function sendBindSmsCode(phone: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/profile/sms/send',
|
||||
method: 'post',
|
||||
params: { phone },
|
||||
})
|
||||
}
|
||||
|
||||
/** 发送绑定邮箱的邮件验证码(发到目标邮箱)。 */
|
||||
export function sendBindEmailCode(email: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/profile/email/send',
|
||||
method: 'post',
|
||||
params: { email },
|
||||
})
|
||||
}
|
||||
|
||||
export async function bindPhone(phone: string, code: string): Promise<Profile> {
|
||||
await request<void>({
|
||||
url: '/web/profile/phone/bind',
|
||||
method: 'post',
|
||||
params: { phone, code },
|
||||
})
|
||||
return getProfile()
|
||||
}
|
||||
|
||||
export function unbindPhone(): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/profile/phone/unbind',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
export async function bindEmail(email: string, code: string): Promise<Profile> {
|
||||
await request<void>({
|
||||
url: '/web/profile/email/bind',
|
||||
method: 'post',
|
||||
params: { email, code },
|
||||
})
|
||||
return getProfile()
|
||||
}
|
||||
|
||||
export async function unbindEmail(): Promise<Profile> {
|
||||
await request<void>({
|
||||
url: '/web/profile/email/unbind',
|
||||
method: 'post',
|
||||
})
|
||||
return getProfile()
|
||||
}
|
||||
|
||||
/** 注销账号:验证码合并到 cancel,phone 必须是账号绑定手机号。 */
|
||||
export function deleteAccount(phone: string, code: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/profile/cancel',
|
||||
method: 'post',
|
||||
params: { phone, code },
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 地址:/web/profile/address/*
|
||||
// 列表接口返回全量数组,前端按页切片以复用现有分页组件。
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getAddresses(query: ListQuery): Promise<PageResult<Address>> {
|
||||
const rows = await request<UserAddressVo[]>({
|
||||
url: '/web/profile/address/list',
|
||||
method: 'get',
|
||||
})
|
||||
const list = toAddresses(rows)
|
||||
const start = (query.page - 1) * query.pageSize
|
||||
return {
|
||||
list: list.slice(start, start + query.pageSize),
|
||||
total: list.length,
|
||||
}
|
||||
return { list: list.slice(start, start + query.pageSize), total: list.length }
|
||||
}
|
||||
|
||||
export function getAddresses(query: ListQuery): Promise<PageResult<Address>> {
|
||||
return Promise.resolve(paginate(MOCK_ADDRESSES, query))
|
||||
export async function createAddress(input: Omit<Address, 'id' | 'isDefault'>): Promise<Address> {
|
||||
const id = await request<number | string>({
|
||||
url: '/web/profile/address',
|
||||
method: 'post',
|
||||
data: toAddressBo(input),
|
||||
})
|
||||
return { id: String(id ?? ''), ...input, isDefault: false }
|
||||
}
|
||||
|
||||
export function createAddress(input: Omit<Address, 'id' | 'isDefault'>): Promise<Address> {
|
||||
const created: Address = {
|
||||
...input,
|
||||
id: `addr-${Date.now()}`,
|
||||
isDefault: MOCK_ADDRESSES.length === 0,
|
||||
}
|
||||
MOCK_ADDRESSES.push(created)
|
||||
return Promise.resolve({ ...created })
|
||||
}
|
||||
|
||||
export function updateAddress(id: string, input: Omit<Address, 'id' | 'isDefault'>): Promise<Address> {
|
||||
const found = MOCK_ADDRESSES.find((item) => item.id === id)
|
||||
if (!found) return Promise.reject(new Error('地址不存在'))
|
||||
Object.assign(found, input)
|
||||
return Promise.resolve({ ...found })
|
||||
export async function updateAddress(
|
||||
id: string,
|
||||
input: Omit<Address, 'id' | 'isDefault'>,
|
||||
): Promise<Address> {
|
||||
await request<void>({
|
||||
url: `/web/profile/address/${encodeURIComponent(id)}`,
|
||||
method: 'put',
|
||||
data: toAddressBo(input),
|
||||
})
|
||||
return { id, ...input, isDefault: false }
|
||||
}
|
||||
|
||||
export function deleteAddress(id: string): Promise<void> {
|
||||
const index = MOCK_ADDRESSES.findIndex((item) => item.id === id)
|
||||
if (index >= 0) MOCK_ADDRESSES.splice(index, 1)
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
export function setDefaultAddress(id: string): Promise<Address[]> {
|
||||
for (const item of MOCK_ADDRESSES) {
|
||||
item.isDefault = item.id === id
|
||||
}
|
||||
return Promise.resolve(MOCK_ADDRESSES.map((item) => ({ ...item })))
|
||||
}
|
||||
|
||||
const MOCK_FAVORITES: Case[] = [
|
||||
{
|
||||
id: 'fav-1',
|
||||
title: '自动化生产线升级改造项目',
|
||||
category: 'manufacturing',
|
||||
cover: '',
|
||||
finishDate: '2026/8/10',
|
||||
teamSize: 50,
|
||||
scale: '300万',
|
||||
industry: '自动化',
|
||||
duration: '150个工作日',
|
||||
clientType: '企业',
|
||||
sections: [
|
||||
{ title: '项目背景', content: '<p>传统产线效率低、人工依赖高,客户需要通过自动化升级提升产能与品控水平。</p>' },
|
||||
{ title: '客户痛点', content: '<p>1、产线依赖人工巡检,异常响应慢;2、设备数据孤岛,缺乏统一监控;3、工艺参数无法追溯。</p>' },
|
||||
{ title: '需求描述', content: '<p>建设产线数据采集与监控平台,完成关键工位自动化改造,打通 MES 系统接口。</p>' },
|
||||
{ title: '交付物', content: '<p>1、产线自动化改造方案;2、PLC 控制程序与上位机软件;3、数据看板与运维手册;4、培训与质保服务。</p>' },
|
||||
],
|
||||
video: '',
|
||||
isFavorite: true,
|
||||
favoriteCount: 0,
|
||||
},
|
||||
{
|
||||
id: 'fav-2',
|
||||
title: '智能工厂物联网整体解决方案',
|
||||
category: 'iot',
|
||||
cover: '',
|
||||
finishDate: '2026/8/10',
|
||||
teamSize: 30,
|
||||
scale: '500万',
|
||||
industry: '工厂服务',
|
||||
duration: '200个工作日',
|
||||
clientType: '企业',
|
||||
sections: [
|
||||
{ title: '项目背景', content: '<p>园区工厂多系统独立运行,能耗与设备管理粗放,需要整体数字化升级。</p>' },
|
||||
{ title: '客户痛点', content: '<p>1、门禁/监控/能耗子系统数据不互通;2、能源浪费缺乏精细监测;3、决策缺少实时数据支撑。</p>' },
|
||||
{ title: '需求描述', content: '<p>构建 IoT 平台接入设备数据,建设综合驾驶舱,实现能耗监测与智能告警。</p>' },
|
||||
{ title: '交付物', content: '<p>1、IoT 接入平台;2、综合驾驶舱大屏;3、能耗分析系统;4、集成联调与培训服务。</p>' },
|
||||
],
|
||||
video: '',
|
||||
isFavorite: true,
|
||||
favoriteCount: 0,
|
||||
},
|
||||
{
|
||||
id: 'fav-3',
|
||||
title: '智能穿戴设备PCB设计与量产',
|
||||
category: 'hardware',
|
||||
cover: '',
|
||||
finishDate: '2026/8/10',
|
||||
teamSize: 50,
|
||||
scale: '10-50万',
|
||||
industry: '智能设备',
|
||||
duration: '30个工作日',
|
||||
clientType: '企业',
|
||||
sections: [
|
||||
{ title: '项目背景', content: '<p>客户推出新一代智能穿戴产品,需要高集成度低功耗 PCB 设计并快速量产。</p>' },
|
||||
{ title: '客户痛点', content: '<p>1、板载空间受限,器件布局密集;2、功耗要求严格;3、量产良率需爬坡。</p>' },
|
||||
{ title: '需求描述', content: '<p>完成原理图与 PCB 设计、打样验证、SMT 贴片与整机装配量产。</p>' },
|
||||
{ title: '交付物', content: '<p>1、原理图与 PCB 设计文件;2、样板与测试报告;3、量产良率报告;4、BOM 与工艺文件。</p>' },
|
||||
],
|
||||
video: '',
|
||||
isFavorite: true,
|
||||
favoriteCount: 0,
|
||||
},
|
||||
{
|
||||
id: 'fav-4',
|
||||
title: '智能园区综合管理平台开发',
|
||||
category: 'internet',
|
||||
cover: '',
|
||||
finishDate: '2026/8/10',
|
||||
teamSize: 20,
|
||||
scale: '200万',
|
||||
industry: '园区服务',
|
||||
duration: '200个工作日',
|
||||
clientType: '企业',
|
||||
sections: [
|
||||
{ title: '项目背景', content: '<p>传统园区管理普遍"数据孤岛",安防、能耗、物业、招商等系统独立运行,缺乏联动,管理手段依赖人工巡检和纸质流程。</p>' },
|
||||
{ title: '客户痛点', content: '<p>1、运营效率低下:安保依赖人工巡逻;2、系统孤岛严重:门禁、监控、停车、能耗等子系统独立建设;3、能源浪费突出;4、服务体验欠佳;5、决策缺乏依据;6、安全隐患犹存。</p>' },
|
||||
{ title: '需求描述', content: '<p>打造集"感知、预警、分析、决策、服务"于一体的智能园区综合管理平台,打通园区各子系统壁垒,实现全场景数字化覆盖。</p>' },
|
||||
{ title: '交付物', content: '<p>1、Web 端管理平台(驾驶舱/安防/能源/物业);2、移动端服务门户;3、IoT 平台与数据大屏;4、全套技术文档;5、培训与不少于1年免费质保。</p>' },
|
||||
],
|
||||
video: '',
|
||||
isFavorite: true,
|
||||
favoriteCount: 0,
|
||||
},
|
||||
]
|
||||
|
||||
export function getFavorites(query: FavoritesQuery): Promise<PageResult<Case>> {
|
||||
const filtered = MOCK_FAVORITES.filter((item) => {
|
||||
if (query.category !== 'all' && item.category !== query.category) return false
|
||||
if (query.keyword && !item.title.includes(query.keyword)) return false
|
||||
return true
|
||||
return request<void>({
|
||||
url: `/web/profile/address/${encodeURIComponent(id)}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
export function setDefaultAddress(id: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: `/web/profile/address/${encodeURIComponent(id)}/default`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 收藏:/web/profile/favorite/{caseId}、/web/profile/favorite/page
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getFavorites(query: FavoritesQuery): Promise<PageResult<Case>> {
|
||||
const page = await request<ProfilePageVo<ProjectCaseVo>>({
|
||||
url: '/web/profile/favorite/page',
|
||||
method: 'get',
|
||||
params: { pageNum: query.page, pageSize: query.pageSize },
|
||||
})
|
||||
const rows = (page?.rows ?? []).filter((item) => item != null && item.id != null)
|
||||
return { list: rows.map((vo) => toCase(vo)), total: Number(page?.total ?? 0) }
|
||||
}
|
||||
|
||||
/** 案例分类统计:走 /web/projectCase/count,不再拉收藏列表本地汇总。 */
|
||||
export async function getCaseCounts(): Promise<Partial<Record<BusinessType, number>>> {
|
||||
const stats = await getProjectCaseCount()
|
||||
const counts: Partial<Record<BusinessType, number>> = {}
|
||||
for (const item of stats?.projectCaseCounts ?? []) {
|
||||
if (item == null) continue
|
||||
const type = toBusinessType(item.businessType)
|
||||
counts[type] = (counts[type] ?? 0) + (item.caseCount ?? 0)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
export function favoriteCase(caseId: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: `/web/profile/favorite/${encodeURIComponent(caseId)}`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
export function unfavoriteCase(caseId: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: `/web/profile/unfavorite/${encodeURIComponent(caseId)}`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 资质:/web/profile/qualification/*
|
||||
// 列表接口返回全量数组,前端按页切片以复用现有分页组件。
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getQualifications(query: ListQuery): Promise<PageResult<Qualification>> {
|
||||
const rows = await request<UserQualificationVo[]>({
|
||||
url: '/web/profile/qualification/list',
|
||||
method: 'get',
|
||||
})
|
||||
const list = toQualifications(rows)
|
||||
const start = (query.page - 1) * query.pageSize
|
||||
return Promise.resolve({
|
||||
list: filtered.slice(start, start + query.pageSize).map((item) => ({ ...item })),
|
||||
total: filtered.length,
|
||||
return { list: list.slice(start, start + query.pageSize), total: list.length }
|
||||
}
|
||||
|
||||
export async function createQualification(input: QualificationInput): Promise<Qualification> {
|
||||
const id = await request<number | string>({
|
||||
url: '/web/profile/qualification',
|
||||
method: 'post',
|
||||
data: toQualificationBo(input),
|
||||
})
|
||||
return { id: String(id ?? ''), ...input, status: '审核中' }
|
||||
}
|
||||
|
||||
export function getCaseCounts(): Promise<Partial<Record<BusinessType, number>>> {
|
||||
const counts: Partial<Record<BusinessType, number>> = {
|
||||
internet: 1,
|
||||
hardware: 1,
|
||||
iot: 1,
|
||||
manufacturing: 1,
|
||||
}
|
||||
return Promise.resolve(counts)
|
||||
}
|
||||
|
||||
const MOCK_QUALIFICATIONS: Qualification[] = [
|
||||
{
|
||||
id: 'qual-1',
|
||||
type: '体系认证',
|
||||
certName: 'ISO9001 质量管理体系认证证书',
|
||||
certNo: 'ISO202609080075',
|
||||
issuer: '中国质量认证中心',
|
||||
validFrom: '2026-9-10',
|
||||
validTo: '2027-9-10',
|
||||
status: '已认证',
|
||||
attachments: [
|
||||
{ name: '体系认证证书', size: 1_048_576, uploadTime: '2026-09-10', url: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'qual-2',
|
||||
type: '营业执照',
|
||||
certName: '营业执照',
|
||||
certNo: '91371102MA3XX8876Q',
|
||||
issuer: '日照市东港区市场监督管理局',
|
||||
validFrom: '2020-3-15',
|
||||
validTo: '2030-3-14',
|
||||
status: '审核中',
|
||||
attachments: [
|
||||
{ name: '营业执照', size: 820_000, uploadTime: '2026-09-12', url: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'qual-3',
|
||||
type: '检测报告',
|
||||
certName: '智能终端产品第三方检测报告',
|
||||
certNo: 'WT20260512001',
|
||||
issuer: '山东省产品质量检验研究院',
|
||||
validFrom: '2026-5-12',
|
||||
validTo: '2027-5-12',
|
||||
status: '未通过',
|
||||
attachments: [
|
||||
{ name: '检测报告', size: 2_097_152, uploadTime: '2026-05-15', url: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'qual-4',
|
||||
type: '生产许可证',
|
||||
certName: '全国工业产品生产许可证',
|
||||
certNo: 'XK06-123-45678',
|
||||
issuer: '山东省市场监督管理局',
|
||||
validFrom: '2024-1-8',
|
||||
validTo: '2029-1-7',
|
||||
status: '已认证',
|
||||
attachments: [
|
||||
{ name: '生产许可证', size: 1_258_291, uploadTime: '2024-01-10', url: '' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export function getQualifications(query: ListQuery): Promise<PageResult<Qualification>> {
|
||||
return Promise.resolve(paginate(MOCK_QUALIFICATIONS, query))
|
||||
}
|
||||
|
||||
export function createQualification(input: QualificationInput): Promise<Qualification> {
|
||||
const created: Qualification = {
|
||||
...input,
|
||||
id: `qual-${Date.now()}`,
|
||||
status: '审核中',
|
||||
}
|
||||
MOCK_QUALIFICATIONS.unshift(created)
|
||||
return Promise.resolve({ ...created })
|
||||
}
|
||||
|
||||
export function updateQualification(id: string, input: QualificationInput): Promise<Qualification> {
|
||||
const found = MOCK_QUALIFICATIONS.find((item) => item.id === id)
|
||||
if (!found) return Promise.reject(new Error('资质不存在'))
|
||||
found.type = input.type
|
||||
found.certName = input.certName
|
||||
found.certNo = input.certNo
|
||||
found.issuer = input.issuer
|
||||
found.validFrom = input.validFrom
|
||||
found.validTo = input.validTo
|
||||
found.attachments = input.attachments
|
||||
if (found.status === '未通过') found.status = '审核中'
|
||||
return Promise.resolve({ ...found })
|
||||
export async function updateQualification(
|
||||
id: string,
|
||||
input: QualificationInput,
|
||||
): Promise<Qualification> {
|
||||
await request<void>({
|
||||
url: `/web/profile/qualification/${encodeURIComponent(id)}`,
|
||||
method: 'put',
|
||||
data: toQualificationBo(input),
|
||||
})
|
||||
return { id, ...input, status: '审核中' }
|
||||
}
|
||||
|
||||
export function deleteQualification(id: string): Promise<void> {
|
||||
const index = MOCK_QUALIFICATIONS.findIndex((item) => item.id === id)
|
||||
if (index >= 0) MOCK_QUALIFICATIONS.splice(index, 1)
|
||||
return Promise.resolve()
|
||||
return request<void>({
|
||||
url: `/web/profile/qualification/${encodeURIComponent(id)}`,
|
||||
method: 'delete',
|
||||
})
|
||||
}
|
||||
|
||||
export function submitFeedback(feedback: Feedback): Promise<void> {
|
||||
void feedback
|
||||
return Promise.resolve()
|
||||
export function resubmitQualification(id: string): Promise<void> {
|
||||
return request<void>({
|
||||
url: `/web/profile/qualification/${encodeURIComponent(id)}/resubmit`,
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
/** TODO(api): 后端帮助中心接口就绪后改为 request 调用;暂用设计稿假数据 */
|
||||
export interface QualificationDownloadFile {
|
||||
blob: Blob
|
||||
/** 后端通过 Content-Disposition 下发的文件名(证书名称 + 序号 + 扩展名) */
|
||||
fileName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载已保存的资质附件(文件流,不走统一 JSON 包装)。
|
||||
* index 为该附件在列表中的下标,从 0 开始,不传默认 0。
|
||||
*/
|
||||
export async function downloadQualificationAttachment(
|
||||
id: string,
|
||||
index = 0,
|
||||
): Promise<QualificationDownloadFile> {
|
||||
const resp = await service.get<Blob>(
|
||||
`/web/profile/qualification/${encodeURIComponent(id)}/download`,
|
||||
{ params: { index }, responseType: 'blob' },
|
||||
)
|
||||
// 后端报错时返回 JSON,被 axios 包成 Blob
|
||||
if (resp.data.type.startsWith('application/json')) {
|
||||
throw new Error(await readBlobErrorMessage(resp.data))
|
||||
}
|
||||
return {
|
||||
blob: resp.data,
|
||||
fileName: resolveContentDispositionFileName(resp.headers['content-disposition']),
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 反馈:/web/profile/feedback、/web/profile/feedback/page
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function submitFeedback(feedback: Feedback): Promise<void> {
|
||||
await request<void>({
|
||||
url: '/web/profile/feedback',
|
||||
method: 'post',
|
||||
data: toFeedbackBo(feedback),
|
||||
})
|
||||
}
|
||||
|
||||
/** 我的反馈分页(页面暂未使用,接口先接好)。 */
|
||||
export function getFeedbackPage(query: ListQuery): Promise<ProfilePageVo<FeedbackVo>> {
|
||||
return request<ProfilePageVo<FeedbackVo>>({
|
||||
url: '/web/profile/feedback/page',
|
||||
method: 'get',
|
||||
params: { pageNum: query.page, pageSize: query.pageSize },
|
||||
})
|
||||
}
|
||||
|
||||
/** 后端确认不提供 FAQ 接口(2026-11-03),保留设计稿静态文案。 */
|
||||
export function getHelpFaqs(): Promise<HelpFaqGroup[]> {
|
||||
return Promise.resolve([
|
||||
{
|
||||
|
||||
@@ -1,68 +1,94 @@
|
||||
import type { ChatMessage } from '@/types/business/service'
|
||||
import type {
|
||||
ChatUploadVo,
|
||||
CsMessageCenterQuery,
|
||||
CsMessagePageVo,
|
||||
CsMessageVo,
|
||||
CsSessionPreviewVo,
|
||||
CsSessionVo,
|
||||
SendCsMessageParams,
|
||||
} from '@/types/business/service'
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
// TODO(api): 待接口文档到位后,将以下 mock 替换为 request<T> 调用
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// POST /web/chat/session/init → 获取/创建当前客户的客服会话
|
||||
// GET /web/chat/message/list → 按 sessionId 拉会话消息
|
||||
// POST /web/chat/message → 客户发送消息(TEXT/IMAGE/FILE/VOICE)
|
||||
// GET /web/chat/session/preview → 消息中心「在线客服」卡片未读数 + 最新一条
|
||||
// GET /web/chat/message/centerList → 消息中心「在线客服」页签消息分页列表
|
||||
// POST /web/chat/message/readAll → 消息中心「在线客服」一键全部已读
|
||||
// 文档未提供聊天附件上传接口,复用用户端 OSS 上传(files 多文件,取首个结果)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
let seq = 0
|
||||
|
||||
function nextId(prefix: string): string {
|
||||
seq += 1
|
||||
return `${prefix}-${Date.now()}-${seq}`
|
||||
}
|
||||
|
||||
function nowTime(): string {
|
||||
const date = new Date()
|
||||
const pad = (n: number): string => (n < 10 ? `0${n}` : String(n))
|
||||
return `今天 ${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||
}
|
||||
|
||||
export function getChatHistory(): Promise<ChatMessage[]> {
|
||||
return Promise.resolve([
|
||||
{
|
||||
id: 'chat-001',
|
||||
role: 'assistant',
|
||||
content: '您好,欢迎咨询智联智造平台!我是您的专属客服小助手,请问有什么可以帮您的?',
|
||||
time: '今天 10:23',
|
||||
export function initChatSession(params?: {
|
||||
chatType?: string
|
||||
contact?: string
|
||||
}): Promise<CsSessionVo> {
|
||||
return request<CsSessionVo>({
|
||||
url: '/web/chat/session/init',
|
||||
method: 'post',
|
||||
params: {
|
||||
chatType: params?.chatType || undefined,
|
||||
contact: params?.contact || undefined,
|
||||
},
|
||||
{
|
||||
id: 'chat-002',
|
||||
role: 'user',
|
||||
content: '我想咨询一下物联网全案开发的流程和周期',
|
||||
time: '今天 10:23',
|
||||
},
|
||||
{
|
||||
id: 'chat-003',
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
file: { name: '物联网全案服务介绍.pdf', size: 2.5 * 1024 * 1024 },
|
||||
time: '今天 10:24',
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
export function sendChatMessage(content: string): Promise<ChatMessage> {
|
||||
return Promise.resolve({
|
||||
id: nextId('chat'),
|
||||
role: 'user',
|
||||
content,
|
||||
time: nowTime(),
|
||||
})
|
||||
}
|
||||
|
||||
export function uploadChatFile(file: File): Promise<ChatMessage> {
|
||||
return Promise.resolve({
|
||||
id: nextId('chat'),
|
||||
role: 'user',
|
||||
content: '',
|
||||
file: { name: file.name, size: file.size },
|
||||
time: nowTime(),
|
||||
export function getChatMessages(
|
||||
sessionId: number | string,
|
||||
silent = false,
|
||||
): Promise<CsMessageVo[]> {
|
||||
return request<CsMessageVo[]>({
|
||||
url: '/web/chat/message/list',
|
||||
method: 'get',
|
||||
params: { sessionId },
|
||||
silent,
|
||||
})
|
||||
}
|
||||
|
||||
export function mockAutoReply(): Promise<ChatMessage> {
|
||||
return Promise.resolve({
|
||||
id: nextId('chat'),
|
||||
role: 'assistant',
|
||||
content: '收到您的消息,专属客服稍后为您答复~',
|
||||
time: nowTime(),
|
||||
export function sendChatMessage(payload: SendCsMessageParams): Promise<CsMessageVo> {
|
||||
return request<CsMessageVo>({
|
||||
url: '/web/chat/message',
|
||||
method: 'post',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
/** 消息中心「在线客服」页签消息分页列表。 */
|
||||
export function getChatCenterMessages(query: CsMessageCenterQuery): Promise<CsMessagePageVo> {
|
||||
return request<CsMessagePageVo>({
|
||||
url: '/web/chat/message/centerList',
|
||||
method: 'get',
|
||||
params: query,
|
||||
})
|
||||
}
|
||||
|
||||
/** 消息中心「在线客服」一键全部已读。 */
|
||||
export function readAllChatMessages(): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/chat/message/readAll',
|
||||
method: 'post',
|
||||
})
|
||||
}
|
||||
|
||||
/** silent:轮询未读数时静默失败,避免瞬时网络异常反复弹提示。 */
|
||||
export function getChatSessionPreview(silent = false): Promise<CsSessionPreviewVo> {
|
||||
return request<CsSessionPreviewVo>({
|
||||
url: '/web/chat/session/preview',
|
||||
method: 'get',
|
||||
silent,
|
||||
})
|
||||
}
|
||||
|
||||
export async function uploadChatFile(file: File): Promise<ChatUploadVo & { url: string }> {
|
||||
const form = new FormData()
|
||||
form.append('files', file)
|
||||
const rows = await request<ChatUploadVo[]>({
|
||||
url: '/app/requirement/oss/upload',
|
||||
method: 'post',
|
||||
data: form,
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
const uploaded = rows?.[0]
|
||||
if (!uploaded?.url) throw new Error('文件上传失败')
|
||||
return { ...uploaded, url: uploaded.url }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { request } from '@/utils/request'
|
||||
import type { UserProfileVo } from '@/types/business/user'
|
||||
import type {
|
||||
AccountSecurityVo,
|
||||
UserProfileUpdatePayload,
|
||||
UserProfileVo,
|
||||
} from '@/types/business/user'
|
||||
|
||||
export async function getUserProfile(): Promise<UserProfileVo> {
|
||||
const data = await request<{ user: UserProfileVo }>({
|
||||
@@ -8,3 +12,23 @@ export async function getUserProfile(): Promise<UserProfileVo> {
|
||||
})
|
||||
return data.user
|
||||
}
|
||||
|
||||
/** 账号安全信息:密码修改时间等(WEB 端复用 APP 接口)。 */
|
||||
export async function getAccountSecurity(): Promise<AccountSecurityVo> {
|
||||
const data = await request<AccountSecurityVo & { accountSecurity?: AccountSecurityVo }>({
|
||||
url: '/app/account/security',
|
||||
method: 'get',
|
||||
silent: true,
|
||||
})
|
||||
// 兼容后端可能包一层 accountSecurity 的返回结构
|
||||
return data?.accountSecurity ?? data
|
||||
}
|
||||
|
||||
/** 更新个人资料,只提交传入的字段。 */
|
||||
export function updateUserProfile(payload: UserProfileUpdatePayload): Promise<void> {
|
||||
return request<void>({
|
||||
url: '/web/system/user/profile',
|
||||
method: 'put',
|
||||
data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useMessageStore } from '@/stores/modules/message'
|
||||
import { useUserStore } from '@/stores/modules/user'
|
||||
|
||||
interface NavItem {
|
||||
label: string
|
||||
@@ -33,7 +34,45 @@ function isActive(item: NavItem): boolean {
|
||||
|
||||
const messageStore = useMessageStore()
|
||||
const { unreadCount } = storeToRefs(messageStore)
|
||||
onMounted(() => void messageStore.fetchUnreadCount())
|
||||
const userStore = useUserStore()
|
||||
const { isLoggedIn } = storeToRefs(userStore)
|
||||
|
||||
/* ------------------------------ 未读数轮询 ------------------------------ */
|
||||
|
||||
/** 顶部铃铛未读数轮询间隔 */
|
||||
const UNREAD_POLL_INTERVAL = 5_000
|
||||
let unreadTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
/** 未登录时接口必然失败,不轮询;轮询请求静默失败,避免网络抖动弹提示。 */
|
||||
function refreshUnread(): void {
|
||||
if (!isLoggedIn.value) return
|
||||
void messageStore.fetchUnreadCount(true)
|
||||
}
|
||||
|
||||
function onVisibilityChange(): void {
|
||||
if (document.visibilityState === 'visible') refreshUnread()
|
||||
}
|
||||
|
||||
// 登录后立即拉取一次,不必等下一个轮询周期
|
||||
watch(isLoggedIn, (loggedIn) => {
|
||||
if (loggedIn) refreshUnread()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
refreshUnread()
|
||||
unreadTimer = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') refreshUnread()
|
||||
}, UNREAD_POLL_INTERVAL)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (unreadTimer) {
|
||||
clearInterval(unreadTimer)
|
||||
unreadTimer = undefined
|
||||
}
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import qrcode from 'qrcode-generator'
|
||||
import { useCountDown } from '@/composables/useCountDown'
|
||||
|
||||
interface Props {
|
||||
expiresIn?: number
|
||||
size?: number
|
||||
/** 二维码内容;未传时保持占位样式(如支付页) */
|
||||
content?: string
|
||||
/** 是否展示有效期倒计时;支付二维码 2 小时有效,无需前端倒计时/刷新 */
|
||||
countdown?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
expiresIn: 272,
|
||||
size: 200,
|
||||
countdown: true,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ refresh: [] }>()
|
||||
const emit = defineEmits<{ refresh: []; expire: [] }>()
|
||||
|
||||
const { seconds, start } = useCountDown(props.expiresIn)
|
||||
const started = ref(false)
|
||||
const started = ref(!props.countdown)
|
||||
|
||||
const expired = computed(() => started.value && seconds.value <= 0)
|
||||
const expired = computed(() => props.countdown && started.value && seconds.value <= 0)
|
||||
|
||||
const countdownText = computed(() => {
|
||||
const m = Math.floor(seconds.value / 60)
|
||||
@@ -25,14 +31,44 @@ const countdownText = computed(() => {
|
||||
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
|
||||
})
|
||||
|
||||
const qrSvg = computed(() => {
|
||||
if (!props.content) return ''
|
||||
try {
|
||||
const qr = qrcode(0, 'M')
|
||||
qr.addData(props.content)
|
||||
qr.make()
|
||||
return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true })
|
||||
}
|
||||
catch {
|
||||
return ''
|
||||
}
|
||||
})
|
||||
|
||||
/** 调用方传入 content 但内容尚未就绪(等待接口返回 token) */
|
||||
const pending = computed(() => props.content !== undefined && !props.content && !expired.value)
|
||||
|
||||
function refresh(): void {
|
||||
if (!props.countdown) return
|
||||
start(props.expiresIn)
|
||||
started.value = true
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
watch(
|
||||
() => props.content,
|
||||
(content) => {
|
||||
if (!props.countdown) return
|
||||
// 未传 content 时沿用「进入页面即倒计时」的占位行为;传了 content 则等内容就绪再倒计时
|
||||
if (content === undefined || content) {
|
||||
start(props.expiresIn)
|
||||
started.value = true
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(expired, (value) => {
|
||||
if (value) emit('expire')
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -44,8 +80,13 @@ onMounted(() => {
|
||||
:style="{ width: `${size}px`, height: `${size}px` }"
|
||||
@click="refresh"
|
||||
>
|
||||
<!-- TODO(api): 二维码内容由支付/签署接口返回后渲染 -->
|
||||
<template v-if="!expired">
|
||||
<template v-if="!expired && qrSvg">
|
||||
<div class="qr-panel__code" v-html="qrSvg" />
|
||||
</template>
|
||||
<template v-else-if="pending">
|
||||
<span class="qr-panel__tip">二维码生成中…</span>
|
||||
</template>
|
||||
<template v-else-if="!expired">
|
||||
<span class="qr-panel__icon">▦</span>
|
||||
<span class="qr-panel__tip">扫码支付/签署</span>
|
||||
</template>
|
||||
@@ -54,8 +95,11 @@ onMounted(() => {
|
||||
<span class="qr-panel__tip">二维码已过期<br>点击刷新</span>
|
||||
</template>
|
||||
</div>
|
||||
<p class="qr-panel__status text-secondary">
|
||||
<template v-if="!expired">
|
||||
<p v-if="countdown" class="qr-panel__status text-secondary">
|
||||
<template v-if="pending">
|
||||
请稍候,正在生成签署二维码
|
||||
</template>
|
||||
<template v-else-if="!expired">
|
||||
<span class="qr-panel__countdown">二维码将在 <strong class="qr-panel__count">{{ countdownText }}</strong> 后失效</span>(过期可点击二维码刷新)
|
||||
</template>
|
||||
<template v-else>
|
||||
@@ -85,6 +129,20 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
&__code {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: @spacing-sm;
|
||||
background: @white;
|
||||
box-sizing: border-box;
|
||||
|
||||
:deep(svg) {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&__icon {
|
||||
font-size: 56px;
|
||||
color: @heading-color;
|
||||
|
||||
60
src/composables/usePayPoll.ts
Normal file
60
src/composables/usePayPoll.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { onScopeDispose, ref } from 'vue'
|
||||
import { useFinanceStore } from '@/stores/modules/finance'
|
||||
|
||||
/** 轮询间隔(毫秒) */
|
||||
const POLL_INTERVAL = 2500
|
||||
/** 最长轮询时长:3 分钟 */
|
||||
const POLL_TIMEOUT = 3 * 60 * 1000
|
||||
|
||||
/**
|
||||
* 支付结果轮询:二维码展示后每 2.5 秒查询一次,最多 3 分钟。
|
||||
* 查询到 SUCCESS 即停止轮询并回调;网络异常静默重试。
|
||||
*/
|
||||
export function usePayPoll(onSuccess: (outTradeNo: string) => void) {
|
||||
const financeStore = useFinanceStore()
|
||||
const polling = ref(false)
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let deadline = 0
|
||||
|
||||
function stop(): void {
|
||||
if (timer !== null) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
polling.value = false
|
||||
}
|
||||
|
||||
async function check(outTradeNo: string): Promise<boolean> {
|
||||
try {
|
||||
const result = await financeStore.queryPay(outTradeNo, true)
|
||||
if (result?.status === 'SUCCESS') {
|
||||
stop()
|
||||
onSuccess(outTradeNo)
|
||||
return true
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// 轮询失败不打断流程,交给下一次重试
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function start(outTradeNo: string): void {
|
||||
stop()
|
||||
if (!outTradeNo) return
|
||||
polling.value = true
|
||||
deadline = Date.now() + POLL_TIMEOUT
|
||||
void check(outTradeNo)
|
||||
timer = setInterval(() => {
|
||||
if (Date.now() >= deadline) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
void check(outTradeNo)
|
||||
}, POLL_INTERVAL)
|
||||
}
|
||||
|
||||
onScopeDispose(stop)
|
||||
|
||||
return { polling, start, stop, check }
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import type { PageResult } from '@/types/api'
|
||||
import type { Contract, ContractQuery } from '@/types/business/contract'
|
||||
import {
|
||||
getContractDetail,
|
||||
getContractDownloadUrl,
|
||||
getContractList,
|
||||
getSignQr,
|
||||
refreshSignQr,
|
||||
getContractPreview,
|
||||
getContractSignQrStatus,
|
||||
initContractSignQr,
|
||||
} from '@/api/contract'
|
||||
import { toContract } from '@/utils/contractVo'
|
||||
|
||||
/** 扫码签署二维码服务端 Redis TTL(5 分钟),用于页面倒计时。 */
|
||||
const SIGN_QR_TTL_SECONDS = 300
|
||||
|
||||
function createDefaultQuery(): ContractQuery {
|
||||
return {
|
||||
keyword: '',
|
||||
page: 1,
|
||||
pageNum: 1,
|
||||
pageSize: 8,
|
||||
}
|
||||
}
|
||||
@@ -22,16 +27,30 @@ export const useContractStore = defineStore('contract', () => {
|
||||
const list = ref<Contract[]>([])
|
||||
const total = ref(0)
|
||||
const current = ref<Contract | null>(null)
|
||||
const signExpires = ref(272)
|
||||
/** 后端 qr-init 返回的完整落地页 URL(含 token),直接用于渲染二维码。 */
|
||||
const signQrUrl = ref('')
|
||||
const signExpires = ref(SIGN_QR_TTL_SECONDS)
|
||||
|
||||
async function fetchList(): Promise<void> {
|
||||
const result: PageResult<Contract> = await getContractList(query.value)
|
||||
list.value = result.list
|
||||
total.value = result.total
|
||||
try {
|
||||
const result = await getContractList(query.value)
|
||||
list.value = (result?.rows ?? []).map(toContract)
|
||||
total.value = result?.total ?? 0
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[contract] 合同列表加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchDetail(id: string): Promise<void> {
|
||||
current.value = await getContractDetail(id)
|
||||
try {
|
||||
const vo = await getContractDetail(id)
|
||||
current.value = vo ? toContract(vo) : null
|
||||
}
|
||||
catch (error) {
|
||||
current.value = null
|
||||
console.warn('[contract] 合同详情加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
function setQuery(next: ContractQuery): void {
|
||||
@@ -39,7 +58,7 @@ export const useContractStore = defineStore('contract', () => {
|
||||
}
|
||||
|
||||
async function search(): Promise<void> {
|
||||
query.value = { ...query.value, page: 1 }
|
||||
query.value = { ...query.value, pageNum: 1 }
|
||||
await fetchList()
|
||||
}
|
||||
|
||||
@@ -48,14 +67,27 @@ export const useContractStore = defineStore('contract', () => {
|
||||
await fetchList()
|
||||
}
|
||||
|
||||
async function changePage(page: number): Promise<void> {
|
||||
query.value = { ...query.value, page }
|
||||
async function changePage(pageNum: number): Promise<void> {
|
||||
query.value = { ...query.value, pageNum }
|
||||
await fetchList()
|
||||
}
|
||||
|
||||
async function fetchSignQr(id: string, refresh = false): Promise<void> {
|
||||
const result = refresh ? await refreshSignQr(id) : await getSignQr(id)
|
||||
signExpires.value = result.expiresInSeconds
|
||||
async function fetchSignQr(id: string): Promise<void> {
|
||||
signQrUrl.value = await initContractSignQr(id)
|
||||
signExpires.value = SIGN_QR_TTL_SECONDS
|
||||
}
|
||||
|
||||
async function fetchSignQrStatus(id: string): Promise<boolean> {
|
||||
return getContractSignQrStatus(id)
|
||||
}
|
||||
|
||||
async function fetchPreviewUrl(id: string): Promise<string> {
|
||||
const vo = await getContractPreview(id)
|
||||
return vo?.file ?? ''
|
||||
}
|
||||
|
||||
async function fetchDownloadUrl(id: string): Promise<string> {
|
||||
return (await getContractDownloadUrl(id)) ?? ''
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -63,6 +95,7 @@ export const useContractStore = defineStore('contract', () => {
|
||||
list,
|
||||
total,
|
||||
current,
|
||||
signQrUrl,
|
||||
signExpires,
|
||||
fetchList,
|
||||
fetchDetail,
|
||||
@@ -71,5 +104,8 @@ export const useContractStore = defineStore('contract', () => {
|
||||
resetQuery,
|
||||
changePage,
|
||||
fetchSignQr,
|
||||
fetchSignQrStatus,
|
||||
fetchPreviewUrl,
|
||||
fetchDownloadUrl,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import type { PageResult } from '@/types/api'
|
||||
import type {
|
||||
Bill,
|
||||
BillQuery,
|
||||
BillStatistics,
|
||||
DictOptionVo,
|
||||
FinanceBillVo,
|
||||
FinancePayQueryVo,
|
||||
FinancePayResultVo,
|
||||
FinanceStats,
|
||||
FinanceSummaryQuery,
|
||||
Invoice,
|
||||
InvoiceApplyPayload,
|
||||
InvoiceAvailableBill,
|
||||
InvoiceQuery,
|
||||
InvoiceTitle,
|
||||
InvoiceTitlePayload,
|
||||
@@ -14,37 +21,61 @@ import type {
|
||||
Payment,
|
||||
PaymentResult,
|
||||
} from '@/types/business/finance'
|
||||
import type { ExportFormat, InvoiceDownloadFile } from '@/api/finance'
|
||||
import {
|
||||
applyInvoice as applyInvoiceApi,
|
||||
createAlipayPageOrder as createAlipayPageOrderApi,
|
||||
createInvoiceTitle,
|
||||
createPayment as createPaymentApi,
|
||||
createWechatNativeOrder as createWechatNativeOrderApi,
|
||||
deleteInvoiceTitle,
|
||||
exportReport as exportReportApi,
|
||||
getBillDetail,
|
||||
getBillList,
|
||||
getCheckoutBills,
|
||||
getFinanceStats,
|
||||
getInvoiceList,
|
||||
getInvoiceTitles,
|
||||
getPlanPayResult,
|
||||
getPayResult,
|
||||
setDefaultTitle as setDefaultTitleApi,
|
||||
switchPaymentMethod as switchPaymentMethodApi,
|
||||
updateInvoiceTitle,
|
||||
createInvoiceTitle as createInvoiceTitleApi,
|
||||
deleteInvoiceTitle as deleteInvoiceTitleApi,
|
||||
downloadInvoice as downloadInvoiceApi,
|
||||
exportBillReport,
|
||||
getAvailableInvoiceBills,
|
||||
getBillDetail as getBillDetailApi,
|
||||
getBillList as getBillListApi,
|
||||
getBillStatistics as getBillStatisticsApi,
|
||||
getFinanceSummary,
|
||||
getInvoiceDetail as getInvoiceDetailApi,
|
||||
getInvoicePage,
|
||||
getInvoiceStatusDict,
|
||||
getInvoiceTitleList,
|
||||
payBill as payBillApi,
|
||||
payBills as payBillsApi,
|
||||
previewInvoice as previewInvoiceApi,
|
||||
queryPayResult,
|
||||
sendInvoiceEmail as sendInvoiceEmailApi,
|
||||
setDefaultInvoiceTitle,
|
||||
updateInvoiceTitle as updateInvoiceTitleApi,
|
||||
} from '@/api/finance'
|
||||
import { toBill, toBillStatistics, toBills, toFinanceStats } from '@/utils/billVo'
|
||||
import {
|
||||
toInvoice,
|
||||
toInvoiceAvailableBills,
|
||||
toInvoiceStatusParam,
|
||||
toInvoiceTitleBo,
|
||||
toInvoiceTitles,
|
||||
toInvoices,
|
||||
} from '@/utils/invoiceVo'
|
||||
import { toPayChannel, toPayMethod } from '@/utils/payMeta'
|
||||
|
||||
function createDefaultBillQuery(): BillQuery {
|
||||
return { keyword: '', status: 'all', page: 1, pageSize: 6 }
|
||||
}
|
||||
|
||||
function createDefaultInvoiceQuery(): InvoiceQuery {
|
||||
return { keyword: '', status: 'all', page: 1, pageSize: 6 }
|
||||
return { status: '', page: 1, pageSize: 6 }
|
||||
}
|
||||
|
||||
function toPayOrder(vo: FinancePayResultVo, method: PayMethod): PayOrderResponse {
|
||||
return {
|
||||
channel: toPayChannel(method),
|
||||
qrCode: vo?.qrCode,
|
||||
}
|
||||
}
|
||||
|
||||
export const useFinanceStore = defineStore('finance', () => {
|
||||
const stats = ref<FinanceStats | null>(null)
|
||||
/** 累计消费总额卡片单独按月份统计,避免月份选择器影响下方图表 */
|
||||
const overviewStats = ref<FinanceStats | null>(null)
|
||||
const billStats = ref<BillStatistics>({ totalAmount: 0, totalCount: 0, pendingCount: 0 })
|
||||
|
||||
const list = ref<Bill[]>([])
|
||||
const total = ref(0)
|
||||
@@ -57,21 +88,53 @@ export const useFinanceStore = defineStore('finance', () => {
|
||||
const checkoutBills = ref<Bill[]>([])
|
||||
const checkoutLoading = ref(false)
|
||||
const payOrder = ref<PayOrderResponse | null>(null)
|
||||
const payOutTradeNo = ref('')
|
||||
|
||||
const invoices = ref<Invoice[]>([])
|
||||
const invoiceTotal = ref(0)
|
||||
const invoiceQuery = ref<InvoiceQuery>(createDefaultInvoiceQuery())
|
||||
const availableBills = ref<InvoiceAvailableBill[]>([])
|
||||
const invoiceStatusOptions = ref<DictOptionVo[]>([])
|
||||
|
||||
const titles = ref<InvoiceTitle[]>([])
|
||||
|
||||
async function fetchStats(period?: string): Promise<void> {
|
||||
stats.value = await getFinanceStats(period)
|
||||
async function fetchStats(query: FinanceSummaryQuery = {}): Promise<void> {
|
||||
try {
|
||||
const [summary, statistics] = await Promise.all([
|
||||
getFinanceSummary(query),
|
||||
getBillStatisticsApi(createDefaultBillQuery()),
|
||||
])
|
||||
stats.value = toFinanceStats(summary, statistics)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 财务概览加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只刷新「累计消费总额」卡片,不影响图表使用的 stats */
|
||||
async function fetchOverviewStats(query: FinanceSummaryQuery = {}): Promise<void> {
|
||||
try {
|
||||
const summary = await getFinanceSummary(query)
|
||||
overviewStats.value = toFinanceStats(summary, null)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 累计消费总额加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchList(): Promise<void> {
|
||||
const pageData: PageResult<Bill> = await getBillList(query.value)
|
||||
list.value = pageData.list
|
||||
total.value = pageData.total
|
||||
try {
|
||||
const [pageData, statistics] = await Promise.all([
|
||||
getBillListApi(query.value),
|
||||
getBillStatisticsApi(query.value),
|
||||
])
|
||||
list.value = toBills(pageData?.rows)
|
||||
total.value = Number(pageData?.total ?? 0)
|
||||
billStats.value = toBillStatistics(statistics)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 账单列表加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
function setQuery(next: BillQuery): void {
|
||||
@@ -94,48 +157,142 @@ export const useFinanceStore = defineStore('finance', () => {
|
||||
}
|
||||
|
||||
async function fetchDetail(id: string): Promise<void> {
|
||||
currentBill.value = await getBillDetail(id)
|
||||
try {
|
||||
const vo = await getBillDetailApi(id)
|
||||
currentBill.value = vo ? toBill(vo) : null
|
||||
}
|
||||
catch (error) {
|
||||
currentBill.value = null
|
||||
console.warn('[finance] 账单详情加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function createPayment(billId: string, method: PayMethod): Promise<void> {
|
||||
payment.value = await createPaymentApi(billId, method)
|
||||
const vo = await payBillApi(billId, toPayChannel(method))
|
||||
payOutTradeNo.value = vo?.outTradeNo ?? ''
|
||||
payOrder.value = toPayOrder(vo, method)
|
||||
payment.value = {
|
||||
billId,
|
||||
method,
|
||||
amount: currentBill.value?.amount ?? Number(vo?.mergedAmount ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
async function switchPaymentMethod(billId: string, method: PayMethod): Promise<void> {
|
||||
payment.value = await switchPaymentMethodApi(billId, method)
|
||||
/** 单笔走 /web/pay/bill,多笔合并走 /web/pay/bill/batch。 */
|
||||
async function payOrders(ids: string[], method: PayMethod): Promise<void> {
|
||||
const channel = toPayChannel(method)
|
||||
const vo = ids.length === 1
|
||||
? await payBillApi(ids[0], channel)
|
||||
: await payBillsApi(ids, channel)
|
||||
payOutTradeNo.value = vo?.outTradeNo ?? ''
|
||||
payOrder.value = toPayOrder(vo, method)
|
||||
}
|
||||
|
||||
async function fetchResult(billId: string, requirementId = ''): Promise<void> {
|
||||
result.value = requirementId
|
||||
? await getPlanPayResult(requirementId, billId)
|
||||
: await getPayResult(billId)
|
||||
function queryPay(outTradeNo: string, silent = false): Promise<FinancePayQueryVo> {
|
||||
return queryPayResult(outTradeNo, silent)
|
||||
}
|
||||
|
||||
async function loadCheckout(requirementId: string, ids: string[] = []): Promise<void> {
|
||||
async function fetchResult(outTradeNo: string, ids: string[]): Promise<void> {
|
||||
try {
|
||||
const rows = await Promise.all(
|
||||
ids.map((id) => getBillDetailApi(id).catch(() => null)),
|
||||
)
|
||||
const bills = rows
|
||||
.filter((vo): vo is FinanceBillVo => vo != null)
|
||||
.map(toBill)
|
||||
const payQuery = outTradeNo ? await queryPayResult(outTradeNo) : null
|
||||
|
||||
if (!payQuery && bills.length === 0) {
|
||||
result.value = null
|
||||
return
|
||||
}
|
||||
|
||||
const first = bills[0]
|
||||
result.value = {
|
||||
method: toPayMethod(first?.payChannel),
|
||||
amount: bills.reduce((sum, bill) => sum + bill.amount, 0),
|
||||
payTime: payQuery?.payTime ?? first?.payTime ?? '—',
|
||||
tradeNo: payQuery?.transactionNo ?? first?.tradeNo ?? '—',
|
||||
bills,
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
result.value = null
|
||||
console.warn('[finance] 支付结果加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCheckout(ids: string[]): Promise<void> {
|
||||
checkoutLoading.value = true
|
||||
try {
|
||||
checkoutBills.value = await getCheckoutBills(requirementId, ids)
|
||||
} finally {
|
||||
if (ids.length === 0) {
|
||||
checkoutBills.value = []
|
||||
return
|
||||
}
|
||||
const rows = await Promise.all(
|
||||
ids.map((id) => getBillDetailApi(id).catch(() => null)),
|
||||
)
|
||||
checkoutBills.value = rows
|
||||
.filter((vo): vo is FinanceBillVo => vo != null)
|
||||
.map(toBill)
|
||||
}
|
||||
finally {
|
||||
checkoutLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function payByWechatNative(orderNo: string, amount: number, billIds: string[]): Promise<void> {
|
||||
payOrder.value = await createWechatNativeOrderApi(orderNo, amount, billIds)
|
||||
}
|
||||
|
||||
async function payByAlipayPage(orderNo: string, amount: number, billIds: string[]): Promise<void> {
|
||||
payOrder.value = await createAlipayPageOrderApi(orderNo, amount, billIds)
|
||||
}
|
||||
|
||||
function clearPayOrder(): void {
|
||||
payOrder.value = null
|
||||
payOutTradeNo.value = ''
|
||||
}
|
||||
|
||||
/** 发票状态字典(0 未开票 / 1 开票中 / 2 已开票)。 */
|
||||
async function fetchInvoiceStatusOptions(): Promise<void> {
|
||||
try {
|
||||
const rows = await getInvoiceStatusDict()
|
||||
invoiceStatusOptions.value = [...(rows ?? [])].sort(
|
||||
(a, b) => (a.dictSort ?? 0) - (b.dictSort ?? 0),
|
||||
)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 发票状态字典加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchInvoices(): Promise<void> {
|
||||
const pageData: PageResult<Invoice> = await getInvoiceList(invoiceQuery.value)
|
||||
invoices.value = pageData.list
|
||||
invoiceTotal.value = pageData.total
|
||||
try {
|
||||
const pageData = await getInvoicePage({
|
||||
status: toInvoiceStatusParam(invoiceQuery.value.status),
|
||||
page: invoiceQuery.value.page,
|
||||
pageSize: invoiceQuery.value.pageSize,
|
||||
})
|
||||
invoices.value = toInvoices(pageData?.rows)
|
||||
invoiceTotal.value = Number(pageData?.total ?? 0)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 发票记录加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchInvoiceDetail(id: string): Promise<Invoice | null> {
|
||||
const vo = await getInvoiceDetailApi(id)
|
||||
return vo ? toInvoice(vo) : null
|
||||
}
|
||||
|
||||
/** 预览电子发票,返回 PDF 直链(仅已开票)。 */
|
||||
async function fetchPreviewUrl(id: string): Promise<string | null> {
|
||||
const vo = await previewInvoiceApi(id)
|
||||
return vo?.file ?? null
|
||||
}
|
||||
|
||||
/** 下载电子发票,返回 PDF 文件流与文件名(仅已开票)。 */
|
||||
async function fetchDownloadFile(id: string): Promise<InvoiceDownloadFile> {
|
||||
return downloadInvoiceApi(id)
|
||||
}
|
||||
|
||||
/** 发送电子发票到邮箱;不传 email 则由后端取用户绑定邮箱。 */
|
||||
async function sendInvoiceEmail(invoiceId: string, email?: string): Promise<void> {
|
||||
await sendInvoiceEmailApi({ invoiceId, email })
|
||||
}
|
||||
|
||||
function setInvoiceQuery(next: InvoiceQuery): void {
|
||||
@@ -152,41 +309,54 @@ export const useFinanceStore = defineStore('finance', () => {
|
||||
await fetchInvoices()
|
||||
}
|
||||
|
||||
async function applyInvoice(id: string): Promise<void> {
|
||||
const updated = await applyInvoiceApi(id)
|
||||
const index = invoices.value.findIndex((item) => item.id === id)
|
||||
if (index >= 0) invoices.value[index] = updated
|
||||
async function fetchAvailableBills(): Promise<void> {
|
||||
const rows = await getAvailableInvoiceBills()
|
||||
availableBills.value = toInvoiceAvailableBills(rows)
|
||||
}
|
||||
|
||||
async function applyInvoice(payload: InvoiceApplyPayload): Promise<void> {
|
||||
await applyInvoiceApi(payload)
|
||||
await Promise.allSettled([fetchInvoices(), fetchAvailableBills()])
|
||||
}
|
||||
|
||||
async function fetchTitles(): Promise<void> {
|
||||
titles.value = await getInvoiceTitles()
|
||||
try {
|
||||
const rows = await getInvoiceTitleList()
|
||||
titles.value = toInvoiceTitles(rows)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[finance] 发票抬头加载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function createTitle(payload: InvoiceTitlePayload): Promise<void> {
|
||||
await createInvoiceTitle(payload)
|
||||
await createInvoiceTitleApi(toInvoiceTitleBo(payload))
|
||||
await fetchTitles()
|
||||
}
|
||||
|
||||
async function updateTitle(id: string, payload: InvoiceTitlePayload): Promise<void> {
|
||||
await updateInvoiceTitle(id, payload)
|
||||
await updateInvoiceTitleApi(toInvoiceTitleBo(payload, id))
|
||||
await fetchTitles()
|
||||
}
|
||||
|
||||
async function deleteTitle(id: string): Promise<void> {
|
||||
await deleteInvoiceTitle(id)
|
||||
await deleteInvoiceTitleApi(id)
|
||||
await fetchTitles()
|
||||
}
|
||||
|
||||
async function setDefaultTitle(id: string): Promise<void> {
|
||||
titles.value = await setDefaultTitleApi(id)
|
||||
await setDefaultInvoiceTitle(id)
|
||||
await fetchTitles()
|
||||
}
|
||||
|
||||
async function exportReport(): Promise<void> {
|
||||
await exportReportApi()
|
||||
async function exportReport(format: ExportFormat = 'excel'): Promise<Blob> {
|
||||
return exportBillReport(query.value, format)
|
||||
}
|
||||
|
||||
return {
|
||||
stats,
|
||||
overviewStats,
|
||||
billStats,
|
||||
list,
|
||||
total,
|
||||
query,
|
||||
@@ -196,11 +366,15 @@ export const useFinanceStore = defineStore('finance', () => {
|
||||
checkoutBills,
|
||||
checkoutLoading,
|
||||
payOrder,
|
||||
payOutTradeNo,
|
||||
invoices,
|
||||
invoiceTotal,
|
||||
invoiceQuery,
|
||||
availableBills,
|
||||
invoiceStatusOptions,
|
||||
titles,
|
||||
fetchStats,
|
||||
fetchOverviewStats,
|
||||
fetchList,
|
||||
setQuery,
|
||||
search,
|
||||
@@ -208,16 +382,21 @@ export const useFinanceStore = defineStore('finance', () => {
|
||||
changePage,
|
||||
fetchDetail,
|
||||
createPayment,
|
||||
switchPaymentMethod,
|
||||
payOrders,
|
||||
queryPay,
|
||||
fetchResult,
|
||||
loadCheckout,
|
||||
payByWechatNative,
|
||||
payByAlipayPage,
|
||||
clearPayOrder,
|
||||
fetchInvoiceStatusOptions,
|
||||
fetchInvoices,
|
||||
fetchInvoiceDetail,
|
||||
fetchPreviewUrl,
|
||||
fetchDownloadFile,
|
||||
sendInvoiceEmail,
|
||||
setInvoiceQuery,
|
||||
searchInvoices,
|
||||
changeInvoicePage,
|
||||
fetchAvailableBills,
|
||||
applyInvoice,
|
||||
fetchTitles,
|
||||
createTitle,
|
||||
|
||||
@@ -2,15 +2,20 @@ import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { PageResult } from '@/types/api'
|
||||
import type { Message, MessageQuery } from '@/types/business/message'
|
||||
import type {
|
||||
Message,
|
||||
MessageApiType,
|
||||
MessageCenterVo,
|
||||
MessageQuery,
|
||||
} from '@/types/business/message'
|
||||
import type { CsSessionPreviewVo } from '@/types/business/service'
|
||||
import {
|
||||
getMessageCenter,
|
||||
getMessageDetail,
|
||||
getMessageList,
|
||||
getTabCounts,
|
||||
getUnreadCount,
|
||||
markAllRead as markAllReadApi,
|
||||
markRead as markReadApi,
|
||||
} from '@/api/message'
|
||||
import { getChatSessionPreview } from '@/api/service'
|
||||
|
||||
export interface MessageTabCounts {
|
||||
all: number
|
||||
@@ -36,20 +41,30 @@ export const useMessageStore = defineStore('message', () => {
|
||||
const unreadCount = ref(0)
|
||||
const tabCounts = ref<MessageTabCounts>({ all: 0, 在线客服: 0, 状态通知: 0, 系统通知: 0 })
|
||||
|
||||
interface CenterPayload {
|
||||
center: MessageCenterVo | null
|
||||
preview: CsSessionPreviewVo | null
|
||||
}
|
||||
|
||||
/**
|
||||
* center 接口提供状态通知/系统通知计数,在线客服入口由 /web/chat/session/preview 单独提供;
|
||||
* 挂载时高频并发调用,合并为一次请求。
|
||||
*/
|
||||
let centerRequest: Promise<CenterPayload> | null = null
|
||||
|
||||
async function fetchList(): Promise<void> {
|
||||
const result: PageResult<Message> = await getMessageList(query.value)
|
||||
list.value = result.list
|
||||
total.value = result.total
|
||||
}
|
||||
|
||||
async function fetchDetail(id: string): Promise<void> {
|
||||
const detail = await getMessageDetail(id)
|
||||
async function fetchDetail(id: string, type: MessageApiType): Promise<void> {
|
||||
const detail = await getMessageDetail(id, type)
|
||||
current.value = detail
|
||||
if (detail && !detail.isRead) {
|
||||
await markReadApi(id)
|
||||
if (detail) {
|
||||
// 详情接口会将该条置为已读,刷新入口未读数与 tab 计数
|
||||
detail.isRead = true
|
||||
if (unreadCount.value > 0) unreadCount.value -= 1
|
||||
await fetchTabCounts()
|
||||
await fetchCenter()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,18 +88,36 @@ export const useMessageStore = defineStore('message', () => {
|
||||
}
|
||||
|
||||
async function markAllRead(): Promise<void> {
|
||||
await markAllReadApi()
|
||||
await markAllReadApi(query.value.type)
|
||||
ElMessage.success('已全部标记为已读')
|
||||
await Promise.all([fetchList(), fetchUnreadCount(), fetchTabCounts()])
|
||||
await Promise.all([fetchList(), fetchCenter()])
|
||||
if (current.value) current.value.isRead = true
|
||||
}
|
||||
|
||||
async function fetchUnreadCount(): Promise<void> {
|
||||
unreadCount.value = await getUnreadCount()
|
||||
/** silent:顶部铃铛轮询时静默失败,避免网络抖动反复弹提示。 */
|
||||
async function fetchCenter(silent = false): Promise<void> {
|
||||
if (!centerRequest) {
|
||||
centerRequest = Promise.all([
|
||||
getMessageCenter(silent).catch(() => null),
|
||||
getChatSessionPreview(silent).catch(() => null),
|
||||
])
|
||||
.then(([center, preview]) => ({ center, preview }))
|
||||
.finally(() => {
|
||||
centerRequest = null
|
||||
})
|
||||
}
|
||||
const { center, preview } = await centerRequest
|
||||
const status = Number(center?.status?.unreadCount ?? 0)
|
||||
const system = Number(center?.system?.unreadCount ?? 0)
|
||||
// center.cs 本接口固定返回 null,在线客服未读数以 preview 为准
|
||||
const cs = Number(preview?.unreadCount ?? center?.cs?.unreadCount ?? 0)
|
||||
unreadCount.value = status + system + cs
|
||||
tabCounts.value = {
|
||||
all: status + system + cs,
|
||||
在线客服: cs,
|
||||
状态通知: status,
|
||||
系统通知: system,
|
||||
}
|
||||
|
||||
async function fetchTabCounts(): Promise<void> {
|
||||
tabCounts.value = await getTabCounts()
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -101,7 +134,8 @@ export const useMessageStore = defineStore('message', () => {
|
||||
resetQuery,
|
||||
changePage,
|
||||
markAllRead,
|
||||
fetchUnreadCount,
|
||||
fetchTabCounts,
|
||||
// 顶部铃铛与消息中心页共用 center 接口
|
||||
fetchUnreadCount: fetchCenter,
|
||||
fetchTabCounts: fetchCenter,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { fetchOssPreviewBlob } from '@/api/oss'
|
||||
import { downloadOssFile, fetchOssPreviewBlob } from '@/api/oss'
|
||||
import { resolvePreviewKind, PREVIEW_TEXT_MAX_BYTES, type PreviewKind } from '@/utils/filePreview'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
|
||||
@@ -72,6 +72,11 @@ export const useOssStore = defineStore('oss', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载已上传的 OSS 文件(尚未保存到业务记录的附件)。 */
|
||||
async function fetchDownloadBlob(ossId: string | number): Promise<Blob> {
|
||||
return downloadOssFile(ossId)
|
||||
}
|
||||
|
||||
function closePreview(): void {
|
||||
revokeObjectUrl()
|
||||
visible.value = false
|
||||
@@ -96,5 +101,6 @@ export const useOssStore = defineStore('oss', () => {
|
||||
totalBytes,
|
||||
openPreview,
|
||||
closePreview,
|
||||
fetchDownloadBlob,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,20 +23,26 @@ import {
|
||||
deleteAccount as deleteAccountApi,
|
||||
deleteAddress,
|
||||
deleteQualification,
|
||||
downloadQualificationAttachment as downloadQualificationAttachmentApi,
|
||||
getAddresses,
|
||||
getCaseCounts,
|
||||
getFavorites,
|
||||
getHelpFaqs,
|
||||
getProfile,
|
||||
getQualifications,
|
||||
sendBindEmailCode as sendBindEmailCodeApi,
|
||||
sendBindSmsCode as sendBindSmsCodeApi,
|
||||
setDefaultAddress,
|
||||
submitFeedback as submitFeedbackApi,
|
||||
unbindEmail,
|
||||
updateAddress,
|
||||
updateAvatar,
|
||||
updateNickname,
|
||||
updateQualification,
|
||||
verifyIdentity,
|
||||
uploadProfileAttachment,
|
||||
} from '@/api/profile'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import type { QualificationDownloadFile } from '@/api/profile'
|
||||
import { storage } from '@/utils/storage'
|
||||
|
||||
function createDefaultAddressQuery(): ListQuery {
|
||||
@@ -63,12 +69,35 @@ export const useProfileStore = defineStore('profile', () => {
|
||||
ElMessage.success('昵称修改成功')
|
||||
}
|
||||
|
||||
async function saveAvatar(url: string): Promise<void> {
|
||||
profile.value = await updateAvatar(url)
|
||||
ElMessage.success('头像修改成功')
|
||||
}
|
||||
|
||||
async function changePasswordAction(params: ChangePasswordParams): Promise<void> {
|
||||
await changePassword(params)
|
||||
// 后端固定使用账号绑定手机号,这里仍补一个 phoneNumber 兼容旧入参
|
||||
await changePassword({ ...params, phoneNumber: profile.value?.phone })
|
||||
profile.value = await getProfile()
|
||||
ElMessage.success('密码修改成功')
|
||||
}
|
||||
|
||||
/** 发送换绑手机号的短信验证码。 */
|
||||
async function sendBindSmsCodeAction(phone: string): Promise<void> {
|
||||
await sendBindSmsCodeApi(phone)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
|
||||
/** 发送绑定邮箱的邮件验证码(发到目标邮箱)。 */
|
||||
async function sendBindEmailCodeAction(email: string): Promise<void> {
|
||||
await sendBindEmailCodeApi(email)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
|
||||
/** 上传资质/反馈等附件,返回带 url 与 ossId 的 FileInfo。 */
|
||||
async function uploadAttachment(file: File): Promise<FileInfo> {
|
||||
return uploadProfileAttachment(file)
|
||||
}
|
||||
|
||||
async function bindPhoneAction(phone: string, code: string): Promise<void> {
|
||||
profile.value = await bindPhone(phone, code)
|
||||
ElMessage.success('手机号绑定成功')
|
||||
@@ -84,12 +113,10 @@ export const useProfileStore = defineStore('profile', () => {
|
||||
ElMessage.success('已取消邮箱绑定')
|
||||
}
|
||||
|
||||
async function verifyIdentityAction(phone: string, code: string): Promise<void> {
|
||||
await verifyIdentity(phone, code)
|
||||
}
|
||||
|
||||
async function deleteAccountAction(): Promise<void> {
|
||||
await deleteAccountApi()
|
||||
/** 验证 + 注销一步完成,phone 必须是账号绑定手机号。 */
|
||||
async function deleteAccountAction(phone: string, code: string): Promise<void> {
|
||||
await deleteAccountApi(phone, code)
|
||||
profile.value = null
|
||||
storage.remove('token')
|
||||
ElMessage.success('注销成功')
|
||||
}
|
||||
@@ -198,6 +225,14 @@ export const useProfileStore = defineStore('profile', () => {
|
||||
await fetchQualifications()
|
||||
}
|
||||
|
||||
/** 下载已保存的资质附件;index 从 0 开始。 */
|
||||
async function fetchQualificationAttachment(
|
||||
id: string,
|
||||
index = 0,
|
||||
): Promise<QualificationDownloadFile> {
|
||||
return downloadQualificationAttachmentApi(id, index)
|
||||
}
|
||||
|
||||
async function submitFeedbackAction(feedback: Feedback): Promise<void> {
|
||||
await submitFeedbackApi(feedback)
|
||||
}
|
||||
@@ -212,11 +247,14 @@ export const useProfileStore = defineStore('profile', () => {
|
||||
profile,
|
||||
fetchProfile,
|
||||
saveNickname,
|
||||
saveAvatar,
|
||||
changePassword: changePasswordAction,
|
||||
sendBindSmsCode: sendBindSmsCodeAction,
|
||||
sendBindEmailCode: sendBindEmailCodeAction,
|
||||
uploadAttachment,
|
||||
bindPhone: bindPhoneAction,
|
||||
bindEmail: bindEmailAction,
|
||||
unbindEmail: unbindEmailAction,
|
||||
verifyIdentity: verifyIdentityAction,
|
||||
deleteAccount: deleteAccountAction,
|
||||
addresses,
|
||||
addressTotal,
|
||||
@@ -244,6 +282,7 @@ export const useProfileStore = defineStore('profile', () => {
|
||||
updateQualification: updateQualificationAction,
|
||||
deleteQualification: deleteQualificationAction,
|
||||
changeQualificationPage,
|
||||
fetchQualificationAttachment,
|
||||
submitFeedback: submitFeedbackAction,
|
||||
helpFaqs,
|
||||
fetchHelpFaqs,
|
||||
|
||||
@@ -1,19 +1,101 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import type { ChatMessage } from '@/types/business/service'
|
||||
import type {
|
||||
ChatMessage,
|
||||
CsContentType,
|
||||
CsSessionVo,
|
||||
} from '@/types/business/service'
|
||||
import {
|
||||
getChatHistory,
|
||||
mockAutoReply,
|
||||
getChatMessages,
|
||||
initChatSession,
|
||||
sendChatMessage,
|
||||
uploadChatFile,
|
||||
} from '@/api/service'
|
||||
import { toChatMessage, toChatMessages } from '@/utils/serviceVo'
|
||||
|
||||
export const useServiceStore = defineStore('service', () => {
|
||||
const session = ref<CsSessionVo | null>(null)
|
||||
const messages = ref<ChatMessage[]>([])
|
||||
const sending = ref(false)
|
||||
|
||||
async function fetchHistory(): Promise<void> {
|
||||
messages.value = await getChatHistory()
|
||||
/** 会话初始化并发合并,避免页面挂载和首次发送各建一次会话。 */
|
||||
let sessionRequest: Promise<CsSessionVo | null> | null = null
|
||||
|
||||
async function ensureSession(): Promise<CsSessionVo | null> {
|
||||
if (session.value?.id !== undefined && session.value?.id !== null) {
|
||||
return session.value
|
||||
}
|
||||
if (!sessionRequest) {
|
||||
sessionRequest = initChatSession()
|
||||
.then((data) => {
|
||||
session.value = data
|
||||
return data
|
||||
})
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
sessionRequest = null
|
||||
})
|
||||
}
|
||||
return sessionRequest
|
||||
}
|
||||
|
||||
/** 轮询/手动刷新共用的在途标记,避免重叠请求把旧结果盖回新结果之上。 */
|
||||
let fetching = false
|
||||
|
||||
function messageSignature(list: ChatMessage[]): string {
|
||||
return list.map((item) => item.id).join('|')
|
||||
}
|
||||
|
||||
async function fetchHistory(silent = false): Promise<void> {
|
||||
if (fetching) return
|
||||
fetching = true
|
||||
try {
|
||||
const current = await ensureSession()
|
||||
if (current?.id === undefined || current?.id === null) {
|
||||
messages.value = []
|
||||
return
|
||||
}
|
||||
const next = toChatMessages(await getChatMessages(current.id, silent))
|
||||
// 内容没变就不替换数组,避免轮询反复触发列表重渲染
|
||||
if (messageSignature(next) !== messageSignature(messages.value)) {
|
||||
messages.value = next
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// 错误提示由 request 拦截器统一处理
|
||||
}
|
||||
finally {
|
||||
fetching = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息同步(HTTP 轮询) ------------------------------ */
|
||||
|
||||
/**
|
||||
* 后端未提供 websocket 端点,与客服工作台保持一致改用轮询:
|
||||
* 每 SYNC_INTERVAL 毫秒静默拉取一次当前会话消息,页面隐藏时暂停。
|
||||
*/
|
||||
const SYNC_INTERVAL = 5000
|
||||
let syncTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
function onVisibilityChange(): void {
|
||||
if (document.visibilityState === 'visible') void fetchHistory(true)
|
||||
}
|
||||
|
||||
function startSync(): void {
|
||||
stopSync()
|
||||
syncTimer = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void fetchHistory(true)
|
||||
}, SYNC_INTERVAL)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
|
||||
function stopSync(): void {
|
||||
if (syncTimer) {
|
||||
clearInterval(syncTimer)
|
||||
syncTimer = undefined
|
||||
}
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
|
||||
async function send(content: string): Promise<void> {
|
||||
@@ -21,37 +103,70 @@ export const useServiceStore = defineStore('service', () => {
|
||||
if (!trimmed || sending.value) return
|
||||
sending.value = true
|
||||
try {
|
||||
const userMsg = await sendChatMessage(trimmed)
|
||||
messages.value.push(userMsg)
|
||||
window.setTimeout(() => {
|
||||
void mockAutoReply().then((reply) => {
|
||||
messages.value.push(reply)
|
||||
sending.value = false
|
||||
const current = await ensureSession()
|
||||
if (current?.id === undefined || current?.id === null) return
|
||||
const vo = await sendChatMessage({
|
||||
sessionId: current.id,
|
||||
senderType: 'USER',
|
||||
contentType: 'TEXT',
|
||||
content: trimmed,
|
||||
})
|
||||
}, 600)
|
||||
messages.value.push(toChatMessage(vo))
|
||||
}
|
||||
catch {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendFile(file: File): Promise<void> {
|
||||
if (sending.value) return
|
||||
sending.value = true
|
||||
try {
|
||||
const fileMsg = await uploadChatFile(file)
|
||||
messages.value.push(fileMsg)
|
||||
// 错误提示由 request 拦截器统一处理
|
||||
}
|
||||
finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendFiles(files: File[]): Promise<void> {
|
||||
if (files.length === 0 || sending.value) return
|
||||
sending.value = true
|
||||
try {
|
||||
const current = await ensureSession()
|
||||
if (current?.id === undefined || current?.id === null) return
|
||||
// 拖拽可一次带入多个文件,按顺序逐个上传,避免并发互相顶掉
|
||||
for (const file of files) {
|
||||
const uploaded = await uploadChatFile(file)
|
||||
const contentType: CsContentType = file.type.startsWith('image/') ? 'IMAGE' : 'FILE'
|
||||
const vo = await sendChatMessage({
|
||||
sessionId: current.id,
|
||||
senderType: 'USER',
|
||||
contentType,
|
||||
fileUrl: uploaded.url,
|
||||
fileSize: file.size,
|
||||
})
|
||||
const message = toChatMessage(vo)
|
||||
// 上传接口能拿到原始文件名,优先用它展示
|
||||
if (message.file && uploaded.originalName) {
|
||||
message.file.name = uploaded.originalName
|
||||
}
|
||||
messages.value.push(message)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// 错误提示由 request 拦截器统一处理
|
||||
}
|
||||
finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendFile(file: File): Promise<void> {
|
||||
await sendFiles([file])
|
||||
}
|
||||
|
||||
return {
|
||||
session,
|
||||
messages,
|
||||
sending,
|
||||
fetchHistory,
|
||||
startSync,
|
||||
stopSync,
|
||||
send,
|
||||
sendFile,
|
||||
sendFiles,
|
||||
}
|
||||
})
|
||||
|
||||
6
src/types/business/cases.d.ts
vendored
6
src/types/business/cases.d.ts
vendored
@@ -88,6 +88,12 @@ export interface ProjectCaseCountVo {
|
||||
caseCount: number | null
|
||||
}
|
||||
|
||||
/** GET /web/projectCase/count 返回。 */
|
||||
export interface ProjectCaseCountResultVo {
|
||||
total: number | null
|
||||
projectCaseCounts: ProjectCaseCountVo[] | null
|
||||
}
|
||||
|
||||
export interface ProjectCaseAndCaseCountVo {
|
||||
projectCasePage: ProjectCasePageVo | null
|
||||
projectCaseStatisticsVo: ProjectCaseStatisticsVo | null
|
||||
|
||||
86
src/types/business/contract.d.ts
vendored
86
src/types/business/contract.d.ts
vendored
@@ -1,7 +1,88 @@
|
||||
|
||||
import type { FileInfo } from '@/types/api'
|
||||
|
||||
export type SignStatus = '履行中' | '已过期' | '待签署'
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 接口出参(字段与 /web/contract 接口文档一一对应)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** ContractVo:合同列表 / 详情 / 扫码落地页共用。 */
|
||||
export interface ContractVo {
|
||||
id: number | string
|
||||
contractNo: string | null
|
||||
projectId: number | string | null
|
||||
projectNo: string | null
|
||||
projectName: string | null
|
||||
/** 合同类型,取自关联项目的 business_type 字典值(中文)。 */
|
||||
bizType: string | null
|
||||
userId: number | string | null
|
||||
/** 合同名称(页面「合同名称」)。 */
|
||||
title: string | null
|
||||
amount: number | string | null
|
||||
/** 签署方信息(JSON 字符串)。 */
|
||||
signParties: string | null
|
||||
/** 签署状态:PENDING / SIGNING / SIGNED / VOID / EXPIRED。 */
|
||||
signStatus: string | null
|
||||
/** 履约状态:INACTIVE / IN_EFFECT / EXPIRED / TERMINATED。 */
|
||||
status: string | null
|
||||
signDate: string | null
|
||||
effectDate: string | null
|
||||
expireDate: string | null
|
||||
/** 合同 PDF 文件地址。 */
|
||||
file: string | null
|
||||
}
|
||||
|
||||
/** GET /web/contract/page 的 data。 */
|
||||
export interface ContractPageResult {
|
||||
total: number
|
||||
rows: ContractVo[]
|
||||
}
|
||||
|
||||
/** GET /web/contract/preview/{id} 的 data。 */
|
||||
export interface ContractPreviewVo {
|
||||
contractId: number | string | null
|
||||
contractNo: string | null
|
||||
title: string | null
|
||||
/** 合同 PDF 文件地址。 */
|
||||
file: string | null
|
||||
}
|
||||
|
||||
/** 各签署方记录。 */
|
||||
export interface ContractSignRecordVo {
|
||||
signId: number | string | null
|
||||
/** PARTY_A 甲方 / PARTY_B 乙方。 */
|
||||
signerType: string | null
|
||||
signerName: string | null
|
||||
/** SMS 短信验证码 / FACE 人脸识别。 */
|
||||
signType: string | null
|
||||
signTime: string | null
|
||||
/** PENDING 待验证 / SUCCESS 成功 / FAILED 失败。 */
|
||||
result: string | null
|
||||
/** 手写签名图片地址。 */
|
||||
signatureImg: string | null
|
||||
}
|
||||
|
||||
/** GET /web/contract/sign/progress/{id} 的 data。 */
|
||||
export interface ContractSignProgressVo {
|
||||
contractId: number | string | null
|
||||
contractNo: string | null
|
||||
signStatus: string | null
|
||||
parties: ContractSignRecordVo[]
|
||||
}
|
||||
|
||||
/** GET /web/contract/sign/qr-token/{token} 的 data。 */
|
||||
export interface ContractQrTokenVo {
|
||||
token: string
|
||||
contract: ContractVo
|
||||
progress: ContractSignProgressVo
|
||||
/** token 过期时间(与 Redis TTL 一致,默认 5 分钟)。 */
|
||||
expireTime: string
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 页面模型(展示字段保持不变,由 utils/contractVo 从 ContractVo 映射)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type SignStatus = '待签署' | '签署中' | '已签署' | '已作废' | '已过期'
|
||||
|
||||
export interface Contract {
|
||||
id: string
|
||||
@@ -9,6 +90,7 @@ export interface Contract {
|
||||
contractName: string
|
||||
contractType: string
|
||||
contractAmount: number
|
||||
relatedProjectId: string
|
||||
relatedProjectName: string
|
||||
projectNo: string
|
||||
signStatus: SignStatus
|
||||
@@ -20,6 +102,6 @@ export interface Contract {
|
||||
|
||||
export interface ContractQuery {
|
||||
keyword: string
|
||||
page: number
|
||||
pageNum: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
390
src/types/business/finance.d.ts
vendored
390
src/types/business/finance.d.ts
vendored
@@ -1,62 +1,22 @@
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 页面模型
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type BillStatus = '待支付' | '已支付' | '未到期' | '已取消'
|
||||
|
||||
export type BillStatusCode = 'UNSTARTED' | 'PENDING' | 'PAID' | 'CANCELLED'
|
||||
|
||||
export interface BillVo {
|
||||
id: number | string
|
||||
billNo?: string
|
||||
projectId?: number | string
|
||||
projectNo?: string
|
||||
projectName?: string
|
||||
userId?: number | string
|
||||
amount?: number
|
||||
bizType?: string
|
||||
billType?: string
|
||||
periodName?: string
|
||||
periodRatio?: number
|
||||
status?: BillStatusCode | string
|
||||
payChannel?: string
|
||||
transactionNo?: string
|
||||
tradeName?: string
|
||||
payTime?: string
|
||||
dueDate?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
export interface BillPlanVo {
|
||||
id: number | string
|
||||
projectId?: number | string
|
||||
projectNo?: string
|
||||
projectName?: string
|
||||
userId?: number | string
|
||||
bizType?: string
|
||||
totalAmount?: number | string
|
||||
periods?: number
|
||||
currentPeriod?: number
|
||||
periodRule?: string
|
||||
nextDate?: string
|
||||
status?: string
|
||||
orderNo?: string
|
||||
transactionNo?: string
|
||||
payChannel?: string
|
||||
payAmount?: number | string
|
||||
payStatus?: string
|
||||
payTime?: string
|
||||
}
|
||||
|
||||
export type InvoiceStatus = '已开票' | '开票中' | '未开票'
|
||||
|
||||
export type PayMethod = 'wechat' | 'alipay'
|
||||
|
||||
export interface PayOrderResponse {
|
||||
channel: string
|
||||
scene: string
|
||||
codeUrl?: string
|
||||
formBody?: string
|
||||
orderString?: string
|
||||
h5Url?: string
|
||||
}
|
||||
export type PayChannelCode = 'WECHAT' | 'ALIPAY' | 'BANK' | 'WORKWX'
|
||||
|
||||
export type FinanceDimension = 'YEAR' | 'MONTH' | 'QUARTER'
|
||||
|
||||
/** 财务中心首页图表视图:月度账单 / 上半年。 */
|
||||
export type FinancePeriod = 'month' | 'half'
|
||||
|
||||
export type PayStatus = 'CREATED' | 'SUCCESS' | 'FAILED' | 'REFUNDED'
|
||||
|
||||
export interface Bill {
|
||||
id: string
|
||||
@@ -78,11 +38,16 @@ export interface BillQuery {
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface BillStatistics {
|
||||
totalAmount: number
|
||||
totalCount: number
|
||||
pendingCount: number
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
billId: string
|
||||
method: PayMethod
|
||||
amount: number
|
||||
qrExpiresInSeconds: number
|
||||
}
|
||||
|
||||
export interface PaymentResult {
|
||||
@@ -93,20 +58,60 @@ export interface PaymentResult {
|
||||
bills: Bill[]
|
||||
}
|
||||
|
||||
export interface FinanceStats {
|
||||
totalExpense: number
|
||||
/** 周期标签,如 2026年 / 2026年03月(取接口 periodLabel)。 */
|
||||
month: string
|
||||
pendingCount: number
|
||||
distribution: Array<{ name: string; value: number; color: string }>
|
||||
dimension: FinanceDimension
|
||||
year: number
|
||||
/** 全年逐月金额(仅 dimension=YEAR 有值,固定 12 项,无数据补 0)。 */
|
||||
monthly: number[]
|
||||
}
|
||||
|
||||
export interface PayOrderResponse {
|
||||
channel: string
|
||||
/** 二维码内容字符串,直接用于前端生成二维码 */
|
||||
qrCode?: string
|
||||
}
|
||||
|
||||
/** 发票记录状态:0 未开票 / 1 开票中 / 2 已开票。 */
|
||||
export type InvoiceStatus = '0' | '1' | '2'
|
||||
|
||||
/** 字典数据项(/web/system/dict/data/type/{type})。 */
|
||||
export interface DictOptionVo {
|
||||
dictLabel: string
|
||||
dictValue: string
|
||||
dictSort?: number
|
||||
/** 标签样式:info / warning / success ... */
|
||||
listClass?: string
|
||||
}
|
||||
|
||||
export type InvoiceType = 'GENERAL' | 'SPECIAL'
|
||||
|
||||
export interface Invoice {
|
||||
id: string
|
||||
planName: string
|
||||
billNo: string
|
||||
tradeNo?: string
|
||||
invoiceNo?: string
|
||||
billId: string
|
||||
projectName: string
|
||||
titleName: string
|
||||
taxNo?: string
|
||||
invoiceType?: InvoiceType | string
|
||||
amount: number
|
||||
transactionNo?: string
|
||||
status: InvoiceStatus
|
||||
/** 状态文案,由后端翻译下发 */
|
||||
statusName?: string
|
||||
invoiceFile?: string
|
||||
issueTime?: string
|
||||
applyTime: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export interface InvoiceQuery {
|
||||
keyword: string
|
||||
status: InvoiceStatus | 'all'
|
||||
/** 空字符串表示全部 */
|
||||
status: InvoiceStatus | ''
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
@@ -125,9 +130,268 @@ export interface InvoiceTitlePayload {
|
||||
taxNo: string
|
||||
}
|
||||
|
||||
export interface FinanceStats {
|
||||
totalExpense: number
|
||||
month: string
|
||||
pendingCount: number
|
||||
distribution: Array<{ name: string; value: number; color: string }>
|
||||
/** 可开票账单(已支付且尚无有效发票记录)。 */
|
||||
export interface InvoiceAvailableBill {
|
||||
billId: string
|
||||
billNo: string
|
||||
periodName: string
|
||||
billType: string
|
||||
projectName: string
|
||||
amount: number
|
||||
payTime?: string
|
||||
transactionNo?: string
|
||||
}
|
||||
|
||||
export interface InvoiceApplyPayload {
|
||||
billId: string
|
||||
titleId: string
|
||||
invoiceType: InvoiceType
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 接口出参(字段与财务中心接口文档一一对应)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 分页出参:{ total, rows }。 */
|
||||
export interface FinancePageResult<T> {
|
||||
total: number
|
||||
rows: T[]
|
||||
}
|
||||
|
||||
/** FinanceBillVo:账单分页 / 详情共用。 */
|
||||
export interface FinanceBillVo {
|
||||
id: number | string
|
||||
billNo?: string
|
||||
projectId?: number | string
|
||||
projectNo?: string
|
||||
projectName?: string
|
||||
userId?: number | string
|
||||
bizType?: string
|
||||
billType?: string
|
||||
periodName?: string
|
||||
periodRatio?: number
|
||||
amount?: number
|
||||
status?: BillStatusCode | string
|
||||
dueDate?: string
|
||||
payChannel?: string
|
||||
transactionNo?: string
|
||||
tradeName?: string
|
||||
payTime?: string
|
||||
contractId?: number | string
|
||||
supplementaryRemark?: string
|
||||
createTime?: string
|
||||
updateTime?: string
|
||||
}
|
||||
|
||||
/** 兼容旧引用:账单 Vo 即 FinanceBillVo。 */
|
||||
export type BillVo = FinanceBillVo
|
||||
|
||||
/** 逐月数据:仅 dimension=YEAR 时返回,固定 12 条。 */
|
||||
export interface FinanceMonthlyPoint {
|
||||
month?: number
|
||||
amount?: number
|
||||
}
|
||||
|
||||
export interface BusinessTypeDistributionVo {
|
||||
bizType?: string
|
||||
bizTypeName?: string
|
||||
totalAmount?: number
|
||||
monthlyData?: FinanceMonthlyPoint[] | null
|
||||
}
|
||||
|
||||
/** GET /web/finance/summary 查询参数。 */
|
||||
export interface FinanceSummaryQuery {
|
||||
dimension?: FinanceDimension
|
||||
year?: number
|
||||
month?: number
|
||||
quarter?: number
|
||||
}
|
||||
|
||||
export interface FinanceSummaryVo {
|
||||
totalAmount?: number
|
||||
year?: number
|
||||
dimension?: FinanceDimension | string
|
||||
periodLabel?: string
|
||||
distributions?: BusinessTypeDistributionVo[]
|
||||
}
|
||||
|
||||
export interface FinanceBillStatisticsVo {
|
||||
totalAmount?: number
|
||||
totalCount?: number
|
||||
pendingCount?: number
|
||||
}
|
||||
|
||||
export interface PayChannelVo {
|
||||
code?: string
|
||||
name?: string
|
||||
enabled?: string
|
||||
}
|
||||
|
||||
export interface FinancePayResultVo {
|
||||
outTradeNo?: string
|
||||
mergedAmount?: number
|
||||
/** 二维码内容字符串(顶层字段,当前仅支付宝通道返回) */
|
||||
qrCode?: string
|
||||
}
|
||||
|
||||
export interface FinancePayQueryVo {
|
||||
status?: PayStatus | string
|
||||
transactionNo?: string
|
||||
payTime?: string
|
||||
}
|
||||
|
||||
/** 发票抬头出参(/web/finance/invoice/title/list)。 */
|
||||
export interface FinanceInvoiceTitleVo {
|
||||
userId?: number | string
|
||||
id: number | string
|
||||
titleType?: string
|
||||
titleName?: string
|
||||
taxNo?: string
|
||||
isDefault?: number
|
||||
type?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/** 发票抬头入参(新增/编辑)。 */
|
||||
export interface FinanceInvoiceTitleBo {
|
||||
id?: number | string
|
||||
titleType: 'ENTERPRISE' | 'PERSONAL'
|
||||
titleName: string
|
||||
taxNo?: string
|
||||
}
|
||||
|
||||
/** 可开票账单(/web/finance/invoice/available)。 */
|
||||
export interface FinanceInvoiceAvailableVo {
|
||||
billId?: number | string
|
||||
billNo?: string
|
||||
periodName?: string
|
||||
billType?: string
|
||||
projectName?: string
|
||||
amount?: number
|
||||
payTime?: string
|
||||
transactionNo?: string
|
||||
}
|
||||
|
||||
/** 开票申请入参(/web/finance/invoice/apply)。 */
|
||||
export interface FinanceInvoiceApplyBo {
|
||||
billId: number | string
|
||||
titleId: number | string
|
||||
invoiceType: 'GENERAL' | 'SPECIAL'
|
||||
}
|
||||
|
||||
/** 发票记录出参(分页 / 详情)。 */
|
||||
export interface FinanceInvoiceVo {
|
||||
id: number | string
|
||||
invoiceNo?: string
|
||||
billId?: number | string
|
||||
projectId?: number | string
|
||||
projectName?: string
|
||||
titleType?: string
|
||||
titleName?: string
|
||||
taxNo?: string
|
||||
invoiceType?: string
|
||||
amount?: number
|
||||
transactionNo?: string
|
||||
status?: string
|
||||
/** 状态文案,由后端翻译下发 */
|
||||
statusName?: string
|
||||
invoiceFile?: string
|
||||
issueTime?: string
|
||||
remark?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/** 预览电子发票出参(/web/finance/invoice/preview/{id})。 */
|
||||
export interface FinanceInvoicePreviewVo {
|
||||
invoiceId?: number | string
|
||||
invoiceNo?: string
|
||||
titleName?: string
|
||||
/** 电子发票文件地址(PDF 直链) */
|
||||
file?: string
|
||||
}
|
||||
|
||||
/** 发送电子发票到邮箱入参(/web/finance/invoice/send-email)。 */
|
||||
export interface FinanceInvoiceSendEmailBo {
|
||||
invoiceId: number | string
|
||||
/** 收件邮箱;不传则取用户绑定邮箱 */
|
||||
email?: string
|
||||
}
|
||||
|
||||
export interface FinanceInvoiceQuery {
|
||||
status?: InvoiceStatus
|
||||
page: number
|
||||
pageSize: number
|
||||
orderByColumn?: string
|
||||
isAsc?: string
|
||||
}
|
||||
|
||||
export interface FinancePayBo {
|
||||
id: number | string
|
||||
payChannel: PayChannelCode
|
||||
}
|
||||
|
||||
export interface FinanceBatchPayBo {
|
||||
ids: Array<number | string>
|
||||
payChannel: PayChannelCode
|
||||
}
|
||||
|
||||
export interface FinanceRefundBo {
|
||||
billId?: number | string
|
||||
amount?: number
|
||||
reason?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
export interface FinanceRefundVo {
|
||||
id?: number | string
|
||||
billId?: number | string
|
||||
paymentId?: number | string
|
||||
userId?: number | string
|
||||
refundNo?: string
|
||||
payChannel?: string
|
||||
amount?: number
|
||||
reason?: string
|
||||
status?: string
|
||||
auditRemark?: string
|
||||
transactionNo?: string
|
||||
refundTime?: string
|
||||
payload?: string
|
||||
createBy?: number | string
|
||||
createTime?: string
|
||||
updateBy?: number | string
|
||||
updateTime?: string
|
||||
delFlag?: string
|
||||
}
|
||||
|
||||
export interface FinanceRefundQuery {
|
||||
billId?: number | string
|
||||
amount?: number | string
|
||||
reason?: string
|
||||
status?: string
|
||||
page: number
|
||||
pageSize: number
|
||||
orderByColumn?: string
|
||||
isAsc?: string
|
||||
}
|
||||
|
||||
/** 项目财务里沿用的付款计划结构。 */
|
||||
export interface BillPlanVo {
|
||||
id: number | string
|
||||
projectId?: number | string
|
||||
projectNo?: string
|
||||
projectName?: string
|
||||
userId?: number | string
|
||||
bizType?: string
|
||||
totalAmount?: number | string
|
||||
periods?: number
|
||||
currentPeriod?: number
|
||||
periodRule?: string
|
||||
nextDate?: string
|
||||
status?: string
|
||||
orderNo?: string
|
||||
transactionNo?: string
|
||||
payChannel?: string
|
||||
payAmount?: number | string
|
||||
payStatus?: string
|
||||
payTime?: string
|
||||
}
|
||||
|
||||
46
src/types/business/message.d.ts
vendored
46
src/types/business/message.d.ts
vendored
@@ -3,6 +3,9 @@ import type { FileInfo } from '@/types/api'
|
||||
|
||||
export type MessageType = '在线客服' | '状态通知' | '系统通知'
|
||||
|
||||
/** 接口 type 入参:cs=在线客服 / status=状态通知 / system=系统通知 */
|
||||
export type MessageApiType = 'cs' | 'status' | 'system'
|
||||
|
||||
export interface Message {
|
||||
id: string
|
||||
type: MessageType
|
||||
@@ -20,3 +23,46 @@ export interface MessageQuery {
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** GET /web/message/center 单个入口:未读数 + 最新一条标题/时间 */
|
||||
export interface MessageEntryVo {
|
||||
unreadCount?: number | null
|
||||
latestTitle?: string | null
|
||||
latestTime?: string | null
|
||||
}
|
||||
|
||||
export interface MessageCenterVo {
|
||||
cs?: MessageEntryVo | null
|
||||
status?: MessageEntryVo | null
|
||||
system?: MessageEntryVo | null
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /web/message/list 列表行 / GET /web/message/detail 返回对象。
|
||||
* 后端返回 Object(SysMessageVo:messageId/title/message/content/createTime/path/data),
|
||||
* 已读标记、客服消息字段按可选兼容。
|
||||
*/
|
||||
export interface MessageVo {
|
||||
messageId?: number | string | null
|
||||
id?: number | string | null
|
||||
category?: string | null
|
||||
type?: string | null
|
||||
source?: string | null
|
||||
title?: string | null
|
||||
message?: string | null
|
||||
content?: string | null
|
||||
data?: unknown
|
||||
path?: string | null
|
||||
createTime?: string | null
|
||||
sendTime?: string | null
|
||||
senderName?: string | null
|
||||
readFlag?: number | boolean | null
|
||||
isRead?: boolean | null
|
||||
attachments?: FileInfo[] | null
|
||||
}
|
||||
|
||||
/** 分页出参:{ total, rows } */
|
||||
export interface MessagePageVo<T> {
|
||||
total?: number | null
|
||||
rows?: T[] | null
|
||||
}
|
||||
|
||||
83
src/types/business/profile.d.ts
vendored
83
src/types/business/profile.d.ts
vendored
@@ -3,14 +3,42 @@ import type { BusinessType, FileInfo } from '@/types/api'
|
||||
|
||||
export interface Profile {
|
||||
nickname: string
|
||||
/** 完整绑定手机号,用于发验证码/注销等操作 */
|
||||
phone: string
|
||||
/** 完整绑定邮箱 */
|
||||
email: string
|
||||
avatar: string
|
||||
/** 上次修改密码时间;老用户可能为空 */
|
||||
passwordModifiedAt: string
|
||||
/** 距上次修改密码天数;老用户可能为 null */
|
||||
passwordModifiedDays: number | null
|
||||
/** 如下字段来自 /app/account/security */
|
||||
passwordSet: boolean
|
||||
phoneBound: boolean
|
||||
emailBound: boolean
|
||||
/** 掩码手机号,仅用于展示 */
|
||||
maskedPhone: string
|
||||
/** 掩码邮箱,仅用于展示 */
|
||||
maskedEmail: string
|
||||
}
|
||||
|
||||
export interface ChangePasswordParams {
|
||||
code: string
|
||||
password: string
|
||||
/** 后端已改为固定使用账号绑定手机号,这里仅作兼容保留 */
|
||||
phoneNumber?: string
|
||||
}
|
||||
|
||||
/** /web/profile/upload 返回(SysOssVo)。 */
|
||||
export interface ProfileUploadVo {
|
||||
ossId: string | number
|
||||
fileName?: string
|
||||
originalName?: string
|
||||
fileSuffix?: string
|
||||
url: string
|
||||
createTime?: string
|
||||
createByName?: string
|
||||
service?: string
|
||||
}
|
||||
|
||||
export interface Address {
|
||||
@@ -71,3 +99,58 @@ export interface HelpFaqGroup {
|
||||
title: string
|
||||
items: HelpFaqItem[]
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 接口出参(字段与个人中心接口文档一一对应)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 地址出参(/web/profile/address/*)。 */
|
||||
export interface UserAddressVo {
|
||||
id?: number | string
|
||||
userId?: number | string
|
||||
receiver?: string
|
||||
phone?: string
|
||||
province?: string
|
||||
city?: string
|
||||
district?: string
|
||||
detail?: string
|
||||
/** 是否默认地址 1是 0否 */
|
||||
isDefault?: number
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/** 资质出参(/web/profile/qualification/*)。 */
|
||||
export interface UserQualificationVo {
|
||||
id?: number | string
|
||||
userId?: number | string
|
||||
qualType?: string
|
||||
companyName?: string
|
||||
qualName?: string
|
||||
qualNo?: string
|
||||
issueOrg?: string
|
||||
validStart?: string
|
||||
validEnd?: string
|
||||
/** 资质附件地址 */
|
||||
file?: string
|
||||
/** DRAFT / PENDING / CERTIFIED / REJECTED */
|
||||
status?: string
|
||||
/** 是否默认 1是 0否 */
|
||||
defaultFlag?: number
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/** 反馈出参(/web/profile/feedback/page)。 */
|
||||
export interface FeedbackVo {
|
||||
id?: number | string
|
||||
userId?: number | string
|
||||
title?: string
|
||||
content?: string
|
||||
attachments?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/** 分页出参:{ total, rows }。 */
|
||||
export interface ProfilePageVo<T> {
|
||||
total?: number
|
||||
rows?: T[]
|
||||
}
|
||||
|
||||
20
src/types/business/project.d.ts
vendored
20
src/types/business/project.d.ts
vendored
@@ -229,25 +229,6 @@ export interface RequirementBill {
|
||||
createTime?: string | null
|
||||
}
|
||||
|
||||
export interface RequirementBillPlan {
|
||||
id: string
|
||||
projectId: string | null
|
||||
projectNo: string | null
|
||||
projectName: string | null
|
||||
totalAmount: string | number | null
|
||||
periods: number | null
|
||||
currentPeriod: number | null
|
||||
periodRule: string | null
|
||||
nextDate: string | null
|
||||
status: string | null
|
||||
orderNo: string | null
|
||||
transactionNo: string | null
|
||||
payChannel: string | null
|
||||
payAmount: string | number | null
|
||||
payStatus: string | null
|
||||
payTime: string | null
|
||||
}
|
||||
|
||||
export interface RequirementInvoice {
|
||||
id: string
|
||||
billId: string | null
|
||||
@@ -314,7 +295,6 @@ export interface RequirementFilesVo extends RequirementBaseVo {
|
||||
|
||||
export interface RequirementFinanceVo extends RequirementBaseVo {
|
||||
bills?: RequirementBill[]
|
||||
billPlans: RequirementBillPlan[]
|
||||
invoices: RequirementInvoice[]
|
||||
contracts: RequirementContract[]
|
||||
}
|
||||
|
||||
96
src/types/business/service.d.ts
vendored
96
src/types/business/service.d.ts
vendored
@@ -1,13 +1,101 @@
|
||||
|
||||
export type ChatRole = 'user' | 'assistant'
|
||||
|
||||
export interface ChatFile {
|
||||
name: string
|
||||
size: number
|
||||
/** 可直接下载的文件地址(上传成功后由后端返回) */
|
||||
url?: string
|
||||
ossId?: string | number
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
role: ChatRole
|
||||
content: string
|
||||
file?: {
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
file?: ChatFile
|
||||
time: string
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// WEB 在线客服接口(/web/chat/*)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** CsSession:GET/POST /web/chat/session/init 返回的会话对象。 */
|
||||
export interface CsSessionVo {
|
||||
id?: number | string | null
|
||||
sessionNo?: string | null
|
||||
userId?: number | string | null
|
||||
userName?: string | null
|
||||
csUserId?: number | string | null
|
||||
csUserName?: string | null
|
||||
contact?: string | null
|
||||
/** WAIT_ACCESS / IN_PROGRESS / FINISHED */
|
||||
status?: string | null
|
||||
chatType?: string | null
|
||||
lastMessage?: string | null
|
||||
lastMsgTime?: string | null
|
||||
unreadUser?: number | null
|
||||
unreadCs?: number | null
|
||||
endTime?: string | null
|
||||
}
|
||||
|
||||
export type CsSenderType = 'USER' | 'CS' | 'SYSTEM'
|
||||
export type CsContentType = 'TEXT' | 'IMAGE' | 'FILE' | 'VOICE'
|
||||
|
||||
/** CsMessage:/web/chat/message、/web/chat/message/list 的消息对象。 */
|
||||
export interface CsMessageVo {
|
||||
id?: number | string | null
|
||||
sessionId?: number | string | null
|
||||
senderType?: string | null
|
||||
senderId?: number | string | null
|
||||
senderName?: string | null
|
||||
senderAvatar?: string | null
|
||||
contentType?: string | null
|
||||
content?: string | null
|
||||
fileUrl?: string | null
|
||||
fileSize?: number | null
|
||||
duration?: number | null
|
||||
/** 0-未读 1-已读 */
|
||||
readFlag?: number | null
|
||||
sendTime?: string | null
|
||||
createTime?: string | null
|
||||
}
|
||||
|
||||
/** GET /web/chat/message/centerList 分页出参:{ total, rows }。 */
|
||||
export interface CsMessagePageVo {
|
||||
total?: number | null
|
||||
rows?: CsMessageVo[] | null
|
||||
}
|
||||
|
||||
/** GET /web/chat/message/centerList 查询参数。 */
|
||||
export interface CsMessageCenterQuery {
|
||||
pageNum: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** POST /web/chat/message 请求体。 */
|
||||
export interface SendCsMessageParams {
|
||||
sessionId: number | string
|
||||
senderType: CsSenderType
|
||||
contentType: CsContentType
|
||||
content?: string
|
||||
fileUrl?: string
|
||||
fileSize?: number
|
||||
duration?: number
|
||||
}
|
||||
|
||||
/** GET /web/chat/session/preview:消息中心「在线客服」入口预览。 */
|
||||
export interface CsSessionPreviewVo {
|
||||
unreadCount?: number | null
|
||||
latestMessage?: string | null
|
||||
latestTime?: string | null
|
||||
}
|
||||
|
||||
/** 用户端 OSS 上传返回(SysOssVo)。 */
|
||||
export interface ChatUploadVo {
|
||||
ossId?: number | string | null
|
||||
fileName?: string | null
|
||||
originalName?: string | null
|
||||
url?: string | null
|
||||
}
|
||||
|
||||
25
src/types/business/user.d.ts
vendored
25
src/types/business/user.d.ts
vendored
@@ -17,6 +17,31 @@ export interface UserProfileVo {
|
||||
deptName: string
|
||||
}
|
||||
|
||||
/** 账号安全信息(GET /app/account/security,WEB 端复用)。 */
|
||||
export interface AccountSecurityVo {
|
||||
/** 是否已设置密码 */
|
||||
passwordSet?: boolean | null
|
||||
/** 上次修改密码时间;存量老用户可能为 null */
|
||||
passwordModifiedAt?: string | null
|
||||
/** 距上次修改密码天数;存量老用户可能为 null */
|
||||
passwordModifiedDays?: number | null
|
||||
/** 掩码手机号,如 138****8888(仅用于展示) */
|
||||
phoneNumber?: string | null
|
||||
phoneBound?: boolean | null
|
||||
/** 掩码邮箱,如 ab***@qq.com(仅用于展示) */
|
||||
email?: string | null
|
||||
emailBound?: boolean | null
|
||||
}
|
||||
|
||||
/** 个人资料更新入参(PUT /web/system/user/profile,只更新传了的字段)。 */
|
||||
export interface UserProfileUpdatePayload {
|
||||
nickName?: string
|
||||
email?: string
|
||||
phoneNumber?: string
|
||||
gender?: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
export interface LoginByAccountParams {
|
||||
account: string
|
||||
password: string
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { Bill, BillStatus, BillVo } from '@/types/business/finance'
|
||||
import type {
|
||||
Bill,
|
||||
BillStatistics,
|
||||
BillStatus,
|
||||
BillStatusCode,
|
||||
BillVo,
|
||||
BusinessTypeDistributionVo,
|
||||
FinanceBillStatisticsVo,
|
||||
FinanceDimension,
|
||||
FinanceStats,
|
||||
FinanceSummaryVo,
|
||||
} from '@/types/business/finance'
|
||||
|
||||
const STATUS_TEXT: Record<string, BillStatus> = {
|
||||
UNSTARTED: '未到期',
|
||||
@@ -7,11 +18,25 @@ const STATUS_TEXT: Record<string, BillStatus> = {
|
||||
CANCELLED: '已取消',
|
||||
}
|
||||
|
||||
const STATUS_CODE: Record<BillStatus, BillStatusCode> = {
|
||||
未到期: 'UNSTARTED',
|
||||
待支付: 'PENDING',
|
||||
已支付: 'PAID',
|
||||
已取消: 'CANCELLED',
|
||||
}
|
||||
|
||||
const DISTRIBUTION_COLORS = ['#3370ff', '#34c724', '#ff8f1f', '#f54a45', '#7b61ff', '#00b8d9']
|
||||
|
||||
export function toBillStatus(code?: string): BillStatus {
|
||||
if (!code) return '未到期'
|
||||
return STATUS_TEXT[code] ?? '未到期'
|
||||
}
|
||||
|
||||
/** 页面状态 → 接口 status 参数(UNSTARTED/PENDING/PAID/CANCELLED)。 */
|
||||
export function toBillStatusCode(status: BillStatus | 'all'): BillStatusCode | undefined {
|
||||
return status === 'all' ? undefined : STATUS_CODE[status]
|
||||
}
|
||||
|
||||
export function toBill(vo: BillVo): Bill {
|
||||
return {
|
||||
id: String(vo.id),
|
||||
@@ -32,6 +57,64 @@ export function toBills(list: BillVo[] | null | undefined): Bill[] {
|
||||
return list.filter((item) => item != null && item.id != null).map(toBill)
|
||||
}
|
||||
|
||||
export function toBillStatistics(vo: FinanceBillStatisticsVo | null | undefined): BillStatistics {
|
||||
return {
|
||||
totalAmount: Number(vo?.totalAmount ?? 0),
|
||||
totalCount: Number(vo?.totalCount ?? 0),
|
||||
pendingCount: Number(vo?.pendingCount ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
function toDistribution(
|
||||
item: BusinessTypeDistributionVo,
|
||||
index: number,
|
||||
): FinanceStats['distribution'][number] {
|
||||
return {
|
||||
name: item.bizTypeName ?? item.bizType ?? '',
|
||||
value: Number(item.totalAmount ?? 0),
|
||||
color: DISTRIBUTION_COLORS[index % DISTRIBUTION_COLORS.length],
|
||||
}
|
||||
}
|
||||
|
||||
function toFinanceDimension(value?: string): FinanceDimension {
|
||||
if (value === 'MONTH' || value === 'QUARTER') return value
|
||||
return 'YEAR'
|
||||
}
|
||||
|
||||
/** 把各业务类型的逐月金额按月份汇总为 12 项(仅 YEAR 维度有数据)。 */
|
||||
function toMonthlyAmounts(distributions: BusinessTypeDistributionVo[]): number[] {
|
||||
const monthly = Array.from({ length: 12 }, () => 0)
|
||||
for (const item of distributions) {
|
||||
for (const point of item.monthlyData ?? []) {
|
||||
const month = Number(point.month ?? 0)
|
||||
if (month >= 1 && month <= 12) {
|
||||
monthly[month - 1] += Number(point.amount ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return monthly
|
||||
}
|
||||
|
||||
/**
|
||||
* 财务概览:累计消费总额 / 周期标签取自 summary,待支付笔数取自账单统计。
|
||||
* 业务类型分布按接口顺序分配图例颜色(接口不返回颜色)。
|
||||
*/
|
||||
export function toFinanceStats(
|
||||
summary: FinanceSummaryVo | null | undefined,
|
||||
statistics?: FinanceBillStatisticsVo | null,
|
||||
): FinanceStats {
|
||||
const distributions = summary?.distributions ?? []
|
||||
return {
|
||||
totalExpense: Number(summary?.totalAmount ?? 0),
|
||||
month: summary?.periodLabel ?? '',
|
||||
pendingCount: Number(statistics?.pendingCount ?? 0),
|
||||
distribution: distributions.map(toDistribution),
|
||||
dimension: toFinanceDimension(summary?.dimension),
|
||||
year: Number(summary?.year ?? new Date().getFullYear()),
|
||||
monthly: toMonthlyAmounts(distributions),
|
||||
}
|
||||
}
|
||||
|
||||
export function toPlanStatus(code?: string | null): BillStatus {
|
||||
const value = (code ?? '').toUpperCase()
|
||||
if (value === 'DONE' || value === 'PAID' || value === 'COMPLETED') return '已支付'
|
||||
|
||||
44
src/utils/contractVo.ts
Normal file
44
src/utils/contractVo.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import type { Contract, ContractVo, SignStatus } from '@/types/business/contract'
|
||||
|
||||
const SIGN_STATUS_LABEL: Record<string, SignStatus> = {
|
||||
PENDING: '待签署',
|
||||
SIGNING: '签署中',
|
||||
SIGNED: '已签署',
|
||||
VOID: '已作废',
|
||||
EXPIRED: '已过期',
|
||||
}
|
||||
|
||||
function toSignStatus(raw: string | null | undefined): SignStatus {
|
||||
return SIGN_STATUS_LABEL[(raw ?? '').trim().toUpperCase()] ?? '待签署'
|
||||
}
|
||||
|
||||
/** 接口只返回单个 PDF 地址,页面文件列表按单条渲染。 */
|
||||
function toFiles(vo: ContractVo, name: string): FileInfo[] {
|
||||
if (!vo.file) return []
|
||||
return [{
|
||||
name,
|
||||
size: 0,
|
||||
uploadTime: vo.signDate ?? '',
|
||||
url: vo.file,
|
||||
}]
|
||||
}
|
||||
|
||||
export function toContract(vo: ContractVo): Contract {
|
||||
const contractName = vo.title || vo.contractNo || ''
|
||||
return {
|
||||
id: String(vo.id),
|
||||
contractNo: vo.contractNo ?? '',
|
||||
contractName,
|
||||
contractType: vo.bizType ?? '',
|
||||
contractAmount: Number(vo.amount ?? 0),
|
||||
relatedProjectId: vo.projectId ? String(vo.projectId) : '',
|
||||
relatedProjectName: vo.projectName ?? '',
|
||||
projectNo: vo.projectNo ?? '',
|
||||
signStatus: toSignStatus(vo.signStatus),
|
||||
signDate: vo.signDate ?? undefined,
|
||||
effectiveDate: vo.effectDate ?? '',
|
||||
expiryDate: vo.expireDate ?? '',
|
||||
files: toFiles(vo, contractName || '合同文件'),
|
||||
}
|
||||
}
|
||||
46
src/utils/download.ts
Normal file
46
src/utils/download.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 文件流下载相关工具。
|
||||
* 后端接口出错时会返回 JSON,但 axios 因 responseType=blob 把它包成了 Blob,
|
||||
* 需要先读出 msg 再抛出,避免把错误串当成文件保存下来。
|
||||
*/
|
||||
|
||||
export async function readBlobErrorMessage(blob: Blob, fallback = '下载失败'): Promise<string> {
|
||||
try {
|
||||
const payload = JSON.parse(await blob.text()) as { msg?: string }
|
||||
return payload.msg || fallback
|
||||
}
|
||||
catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 Content-Disposition 中的文件名(优先 RFC 5987 的 filename*)。 */
|
||||
export function resolveContentDispositionFileName(value: unknown): string | undefined {
|
||||
const raw = Array.isArray(value) ? value[0] : value
|
||||
if (typeof raw !== 'string' || !raw) return undefined
|
||||
|
||||
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(raw)
|
||||
if (encoded?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(encoded[1].trim())
|
||||
}
|
||||
catch {
|
||||
return encoded[1].trim()
|
||||
}
|
||||
}
|
||||
|
||||
const plain = /filename="?([^";]+)"?/i.exec(raw)
|
||||
return plain?.[1]?.trim()
|
||||
}
|
||||
|
||||
/** 触发浏览器另存文件。 */
|
||||
export function saveBlobAsFile(blob: Blob, fileName: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
109
src/utils/invoiceVo.ts
Normal file
109
src/utils/invoiceVo.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import type {
|
||||
FinanceInvoiceAvailableVo,
|
||||
FinanceInvoiceTitleBo,
|
||||
FinanceInvoiceTitleVo,
|
||||
FinanceInvoiceVo,
|
||||
Invoice,
|
||||
InvoiceAvailableBill,
|
||||
InvoiceStatus,
|
||||
InvoiceTitle,
|
||||
InvoiceTitlePayload,
|
||||
} from '@/types/business/finance'
|
||||
|
||||
export const INVOICE_TYPE_LABELS: Record<string, string> = {
|
||||
GENERAL: '普通发票',
|
||||
SPECIAL: '专用发票',
|
||||
}
|
||||
|
||||
const TITLE_TYPE_LABELS: Record<string, InvoiceTitle['type']> = {
|
||||
ENTERPRISE: '企业单位',
|
||||
PERSONAL: '非企业单位',
|
||||
}
|
||||
|
||||
/** 兼容旧版 PENDING/ISSUED/REJECTED,统一归一化为数字状态码。 */
|
||||
export function toInvoiceStatus(code?: string): InvoiceStatus {
|
||||
if (code === '0' || code === '1' || code === '2') return code
|
||||
if (code === 'ISSUED') return '2'
|
||||
if (code === 'PENDING') return '1'
|
||||
// 驳回已取消,直接回到未开票,用户可重新申请
|
||||
if (code === 'REJECTED') return '0'
|
||||
return '0'
|
||||
}
|
||||
|
||||
/** 页面筛选状态 → 接口 status 参数(空值表示全部,不传)。 */
|
||||
export function toInvoiceStatusParam(status: InvoiceStatus | ''): InvoiceStatus | undefined {
|
||||
return status === '' ? undefined : status
|
||||
}
|
||||
|
||||
export function toInvoice(vo: FinanceInvoiceVo): Invoice {
|
||||
return {
|
||||
id: String(vo.id),
|
||||
invoiceNo: vo.invoiceNo,
|
||||
billId: String(vo.billId ?? ''),
|
||||
projectName: vo.projectName ?? '',
|
||||
titleName: vo.titleName ?? '',
|
||||
taxNo: vo.taxNo,
|
||||
invoiceType: vo.invoiceType,
|
||||
amount: Number(vo.amount ?? 0),
|
||||
transactionNo: vo.transactionNo,
|
||||
status: toInvoiceStatus(vo.status),
|
||||
statusName: vo.statusName ?? '',
|
||||
invoiceFile: vo.invoiceFile,
|
||||
issueTime: vo.issueTime,
|
||||
applyTime: vo.createTime ?? '',
|
||||
remark: vo.remark,
|
||||
}
|
||||
}
|
||||
|
||||
export function toInvoices(list: FinanceInvoiceVo[] | null | undefined): Invoice[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list.filter((item) => item != null && item.id != null).map(toInvoice)
|
||||
}
|
||||
|
||||
export function toInvoiceTitle(vo: FinanceInvoiceTitleVo): InvoiceTitle {
|
||||
const type = TITLE_TYPE_LABELS[vo.titleType ?? '']
|
||||
?? (vo.type === '非企业单位' || vo.type === 'PERSONAL' ? '非企业单位' : '企业单位')
|
||||
return {
|
||||
id: String(vo.id),
|
||||
type,
|
||||
title: vo.titleName ?? '',
|
||||
taxNo: vo.taxNo ?? '',
|
||||
isDefault: Number(vo.isDefault ?? 0) === 1,
|
||||
}
|
||||
}
|
||||
|
||||
export function toInvoiceTitles(list: FinanceInvoiceTitleVo[] | null | undefined): InvoiceTitle[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list.filter((item) => item != null && item.id != null).map(toInvoiceTitle)
|
||||
}
|
||||
|
||||
export function toInvoiceTitleBo(payload: InvoiceTitlePayload, id?: string): FinanceInvoiceTitleBo {
|
||||
return {
|
||||
id,
|
||||
titleType: payload.type === '非企业单位' ? 'PERSONAL' : 'ENTERPRISE',
|
||||
titleName: payload.title,
|
||||
taxNo: payload.taxNo,
|
||||
}
|
||||
}
|
||||
|
||||
export function toInvoiceAvailableBill(vo: FinanceInvoiceAvailableVo): InvoiceAvailableBill {
|
||||
return {
|
||||
billId: String(vo.billId ?? ''),
|
||||
billNo: vo.billNo ?? '',
|
||||
periodName: vo.periodName ?? '',
|
||||
billType: vo.billType ?? '',
|
||||
projectName: vo.projectName ?? '',
|
||||
amount: Number(vo.amount ?? 0),
|
||||
payTime: vo.payTime,
|
||||
transactionNo: vo.transactionNo,
|
||||
}
|
||||
}
|
||||
|
||||
export function toInvoiceAvailableBills(
|
||||
list: FinanceInvoiceAvailableVo[] | null | undefined,
|
||||
): InvoiceAvailableBill[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list
|
||||
.filter((item) => item != null && item.billId != null)
|
||||
.map(toInvoiceAvailableBill)
|
||||
}
|
||||
116
src/utils/messageVo.ts
Normal file
116
src/utils/messageVo.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import type { Message, MessageApiType, MessageType, MessageVo } from '@/types/business/message'
|
||||
import type { CsMessageVo } from '@/types/business/service'
|
||||
import { formatDate } from '@/utils/format'
|
||||
|
||||
const TYPE_LABEL: Record<MessageApiType, MessageType> = {
|
||||
cs: '在线客服',
|
||||
status: '状态通知',
|
||||
system: '系统通知',
|
||||
}
|
||||
|
||||
const TYPE_CODE: Record<MessageType, MessageApiType> = {
|
||||
在线客服: 'cs',
|
||||
状态通知: 'status',
|
||||
系统通知: 'system',
|
||||
}
|
||||
|
||||
/** 消息中心入口只提供状态通知 + 系统通知(cs 由客服模块提供,本接口返回 null)。 */
|
||||
export const WEB_MESSAGE_TYPES: MessageApiType[] = ['status', 'system']
|
||||
|
||||
/** 接口 type 值 → 页面类型(兼容中文标签)。 */
|
||||
export function toMessageType(raw: string | null | undefined, fallback: MessageType): MessageType {
|
||||
const value = (raw ?? '').trim()
|
||||
if (value === '在线客服' || value === '状态通知' || value === '系统通知') return value
|
||||
const lower = value.toLowerCase()
|
||||
if (lower === 'cs') return '在线客服'
|
||||
if (lower === 'status') return '状态通知'
|
||||
if (lower === 'system') return '系统通知'
|
||||
return fallback
|
||||
}
|
||||
|
||||
/** 页面类型 → 接口 type 值。 */
|
||||
export function toMessageApiType(type: MessageType): MessageApiType {
|
||||
return TYPE_CODE[type]
|
||||
}
|
||||
|
||||
/** 页面 tab(含「全部」)→ readAll 需要逐个传入的接口 type 列表。 */
|
||||
export function toMessageApiTypes(type: MessageType | 'all'): MessageApiType[] {
|
||||
return type === 'all' ? [...WEB_MESSAGE_TYPES] : [TYPE_CODE[type]]
|
||||
}
|
||||
|
||||
/** 接口 createTime/sendTime → 页面展示时间。 */
|
||||
function toMessageTime(raw: string | null | undefined): string {
|
||||
const value = (raw ?? '').trim()
|
||||
if (!value) return ''
|
||||
return formatDate(value) || value
|
||||
}
|
||||
|
||||
/**
|
||||
* 已读标记:后端未在文档中固定该字段,兼容 readFlag/isRead;
|
||||
* 都未返回时按已读处理,避免整列表误导为未读。
|
||||
*/
|
||||
function toMessageRead(vo: MessageVo): boolean {
|
||||
if (typeof vo.isRead === 'boolean') return vo.isRead
|
||||
if (typeof vo.readFlag === 'boolean') return vo.readFlag
|
||||
if (typeof vo.readFlag === 'number') return vo.readFlag === 1
|
||||
return true
|
||||
}
|
||||
|
||||
export function toMessage(vo: MessageVo, fallbackType: MessageApiType): Message {
|
||||
const id = vo.messageId ?? vo.id
|
||||
const content = vo.content ?? vo.message ?? ''
|
||||
return {
|
||||
id: String(id ?? ''),
|
||||
type: toMessageType(vo.type, TYPE_LABEL[fallbackType]),
|
||||
title: vo.title ?? vo.senderName ?? '',
|
||||
summary: vo.message ?? content,
|
||||
content,
|
||||
publishTime: toMessageTime(vo.createTime ?? vo.sendTime),
|
||||
isRead: toMessageRead(vo),
|
||||
attachments: vo.attachments ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
export function toMessages(
|
||||
list: MessageVo[] | null | undefined,
|
||||
fallbackType: MessageApiType,
|
||||
): Message[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list.filter((item) => item != null).map((item) => toMessage(item, fallbackType))
|
||||
}
|
||||
|
||||
/** 非文本消息在列表里的摘要占位。 */
|
||||
const CS_CONTENT_LABEL: Record<string, string> = {
|
||||
IMAGE: '[图片]',
|
||||
FILE: '[文件]',
|
||||
VOICE: '[语音]',
|
||||
}
|
||||
|
||||
/**
|
||||
* 在线客服消息(GET /web/chat/message/centerList)→ 消息中心列表行。
|
||||
* 客服消息没有标题,按发送方取展示名;非文本消息用类型占位符做摘要。
|
||||
*/
|
||||
export function toCenterMessage(vo: CsMessageVo): Message {
|
||||
const senderType = (vo.senderType ?? '').trim().toUpperCase()
|
||||
const contentType = (vo.contentType ?? '').trim().toUpperCase()
|
||||
const content = (vo.content ?? '').trim()
|
||||
const fallbackTitle
|
||||
= senderType === 'USER' ? '我' : senderType === 'CS' ? '在线客服' : '系统消息'
|
||||
|
||||
return {
|
||||
id: String(vo.id ?? ''),
|
||||
type: '在线客服',
|
||||
title: (vo.senderName ?? '').trim() || fallbackTitle,
|
||||
summary: CS_CONTENT_LABEL[contentType] ?? content,
|
||||
content,
|
||||
publishTime: toMessageTime(vo.sendTime ?? vo.createTime),
|
||||
// readFlag 缺省时按已读处理,避免整列表误标未读
|
||||
isRead: Number(vo.readFlag ?? 1) !== 0,
|
||||
attachments: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function toCenterMessages(list: CsMessageVo[] | null | undefined): Message[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list.filter((item) => item != null).map(toCenterMessage)
|
||||
}
|
||||
@@ -7,13 +7,13 @@ export interface PayMethodMeta {
|
||||
channel: 'WECHAT' | 'ALIPAY'
|
||||
}
|
||||
|
||||
/** 当前仅接入支付宝通道,微信待后续接入。 */
|
||||
export const PAY_METHODS: PayMethodMeta[] = [
|
||||
{ value: 'wechat', label: '微信支付', hint: '推荐使用', channel: 'WECHAT' },
|
||||
{ value: 'alipay', label: '支付宝支付', hint: '其他用户选择', channel: 'ALIPAY' },
|
||||
{ value: 'alipay', label: '支付宝支付', hint: '推荐使用', channel: 'ALIPAY' },
|
||||
]
|
||||
|
||||
export function toPayChannel(method: PayMethod): PayMethodMeta['channel'] {
|
||||
return PAY_METHODS.find((item) => item.value === method)?.channel ?? 'WECHAT'
|
||||
return PAY_METHODS.find((item) => item.value === method)?.channel ?? 'ALIPAY'
|
||||
}
|
||||
|
||||
const CHANNEL_LABELS: Record<string, string> = {
|
||||
@@ -29,7 +29,7 @@ export function toChannelLabel(code?: string): string {
|
||||
}
|
||||
|
||||
export function toPayMethod(code?: string): PayMethod {
|
||||
return code?.toUpperCase() === 'ALIPAY' ? 'alipay' : 'wechat'
|
||||
return code?.toUpperCase() === 'WECHAT' ? 'wechat' : 'alipay'
|
||||
}
|
||||
|
||||
function pad(value: number, length = 2): string {
|
||||
|
||||
238
src/utils/profileVo.ts
Normal file
238
src/utils/profileVo.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import type {
|
||||
Address,
|
||||
Feedback,
|
||||
Profile,
|
||||
Qualification,
|
||||
QualificationInput,
|
||||
QualificationStatus,
|
||||
QualificationType,
|
||||
UserAddressVo,
|
||||
UserQualificationVo,
|
||||
} from '@/types/business/profile'
|
||||
import type { AccountSecurityVo, UserProfileVo } from '@/types/business/user'
|
||||
import { toAssetUrl } from '@/utils/asset'
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 个人资料
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** /web/system/user/profile + /app/account/security → 页面 Profile。 */
|
||||
export function toProfile(
|
||||
user: UserProfileVo,
|
||||
security?: AccountSecurityVo | null,
|
||||
): Profile {
|
||||
const avatar = (user.avatarUrl ?? '').trim()
|
||||
// 注意:安全接口返回的 phoneNumber/email 是掩码,只能展示,
|
||||
// 不允许回填到 profile.phone/email(发验证码、注销会用到完整值)。
|
||||
return {
|
||||
nickname: (user.nickName || user.userName || '').trim(),
|
||||
phone: user.phoneNumber ?? '',
|
||||
email: user.email ?? '',
|
||||
avatar: toAssetUrl(avatar) || avatar,
|
||||
// 存量老用户没有改密记录,接口返回 null,页面展示占位
|
||||
passwordModifiedAt: security?.passwordModifiedAt ?? '',
|
||||
passwordModifiedDays: security?.passwordModifiedDays ?? null,
|
||||
passwordSet: security?.passwordSet ?? Boolean(user.phoneNumber),
|
||||
phoneBound: security?.phoneBound ?? Boolean(user.phoneNumber),
|
||||
emailBound: security?.emailBound ?? Boolean(user.email),
|
||||
maskedPhone: security?.phoneNumber ?? '',
|
||||
maskedEmail: security?.email ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 地址
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const MUNICIPALITIES = ['北京市', '上海市', '天津市', '重庆市']
|
||||
const PROVINCE_SUFFIXES = ['省', '自治区', '特别行政区']
|
||||
const CITY_SUFFIXES = ['市', '自治州', '地区', '盟']
|
||||
|
||||
/** 返回 text 中最早出现的后缀结束位置,找不到返回 -1。 */
|
||||
function suffixEnd(text: string, suffixes: string[]): number {
|
||||
let end = -1
|
||||
for (const suffix of suffixes) {
|
||||
const index = text.indexOf(suffix)
|
||||
if (index < 0) continue
|
||||
const candidate = index + suffix.length
|
||||
if (end < 0 || candidate < end) end = candidate
|
||||
}
|
||||
return end
|
||||
}
|
||||
|
||||
/** 页面填写的「省/市/区」整串 → 接口拆分字段。 */
|
||||
export function splitRegion(region: string): { province: string; city: string; district: string } {
|
||||
const text = region.trim()
|
||||
if (!text) return { province: '', city: '', district: '' }
|
||||
|
||||
const municipality = MUNICIPALITIES.find((name) => text.startsWith(name))
|
||||
if (municipality) {
|
||||
return { province: municipality, city: municipality, district: text.slice(municipality.length) }
|
||||
}
|
||||
|
||||
const provinceEnd = suffixEnd(text, PROVINCE_SUFFIXES)
|
||||
const province = provinceEnd > 0 ? text.slice(0, provinceEnd) : ''
|
||||
const rest = province ? text.slice(provinceEnd) : text
|
||||
|
||||
const cityEnd = suffixEnd(rest, CITY_SUFFIXES)
|
||||
const city = cityEnd > 0 ? rest.slice(0, cityEnd) : ''
|
||||
const district = city ? rest.slice(cityEnd) : rest
|
||||
|
||||
return { province, city, district }
|
||||
}
|
||||
|
||||
/** 接口省/市/区 → 页面展示的地区整串(直辖市去重)。 */
|
||||
function joinRegion(vo: UserAddressVo): string {
|
||||
const parts = [vo.province, vo.city, vo.district]
|
||||
.map((item) => (item ?? '').trim())
|
||||
.filter(Boolean)
|
||||
return parts.filter((item, index) => parts.indexOf(item) === index).join('')
|
||||
}
|
||||
|
||||
export function toAddress(vo: UserAddressVo): Address {
|
||||
return {
|
||||
id: String(vo.id ?? ''),
|
||||
receiverName: vo.receiver ?? '',
|
||||
phone: vo.phone ?? '',
|
||||
region: joinRegion(vo),
|
||||
detailAddress: vo.detail ?? '',
|
||||
isDefault: Number(vo.isDefault ?? 0) === 1,
|
||||
}
|
||||
}
|
||||
|
||||
export function toAddresses(list: UserAddressVo[] | null | undefined): Address[] {
|
||||
return (list ?? [])
|
||||
.filter((item) => item != null && item.id != null)
|
||||
.map(toAddress)
|
||||
}
|
||||
|
||||
/** 页面地址表单 → 接口入参(地区拆成省/市/区)。 */
|
||||
export function toAddressBo(input: Omit<Address, 'id' | 'isDefault'>): {
|
||||
receiver: string
|
||||
phone: string
|
||||
province: string
|
||||
city: string
|
||||
district: string
|
||||
detail: string
|
||||
} {
|
||||
const { province, city, district } = splitRegion(input.region)
|
||||
return {
|
||||
receiver: input.receiverName,
|
||||
phone: input.phone,
|
||||
province,
|
||||
city,
|
||||
district,
|
||||
detail: input.detailAddress,
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 资质
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const QUALIFICATION_TYPES: QualificationType[] = [
|
||||
'营业执照',
|
||||
'生产许可证',
|
||||
'体系认证',
|
||||
'检测报告',
|
||||
'授权书',
|
||||
'其他资质',
|
||||
]
|
||||
|
||||
const QUALIFICATION_STATUS: Record<string, QualificationStatus> = {
|
||||
CERTIFIED: '已认证',
|
||||
PENDING: '审核中',
|
||||
DRAFT: '审核中',
|
||||
REJECTED: '未通过',
|
||||
}
|
||||
|
||||
export function toQualificationStatus(code?: string): QualificationStatus {
|
||||
return QUALIFICATION_STATUS[(code ?? '').trim().toUpperCase()] ?? '审核中'
|
||||
}
|
||||
|
||||
function toQualificationType(raw?: string): QualificationType {
|
||||
const value = (raw ?? '').trim()
|
||||
return QUALIFICATION_TYPES.find((item) => item === value) ?? '其他资质'
|
||||
}
|
||||
|
||||
function fileNameFromUrl(url: string): string {
|
||||
const path = url.split('?')[0]?.split('#')[0] ?? ''
|
||||
const segment = path.slice(path.lastIndexOf('/') + 1)
|
||||
if (!segment) return '资质附件'
|
||||
try {
|
||||
return decodeURIComponent(segment)
|
||||
}
|
||||
catch {
|
||||
return segment
|
||||
}
|
||||
}
|
||||
|
||||
function toQualificationFiles(file?: string): FileInfo[] {
|
||||
const url = (file ?? '').trim()
|
||||
if (!url) return []
|
||||
return [{ name: fileNameFromUrl(url), size: 0, uploadTime: '', url }]
|
||||
}
|
||||
|
||||
export function toQualification(vo: UserQualificationVo): Qualification {
|
||||
return {
|
||||
id: String(vo.id ?? ''),
|
||||
type: toQualificationType(vo.qualType),
|
||||
certName: vo.qualName ?? '',
|
||||
certNo: vo.qualNo ?? '',
|
||||
issuer: vo.issueOrg ?? '',
|
||||
validFrom: vo.validStart ?? '',
|
||||
validTo: vo.validEnd ?? '',
|
||||
status: toQualificationStatus(vo.status),
|
||||
attachments: toQualificationFiles(vo.file),
|
||||
}
|
||||
}
|
||||
|
||||
export function toQualifications(list: UserQualificationVo[] | null | undefined): Qualification[] {
|
||||
return (list ?? [])
|
||||
.filter((item) => item != null && item.id != null)
|
||||
.map(toQualification)
|
||||
}
|
||||
|
||||
/** 页面资质表单 → 接口入参(单附件传 file,多附件同时传 files 数组)。 */
|
||||
export function toQualificationBo(input: QualificationInput): {
|
||||
qualType: string
|
||||
qualName: string
|
||||
qualNo: string
|
||||
issueOrg: string
|
||||
validStart: string
|
||||
validEnd: string
|
||||
file: string
|
||||
files?: string[]
|
||||
} {
|
||||
const urls = input.attachments.map((item) => item.url).filter(Boolean)
|
||||
return {
|
||||
qualType: input.type,
|
||||
qualName: input.certName,
|
||||
qualNo: input.certNo,
|
||||
issueOrg: input.issuer,
|
||||
validStart: input.validFrom,
|
||||
validEnd: input.validTo,
|
||||
file: urls[0] ?? '',
|
||||
...(urls.length > 1 ? { files: urls } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 反馈
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 页面反馈表单 → 接口入参(attachments 为附件地址列表字符串)。 */
|
||||
export function toFeedbackBo(feedback: Feedback): {
|
||||
title: string
|
||||
content: string
|
||||
attachments: string
|
||||
} {
|
||||
const urls = feedback.attachments.map((file) => file.url).filter(Boolean)
|
||||
return {
|
||||
title: feedback.title,
|
||||
content: feedback.description,
|
||||
// 后端要求字符串,按 JSON 数组存附件地址
|
||||
attachments: urls.length > 0 ? JSON.stringify(urls) : '',
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import type {
|
||||
RequirementAfterSale,
|
||||
RequirementAttachment,
|
||||
RequirementBill,
|
||||
RequirementBillPlan,
|
||||
RequirementContract,
|
||||
RequirementDetailBundle,
|
||||
RequirementInvoice,
|
||||
@@ -103,34 +102,6 @@ function toProjectBill(item: RequirementBill): ProjectBill {
|
||||
}
|
||||
}
|
||||
|
||||
function planPeriodLabel(period: number, periods: number): string {
|
||||
if (period <= 1) return '预付款'
|
||||
if (period >= periods) return '尾款'
|
||||
return '进度款'
|
||||
}
|
||||
|
||||
function toPlanCard(item: RequirementBillPlan): ProjectBill {
|
||||
const period = item.currentPeriod ?? 0
|
||||
const periods = item.periods ?? 0
|
||||
const rule = (item.periodRule ?? '').split(',').map((part) => Number(part.trim()))
|
||||
const segment = rule[period - 1]
|
||||
const ratio = Number.isFinite(segment) ? segment : periods > 0 ? 100 / periods : 0
|
||||
const paid = (item.payStatus ?? '').toUpperCase() === 'SUCCESS'
|
||||
return {
|
||||
id: String(item.id),
|
||||
source: 'plan',
|
||||
planName: period > 0 && periods > 0
|
||||
? `第${period}期·${planPeriodLabel(period, periods)}`
|
||||
: (item.periodRule ?? '付款计划'),
|
||||
periodRatio: toRatioText(ratio),
|
||||
billNo: item.orderNo ?? '',
|
||||
amount: Math.round(toNumber(item.totalAmount) * ratio) / 100,
|
||||
status: paid ? '已支付' : toBillStatus(item.status),
|
||||
tradeNo: item.transactionNo ?? undefined,
|
||||
projectName: item.projectName ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
function toTeamMember(item: RequirementMember): TeamMember {
|
||||
const name = item.userName ?? ''
|
||||
return {
|
||||
@@ -183,9 +154,7 @@ export function toProjectDetail(bundle: RequirementDetailBundle): Project {
|
||||
.sort((a, b) => Number(b.isOwner ?? false) - Number(a.isOwner ?? false))
|
||||
.map(toTeamMember),
|
||||
files: (files.requirementAttachments ?? []).map(attachmentToFile),
|
||||
paymentPlans: (finance.billPlans ?? []).length > 0
|
||||
? (finance.billPlans ?? []).map(toPlanCard)
|
||||
: (finance.bills ?? []).map(toProjectBill),
|
||||
paymentPlans: (finance.bills ?? []).map(toProjectBill),
|
||||
invoiceRecords: (finance.invoices ?? []).map(invoiceToFile),
|
||||
contractFile: contract ? contractToFile(contract) : undefined,
|
||||
afterSales: afterSales.afterSale
|
||||
|
||||
@@ -3,6 +3,13 @@ import { ElMessage } from 'element-plus'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
import { storage } from '@/utils/storage'
|
||||
|
||||
declare module 'axios' {
|
||||
export interface AxiosRequestConfig {
|
||||
/** 静默请求:失败时不弹全局错误提示(轮询等高频请求使用) */
|
||||
silent?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
const SUCCESS_CODE = 200
|
||||
|
||||
export const CLIENT_ID = '9f2c4e7a1b3d5c8e2f6a0b4d7c1e9f3a'
|
||||
@@ -22,7 +29,9 @@ service.interceptors.request.use((config) => {
|
||||
})
|
||||
|
||||
service.interceptors.response.use(undefined, (error) => {
|
||||
if (!error?.config?.silent) {
|
||||
ElMessage.error(error?.message || '网络异常,请稍后重试')
|
||||
}
|
||||
return Promise.reject(error)
|
||||
})
|
||||
|
||||
@@ -56,7 +65,9 @@ export async function request<T>(config: AxiosRequestConfig): Promise<T> {
|
||||
const resp = await service.request<ApiResponse<T>>(config)
|
||||
const payload = resp.data
|
||||
if (payload.code !== SUCCESS_CODE) {
|
||||
if (!config.silent) {
|
||||
ElMessage.error(payload.msg || '请求失败')
|
||||
}
|
||||
return Promise.reject(new Error(payload.msg || '请求失败'))
|
||||
}
|
||||
return payload.data
|
||||
|
||||
48
src/utils/serviceVo.ts
Normal file
48
src/utils/serviceVo.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type {
|
||||
ChatMessage,
|
||||
ChatRole,
|
||||
CsMessageVo,
|
||||
} from '@/types/business/service'
|
||||
import { formatDate } from '@/utils/format'
|
||||
|
||||
const TIME_PATTERN = 'MM-DD HH:mm'
|
||||
|
||||
function toChatRole(senderType: string | null | undefined): ChatRole {
|
||||
return (senderType ?? '').trim().toUpperCase() === 'USER' ? 'user' : 'assistant'
|
||||
}
|
||||
|
||||
function toChatTime(raw: string | null | undefined): string {
|
||||
const value = (raw ?? '').trim()
|
||||
if (!value) return ''
|
||||
return formatDate(value, TIME_PATTERN) || value
|
||||
}
|
||||
|
||||
/** OSS 地址没有单独的文件名字段,取 URL 最后一段兜底。 */
|
||||
function toFileName(url: string): string {
|
||||
const clean = url.split('?')[0]?.split('#')[0] ?? ''
|
||||
const name = clean.slice(clean.lastIndexOf('/') + 1)
|
||||
if (!name) return '附件'
|
||||
try {
|
||||
return decodeURIComponent(name)
|
||||
} catch {
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
export function toChatMessage(vo: CsMessageVo): ChatMessage {
|
||||
const fileUrl = vo.fileUrl?.trim() ?? ''
|
||||
return {
|
||||
id: String(vo.id ?? ''),
|
||||
role: toChatRole(vo.senderType),
|
||||
content: vo.content ?? '',
|
||||
file: fileUrl
|
||||
? { name: toFileName(fileUrl), size: Number(vo.fileSize ?? 0), url: fileUrl }
|
||||
: undefined,
|
||||
time: toChatTime(vo.sendTime ?? vo.createTime),
|
||||
}
|
||||
}
|
||||
|
||||
export function toChatMessages(list: CsMessageVo[] | null | undefined): ChatMessage[] {
|
||||
if (!list || list.length === 0) return []
|
||||
return list.filter((item) => item != null).map(toChatMessage)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { StatusTag } from '@/components'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import type { Contract, SignStatus } from '@/types/business/contract'
|
||||
@@ -8,7 +9,10 @@ interface Props {
|
||||
contract: Contract
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
const props = defineProps<Props>()
|
||||
|
||||
/** 后端规则:仅「已签署」合同允许下载。 */
|
||||
const canDownload = computed(() => props.contract.signStatus === '已签署')
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewProject: []
|
||||
@@ -17,9 +21,15 @@ const emit = defineEmits<{
|
||||
}>()
|
||||
|
||||
const SIGN_VARIANTS: Record<SignStatus, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
|
||||
'履行中': 'success',
|
||||
'已过期': 'danger',
|
||||
'待签署': 'warning',
|
||||
'签署中': 'primary',
|
||||
'已签署': 'success',
|
||||
'已作废': 'info',
|
||||
'已过期': 'danger',
|
||||
}
|
||||
|
||||
function fileMeta(file: FileInfo): string {
|
||||
return [file.size ? formatFileSize(file.size) : '', file.uploadTime].filter(Boolean).join(' · ')
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -101,8 +111,8 @@ const SIGN_VARIANTS: Record<SignStatus, 'primary' | 'success' | 'warning' | 'dan
|
||||
>
|
||||
<div class="contract-info__file-info">
|
||||
<span class="contract-info__file-name" :title="file.name">{{ file.name }}</span>
|
||||
<span class="contract-info__file-meta">
|
||||
{{ formatFileSize(file.size) }} · {{ file.uploadTime }}
|
||||
<span v-if="fileMeta(file)" class="contract-info__file-meta">
|
||||
{{ fileMeta(file) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="contract-info__file-actions">
|
||||
@@ -114,6 +124,7 @@ const SIGN_VARIANTS: Record<SignStatus, 'primary' | 'success' | 'warning' | 'dan
|
||||
预览
|
||||
</button>
|
||||
<button
|
||||
v-if="canDownload"
|
||||
type="button"
|
||||
class="contract-info__link"
|
||||
@click="emit('download', file)"
|
||||
|
||||
@@ -4,17 +4,23 @@ import SignSteps from './SignSteps.vue'
|
||||
|
||||
interface Props {
|
||||
expiresIn?: number
|
||||
content?: string
|
||||
}
|
||||
|
||||
withDefaults(defineProps<Props>(), { expiresIn: 272 })
|
||||
withDefaults(defineProps<Props>(), { expiresIn: 300 })
|
||||
|
||||
const emit = defineEmits<{ refresh: [] }>()
|
||||
const emit = defineEmits<{ refresh: []; expire: [] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="sign-panel">
|
||||
<div class="sign-panel__left">
|
||||
<QrCodePanel :expires-in="expiresIn" @refresh="emit('refresh')" />
|
||||
<QrCodePanel
|
||||
:expires-in="expiresIn"
|
||||
:content="content"
|
||||
@refresh="emit('refresh')"
|
||||
@expire="emit('expire')"
|
||||
/>
|
||||
</div>
|
||||
<div class="sign-panel__right">
|
||||
<SignSteps />
|
||||
|
||||
@@ -16,9 +16,11 @@ const emit = defineEmits<{
|
||||
}>()
|
||||
|
||||
const SIGN_VARIANTS: Record<SignStatus, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
|
||||
'履行中': 'success',
|
||||
'已过期': 'danger',
|
||||
'待签署': 'warning',
|
||||
'签署中': 'primary',
|
||||
'已签署': 'success',
|
||||
'已作废': 'info',
|
||||
'已过期': 'danger',
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import { useContractStore } from '@/stores/modules/contract'
|
||||
import ContractInfoCard from './cpns/ContractInfoCard.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const contractStore = useContractStore()
|
||||
const { current } = storeToRefs(contractStore)
|
||||
|
||||
@@ -18,18 +19,48 @@ function load(): void {
|
||||
}
|
||||
|
||||
function onViewProject(): void {
|
||||
// TODO: 关联项目 id 由接口返回后跳转项目详情
|
||||
ElMessage.info('项目详情跳转待接口接入')
|
||||
const projectId = current.value?.relatedProjectId
|
||||
if (!projectId) {
|
||||
ElMessage.info('该合同暂未关联项目')
|
||||
return
|
||||
}
|
||||
void router.push(`/project/${projectId}`)
|
||||
}
|
||||
|
||||
function onPreview(file: FileInfo): void {
|
||||
// TODO(api): 合同文件预览接口
|
||||
ElMessage.info(`「${file.name}」预览待接口接入`)
|
||||
async function onPreview(): Promise<void> {
|
||||
try {
|
||||
const url = await contractStore.fetchPreviewUrl(contractId.value)
|
||||
if (!url) {
|
||||
ElMessage.info('暂无可预览的合同文件')
|
||||
return
|
||||
}
|
||||
window.open(url, '_blank', 'noopener')
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[contract] 合同预览失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
function onDownload(file: FileInfo): void {
|
||||
// TODO(api): 合同文件下载接口
|
||||
ElMessage.info(`「${file.name}」下载待接口接入`)
|
||||
async function onDownload(file: FileInfo): Promise<void> {
|
||||
try {
|
||||
const url = await contractStore.fetchDownloadUrl(contractId.value)
|
||||
if (!url) {
|
||||
ElMessage.info('暂无可下载的合同文件')
|
||||
return
|
||||
}
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.target = '_blank'
|
||||
link.rel = 'noopener'
|
||||
// 没有 download 属性时跨域 URL 只会打开新标签页而不会触发下载
|
||||
link.download = /\.pdf$/i.test(file.name) ? file.name : `${file.name || 'contract'}.pdf`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[contract] 合同下载失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
watch(contractId, load)
|
||||
|
||||
@@ -70,7 +70,7 @@ onMounted(() => {
|
||||
/>
|
||||
|
||||
<PaginationBar
|
||||
:page="query.page"
|
||||
:page="query.pageNum"
|
||||
:page-size="query.pageSize"
|
||||
:total="total"
|
||||
@page-change="onPageChange"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
@@ -7,20 +7,93 @@ import { AppButton } from '@/components'
|
||||
import { useContractStore } from '@/stores/modules/contract'
|
||||
import ContractSignPanel from './cpns/ContractSignPanel.vue'
|
||||
|
||||
const SIGN_STATUS_POLL_INTERVAL = 3000
|
||||
/** 连续失败达到该次数后停止轮询,避免后端异常时无意义地一直请求。 */
|
||||
const SIGN_STATUS_MAX_FAILURES = 5
|
||||
/** qr-init 带 @RepeatSubmit 防重,短时间内重复刷新会被后端拦截,这里做点击节流。 */
|
||||
const SIGN_QR_REFRESH_COOLDOWN = 5000
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const contractStore = useContractStore()
|
||||
const { signExpires } = storeToRefs(contractStore)
|
||||
const { signQrUrl, signExpires } = storeToRefs(contractStore)
|
||||
|
||||
const contractId = computed(() => String(route.params.id))
|
||||
|
||||
function load(): void {
|
||||
void contractStore.fetchSignQr(contractId.value)
|
||||
let lastQrInitAt = 0
|
||||
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
let pollFailures = 0
|
||||
let polling = false
|
||||
|
||||
function stopPolling(): void {
|
||||
if (pollTimer !== null) {
|
||||
clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSigned(): Promise<void> {
|
||||
// 单次请求超过 3 秒时避免定时器叠加发起重复请求
|
||||
if (polling) return
|
||||
polling = true
|
||||
try {
|
||||
if (await contractStore.fetchSignQrStatus(contractId.value)) {
|
||||
stopPolling()
|
||||
ElMessage.success('合同签署完成')
|
||||
void router.replace(`/contract/${contractId.value}`)
|
||||
}
|
||||
else {
|
||||
pollFailures = 0
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
pollFailures += 1
|
||||
console.warn('[contract] 签署状态轮询失败', error)
|
||||
if (pollFailures >= SIGN_STATUS_MAX_FAILURES) {
|
||||
console.warn('[contract] 签署状态轮询连续失败,已停止轮询')
|
||||
stopPolling()
|
||||
}
|
||||
}
|
||||
finally {
|
||||
polling = false
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling(): void {
|
||||
stopPolling()
|
||||
pollFailures = 0
|
||||
pollTimer = setInterval(() => {
|
||||
void checkSigned()
|
||||
}, SIGN_STATUS_POLL_INTERVAL)
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
stopPolling()
|
||||
try {
|
||||
lastQrInitAt = Date.now()
|
||||
await contractStore.fetchSignQr(contractId.value)
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[contract] 签署二维码生成失败', error)
|
||||
return
|
||||
}
|
||||
startPolling()
|
||||
}
|
||||
|
||||
async function onRefresh(): Promise<void> {
|
||||
await contractStore.fetchSignQr(contractId.value, true)
|
||||
// 后端 @RepeatSubmit 会拦截短时间内的重复提交,冷却期内直接忽略点击
|
||||
if (Date.now() - lastQrInitAt < SIGN_QR_REFRESH_COOLDOWN) return
|
||||
try {
|
||||
lastQrInitAt = Date.now()
|
||||
await contractStore.fetchSignQr(contractId.value)
|
||||
// 二维码过期时轮询已停止,刷新后需要重新开始
|
||||
startPolling()
|
||||
ElMessage.success('二维码已刷新')
|
||||
}
|
||||
catch (error) {
|
||||
console.warn('[contract] 签署二维码刷新失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
function onBack(): void {
|
||||
@@ -29,7 +102,11 @@ function onBack(): void {
|
||||
|
||||
watch(contractId, load)
|
||||
|
||||
onMounted(load)
|
||||
onMounted(() => {
|
||||
void load()
|
||||
})
|
||||
|
||||
onBeforeUnmount(stopPolling)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -49,7 +126,9 @@ onMounted(load)
|
||||
|
||||
<ContractSignPanel
|
||||
:expires-in="signExpires"
|
||||
:content="signQrUrl"
|
||||
@refresh="onRefresh"
|
||||
@expire="stopPolling"
|
||||
/>
|
||||
|
||||
<div class="contract-sign__footer">
|
||||
|
||||
@@ -11,7 +11,7 @@ import BillTable from './cpns/BillTable.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const financeStore = useFinanceStore()
|
||||
const { query, list, total } = storeToRefs(financeStore)
|
||||
const { query, list, total, billStats } = storeToRefs(financeStore)
|
||||
|
||||
const keyword = ref('')
|
||||
const selectedIds = ref<string[]>([])
|
||||
@@ -24,9 +24,9 @@ const STATUS_TABS: Array<{ label: string; value: BillStatus | 'all' }> = [
|
||||
]
|
||||
|
||||
const STATS = computed(() => [
|
||||
{ label: '总笔数', value: String(total.value) },
|
||||
{ label: '总金额', value: String(list.value.reduce((sum, bill) => sum + bill.amount, 0)) },
|
||||
{ label: '待支付', value: String(list.value.filter((bill) => bill.status === '待支付').length) },
|
||||
{ label: '总笔数', value: String(billStats.value.totalCount) },
|
||||
{ label: '总金额', value: String(billStats.value.totalAmount) },
|
||||
{ label: '待支付', value: String(billStats.value.pendingCount) },
|
||||
])
|
||||
|
||||
function onTab(value: BillStatus | 'all'): void {
|
||||
@@ -195,10 +195,12 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
&__stat {
|
||||
.flex(column, flex-start, flex-start);
|
||||
.flex(column, center, center);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: 6px;
|
||||
width: 592.67px;
|
||||
padding: 22px 0 0 269px;
|
||||
padding: 22px 0 0;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@@ -249,6 +251,8 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
:deep(.el-radio-button.is-active .el-radio-button__inner) {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
border-color: @primary-strong;
|
||||
background: @filter-selected-bg;
|
||||
color: @primary-strong;
|
||||
|
||||
@@ -3,24 +3,20 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElButton } from 'element-plus'
|
||||
import { usePayPoll } from '@/composables/usePayPoll'
|
||||
import { useFinanceStore } from '@/stores/modules/finance'
|
||||
import type { PayMethod } from '@/types/business/finance'
|
||||
import { createMerchantOrderNo, PAY_METHODS } from '@/utils/payMeta'
|
||||
import { PAY_METHODS } from '@/utils/payMeta'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
import CheckoutBillCard from './cpns/CheckoutBillCard.vue'
|
||||
import PayMethodList from './cpns/PayMethodList.vue'
|
||||
import WechatQrDialog from './cpns/WechatQrDialog.vue'
|
||||
import PayQrDialog from './cpns/PayQrDialog.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const financeStore = useFinanceStore()
|
||||
const { checkoutBills, checkoutLoading, payOrder } = storeToRefs(financeStore)
|
||||
|
||||
const requirementId = computed(() => {
|
||||
const raw = route.query.requirementId
|
||||
return String(Array.isArray(raw) ? raw[0] : (raw ?? '')).trim()
|
||||
})
|
||||
|
||||
const planIds = computed(() => {
|
||||
const raw = route.query.ids
|
||||
const text = Array.isArray(raw) ? raw.join(',') : String(raw ?? '')
|
||||
@@ -29,10 +25,12 @@ const planIds = computed(() => {
|
||||
|
||||
const billIds = computed(() => checkoutBills.value.map((bill) => bill.id))
|
||||
|
||||
const method = ref<PayMethod>('wechat')
|
||||
const method = ref<PayMethod>('alipay')
|
||||
const submitting = ref(false)
|
||||
const qrVisible = ref(false)
|
||||
|
||||
const { start: startPoll, stop: stopPoll, check } = usePayPoll(onPaySuccess)
|
||||
|
||||
const totalAmount = computed(() =>
|
||||
checkoutBills.value.reduce((sum, bill) => sum + Number(bill.amount || 0), 0),
|
||||
)
|
||||
@@ -44,55 +42,28 @@ const methodLabel = computed(
|
||||
const canPay = computed(() => checkoutBills.value.length > 0 && !submitting.value)
|
||||
|
||||
async function load(): Promise<void> {
|
||||
await financeStore.loadCheckout(requirementId.value, planIds.value)
|
||||
}
|
||||
|
||||
function openAlipay(body: string): void {
|
||||
if (/^\s*https?:\/\//i.test(body)) {
|
||||
window.open(body, '_blank', 'noopener')
|
||||
return
|
||||
}
|
||||
|
||||
const holder = document.createElement('div')
|
||||
holder.style.display = 'none'
|
||||
holder.innerHTML = body
|
||||
document.body.appendChild(holder)
|
||||
|
||||
const form = holder.querySelector('form')
|
||||
if (form) {
|
||||
form.submit()
|
||||
window.setTimeout(() => holder.remove(), 0)
|
||||
return
|
||||
}
|
||||
|
||||
holder.remove()
|
||||
ElMessage.error('支付宝下单返回内容无法识别')
|
||||
await financeStore.loadCheckout(planIds.value)
|
||||
}
|
||||
|
||||
async function onConfirm(): Promise<void> {
|
||||
if (!canPay.value) return
|
||||
submitting.value = true
|
||||
try {
|
||||
const orderNo = createMerchantOrderNo()
|
||||
await financeStore.payOrders(billIds.value, method.value)
|
||||
|
||||
if (method.value === 'wechat') {
|
||||
await financeStore.payByWechatNative(orderNo, totalAmount.value, billIds.value)
|
||||
const codeUrl = payOrder.value?.codeUrl
|
||||
if (!codeUrl) {
|
||||
ElMessage.error('微信下单失败:未返回二维码内容')
|
||||
const qrCode = payOrder.value?.qrCode
|
||||
if (!qrCode) {
|
||||
ElMessage.error('支付宝下单失败:未返回二维码内容')
|
||||
return
|
||||
}
|
||||
const outTradeNo = financeStore.payOutTradeNo
|
||||
if (!outTradeNo) {
|
||||
ElMessage.error('未获取到支付单号,请重新发起支付')
|
||||
return
|
||||
}
|
||||
|
||||
qrVisible.value = true
|
||||
return
|
||||
}
|
||||
|
||||
await financeStore.payByAlipayPage(orderNo, totalAmount.value, billIds.value)
|
||||
const body = payOrder.value?.formBody
|
||||
if (!body) {
|
||||
ElMessage.error('支付宝下单失败:未返回跳转地址')
|
||||
return
|
||||
}
|
||||
openAlipay(body)
|
||||
startPoll(outTradeNo)
|
||||
}
|
||||
catch {
|
||||
}
|
||||
@@ -101,21 +72,22 @@ async function onConfirm(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function onRefreshQr(): Promise<void> {
|
||||
try {
|
||||
await financeStore.payByWechatNative(createMerchantOrderNo(), totalAmount.value, billIds.value)
|
||||
}
|
||||
catch {
|
||||
async function onCheckPaid(): Promise<void> {
|
||||
const outTradeNo = financeStore.payOutTradeNo
|
||||
if (!outTradeNo) return
|
||||
const done = await check(outTradeNo)
|
||||
if (!done && qrVisible.value) {
|
||||
ElMessage.warning('支付结果确认中,请稍后再试')
|
||||
}
|
||||
}
|
||||
|
||||
function onPaid(): void {
|
||||
function onPaySuccess(outTradeNo: string): void {
|
||||
qrVisible.value = false
|
||||
const first = checkoutBills.value[0]
|
||||
if (!first) return
|
||||
void router.push({
|
||||
path: `/finance/bills/${first.id}/pay/result`,
|
||||
query: { requirementId: requirementId.value },
|
||||
query: { outTradeNo, ids: billIds.value.join(',') },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -123,11 +95,16 @@ function goBack(): void {
|
||||
void router.push('/finance/bills')
|
||||
}
|
||||
|
||||
watch([requirementId, planIds], () => {
|
||||
watch(planIds, () => {
|
||||
void load()
|
||||
}, { immediate: true })
|
||||
|
||||
watch(qrVisible, (visible) => {
|
||||
if (!visible) stopPoll()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopPoll()
|
||||
financeStore.clearPayOrder()
|
||||
})
|
||||
</script>
|
||||
@@ -196,12 +173,11 @@ onBeforeUnmount(() => {
|
||||
</el-button>
|
||||
</section>
|
||||
|
||||
<WechatQrDialog
|
||||
<PayQrDialog
|
||||
v-model:visible="qrVisible"
|
||||
:content="payOrder?.codeUrl ?? ''"
|
||||
:content="payOrder?.qrCode ?? ''"
|
||||
:amount="totalAmount"
|
||||
@refresh="onRefreshQr"
|
||||
@paid="onPaid"
|
||||
@check="onCheckPaid"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -92,7 +92,7 @@ watch(
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
label="操作"
|
||||
width="96"
|
||||
width="110"
|
||||
fixed="right"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
@@ -189,6 +189,7 @@ watch(
|
||||
font-size: @font-size-sm;
|
||||
font-weight: 400;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&__empty {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { ElButton } from 'element-plus'
|
||||
import type { FinancePeriod } from '@/types/business/finance'
|
||||
|
||||
interface DistributionItem {
|
||||
name: string
|
||||
@@ -10,10 +11,15 @@ interface DistributionItem {
|
||||
|
||||
interface Props {
|
||||
distribution: DistributionItem[]
|
||||
/** 全年逐月金额(dimension=YEAR 时接口返回,12 项) */
|
||||
monthly: number[]
|
||||
period: FinancePeriod
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{ periodChange: [period: FinancePeriod] }>()
|
||||
|
||||
const total = computed(() => props.distribution.reduce((sum, item) => sum + item.value, 0))
|
||||
|
||||
const gradient = computed(() => {
|
||||
@@ -27,13 +33,9 @@ const gradient = computed(() => {
|
||||
return `conic-gradient(${stops.join(', ')})`
|
||||
})
|
||||
|
||||
const AXIS = [250, 200, 150, 100, 50]
|
||||
const AXIS_MAX = AXIS[0]
|
||||
const MONTHS = ['1月', '2月', '3月', '4月', '5月']
|
||||
|
||||
interface PeriodOption {
|
||||
label: string
|
||||
value: 'month' | 'half'
|
||||
value: FinancePeriod
|
||||
}
|
||||
|
||||
// 设计稿 #20 右上角切换:月度账单(激活)/ 上半
|
||||
@@ -42,16 +44,42 @@ const PERIODS: PeriodOption[] = [
|
||||
{ label: '上半', value: 'half' },
|
||||
]
|
||||
|
||||
const period = ref<'month' | 'half'>('month')
|
||||
const TICK_COUNT = 5
|
||||
const DEFAULT_AXIS_MAX = 250
|
||||
|
||||
function onPeriodChange(value: 'month' | 'half'): void {
|
||||
period.value = value
|
||||
}
|
||||
/** 月度账单按业务类型分布取值;上半年取 YEAR 维度的 1-6 月逐月金额。 */
|
||||
const bars = computed(() => {
|
||||
if (props.period === 'half') {
|
||||
return props.monthly.slice(0, 6).map((value, index) => ({
|
||||
label: `${index + 1}月`,
|
||||
value,
|
||||
}))
|
||||
}
|
||||
return props.distribution.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.value,
|
||||
}))
|
||||
})
|
||||
|
||||
// 柱高按 Y 轴量程绝对值换算(设计稿 #20:Y 轴 250 为满量程),非占比
|
||||
const axisMax = computed(() => {
|
||||
const max = Math.max(0, ...bars.value.map((bar) => bar.value))
|
||||
if (max <= 0) return DEFAULT_AXIS_MAX
|
||||
const rough = max / TICK_COUNT
|
||||
const magnitude = 10 ** Math.floor(Math.log10(rough))
|
||||
const step = Math.ceil(rough / magnitude) * magnitude
|
||||
return step * TICK_COUNT
|
||||
})
|
||||
|
||||
const axis = computed(() =>
|
||||
Array.from({ length: TICK_COUNT }, (_, index) =>
|
||||
Math.round((axisMax.value / TICK_COUNT) * (TICK_COUNT - index)),
|
||||
),
|
||||
)
|
||||
|
||||
// 柱高按 Y 轴量程绝对值换算,非占比
|
||||
function heightPercentOf(value: number): number {
|
||||
if (value <= 0) return 0
|
||||
return Math.min((value / AXIS_MAX) * 100, 100)
|
||||
return Math.min((value / axisMax.value) * 100, 100)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -67,7 +95,7 @@ function heightPercentOf(value: number): number {
|
||||
:key="item.value"
|
||||
class="finance-chart__switch-btn"
|
||||
:class="{ 'is-active': period === item.value }"
|
||||
@click="onPeriodChange(item.value)"
|
||||
@click="emit('periodChange', item.value)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</el-button>
|
||||
@@ -75,30 +103,30 @@ function heightPercentOf(value: number): number {
|
||||
|
||||
<div class="finance-chart__body">
|
||||
<ul class="finance-chart__axis" aria-hidden="true">
|
||||
<li v-for="v in AXIS" :key="v" class="finance-chart__axis-item">
|
||||
<li v-for="v in axis" :key="v" class="finance-chart__axis-item">
|
||||
{{ v }}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="finance-chart__plot">
|
||||
<div class="finance-chart__grid" aria-hidden="true">
|
||||
<i v-for="v in AXIS" :key="v" class="finance-chart__line" />
|
||||
<i v-for="v in axis" :key="v" class="finance-chart__line" />
|
||||
</div>
|
||||
|
||||
<div class="finance-chart__bars">
|
||||
<span
|
||||
v-for="(m, i) in MONTHS"
|
||||
:key="m"
|
||||
v-for="(bar, i) in bars"
|
||||
:key="`${bar.label}-${i}`"
|
||||
class="finance-chart__bar"
|
||||
:style="{ height: `${heightPercentOf(distribution[i]?.value ?? 0)}%` }"
|
||||
:style="{ height: `${heightPercentOf(bar.value)}%` }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="finance-chart__pie" :style="{ background: gradient }" />
|
||||
|
||||
<ul class="finance-chart__months" aria-hidden="true">
|
||||
<li v-for="m in MONTHS" :key="m" class="finance-chart__month">
|
||||
{{ m }}
|
||||
<li v-for="(bar, i) in bars" :key="`${bar.label}-${i}`" class="finance-chart__month">
|
||||
{{ bar.label }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import { ElDatePicker } from 'element-plus'
|
||||
import type { FinanceStats } from '@/types/business/finance'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
|
||||
interface Props {
|
||||
stats: FinanceStats | null
|
||||
/** 'year' 表示当年全年,或具体月份 YYYY-MM */
|
||||
period: string
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
periodChange: [period: string]
|
||||
export: []
|
||||
}>()
|
||||
|
||||
const year = new Date().getFullYear()
|
||||
|
||||
/** 不允许选择未来月份 */
|
||||
function isFutureMonth(date: Date): boolean {
|
||||
const today = new Date()
|
||||
return date.getFullYear() > today.getFullYear()
|
||||
|| (date.getFullYear() === today.getFullYear() && date.getMonth() > today.getMonth())
|
||||
}
|
||||
|
||||
/** 清空月份时回到「全年」 */
|
||||
function onPeriodChange(value: string | number | Date | null): void {
|
||||
emit('periodChange', typeof value === 'string' && value ? value : 'year')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -25,10 +42,19 @@ const emit = defineEmits<{
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button class="finance-overview__period-link" @click="emit('periodChange', 'year')">
|
||||
{{ stats?.month || '2026年账单' }}
|
||||
<span aria-hidden="true">›</span>
|
||||
</button>
|
||||
<div class="finance-overview__month">
|
||||
<ElDatePicker
|
||||
:model-value="props.period === 'year' ? '' : props.period"
|
||||
type="month"
|
||||
format="YYYY年MM月"
|
||||
value-format="YYYY-MM"
|
||||
:placeholder="`${year}年全年`"
|
||||
:clearable="true"
|
||||
:editable="false"
|
||||
:disabled-date="isFutureMonth"
|
||||
@update:model-value="onPeriodChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -62,20 +88,48 @@ const emit = defineEmits<{
|
||||
color: @white;
|
||||
}
|
||||
|
||||
&__period-link {
|
||||
&__month {
|
||||
position: absolute;
|
||||
top: 25px;
|
||||
right: 27px;
|
||||
border: none;
|
||||
top: 22px;
|
||||
right: 17px;
|
||||
width: 125px;
|
||||
|
||||
:deep(.el-date-editor) {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:deep(.el-input__wrapper) {
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
:deep(.el-input__inner) {
|
||||
min-width: 0;
|
||||
padding: 0 16px 0 0;
|
||||
color: @white;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
line-height: 15px;
|
||||
color: @white;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
&::placeholder {
|
||||
color: @white;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 日历图标和文字挨在一起
|
||||
:deep(.el-input__prefix) {
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
:deep(.el-input__prefix),
|
||||
:deep(.el-input__suffix) {
|
||||
color: @white;
|
||||
}
|
||||
|
||||
&:hover :deep(.el-input__inner) {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
248
src/views/finance/cpns/InvoiceApplyDialog.vue
Normal file
248
src/views/finance/cpns/InvoiceApplyDialog.vue
Normal file
@@ -0,0 +1,248 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { ElMessage, ElSelect, ElOption, ElRadio, ElButton } from 'element-plus'
|
||||
import type {
|
||||
InvoiceApplyPayload,
|
||||
InvoiceAvailableBill,
|
||||
InvoiceTitle,
|
||||
InvoiceType,
|
||||
} from '@/types/business/finance'
|
||||
import { INVOICE_TYPE_LABELS } from '@/utils/invoiceVo'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
|
||||
interface Props {
|
||||
bills: InvoiceAvailableBill[]
|
||||
titles: InvoiceTitle[]
|
||||
/** 从某条已驳回记录进入时,优先选中的账单 */
|
||||
preselectBillId?: string
|
||||
submitting?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const visible = defineModel<boolean>('visible', { default: false })
|
||||
|
||||
const emit = defineEmits<{ submit: [payload: InvoiceApplyPayload] }>()
|
||||
|
||||
const billId = ref('')
|
||||
const titleId = ref('')
|
||||
const invoiceType = ref<InvoiceType>('GENERAL')
|
||||
|
||||
function defaultTitleId(): string {
|
||||
return props.titles.find((item) => item.isDefault)?.id ?? props.titles[0]?.id ?? ''
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
const preferred = props.preselectBillId
|
||||
const preferredExists = Boolean(preferred) && props.bills.some((bill) => bill.billId === preferred)
|
||||
billId.value = preferredExists && preferred ? preferred : (props.bills[0]?.billId ?? '')
|
||||
titleId.value = defaultTitleId()
|
||||
invoiceType.value = 'GENERAL'
|
||||
}
|
||||
|
||||
watch(visible, (open) => {
|
||||
if (open) reset()
|
||||
})
|
||||
|
||||
// 抬头/账单可能在弹窗打开后才加载完成,补选默认项
|
||||
watch(
|
||||
() => props.titles,
|
||||
(list) => {
|
||||
if (visible.value && !titleId.value && list.length > 0) titleId.value = defaultTitleId()
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.bills,
|
||||
(list) => {
|
||||
if (visible.value && !billId.value && list.length > 0) billId.value = list[0].billId
|
||||
},
|
||||
)
|
||||
|
||||
function onSubmit(): void {
|
||||
if (!billId.value) {
|
||||
ElMessage.warning('请选择要开票的账单')
|
||||
return
|
||||
}
|
||||
if (!titleId.value) {
|
||||
ElMessage.warning('请选择发票抬头')
|
||||
return
|
||||
}
|
||||
emit('submit', {
|
||||
billId: billId.value,
|
||||
titleId: titleId.value,
|
||||
invoiceType: invoiceType.value,
|
||||
})
|
||||
}
|
||||
|
||||
function onCancel(): void {
|
||||
visible.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="visible" class="invoice-apply" @click.self="onCancel">
|
||||
<div class="invoice-apply__panel">
|
||||
<h3 class="invoice-apply__title">
|
||||
申请开票
|
||||
</h3>
|
||||
|
||||
<div class="invoice-apply__field">
|
||||
<span class="invoice-apply__label">选择账单</span>
|
||||
<el-select
|
||||
v-model="billId"
|
||||
class="invoice-apply__control"
|
||||
placeholder="请选择可开票账单"
|
||||
:disabled="bills.length === 0"
|
||||
>
|
||||
<el-option
|
||||
v-for="bill in bills"
|
||||
:key="bill.billId"
|
||||
:value="bill.billId"
|
||||
:label="`${bill.billNo} · ${bill.periodName} · ¥${formatMoney(bill.amount)}`"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<div class="invoice-apply__field">
|
||||
<span class="invoice-apply__label">发票抬头</span>
|
||||
<el-select
|
||||
v-model="titleId"
|
||||
class="invoice-apply__control"
|
||||
placeholder="请选择发票抬头"
|
||||
:disabled="titles.length === 0"
|
||||
>
|
||||
<el-option
|
||||
v-for="title in titles"
|
||||
:key="title.id"
|
||||
:value="title.id"
|
||||
:label="`${title.title}(${title.type})`"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<div class="invoice-apply__field">
|
||||
<span class="invoice-apply__label">发票类型</span>
|
||||
<el-radio v-model="invoiceType" value="GENERAL">
|
||||
{{ INVOICE_TYPE_LABELS.GENERAL }}
|
||||
</el-radio>
|
||||
<el-radio v-model="invoiceType" value="SPECIAL">
|
||||
{{ INVOICE_TYPE_LABELS.SPECIAL }}
|
||||
</el-radio>
|
||||
</div>
|
||||
|
||||
<p v-if="bills.length === 0" class="invoice-apply__empty">
|
||||
暂无可开票账单(仅已支付且未开票的账单可申请)
|
||||
</p>
|
||||
|
||||
<div class="invoice-apply__footer">
|
||||
<el-button class="invoice-apply__btn" @click="onCancel">
|
||||
取消
|
||||
</el-button>
|
||||
<el-button
|
||||
class="invoice-apply__btn invoice-apply__btn--confirm"
|
||||
:disabled="bills.length === 0 || titles.length === 0 || submitting"
|
||||
@click="onSubmit"
|
||||
>
|
||||
{{ submitting ? '提交中…' : '提交申请' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.invoice-apply {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
.flex(row, center);
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
|
||||
&__panel {
|
||||
width: 480px;
|
||||
max-width: calc(100vw - 32px);
|
||||
padding: @spacing-lg;
|
||||
border-radius: @radius-lg;
|
||||
background: @white;
|
||||
box-shadow: @shadow-lg;
|
||||
}
|
||||
|
||||
&__title {
|
||||
margin-bottom: @spacing-base;
|
||||
font-size: @font-size-lg;
|
||||
font-weight: 600;
|
||||
color: @heading-color;
|
||||
}
|
||||
|
||||
&__field {
|
||||
.flex(row, flex-start, center);
|
||||
gap: @spacing-sm;
|
||||
margin-bottom: @spacing-base;
|
||||
|
||||
:deep(.el-radio__label) {
|
||||
color: @text-color;
|
||||
font-size: @font-size-base;
|
||||
}
|
||||
}
|
||||
|
||||
&__label {
|
||||
width: 72px;
|
||||
flex-shrink: 0;
|
||||
font-size: @font-size-base;
|
||||
color: @text-color;
|
||||
}
|
||||
|
||||
&__control {
|
||||
flex: 1;
|
||||
|
||||
:deep(.el-select__wrapper) {
|
||||
min-height: 34px;
|
||||
background: @bg-color-light;
|
||||
box-shadow: none;
|
||||
border-radius: @radius-base;
|
||||
}
|
||||
}
|
||||
|
||||
&__empty {
|
||||
margin-top: @spacing-sm;
|
||||
font-size: @font-size-sm;
|
||||
color: @text-color-secondary;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
.flex(row, flex-end);
|
||||
gap: @spacing-sm;
|
||||
margin-top: @spacing-lg;
|
||||
}
|
||||
|
||||
&__btn {
|
||||
height: 34px;
|
||||
padding: 0 @spacing-base;
|
||||
border: 1px solid @border-color-dark;
|
||||
border-radius: @radius-base;
|
||||
background: @white;
|
||||
color: @text-color;
|
||||
font-size: @font-size-base;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
border-color: @primary-color;
|
||||
color: @primary-color;
|
||||
}
|
||||
|
||||
&--confirm {
|
||||
border-color: @primary-color;
|
||||
background: @primary-color;
|
||||
color: @white;
|
||||
|
||||
&:hover {
|
||||
background: @primary-hover;
|
||||
color: @white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -22,12 +22,13 @@ const emit = defineEmits<{
|
||||
<span v-else class="invoice-title-card__badge-placeholder" />
|
||||
<div class="invoice-title-card__actions">
|
||||
<el-button
|
||||
v-if="!invoiceTitle.isDefault"
|
||||
link
|
||||
type="primary"
|
||||
class="invoice-title-card__btn"
|
||||
@click="emit('setDefault', invoiceTitle.id)"
|
||||
>
|
||||
{{ invoiceTitle.isDefault ? '取消默认' : '设为默认' }}
|
||||
设为默认
|
||||
</el-button>
|
||||
<el-button
|
||||
link
|
||||
|
||||
@@ -27,8 +27,12 @@ watch(visible, (open) => {
|
||||
})
|
||||
|
||||
function onSave(): void {
|
||||
if (!form.title.trim() || !form.taxNo.trim()) {
|
||||
ElMessage.warning('请填写发票抬头与税号')
|
||||
if (!form.title.trim()) {
|
||||
ElMessage.warning('请填写发票抬头')
|
||||
return
|
||||
}
|
||||
if (form.type === '企业单位' && !form.taxNo.trim()) {
|
||||
ElMessage.warning('企业单位请填写税号')
|
||||
return
|
||||
}
|
||||
emit('save', { type: form.type, title: form.title.trim(), taxNo: form.taxNo.trim() })
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { ElRadio, ElButton } from 'element-plus'
|
||||
import type { PayMethod } from '@/types/business/finance'
|
||||
|
||||
interface Props {
|
||||
method: PayMethod
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const visible = defineModel<boolean>('visible', { default: false })
|
||||
|
||||
const emit = defineEmits<{ confirm: [method: PayMethod] }>()
|
||||
|
||||
const selected = ref<PayMethod>(props.method)
|
||||
|
||||
watch(
|
||||
() => props.method,
|
||||
(value) => {
|
||||
selected.value = value
|
||||
},
|
||||
)
|
||||
|
||||
watch(visible, (open) => {
|
||||
if (open) selected.value = props.method
|
||||
})
|
||||
|
||||
function onConfirm(): void {
|
||||
emit('confirm', selected.value)
|
||||
visible.value = false
|
||||
}
|
||||
|
||||
function onCancel(): void {
|
||||
visible.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="visible" class="pay-method-dialog" @click.self="onCancel">
|
||||
<div class="pay-method-dialog__panel">
|
||||
<h3 class="pay-method-dialog__title">
|
||||
切换支付方式
|
||||
</h3>
|
||||
|
||||
<label
|
||||
class="pay-method-dialog__option"
|
||||
:class="{ 'is-active': selected === 'wechat' }"
|
||||
>
|
||||
<el-radio
|
||||
v-model="selected"
|
||||
value="wechat"
|
||||
class="pay-method-dialog__radio"
|
||||
>
|
||||
微信支付
|
||||
</el-radio>
|
||||
<span class="pay-method-dialog__tip text-secondary">推荐使用</span>
|
||||
</label>
|
||||
|
||||
<label
|
||||
class="pay-method-dialog__option"
|
||||
:class="{ 'is-active': selected === 'alipay' }"
|
||||
>
|
||||
<el-radio
|
||||
v-model="selected"
|
||||
value="alipay"
|
||||
class="pay-method-dialog__radio"
|
||||
>
|
||||
支付宝支付
|
||||
</el-radio>
|
||||
<span class="pay-method-dialog__tip text-secondary">其他用户选择</span>
|
||||
</label>
|
||||
|
||||
<div class="pay-method-dialog__footer">
|
||||
<el-button class="pay-method-dialog__btn" @click="onCancel">
|
||||
取消
|
||||
</el-button>
|
||||
<el-button class="pay-method-dialog__btn pay-method-dialog__btn--confirm" @click="onConfirm">
|
||||
确认
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.pay-method-dialog {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
.flex(row, center);
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
|
||||
&__panel {
|
||||
width: 420px;
|
||||
max-width: calc(100vw - 32px);
|
||||
padding: @spacing-lg;
|
||||
border-radius: @radius-lg;
|
||||
background: @white;
|
||||
box-shadow: @shadow-lg;
|
||||
}
|
||||
|
||||
&__title {
|
||||
margin-bottom: @spacing-base;
|
||||
font-size: @font-size-lg;
|
||||
font-weight: 600;
|
||||
color: @heading-color;
|
||||
}
|
||||
|
||||
&__option {
|
||||
.flex(row, flex-start, center);
|
||||
gap: @spacing-sm;
|
||||
padding: @spacing-base;
|
||||
margin-bottom: @spacing-sm;
|
||||
border: 1px solid @border-color;
|
||||
border-radius: @radius-base;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
border-color: @primary-color;
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
border-color: @primary-color;
|
||||
background: @primary-light;
|
||||
}
|
||||
}
|
||||
|
||||
&__radio {
|
||||
.el-radio__label {
|
||||
color: @heading-color;
|
||||
font-size: @font-size-base;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
&__tip {
|
||||
margin-left: auto;
|
||||
font-size: @font-size-sm;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
.flex(row, flex-end);
|
||||
gap: @spacing-sm;
|
||||
margin-top: @spacing-base;
|
||||
}
|
||||
|
||||
&__btn {
|
||||
height: 34px;
|
||||
padding: 0 @spacing-base;
|
||||
border: 1px solid @border-color-dark;
|
||||
border-radius: @radius-base;
|
||||
background: @white;
|
||||
color: @text-color;
|
||||
font-size: @font-size-base;
|
||||
transition: all 0.2s;
|
||||
&:hover {
|
||||
border-color: @primary-color;
|
||||
color: @primary-color;
|
||||
}
|
||||
|
||||
&--confirm {
|
||||
border-color: @primary-color;
|
||||
background: @primary-color;
|
||||
color: @white;
|
||||
|
||||
&:hover {
|
||||
background: @primary-hover;
|
||||
color: @white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,35 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import qrcode from 'qrcode-generator'
|
||||
import { useCountDown } from '@/composables/useCountDown'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
/** 后端返回的二维码内容字符串 */
|
||||
content: string
|
||||
amount: number
|
||||
expiresIn?: number
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), { expiresIn: 300 })
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [visible: boolean]
|
||||
refresh: []
|
||||
paid: []
|
||||
check: []
|
||||
}>()
|
||||
|
||||
const { seconds, start, reset: resetCountDown } = useCountDown(props.expiresIn)
|
||||
const started = ref(false)
|
||||
|
||||
const expired = computed(() => started.value && seconds.value <= 0)
|
||||
|
||||
const countdownText = computed(() => {
|
||||
const m = Math.floor(seconds.value / 60)
|
||||
const s = seconds.value % 60
|
||||
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
|
||||
})
|
||||
|
||||
const qrSvg = computed(() => {
|
||||
if (!props.content) return ''
|
||||
try {
|
||||
@@ -37,78 +24,45 @@ const qrSvg = computed(() => {
|
||||
qr.addData(props.content)
|
||||
qr.make()
|
||||
return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true })
|
||||
} catch {
|
||||
}
|
||||
catch {
|
||||
return ''
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.content] as const,
|
||||
([visible, content]) => {
|
||||
if (visible && content) {
|
||||
start(props.expiresIn)
|
||||
started.value = true
|
||||
return
|
||||
}
|
||||
if (!visible) {
|
||||
resetCountDown()
|
||||
started.value = false
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function close(): void {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function refresh(): void {
|
||||
start(props.expiresIn)
|
||||
started.value = true
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
function onPaid(): void {
|
||||
emit('paid')
|
||||
}
|
||||
|
||||
function onBoxClick(): void {
|
||||
if (expired.value) refresh()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="visible" class="wx-qr" @click.self="close">
|
||||
<div class="wx-qr__panel">
|
||||
<h3 class="wx-qr__title">微信扫码支付</h3>
|
||||
<p class="wx-qr__amount">¥{{ formatMoney(amount) }}</p>
|
||||
|
||||
<div
|
||||
class="wx-qr__box"
|
||||
:class="{ 'is-expired': expired }"
|
||||
@click="onBoxClick"
|
||||
>
|
||||
<div v-if="!expired && qrSvg" class="wx-qr__code" v-html="qrSvg" />
|
||||
<div v-else class="wx-qr__mask">
|
||||
<span class="wx-qr__mask-icon">⟳</span>
|
||||
<span class="wx-qr__mask-text">
|
||||
{{ expired ? '二维码已过期' : '二维码生成中' }}<br />点击刷新
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="wx-qr__status">
|
||||
<template v-if="!expired">
|
||||
请使用手机微信 <strong>[扫一扫]</strong> 扫描上方二维码, 二维码
|
||||
<strong class="wx-qr__count">{{ countdownText }}</strong> 后失效
|
||||
</template>
|
||||
<template v-else> 二维码已过期,请点击二维码或下方按钮刷新 </template>
|
||||
<div v-if="visible" class="pay-qr" @click.self="close">
|
||||
<div class="pay-qr__panel">
|
||||
<h3 class="pay-qr__title">
|
||||
支付宝扫码支付
|
||||
</h3>
|
||||
<p class="pay-qr__amount">
|
||||
¥{{ formatMoney(amount) }}
|
||||
</p>
|
||||
|
||||
<div class="wx-qr__actions">
|
||||
<button class="wx-qr__btn" @click="refresh">刷新二维码</button>
|
||||
<button class="wx-qr__btn wx-qr__btn--cta" @click="onPaid">
|
||||
<div class="pay-qr__box">
|
||||
<div v-if="qrSvg" class="pay-qr__code" v-html="qrSvg" />
|
||||
<div v-else class="pay-qr__mask">
|
||||
<span class="pay-qr__mask-icon">▦</span>
|
||||
<span class="pay-qr__mask-text">二维码生成中</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="pay-qr__status">
|
||||
请使用手机支付宝 <strong>[扫一扫]</strong> 扫描上方二维码完成支付,支付成功后自动跳转
|
||||
</p>
|
||||
|
||||
<div class="pay-qr__actions">
|
||||
<button class="pay-qr__btn" @click="close">
|
||||
取消支付
|
||||
</button>
|
||||
<button class="pay-qr__btn pay-qr__btn--cta" @click="emit('check')">
|
||||
我已完成支付
|
||||
</button>
|
||||
</div>
|
||||
@@ -118,7 +72,7 @@ function onBoxClick(): void {
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.wx-qr {
|
||||
.pay-qr {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
@@ -156,11 +110,6 @@ function onBoxClick(): void {
|
||||
border: 1px solid @checkout-line;
|
||||
border-radius: @radius-base;
|
||||
background: @checkout-card;
|
||||
|
||||
&.is-expired {
|
||||
background: @bg-color;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
&__code {
|
||||
@@ -204,11 +153,6 @@ function onBoxClick(): void {
|
||||
}
|
||||
}
|
||||
|
||||
&__count {
|
||||
color: @checkout-amount;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
.flex(row, center);
|
||||
gap: @spacing-sm;
|
||||
@@ -3,9 +3,8 @@ export { default as FinanceOverview } from './cpns/FinanceOverview.vue'
|
||||
export { default as FinanceChart } from './cpns/FinanceChart.vue'
|
||||
export { default as BillTable } from './cpns/BillTable.vue'
|
||||
export { default as BillSummaryBar } from './cpns/BillSummaryBar.vue'
|
||||
export { default as PayMethodDialog } from './cpns/PayMethodDialog.vue'
|
||||
export { default as InvoiceTitleCard } from './cpns/InvoiceTitleCard.vue'
|
||||
export { default as InvoiceTitleDialog } from './cpns/InvoiceTitleDialog.vue'
|
||||
export { default as CheckoutBillCard } from './cpns/CheckoutBillCard.vue'
|
||||
export { default as PayMethodList } from './cpns/PayMethodList.vue'
|
||||
export { default as WechatQrDialog } from './cpns/WechatQrDialog.vue'
|
||||
export { default as PayQrDialog } from './cpns/PayQrDialog.vue'
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
<!-- 页面:财务中心(Finance) -->
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { PageHead } from '@/components'
|
||||
import { useFinanceStore } from '@/stores/modules/finance'
|
||||
import type { FinancePeriod, FinanceSummaryQuery } from '@/types/business/finance'
|
||||
import FinanceChart from './cpns/FinanceChart.vue'
|
||||
import FinanceOverview from './cpns/FinanceOverview.vue'
|
||||
|
||||
const financeStore = useFinanceStore()
|
||||
const { stats } = storeToRefs(financeStore)
|
||||
const { stats, overviewStats } = storeToRefs(financeStore)
|
||||
|
||||
const ENTRIES = [
|
||||
{ key: 'bill', label: '账单明细', to: '/finance/bills' },
|
||||
@@ -19,17 +20,86 @@ const ENTRIES = [
|
||||
{ key: 'export', label: '报表导出', to: '' },
|
||||
] as const
|
||||
|
||||
function onPeriodChange(period: string): void {
|
||||
void financeStore.fetchStats(period)
|
||||
const chartPeriod = ref<FinancePeriod>('month')
|
||||
const now = new Date()
|
||||
|
||||
/** 累计消费总额:默认当年全年,可切换具体月份 */
|
||||
const overviewPeriod = ref('year')
|
||||
|
||||
/** 下方图表仍按当前月/当前年请求,不受月份选择器影响 */
|
||||
function buildChartQuery(): FinanceSummaryQuery {
|
||||
if (chartPeriod.value === 'half') {
|
||||
return { dimension: 'YEAR', year: now.getFullYear() }
|
||||
}
|
||||
return {
|
||||
dimension: 'MONTH',
|
||||
year: now.getFullYear(),
|
||||
month: now.getMonth() + 1,
|
||||
}
|
||||
}
|
||||
|
||||
function buildOverviewQuery(): FinanceSummaryQuery {
|
||||
if (overviewPeriod.value === 'year') {
|
||||
return { dimension: 'YEAR', year: now.getFullYear() }
|
||||
}
|
||||
const [year, month] = overviewPeriod.value.split('-').map(Number)
|
||||
return {
|
||||
dimension: 'MONTH',
|
||||
year: year || now.getFullYear(),
|
||||
month: month || now.getMonth() + 1,
|
||||
}
|
||||
}
|
||||
|
||||
function loadStats(): void {
|
||||
void financeStore.fetchStats(buildChartQuery())
|
||||
}
|
||||
|
||||
function loadOverviewStats(): void {
|
||||
void financeStore.fetchOverviewStats(buildOverviewQuery())
|
||||
}
|
||||
|
||||
function onPeriodChange(period: FinancePeriod): void {
|
||||
if (chartPeriod.value === period) return
|
||||
chartPeriod.value = period
|
||||
loadStats()
|
||||
}
|
||||
|
||||
function onOverviewPeriodChange(period: string): void {
|
||||
if (!period || period === overviewPeriod.value) return
|
||||
overviewPeriod.value = period
|
||||
// 只刷新累计消费总额,不动下方图表
|
||||
loadOverviewStats()
|
||||
}
|
||||
|
||||
function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function onExport(): Promise<void> {
|
||||
await financeStore.export()
|
||||
ElMessage.success('报表导出成功(演示)')
|
||||
try {
|
||||
const blob = await financeStore.export('excel')
|
||||
if (!blob || blob.size === 0) {
|
||||
ElMessage.error('导出内容为空')
|
||||
return
|
||||
}
|
||||
downloadBlob(blob, `账单明细_${new Date().toISOString().slice(0, 10)}.xlsx`)
|
||||
ElMessage.success('报表导出成功')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void financeStore.fetchStats()
|
||||
loadStats()
|
||||
loadOverviewStats()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -43,8 +113,9 @@ onMounted(() => {
|
||||
<div class="container">
|
||||
<div class="finance__top">
|
||||
<FinanceOverview
|
||||
:stats="stats"
|
||||
@period-change="onPeriodChange"
|
||||
:stats="overviewStats"
|
||||
:period="overviewPeriod"
|
||||
@period-change="onOverviewPeriodChange"
|
||||
@export="onExport"
|
||||
/>
|
||||
|
||||
@@ -156,7 +227,12 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FinanceChart :distribution="stats?.distribution ?? []" />
|
||||
<FinanceChart
|
||||
:distribution="stats?.distribution ?? []"
|
||||
:monthly="stats?.monthly ?? []"
|
||||
:period="chartPeriod"
|
||||
@period-change="onPeriodChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -41,6 +41,7 @@ function onEdit(item: InvoiceTitle): void {
|
||||
}
|
||||
|
||||
async function onSave(payload: InvoiceTitlePayload): Promise<void> {
|
||||
try {
|
||||
if (editing.value) {
|
||||
await financeStore.updateTitle(editing.value.id, payload)
|
||||
ElMessage.success('抬头已更新')
|
||||
@@ -49,6 +50,10 @@ async function onSave(payload: InvoiceTitlePayload): Promise<void> {
|
||||
await financeStore.createTitle(payload)
|
||||
ElMessage.success('抬头已新增')
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
function onDelete(id: string): void {
|
||||
@@ -57,16 +62,27 @@ function onDelete(id: string): void {
|
||||
}
|
||||
|
||||
async function onConfirmDelete(): Promise<void> {
|
||||
try {
|
||||
await financeStore.deleteTitle(pendingDeleteId.value)
|
||||
pendingDeleteId.value = ''
|
||||
if (page.value > pageCount.value) page.value = pageCount.value
|
||||
ElMessage.success('抬头已删除')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
async function onSetDefault(id: string): Promise<void> {
|
||||
const item = titles.value.find((title) => title.id === id)
|
||||
if (!item) return
|
||||
if (!item || item.isDefault) return
|
||||
try {
|
||||
await financeStore.setDefaultTitle(id)
|
||||
ElMessage.success(item.isDefault ? '已取消默认抬头' : '已设为默认抬头')
|
||||
ElMessage.success('已设为默认抬头')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
|
||||
@@ -1,81 +1,166 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import { ElMessage, ElButton, ElTable, ElTableColumn } from 'element-plus'
|
||||
import { FilterPanel, PaginationBar, StatusTag } from '@/components'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, ElButton, ElTable, ElTableColumn } from 'element-plus'
|
||||
import { PaginationBar, StatusTag } from '@/components'
|
||||
import { useFinanceStore } from '@/stores/modules/finance'
|
||||
import type { Invoice, InvoiceStatus } from '@/types/business/finance'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import type { Invoice, InvoiceApplyPayload, InvoiceStatus } from '@/types/business/finance'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
import { INVOICE_TYPE_LABELS } from '@/utils/invoiceVo'
|
||||
import InvoiceApplyDialog from './cpns/InvoiceApplyDialog.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const financeStore = useFinanceStore()
|
||||
const { titles, invoices, invoiceQuery, invoiceTotal } = storeToRefs(financeStore)
|
||||
const { titles, invoices, invoiceQuery, invoiceTotal, availableBills, invoiceStatusOptions } = storeToRefs(financeStore)
|
||||
|
||||
const keyword = ref('')
|
||||
const selectedIds = ref<string[]>([])
|
||||
const profileStore = useProfileStore()
|
||||
const { profile } = storeToRefs(profileStore)
|
||||
|
||||
const applyVisible = ref(false)
|
||||
const applying = ref(false)
|
||||
const applyBillId = ref<string | undefined>(undefined)
|
||||
|
||||
const defaultTitle = computed(() => titles.value.find((item) => item.isDefault) ?? titles.value[0] ?? null)
|
||||
|
||||
const STATUS_TABS: Array<{ label: string; value: InvoiceStatus | 'all' }> = [
|
||||
{ label: '全部', value: 'all' },
|
||||
{ label: '已开票', value: '已开票' },
|
||||
{ label: '开票中', value: '开票中' },
|
||||
{ label: '未开票', value: '未开票' },
|
||||
]
|
||||
type TagVariant = 'primary' | 'success' | 'warning' | 'danger' | 'info'
|
||||
|
||||
const STATUS_VARIANTS: Record<InvoiceStatus, 'success' | 'warning' | 'info'> = {
|
||||
已开票: 'success',
|
||||
开票中: 'warning',
|
||||
未开票: 'info',
|
||||
/** 发票状态选项卡:字典 + 首项「全部」(value 为空,表示不传 status)。 */
|
||||
const STATUS_TABS = computed<Array<{ label: string; value: InvoiceStatus | '' }>>(() => [
|
||||
{ label: '全部', value: '' },
|
||||
...invoiceStatusOptions.value.map((item) => ({
|
||||
label: item.dictLabel,
|
||||
value: item.dictValue as InvoiceStatus,
|
||||
})),
|
||||
])
|
||||
|
||||
/** 状态文案优先用后端 statusName,缺失时回退字典文案。 */
|
||||
function statusLabel(invoice: Invoice): string {
|
||||
return invoice.statusName
|
||||
|| invoiceStatusOptions.value.find((item) => item.dictValue === invoice.status)?.dictLabel
|
||||
|| '—'
|
||||
}
|
||||
|
||||
function onTab(value: InvoiceStatus | 'all'): void {
|
||||
/** 标签颜色取字典 listClass(info/warning/success)。 */
|
||||
function statusVariant(status: InvoiceStatus): TagVariant {
|
||||
const listClass = invoiceStatusOptions.value.find((item) => item.dictValue === status)?.listClass
|
||||
if (listClass === 'primary' || listClass === 'success' || listClass === 'warning' || listClass === 'danger') {
|
||||
return listClass
|
||||
}
|
||||
return 'info'
|
||||
}
|
||||
|
||||
function onTab(value: InvoiceStatus | ''): void {
|
||||
if (invoiceQuery.value.status === value) return
|
||||
financeStore.setInvoiceQuery({ ...invoiceQuery.value, status: value, keyword: keyword.value })
|
||||
selectedIds.value = []
|
||||
financeStore.setInvoiceQuery({ ...invoiceQuery.value, status: value })
|
||||
void financeStore.searchInvoices()
|
||||
}
|
||||
|
||||
function onSearch(): void {
|
||||
financeStore.setInvoiceQuery({ ...invoiceQuery.value, keyword: keyword.value })
|
||||
void financeStore.searchInvoices()
|
||||
}
|
||||
|
||||
function onReset(): void {
|
||||
keyword.value = ''
|
||||
selectedIds.value = []
|
||||
financeStore.setInvoiceQuery({ keyword: '', status: 'all', page: 1, pageSize: invoiceQuery.value.pageSize })
|
||||
void financeStore.fetchInvoices()
|
||||
}
|
||||
|
||||
function onPageChange(page: number): void {
|
||||
void financeStore.changeInvoicePage(page)
|
||||
}
|
||||
|
||||
async function onApply(invoice: Invoice): Promise<void> {
|
||||
await financeStore.applyInvoice(invoice.id)
|
||||
async function onOpenApply(billId?: string): Promise<void> {
|
||||
applyBillId.value = billId || undefined
|
||||
try {
|
||||
await financeStore.fetchAvailableBills()
|
||||
applyVisible.value = true
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmitApply(payload: InvoiceApplyPayload): Promise<void> {
|
||||
applying.value = true
|
||||
try {
|
||||
await financeStore.applyInvoice(payload)
|
||||
applyVisible.value = false
|
||||
ElMessage.success('开票申请已提交')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
finally {
|
||||
applying.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onPreview(): void {
|
||||
ElMessage.info('附件待接口接入')
|
||||
/** 已驳回的发票可重新发起开票申请。 */
|
||||
function onApplyForRow(invoice: Invoice): void {
|
||||
void onOpenApply(invoice.billId)
|
||||
}
|
||||
|
||||
function onDownload(): void {
|
||||
ElMessage.info('附件待接口接入')
|
||||
async function onPreview(invoice: Invoice): Promise<void> {
|
||||
try {
|
||||
const url = await financeStore.fetchPreviewUrl(invoice.id)
|
||||
if (!url) {
|
||||
ElMessage.warning('暂无可预览的发票文件')
|
||||
return
|
||||
}
|
||||
window.open(url, '_blank', 'noopener')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
function onSendEmail(): void {
|
||||
ElMessage.success('发票已发送至绑定邮箱(演示)')
|
||||
async function onDownload(invoice: Invoice): Promise<void> {
|
||||
try {
|
||||
const { blob, fileName } = await financeStore.fetchDownloadFile(invoice.id)
|
||||
if (!blob || blob.size === 0) {
|
||||
ElMessage.warning('暂无可下载的发票文件')
|
||||
return
|
||||
}
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = fileName || `${invoice.invoiceNo || 'invoice'}.pdf`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
function onSelectionChange(rows: Invoice[]): void {
|
||||
selectedIds.value = rows.map((row) => row.id)
|
||||
async function onSendEmail(invoice: Invoice): Promise<void> {
|
||||
if (!profile.value?.email) {
|
||||
try {
|
||||
await ElMessageBox.confirm('您还未绑定邮箱,请先绑定邮箱后再发送发票', '提示', {
|
||||
confirmButtonText: '去绑定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
void router.push({ name: 'ProfileBindEmail', query: { redirect: route.fullPath } })
|
||||
}
|
||||
catch {
|
||||
// 用户取消
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await financeStore.sendInvoiceEmail(invoice.id)
|
||||
ElMessage.success('发票已发送至绑定邮箱')
|
||||
}
|
||||
catch {
|
||||
// 请求异常已由 request.ts 统一提示
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
keyword.value = invoiceQuery.value.keyword
|
||||
void Promise.all([financeStore.fetchTitles(), financeStore.fetchInvoices()])
|
||||
void Promise.all([
|
||||
financeStore.fetchInvoiceStatusOptions(),
|
||||
financeStore.fetchTitles(),
|
||||
financeStore.fetchInvoices(),
|
||||
profileStore.fetchProfile().catch(() => null),
|
||||
])
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -108,6 +193,7 @@ onMounted(() => {
|
||||
</RouterLink>
|
||||
</section>
|
||||
|
||||
<div class="invoices__toolbar">
|
||||
<div class="invoices__tabs">
|
||||
<el-button
|
||||
v-for="tab in STATUS_TABS"
|
||||
@@ -120,47 +206,31 @@ onMounted(() => {
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<FilterPanel
|
||||
v-model:keyword="keyword"
|
||||
keyword-placeholder="搜索发票抬头 / 账单号 / 项目名称"
|
||||
@search="onSearch"
|
||||
@reset="onReset"
|
||||
/>
|
||||
<el-button class="invoices__apply" @click="onOpenApply()">
|
||||
+ 申请开票
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="invoices__table card">
|
||||
<el-table
|
||||
class="invoices__table-el"
|
||||
:data="invoices"
|
||||
row-key="id"
|
||||
@selection-change="onSelectionChange"
|
||||
>
|
||||
<el-table-column
|
||||
type="selection"
|
||||
width="48"
|
||||
/>
|
||||
<el-table-column
|
||||
type="index"
|
||||
label="序号"
|
||||
width="60"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="planName"
|
||||
label="账单名称"
|
||||
min-width="180"
|
||||
label="发票号码"
|
||||
min-width="150"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
prop="billNo"
|
||||
label="账单号"
|
||||
width="150"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
prop="tradeNo"
|
||||
label="交易流水号"
|
||||
min-width="180"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
>
|
||||
<template #default="{ row }">
|
||||
{{ (row as Invoice).invoiceNo || '—' }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="projectName"
|
||||
label="项目名称"
|
||||
@@ -168,21 +238,41 @@ onMounted(() => {
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
label="订单金额"
|
||||
prop="titleName"
|
||||
label="发票抬头"
|
||||
min-width="180"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
label="发票类型"
|
||||
width="100"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
{{ INVOICE_TYPE_LABELS[(row as Invoice).invoiceType ?? ''] ?? '—' }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
label="开票金额"
|
||||
width="110"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="invoices__amount">¥{{ formatMoney((row as Invoice).amount) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="transactionNo"
|
||||
label="交易流水号"
|
||||
min-width="180"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
label="状态"
|
||||
width="90"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<StatusTag
|
||||
:label="(row as Invoice).status"
|
||||
:variant="STATUS_VARIANTS[(row as Invoice).status]"
|
||||
:label="statusLabel(row as Invoice)"
|
||||
:variant="statusVariant((row as Invoice).status)"
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -199,12 +289,12 @@ onMounted(() => {
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="invoices__ops">
|
||||
<template v-if="(row as Invoice).status === '已开票'">
|
||||
<template v-if="(row as Invoice).status === '2'">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
class="invoices__link"
|
||||
@click="onPreview"
|
||||
@click="onPreview(row as Invoice)"
|
||||
>
|
||||
预览
|
||||
</el-button>
|
||||
@@ -212,7 +302,7 @@ onMounted(() => {
|
||||
link
|
||||
type="primary"
|
||||
class="invoices__link"
|
||||
@click="onDownload"
|
||||
@click="onDownload(row as Invoice)"
|
||||
>
|
||||
下载
|
||||
</el-button>
|
||||
@@ -220,21 +310,21 @@ onMounted(() => {
|
||||
link
|
||||
type="primary"
|
||||
class="invoices__link"
|
||||
@click="onSendEmail"
|
||||
@click="onSendEmail(row as Invoice)"
|
||||
>
|
||||
发送邮箱
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-else-if="(row as Invoice).status === '开票中'" class="invoices__dash">—</span>
|
||||
<el-button
|
||||
v-else
|
||||
v-else-if="(row as Invoice).status === '0'"
|
||||
link
|
||||
type="primary"
|
||||
class="invoices__link"
|
||||
@click="onApply(row as Invoice)"
|
||||
@click="onApplyForRow(row as Invoice)"
|
||||
>
|
||||
申请开票
|
||||
</el-button>
|
||||
<span v-else class="invoices__dash">—</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -253,8 +343,18 @@ onMounted(() => {
|
||||
/>
|
||||
|
||||
<p class="invoices__tip text-secondary">
|
||||
开票将使用默认抬头,如需调整请前往 <RouterLink to="/finance/invoice-titles" class="link">管理抬头</RouterLink>。
|
||||
仅已支付且未开票的账单可申请开票,开票进度可在本页查看。抬头管理请前往
|
||||
<RouterLink to="/finance/invoice-titles" class="link">管理抬头</RouterLink>。
|
||||
</p>
|
||||
|
||||
<InvoiceApplyDialog
|
||||
v-model:visible="applyVisible"
|
||||
:bills="availableBills"
|
||||
:titles="titles"
|
||||
:preselect-bill-id="applyBillId"
|
||||
:submitting="applying"
|
||||
@submit="onSubmitApply"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -321,6 +421,11 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
&__toolbar {
|
||||
.flex(row, space-between, center);
|
||||
gap: @spacing-base;
|
||||
}
|
||||
|
||||
&__tabs {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
@@ -328,6 +433,23 @@ onMounted(() => {
|
||||
gap: @spacing-sm;
|
||||
}
|
||||
|
||||
&__apply {
|
||||
height: 34px;
|
||||
padding: 0 @spacing-base;
|
||||
border: none;
|
||||
border-radius: @radius-base;
|
||||
background: @primary-strong;
|
||||
color: @white;
|
||||
font-size: @font-size-base;
|
||||
font-weight: 500;
|
||||
transition: background 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: @primary-color;
|
||||
color: @white;
|
||||
}
|
||||
}
|
||||
|
||||
&__tab {
|
||||
height: 34px;
|
||||
margin: 0;
|
||||
|
||||
@@ -13,18 +13,25 @@ const { result } = storeToRefs(financeStore)
|
||||
|
||||
const billId = computed(() => String(route.params.id))
|
||||
|
||||
const requirementId = computed(() => {
|
||||
const raw = route.query.requirementId
|
||||
const outTradeNo = computed(() => {
|
||||
const raw = route.query.outTradeNo
|
||||
return String(Array.isArray(raw) ? raw[0] : (raw ?? '')).trim()
|
||||
})
|
||||
|
||||
const ids = computed(() => {
|
||||
const raw = route.query.ids
|
||||
const text = Array.isArray(raw) ? raw.join(',') : String(raw ?? '')
|
||||
const list = text.split(',').map((id) => id.trim()).filter(Boolean)
|
||||
return list.length > 0 ? list : [billId.value]
|
||||
})
|
||||
|
||||
const methodLabel = computed(() => {
|
||||
if (!result.value) return '—'
|
||||
return result.value.method === 'wechat' ? '微信支付' : '支付宝支付'
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
void financeStore.fetchResult(billId.value, requirementId.value)
|
||||
void financeStore.fetchResult(outTradeNo.value, ids.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,62 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { AppButton, QrCodePanel } from '@/components'
|
||||
import { usePayPoll } from '@/composables/usePayPoll'
|
||||
import { useFinanceStore } from '@/stores/modules/finance'
|
||||
import type { PayMethod } from '@/types/business/finance'
|
||||
import { formatMoney } from '@/utils/format'
|
||||
import PayMethodDialog from './cpns/PayMethodDialog.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const financeStore = useFinanceStore()
|
||||
const { payment, currentBill } = storeToRefs(financeStore)
|
||||
const { payment, currentBill, payOrder } = storeToRefs(financeStore)
|
||||
const { start: startPoll, stop: stopPoll, check } = usePayPoll(onPaySuccess)
|
||||
|
||||
const billId = computed(() => String(route.params.id))
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const methodLabel = '支付宝支付'
|
||||
|
||||
const method = computed<PayMethod>(() => payment.value?.method ?? 'wechat')
|
||||
|
||||
const methodLabel = computed(() => (method.value === 'wechat' ? '微信支付' : '支付宝支付'))
|
||||
|
||||
const steps = computed<string[]>(() =>
|
||||
method.value === 'wechat'
|
||||
? [
|
||||
'打开手机微信',
|
||||
'扫描左侧二维码',
|
||||
'输入支付密码完成支付,本页将自动跳转至支付结果页',
|
||||
]
|
||||
: [
|
||||
const steps = [
|
||||
'打开手机支付宝',
|
||||
'对准屏幕上方的二维码进行扫描,核对金额后确认支付',
|
||||
'输入支付密码完成支付',
|
||||
],
|
||||
)
|
||||
'输入支付密码完成支付,本页将自动跳转至支付结果页',
|
||||
]
|
||||
|
||||
function onRefresh(): void {
|
||||
void financeStore.switchPaymentMethod(billId.value, method.value)
|
||||
ElMessage.success('二维码已刷新')
|
||||
function onPaySuccess(outTradeNo: string): void {
|
||||
void router.push({
|
||||
path: `/finance/bills/${billId.value}/pay/result`,
|
||||
query: { outTradeNo, ids: billId.value },
|
||||
})
|
||||
}
|
||||
|
||||
function onConfirmMethod(next: PayMethod): void {
|
||||
void financeStore.switchPaymentMethod(billId.value, next)
|
||||
ElMessage.success('二维码已刷新')
|
||||
async function onCheckPaid(): Promise<void> {
|
||||
const outTradeNo = financeStore.payOutTradeNo
|
||||
if (!outTradeNo) return
|
||||
const done = await check(outTradeNo)
|
||||
if (!done) ElMessage.warning('支付结果确认中,请稍后再试')
|
||||
}
|
||||
|
||||
async function onPaid(): Promise<void> {
|
||||
await financeStore.createPayment(billId.value, method.value)
|
||||
void router.push(`/finance/bills/${billId.value}/pay/result`)
|
||||
async function initPayment(): Promise<void> {
|
||||
await financeStore.fetchDetail(billId.value)
|
||||
if (currentBill.value?.status !== '待支付') return
|
||||
await financeStore.createPayment(billId.value, 'alipay')
|
||||
const outTradeNo = financeStore.payOutTradeNo
|
||||
if (outTradeNo) startPoll(outTradeNo)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([
|
||||
financeStore.createPayment(billId.value, 'wechat'),
|
||||
financeStore.fetchDetail(billId.value),
|
||||
])
|
||||
void initPayment()
|
||||
})
|
||||
|
||||
onBeforeUnmount(stopPoll)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -77,11 +71,8 @@ onMounted(() => {
|
||||
<section class="pay__left">
|
||||
<div class="pay__left-top">
|
||||
<p class="pay__method">
|
||||
{{ methodLabel }} · 请使用手机微信 <strong>[扫一扫]</strong> 扫描下方二维码完成支付
|
||||
{{ methodLabel }} · 请使用手机支付宝 <strong>[扫一扫]</strong> 扫描下方二维码完成支付
|
||||
</p>
|
||||
<AppButton class="pay__switch" @click="dialogVisible = true">
|
||||
切换支付方式
|
||||
</AppButton>
|
||||
</div>
|
||||
|
||||
<div class="pay__amount-block">
|
||||
@@ -92,8 +83,8 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<QrCodePanel
|
||||
:expires-in="payment?.qrExpiresInSeconds ?? 300"
|
||||
@refresh="onRefresh"
|
||||
:content="payOrder?.qrCode ?? ''"
|
||||
:countdown="false"
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -141,19 +132,13 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<div class="pay__footer">
|
||||
<AppButton type="primary" size="lg" @click="onPaid">
|
||||
完成支付
|
||||
<AppButton type="primary" size="lg" @click="onCheckPaid">
|
||||
我已完成支付
|
||||
</AppButton>
|
||||
<AppButton @click="router.push('/finance/bills')">
|
||||
返回
|
||||
</AppButton>
|
||||
</div>
|
||||
|
||||
<PayMethodDialog
|
||||
v-model:visible="dialogVisible"
|
||||
:method="method"
|
||||
@confirm="onConfirmMethod"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ElMessage } from 'element-plus'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { PageHead } from '@/components'
|
||||
import { useMessageStore } from '@/stores/modules/message'
|
||||
import type { MessageApiType } from '@/types/business/message'
|
||||
import { formatFileSize } from '@/utils/format'
|
||||
|
||||
const route = useRoute()
|
||||
@@ -13,9 +14,14 @@ const messageStore = useMessageStore()
|
||||
|
||||
const item = computed(() => messageStore.current)
|
||||
const messageId = computed(() => String(route.params.id))
|
||||
// 详情接口要求 id + type,列表跳转时通过 query 携带
|
||||
const messageType = computed<MessageApiType>(() => {
|
||||
const raw = String(route.query.type ?? '')
|
||||
return raw === 'cs' || raw === 'status' || raw === 'system' ? raw : 'status'
|
||||
})
|
||||
|
||||
function load(): void {
|
||||
void messageStore.fetchDetail(messageId.value)
|
||||
void messageStore.fetchDetail(messageId.value, messageType.value)
|
||||
}
|
||||
|
||||
function onBack(): void {
|
||||
@@ -30,7 +36,7 @@ function onDownload(): void {
|
||||
ElMessage.info('附件待接口接入')
|
||||
}
|
||||
|
||||
watch(messageId, load)
|
||||
watch([messageId, messageType], load)
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ElButton, ElInput } from 'element-plus'
|
||||
import { PageHead, PaginationBar } from '@/components'
|
||||
import { useMessageStore } from '@/stores/modules/message'
|
||||
import type { Message, MessageType } from '@/types/business/message'
|
||||
import { toMessageApiType } from '@/utils/messageVo'
|
||||
import MessageTabs from './cpns/MessageTabs.vue'
|
||||
import MessageList from './cpns/MessageList.vue'
|
||||
|
||||
@@ -41,7 +42,11 @@ function onView(message: Message): void {
|
||||
void router.push('/service')
|
||||
return
|
||||
}
|
||||
void router.push(`/message/${message.id}`)
|
||||
// 详情接口需要 type,随路由带上,刷新/直链时仍可查询
|
||||
void router.push({
|
||||
path: `/message/${message.id}`,
|
||||
query: { type: toMessageApiType(message.type) },
|
||||
})
|
||||
}
|
||||
|
||||
function onMarkAllRead(): void {
|
||||
|
||||
@@ -1,47 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import { useCountDown } from '@/composables/useCountDown'
|
||||
import { isEmail } from '@/utils/validate'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const profileStore = useProfileStore()
|
||||
const { profile } = storeToRefs(profileStore)
|
||||
|
||||
const hasEmail = computed(() => Boolean(profile.value?.email))
|
||||
const hasEmail = computed(
|
||||
() => profile.value?.emailBound ?? Boolean(profile.value?.email),
|
||||
)
|
||||
const boundEmailText = computed(
|
||||
() => profile.value?.email || profile.value?.maskedEmail || '',
|
||||
)
|
||||
|
||||
const email = ref('')
|
||||
const code = ref('')
|
||||
|
||||
const { seconds, isCounting, start } = useCountDown(60)
|
||||
|
||||
function onGetCode(): void {
|
||||
if (!hasEmail.value && !email.value) {
|
||||
const targetEmail = computed(() => email.value.trim())
|
||||
|
||||
async function onGetCode(): Promise<void> {
|
||||
if (!targetEmail.value) {
|
||||
ElMessage.warning('请输入新邮箱')
|
||||
return
|
||||
}
|
||||
if (!isEmail(targetEmail.value)) {
|
||||
ElMessage.warning('邮箱格式不正确')
|
||||
return
|
||||
}
|
||||
try {
|
||||
// 验证码发到目标(新)邮箱
|
||||
await profileStore.sendBindEmailCode(targetEmail.value)
|
||||
start(60)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
function onBind(): void {
|
||||
if (!hasEmail.value && !email.value) {
|
||||
if (!targetEmail.value) {
|
||||
ElMessage.warning('请输入新邮箱')
|
||||
return
|
||||
}
|
||||
if (!isEmail(targetEmail.value)) {
|
||||
ElMessage.warning('邮箱格式不正确')
|
||||
return
|
||||
}
|
||||
if (!code.value) {
|
||||
ElMessage.warning('请输入验证码')
|
||||
return
|
||||
}
|
||||
// 换绑态设计稿无新邮箱输入框(#43),按现状提交当前邮箱 + 验证码
|
||||
const target = hasEmail.value ? profile.value?.email ?? '' : email.value
|
||||
void profileStore.bindEmail(target, code.value).then(() => {
|
||||
void router.push('/profile/security')
|
||||
void profileStore.bindEmail(targetEmail.value, code.value).then(() => {
|
||||
goBack()
|
||||
})
|
||||
}
|
||||
|
||||
/** 从其他页面带着 redirect 跳转过来时,绑定成功后回到来源页。 */
|
||||
function goBack(): void {
|
||||
const redirect = route.query.redirect
|
||||
if (typeof redirect === 'string' && redirect) {
|
||||
void router.replace(redirect)
|
||||
return
|
||||
}
|
||||
void router.push('/profile/security')
|
||||
}
|
||||
|
||||
function onUnbind(): void {
|
||||
void profileStore.unbindEmail().then(() => {
|
||||
void router.push('/profile/security')
|
||||
@@ -57,20 +87,12 @@ function onUnbind(): void {
|
||||
|
||||
<form class="bind-email-page__form" @submit.prevent="onBind">
|
||||
<div class="bind-email-page__field">
|
||||
<label class="bind-email-page__label">{{ hasEmail ? '邮箱' : '新邮箱' }}</label>
|
||||
<label class="bind-email-page__label">{{ hasEmail ? '新邮箱' : '邮箱' }}</label>
|
||||
<input
|
||||
v-if="hasEmail"
|
||||
class="bind-email-page__input bind-email-page__input--disabled"
|
||||
type="text"
|
||||
:value="profile?.email ?? ''"
|
||||
readonly
|
||||
>
|
||||
<input
|
||||
v-else
|
||||
v-model="email"
|
||||
class="bind-email-page__input"
|
||||
type="text"
|
||||
placeholder="请输入新邮箱"
|
||||
:placeholder="hasEmail ? `当前绑定 ${boundEmailText}` : '请输入新邮箱'"
|
||||
maxlength="50"
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -5,39 +5,58 @@ import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import { useCountDown } from '@/composables/useCountDown'
|
||||
import { isPhone } from '@/utils/validate'
|
||||
|
||||
const router = useRouter()
|
||||
const profileStore = useProfileStore()
|
||||
const { profile } = storeToRefs(profileStore)
|
||||
|
||||
const hasPhone = computed(() => Boolean(profile.value?.phone))
|
||||
const hasPhone = computed(
|
||||
() => profile.value?.phoneBound ?? Boolean(profile.value?.phone),
|
||||
)
|
||||
const boundPhoneText = computed(
|
||||
() => profile.value?.phone || profile.value?.maskedPhone || '',
|
||||
)
|
||||
|
||||
const phone = ref('')
|
||||
const code = ref('')
|
||||
|
||||
const { seconds, isCounting, start } = useCountDown(60)
|
||||
|
||||
function onGetCode(): void {
|
||||
const target = hasPhone.value ? profile.value?.phone : phone.value
|
||||
if (!target) {
|
||||
ElMessage.warning('请输入手机号')
|
||||
const targetPhone = computed(() => phone.value.trim())
|
||||
|
||||
async function onGetCode(): Promise<void> {
|
||||
if (!targetPhone.value) {
|
||||
ElMessage.warning(hasPhone.value ? '请输入新手机号' : '请输入手机号')
|
||||
return
|
||||
}
|
||||
if (!isPhone(targetPhone.value)) {
|
||||
ElMessage.warning('手机号格式不正确')
|
||||
return
|
||||
}
|
||||
try {
|
||||
// 已绑定手机号时,验证码发到新手机号
|
||||
await profileStore.sendBindSmsCode(targetPhone.value)
|
||||
start(60)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
function onSubmit(): void {
|
||||
const target = hasPhone.value ? profile.value?.phone : phone.value
|
||||
if (!target) {
|
||||
ElMessage.warning('请输入手机号')
|
||||
if (!targetPhone.value) {
|
||||
ElMessage.warning(hasPhone.value ? '请输入新手机号' : '请输入手机号')
|
||||
return
|
||||
}
|
||||
if (!isPhone(targetPhone.value)) {
|
||||
ElMessage.warning('手机号格式不正确')
|
||||
return
|
||||
}
|
||||
if (!code.value) {
|
||||
ElMessage.warning('请输入验证码')
|
||||
return
|
||||
}
|
||||
void profileStore.bindPhone(target, code.value).then(() => {
|
||||
void profileStore.bindPhone(targetPhone.value, code.value).then(() => {
|
||||
void router.push('/profile/security')
|
||||
})
|
||||
}
|
||||
@@ -51,20 +70,12 @@ function onSubmit(): void {
|
||||
|
||||
<form class="bind-phone-page__form" @submit.prevent="onSubmit">
|
||||
<div class="bind-phone-page__field">
|
||||
<label class="bind-phone-page__label">手机号</label>
|
||||
<label class="bind-phone-page__label">{{ hasPhone ? '新手机号' : '手机号' }}</label>
|
||||
<input
|
||||
v-if="hasPhone"
|
||||
class="bind-phone-page__input bind-phone-page__input--disabled"
|
||||
type="text"
|
||||
:value="profile?.phone ?? ''"
|
||||
readonly
|
||||
>
|
||||
<input
|
||||
v-else
|
||||
v-model="phone"
|
||||
class="bind-phone-page__input"
|
||||
type="text"
|
||||
placeholder="请输入手机号"
|
||||
:placeholder="hasPhone ? `当前绑定 ${boundPhoneText}` : '请输入手机号'"
|
||||
maxlength="20"
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
@@ -12,26 +12,32 @@ const router = useRouter()
|
||||
const profileStore = useProfileStore()
|
||||
const { profile } = storeToRefs(profileStore)
|
||||
|
||||
const phone = ref('')
|
||||
const code = ref('')
|
||||
const password = ref('')
|
||||
const confirm = ref('')
|
||||
const agree = ref(false)
|
||||
|
||||
// 后端固定使用账号绑定手机号,页面只读展示
|
||||
const boundPhone = computed(() => profile.value?.phone ?? '')
|
||||
|
||||
const { seconds, isCounting, start } = useCountDown(60)
|
||||
|
||||
function onGetCode(): void {
|
||||
if (!phone.value) {
|
||||
ElMessage.warning('请输入手机号')
|
||||
async function onGetCode(): Promise<void> {
|
||||
if (!boundPhone.value) {
|
||||
ElMessage.warning('当前账号未绑定手机号,无法通过短信验证修改密码')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await profileStore.sendBindSmsCode(boundPhone.value)
|
||||
start(60)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
function onSubmit(): void {
|
||||
if (!phone.value) {
|
||||
ElMessage.warning('请输入手机号')
|
||||
if (!boundPhone.value) {
|
||||
ElMessage.warning('当前账号未绑定手机号,无法通过短信验证修改密码')
|
||||
return
|
||||
}
|
||||
if (!code.value) {
|
||||
@@ -70,11 +76,10 @@ function onSubmit(): void {
|
||||
<div class="change-pwd-page__field">
|
||||
<label class="change-pwd-page__label">手机号</label>
|
||||
<input
|
||||
v-model="phone"
|
||||
class="change-pwd-page__input"
|
||||
class="change-pwd-page__input change-pwd-page__input--readonly"
|
||||
type="text"
|
||||
:placeholder="profile?.phone ?? '请输入手机号'"
|
||||
maxlength="20"
|
||||
:value="boundPhone || '未绑定'"
|
||||
readonly
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -201,6 +206,13 @@ function onSubmit(): void {
|
||||
&::placeholder {
|
||||
color: @finance-axis-text;
|
||||
}
|
||||
|
||||
&--readonly {
|
||||
border-color: transparent;
|
||||
background: @profile-input-disabled-bg;
|
||||
color: @finance-muted-text;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
&__code {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import type { Feedback } from '@/types/business/profile'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
|
||||
interface Props {
|
||||
resetSignal?: number
|
||||
@@ -15,6 +16,8 @@ const emit = defineEmits<{
|
||||
preview: [file: FileInfo]
|
||||
}>()
|
||||
|
||||
const profileStore = useProfileStore()
|
||||
|
||||
const form = reactive({
|
||||
title: '',
|
||||
description: '',
|
||||
@@ -22,6 +25,7 @@ const form = reactive({
|
||||
|
||||
const attachments = reactive<FileInfo[]>([])
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
const uploading = ref(false)
|
||||
|
||||
function clear(): void {
|
||||
form.title = ''
|
||||
@@ -38,19 +42,25 @@ function openFilePicker(): void {
|
||||
fileInputRef.value?.click()
|
||||
}
|
||||
|
||||
function onFileChange(event: Event): void {
|
||||
async function onFileChange(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement
|
||||
const files = input.files
|
||||
if (!files) return
|
||||
uploading.value = true
|
||||
try {
|
||||
for (const file of Array.from(files)) {
|
||||
attachments.push({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
uploadTime: new Date().toISOString().slice(0, 10),
|
||||
url: '',
|
||||
})
|
||||
try {
|
||||
// 先上传拿地址,提交反馈时 attachments 才有内容
|
||||
attachments.push(await profileStore.uploadAttachment(file))
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
uploading.value = false
|
||||
input.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function extOf(name: string): string {
|
||||
@@ -119,14 +129,20 @@ function onSubmit(): void {
|
||||
附件上传
|
||||
</h3>
|
||||
<span class="feedback-form__attach-hint">支持图片/文档/压缩包,大小不超过1G</span>
|
||||
<button class="feedback-form__upload-btn" @click="openFilePicker">
|
||||
上传
|
||||
<button
|
||||
type="button"
|
||||
class="feedback-form__upload-btn"
|
||||
:disabled="uploading"
|
||||
@click="openFilePicker"
|
||||
>
|
||||
{{ uploading ? '上传中…' : '上传' }}
|
||||
</button>
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
class="feedback-form__file-input"
|
||||
type="file"
|
||||
multiple
|
||||
:disabled="uploading"
|
||||
@change="onFileChange"
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,7 @@ const menus: MenuItem[] = [
|
||||
{ to: '/profile/address', label: '地址管理' },
|
||||
{ to: '/favorites', label: '收藏列表' },
|
||||
{ to: '/profile/qualifications', label: '资质列表' },
|
||||
{ to: '/message', label: '消息中心' },
|
||||
{ to: '/profile/feedback', label: '意见反馈' },
|
||||
{ to: '/profile/help', label: '帮助中心' },
|
||||
{ to: '/profile/about', label: '关于我们' },
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import type { Profile } from '@/types/business/profile'
|
||||
|
||||
interface Props {
|
||||
@@ -8,9 +10,45 @@ interface Props {
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{ saveNickname: [name: string] }>()
|
||||
const emit = defineEmits<{
|
||||
saveNickname: [name: string]
|
||||
saveAvatar: [url: string]
|
||||
}>()
|
||||
|
||||
const profileStore = useProfileStore()
|
||||
|
||||
const draft = ref('')
|
||||
const avatarInputRef = ref<HTMLInputElement | null>(null)
|
||||
const uploadingAvatar = ref(false)
|
||||
|
||||
const avatarInitial = computed(() => (props.profile?.nickname ?? '').trim().charAt(0) || '用')
|
||||
|
||||
function pickAvatar(): void {
|
||||
if (uploadingAvatar.value) return
|
||||
avatarInputRef.value?.click()
|
||||
}
|
||||
|
||||
async function onAvatarChange(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
if (!file.type.startsWith('image/')) {
|
||||
ElMessage.warning('请选择图片文件')
|
||||
return
|
||||
}
|
||||
uploadingAvatar.value = true
|
||||
try {
|
||||
// /web/profile/upload 拿 url,再更新资料里的 avatar
|
||||
const info = await profileStore.uploadAttachment(file)
|
||||
if (info.url) emit('saveAvatar', info.url)
|
||||
}
|
||||
catch {
|
||||
}
|
||||
finally {
|
||||
uploadingAvatar.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.profile?.nickname,
|
||||
@@ -29,9 +67,23 @@ function save(): void {
|
||||
|
||||
<template>
|
||||
<div class="profile-user-card">
|
||||
<div class="profile-user-card__avatar" aria-hidden="true">
|
||||
王
|
||||
<div
|
||||
class="profile-user-card__avatar"
|
||||
:class="{ 'is-uploading': uploadingAvatar }"
|
||||
title="点击更换头像"
|
||||
@click="pickAvatar"
|
||||
>
|
||||
<img v-if="profile?.avatar" :src="profile.avatar" alt="头像">
|
||||
<span v-else>{{ avatarInitial }}</span>
|
||||
<span v-if="uploadingAvatar" class="profile-user-card__avatar-mask">…</span>
|
||||
</div>
|
||||
<input
|
||||
ref="avatarInputRef"
|
||||
class="profile-user-card__file"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
@change="onAvatarChange"
|
||||
>
|
||||
<input
|
||||
v-model="draft"
|
||||
class="profile-user-card__name"
|
||||
@@ -57,6 +109,7 @@ function save(): void {
|
||||
|
||||
&__avatar {
|
||||
.flex(row, center);
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
@@ -65,6 +118,31 @@ function save(): void {
|
||||
color: @white;
|
||||
font-size: @font-size-lg;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
&.is-uploading {
|
||||
cursor: wait;
|
||||
}
|
||||
}
|
||||
|
||||
&__avatar-mask {
|
||||
.flex(row, center);
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: fade(@black, 40%);
|
||||
color: @white;
|
||||
font-size: @font-size-sm;
|
||||
}
|
||||
|
||||
&__file {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&__name {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from 'vue'
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { AppButton, FileList, UploadArea } from '@/components'
|
||||
import { useOssStore } from '@/stores/modules/oss'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import type { FileInfo } from '@/types/api'
|
||||
import { saveBlobAsFile } from '@/utils/download'
|
||||
import type { Qualification, QualificationInput, QualificationType } from '@/types/business/profile'
|
||||
|
||||
interface Props {
|
||||
@@ -13,6 +15,7 @@ interface Props {
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const ossStore = useOssStore()
|
||||
const profileStore = useProfileStore()
|
||||
|
||||
const visible = defineModel<boolean>('visible', { default: false })
|
||||
|
||||
@@ -37,6 +40,7 @@ const form = reactive({
|
||||
})
|
||||
|
||||
const attachments = reactive<FileInfo[]>([])
|
||||
const uploading = ref(false)
|
||||
|
||||
watch(visible, (open) => {
|
||||
if (!open) return
|
||||
@@ -49,19 +53,53 @@ watch(visible, (open) => {
|
||||
attachments.splice(0, attachments.length, ...(props.qualification?.attachments ?? []))
|
||||
})
|
||||
|
||||
function onUpload(file: File): void {
|
||||
attachments.push({
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
uploadTime: new Date().toISOString().slice(0, 10),
|
||||
url: '',
|
||||
})
|
||||
async function onUpload(file: File): Promise<void> {
|
||||
if (uploading.value) return
|
||||
uploading.value = true
|
||||
try {
|
||||
// 先走 /web/profile/upload 拿到可访问地址,再随资质一起提交
|
||||
attachments.push(await profileStore.uploadAttachment(file))
|
||||
}
|
||||
catch {
|
||||
}
|
||||
finally {
|
||||
uploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onPreview(file: FileInfo): void {
|
||||
ossStore.openPreview(file)
|
||||
}
|
||||
|
||||
async function onDownload(file: FileInfo): Promise<void> {
|
||||
try {
|
||||
// 已保存的附件走资质下载接口,刚上传未保存的附件走 OSS 下载
|
||||
if (file.ossId === undefined || file.ossId === null) {
|
||||
const id = props.qualification?.id
|
||||
if (!id) {
|
||||
ElMessage.warning('附件尚未保存,无法下载')
|
||||
return
|
||||
}
|
||||
const index = props.qualification?.attachments.findIndex((item) => item.url === file.url) ?? 0
|
||||
const { blob, fileName } = await profileStore.fetchQualificationAttachment(
|
||||
id,
|
||||
Math.max(index, 0),
|
||||
)
|
||||
saveBlobAsFile(blob, fileName || file.name || '资质附件')
|
||||
return
|
||||
}
|
||||
|
||||
const blob = await ossStore.fetchDownloadBlob(file.ossId)
|
||||
saveBlobAsFile(blob, file.name || '资质附件')
|
||||
}
|
||||
catch (error) {
|
||||
// 网络异常已由 request.ts 统一提示,这里只提示接口返回的业务错误
|
||||
if (error instanceof Error && !('isAxiosError' in error)) {
|
||||
ElMessage.error(error.message || '下载失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onDeleteFile(file: FileInfo): void {
|
||||
const index = attachments.indexOf(file)
|
||||
if (index >= 0) attachments.splice(index, 1)
|
||||
@@ -160,11 +198,12 @@ function onSave(): void {
|
||||
</div>
|
||||
|
||||
<div class="qual-dialog__field">
|
||||
<label class="qual-dialog__label">附件</label>
|
||||
<UploadArea @upload="onUpload" />
|
||||
<label class="qual-dialog__label">附件{{ uploading ? '(上传中…)' : '' }}</label>
|
||||
<UploadArea :disabled="uploading" @upload="onUpload" />
|
||||
<FileList
|
||||
:files="attachments"
|
||||
@preview="onPreview"
|
||||
@download="onDownload"
|
||||
@delete="onDeleteFile"
|
||||
/>
|
||||
</div>
|
||||
@@ -173,7 +212,7 @@ function onSave(): void {
|
||||
<AppButton type="default" @click="visible = false">
|
||||
取消
|
||||
</AppButton>
|
||||
<AppButton type="primary" @click="onSave">
|
||||
<AppButton type="primary" :disabled="uploading" @click="onSave">
|
||||
保存
|
||||
</AppButton>
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,21 @@ const props = defineProps<Props>()
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const hasEmail = computed(() => Boolean(props.profile?.email))
|
||||
const hasPassword = computed(() => props.profile?.passwordSet ?? false)
|
||||
const hasPhone = computed(
|
||||
() => props.profile?.phoneBound ?? Boolean(props.profile?.phone),
|
||||
)
|
||||
const hasEmail = computed(
|
||||
() => props.profile?.emailBound ?? Boolean(props.profile?.email),
|
||||
)
|
||||
|
||||
// 安全接口只返回掩码手机/邮箱,完整值优先;没有完整值时展示掩码
|
||||
const phoneText = computed(
|
||||
() => props.profile?.phone || props.profile?.maskedPhone || '未绑定手机',
|
||||
)
|
||||
const emailText = computed(
|
||||
() => props.profile?.email || props.profile?.maskedEmail || '',
|
||||
)
|
||||
|
||||
function goChangePassword(): void {
|
||||
void router.push('/profile/security/change-password')
|
||||
@@ -51,10 +65,13 @@ function goDeleteAccount(): void {
|
||||
修改密码
|
||||
</h3>
|
||||
<p class="security-panel__sub">
|
||||
上次修改:{{ profile?.passwordModifiedAt }}
|
||||
上次修改:{{ profile?.passwordModifiedAt || '暂无记录' }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="security-panel__state">已设置</span>
|
||||
<span
|
||||
class="security-panel__state"
|
||||
:class="{ 'security-panel__state--idle': !hasPassword }"
|
||||
>{{ hasPassword ? '已设置' : '未设置' }}</span>
|
||||
<span class="security-panel__arrow" aria-hidden="true">›</span>
|
||||
</section>
|
||||
|
||||
@@ -73,10 +90,13 @@ function goDeleteAccount(): void {
|
||||
绑定手机
|
||||
</h3>
|
||||
<p class="security-panel__sub">
|
||||
{{ profile?.phone ?? '' }}
|
||||
{{ hasPhone ? phoneText : '未绑定手机' }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="security-panel__state">已绑定</span>
|
||||
<span
|
||||
class="security-panel__state"
|
||||
:class="{ 'security-panel__state--idle': !hasPhone }"
|
||||
>{{ hasPhone ? '已绑定' : '未绑定' }}</span>
|
||||
<span class="security-panel__arrow" aria-hidden="true">›</span>
|
||||
</section>
|
||||
|
||||
@@ -95,7 +115,7 @@ function goDeleteAccount(): void {
|
||||
绑定邮箱
|
||||
</h3>
|
||||
<p class="security-panel__sub">
|
||||
{{ hasEmail ? profile?.email : '未绑定邮箱' }}
|
||||
{{ hasEmail ? emailText : '未绑定邮箱' }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
|
||||
@@ -58,10 +58,19 @@ const maskedPhone = computed(() => {
|
||||
|
||||
const { seconds, isCounting, start } = useCountDown(60)
|
||||
|
||||
function onGetCode(): void {
|
||||
async function onGetCode(): Promise<void> {
|
||||
if (isCounting.value) return
|
||||
const phone = profile.value?.phone ?? ''
|
||||
if (!phone) {
|
||||
ElMessage.warning('当前账号未绑定手机号,无法注销')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await profileStore.sendBindSmsCode(phone)
|
||||
start(60)
|
||||
ElMessage.success('验证码已发送')
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
function focusCode(): void {
|
||||
@@ -74,15 +83,18 @@ function onCodeInput(event: Event): void {
|
||||
}
|
||||
|
||||
function onDeleteAccount(): void {
|
||||
const phone = profile.value?.phone ?? ''
|
||||
if (!phone) {
|
||||
ElMessage.warning('当前账号未绑定手机号,无法注销')
|
||||
return
|
||||
}
|
||||
if (code.value.length !== 6) {
|
||||
ElMessage.warning('请输入 6 位验证码')
|
||||
return
|
||||
}
|
||||
void (async () => {
|
||||
await profileStore.verifyIdentity(profile.value?.phone ?? '', code.value)
|
||||
await profileStore.deleteAccount()
|
||||
void profileStore.deleteAccount(phone, code.value).then(() => {
|
||||
void router.push('/login')
|
||||
})()
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ function onSaveNickname(name: string): void {
|
||||
void profileStore.saveNickname(name)
|
||||
}
|
||||
|
||||
function onSaveAvatar(url: string): void {
|
||||
void profileStore.saveAvatar(url)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void profileStore.fetchProfile()
|
||||
})
|
||||
@@ -23,7 +27,11 @@ onMounted(() => {
|
||||
<div class="profile__container container">
|
||||
<div class="profile__body">
|
||||
<aside class="profile__aside">
|
||||
<ProfileUserCard :profile="profile" @save-nickname="onSaveNickname" />
|
||||
<ProfileUserCard
|
||||
:profile="profile"
|
||||
@save-nickname="onSaveNickname"
|
||||
@save-avatar="onSaveAvatar"
|
||||
/>
|
||||
<ProfileSider />
|
||||
</aside>
|
||||
<main class="profile__main">
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ConfirmDialog, PaginationBar } from '@/components'
|
||||
import { useProfileStore } from '@/stores/modules/profile'
|
||||
import type { Qualification, QualificationInput } from '@/types/business/profile'
|
||||
@@ -47,8 +46,10 @@ function onDeleteConfirm(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function onReupload(): void {
|
||||
ElMessage.info('请在编辑中重新上传附件')
|
||||
function onReupload(item: Qualification): void {
|
||||
// 未通过时重新打开编辑弹窗,替换附件后重新提交
|
||||
editing.value = item
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
function onPageChange(page: number): void {
|
||||
|
||||
@@ -1,21 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ChatFile } from '@/types/business/service'
|
||||
import { formatFileSize } from '@/utils/format'
|
||||
|
||||
interface FilePayload {
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
file: FilePayload
|
||||
file: ChatFile
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
const props = defineProps<Props>()
|
||||
|
||||
function extOf(name: string): string {
|
||||
const idx = name.lastIndexOf('.')
|
||||
return idx > -1 ? name.slice(idx + 1).toUpperCase() : 'FILE'
|
||||
}
|
||||
|
||||
async function onDownload(): Promise<void> {
|
||||
const url = props.file.url
|
||||
if (!url) {
|
||||
ElMessage.warning('文件地址缺失,无法下载')
|
||||
return
|
||||
}
|
||||
try {
|
||||
// 先取 blob 再触发下载,避免浏览器直接打开文件预览
|
||||
const resp = await fetch(url)
|
||||
if (!resp.ok) throw new Error('下载失败')
|
||||
const blob = await resp.blob()
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = objectUrl
|
||||
link.download = props.file.name
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
catch {
|
||||
// 跨域导致 fetch 失败时退回新窗口打开,由浏览器决定下载/预览
|
||||
window.open(url, '_blank', 'noopener')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -25,6 +48,29 @@ function extOf(name: string): string {
|
||||
<span class="chat-file-card__name" :title="file.name">{{ file.name }}</span>
|
||||
<span class="chat-file-card__size">{{ formatFileSize(file.size) }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="chat-file-card__download"
|
||||
title="下载到本地"
|
||||
aria-label="下载到本地"
|
||||
@click="onDownload"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 16 16"
|
||||
width="16"
|
||||
height="16"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M8 2v7m0 0 3-3m-3 3L5 6M3 11v2.5h10V11"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -73,5 +119,25 @@ function extOf(name: string): string {
|
||||
line-height: 1.4;
|
||||
color: @text-color-secondary;
|
||||
}
|
||||
|
||||
&__download {
|
||||
.flex(row, center);
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 1px solid @primary-strong;
|
||||
border-radius: @radius-round;
|
||||
background: @white;
|
||||
color: @primary-strong;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: @primary-strong;
|
||||
color: @white;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -5,7 +5,6 @@ import { ElMessage } from 'element-plus'
|
||||
const MAX_FILE_SIZE = 1024 * 1024 * 1024
|
||||
|
||||
const content = ref('')
|
||||
const fileRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const emit = defineEmits<{
|
||||
send: [content: string]
|
||||
@@ -27,10 +26,6 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
}
|
||||
}
|
||||
|
||||
function onPickFile(): void {
|
||||
fileRef.value?.click()
|
||||
}
|
||||
|
||||
function onFileChange(event: Event): void {
|
||||
const target = event.target
|
||||
if (!(target instanceof HTMLInputElement)) return
|
||||
@@ -56,17 +51,16 @@ function onFileChange(event: Event): void {
|
||||
/>
|
||||
<div class="chat-input__bar">
|
||||
<div class="chat-input__tools">
|
||||
<button
|
||||
<!-- <button
|
||||
type="button"
|
||||
class="chat-input__attach"
|
||||
@click="onPickFile"
|
||||
>
|
||||
附件
|
||||
</button>
|
||||
<span class="chat-input__hint">Enter 发送</span>
|
||||
</button> -->
|
||||
<span class="chat-input__hint">按Enter发送|支持拖拽上传文件</span>
|
||||
</div>
|
||||
<input
|
||||
ref="fileRef"
|
||||
type="file"
|
||||
class="chat-input__file"
|
||||
@change="onFileChange"
|
||||
|
||||
@@ -19,15 +19,17 @@ withDefaults(defineProps<Props>(), { unread: false })
|
||||
|
||||
<div class="chat-message-item__main">
|
||||
<div class="chat-message-item__bubble">
|
||||
<span v-if="unread" class="chat-message-item__unread">未读</span>
|
||||
<ChatFileCard
|
||||
v-if="message.file"
|
||||
:file="message.file"
|
||||
/>
|
||||
<template v-else>{{ message.content }}</template>
|
||||
</div>
|
||||
<div class="chat-message-item__meta">
|
||||
<span v-if="unread" class="chat-message-item__unread">未读</span>
|
||||
<span class="chat-message-item__time">{{ message.time }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span v-if="message.role === 'user'" class="chat-message-item__avatar chat-message-item__avatar--user">我</span>
|
||||
</div>
|
||||
@@ -81,6 +83,11 @@ withDefaults(defineProps<Props>(), { unread: false })
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
&__meta {
|
||||
.flex(row, flex-start, center);
|
||||
gap: @spacing-xs;
|
||||
}
|
||||
|
||||
&__time {
|
||||
font-size: @font-size-xs;
|
||||
line-height: 1.4;
|
||||
@@ -88,9 +95,7 @@ withDefaults(defineProps<Props>(), { unread: false })
|
||||
}
|
||||
|
||||
&__unread {
|
||||
position: absolute;
|
||||
top: calc(100% + @spacing-xs);
|
||||
left: 0;
|
||||
flex-shrink: 0;
|
||||
color: @text-color-secondary;
|
||||
font-size: @font-size-xs;
|
||||
line-height: 1.4;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ChatMessage } from '@/types/business/service'
|
||||
import ChatMessageItem from './ChatMessageItem.vue'
|
||||
import ChatInput from './ChatInput.vue'
|
||||
@@ -13,10 +14,54 @@ const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
send: [content: string]
|
||||
sendFile: [file: File]
|
||||
sendFiles: [files: File[]]
|
||||
}>()
|
||||
|
||||
const MAX_FILE_SIZE = 1024 * 1024 * 1024
|
||||
|
||||
const scrollRef = ref<HTMLElement | null>(null)
|
||||
|
||||
// dragenter/dragleave 会在子元素间反复触发,用计数器判断是否仍在窗口内
|
||||
const dragDepth = ref(0)
|
||||
const dragging = computed(() => dragDepth.value > 0)
|
||||
|
||||
function hasFiles(event: DragEvent): boolean {
|
||||
return Array.from(event.dataTransfer?.types ?? []).includes('Files')
|
||||
}
|
||||
|
||||
function onDragEnter(event: DragEvent): void {
|
||||
if (!hasFiles(event)) return
|
||||
event.preventDefault()
|
||||
dragDepth.value += 1
|
||||
}
|
||||
|
||||
function onDragOver(event: DragEvent): void {
|
||||
if (!hasFiles(event)) return
|
||||
event.preventDefault()
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'
|
||||
}
|
||||
|
||||
function onDragLeave(event: DragEvent): void {
|
||||
if (!hasFiles(event)) return
|
||||
dragDepth.value = Math.max(0, dragDepth.value - 1)
|
||||
}
|
||||
|
||||
function onDrop(event: DragEvent): void {
|
||||
if (!hasFiles(event)) return
|
||||
event.preventDefault()
|
||||
dragDepth.value = 0
|
||||
const files = Array.from(event.dataTransfer?.files ?? [])
|
||||
const valid: File[] = []
|
||||
for (const file of files) {
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
ElMessage.warning(`「${file.name}」超过1G,未上传`)
|
||||
continue
|
||||
}
|
||||
valid.push(file)
|
||||
}
|
||||
if (valid.length > 0) emit('sendFiles', valid)
|
||||
}
|
||||
|
||||
function isUnread(index: number): boolean {
|
||||
const first = props.messages[0]
|
||||
return index === 0 && first?.role === 'assistant'
|
||||
@@ -35,7 +80,13 @@ watch(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="chat-window">
|
||||
<div
|
||||
class="chat-window"
|
||||
@dragenter="onDragEnter"
|
||||
@dragover="onDragOver"
|
||||
@dragleave="onDragLeave"
|
||||
@drop="onDrop"
|
||||
>
|
||||
<div class="chat-window__header">
|
||||
<span class="chat-window__header-avatar" aria-hidden="true">客</span>
|
||||
<div class="chat-window__header-meta">
|
||||
@@ -57,18 +108,53 @@ watch(
|
||||
</div>
|
||||
|
||||
<ChatInput @send="emit('send', $event)" @send-file="emit('sendFile', $event)" />
|
||||
|
||||
<Transition name="chat-drop">
|
||||
<div v-if="dragging" class="chat-window__drop">
|
||||
<span class="chat-window__drop-icon">⬆</span>
|
||||
<span>松开鼠标上传文件</span>
|
||||
<span class="chat-window__drop-hint">支持一次拖入多个文件,单个文件不超过 1G</span>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.chat-window {
|
||||
.flex(column, flex-start, stretch);
|
||||
position: relative;
|
||||
border: 1px solid @border-color;
|
||||
border-radius: @radius-base;
|
||||
background: @white;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
|
||||
&__drop {
|
||||
.flex(column, center, center);
|
||||
position: absolute;
|
||||
inset: 8px;
|
||||
z-index: 10;
|
||||
gap: @spacing-xs;
|
||||
border: 2px dashed @primary-strong;
|
||||
border-radius: @radius-base;
|
||||
background: fade(@white, 92%);
|
||||
color: @primary-strong;
|
||||
font-size: @font-size-base;
|
||||
font-weight: 500;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&__drop-icon {
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
&__drop-hint {
|
||||
font-size: @font-size-xs;
|
||||
font-weight: 400;
|
||||
color: @text-color-secondary;
|
||||
}
|
||||
|
||||
&__header {
|
||||
.flex(row, flex-start, center);
|
||||
gap: @spacing-base;
|
||||
@@ -142,4 +228,14 @@ watch(
|
||||
color: @text-color-secondary;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-drop-enter-active,
|
||||
.chat-drop-leave-active {
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.chat-drop-enter-from,
|
||||
.chat-drop-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<!-- 页面:在线客服(Service) -->
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { PageHead } from '@/components'
|
||||
import { useServiceStore } from '@/stores/modules/service'
|
||||
@@ -17,8 +17,24 @@ function onSendFile(file: File): void {
|
||||
void serviceStore.sendFile(file)
|
||||
}
|
||||
|
||||
async function onSendFiles(files: File[]): Promise<void> {
|
||||
// 逐个 await,复用已有的 sendFile,避免 store 热更新后旧实例缺少新 action
|
||||
for (const file of files) {
|
||||
try {
|
||||
await serviceStore.sendFile(file)
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void serviceStore.fetchHistory()
|
||||
serviceStore.startSync()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
serviceStore.stopSync()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -34,6 +50,7 @@ onMounted(() => {
|
||||
:messages="messages"
|
||||
@send="onSend"
|
||||
@send-file="onSendFile"
|
||||
@send-files="onSendFiles"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,8 +10,10 @@ export default defineConfig({
|
||||
host: true,
|
||||
proxy: {
|
||||
// 开发期把 /api 转发到 vermis-maker 后端(8080),并去掉 /api 前缀
|
||||
// 192.168.0.206
|
||||
// 192.168.0.175
|
||||
'/api': {
|
||||
target: 'http://192.168.0.43:8080',
|
||||
target: 'http://192.168.0.206:8080',
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/api/, ''),
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user