拆分订单详情结账逻辑

This commit is contained in:
yml
2026-06-09 22:07:55 +08:00
parent d68020db4e
commit 3bbe356c3f
9 changed files with 1445 additions and 1402 deletions
@@ -8,15 +8,26 @@ import QRCode from 'qrcode'
import { fetchOrderChat } from '@/features/chats/api/chats'
import { createDispute } from '@/features/disputes'
import { uploadFile } from '@/shared/api/files'
import { centToYuan, formatCent, formatMoney } from '@/shared/utils/money'
import { readError } from '@/shared/utils/error'
import { formatCent } from '@/shared/utils/money'
import {
acceptCheckout,
amountYuan,
cancelOrder,
confirmCheckout,
confirmReceive,
counterCheckout,
fetchHandoffRecords,
fetchOrder,
hydrateCounterFormFromCheckout,
linesToList,
money,
OrderCheckoutSummary,
OrderHandoffTimeline,
OrderResourceUsageEditor,
orderEstimatedEndAt as readOrderEstimatedEndAt,
orderRentAmount,
ownerActualIncome,
queryOrderPayment,
startOrderPayment,
submitCheckout,
@@ -24,6 +35,7 @@ import {
type HandoffRecord,
type Order,
type PaymentOrder,
useOrderCheckoutSnapshot,
} from '@/features/orders'
import { useSessionStore } from '@/stores/session'
import { handoffStatusLabel, orderStatusLabel } from '@/shared/utils/statusLabels'
@@ -84,9 +96,11 @@ let autoPayHandled = false
const isOwner = computed(() => order.value?.owner_id === session.userId)
const isRenter = computed(() => order.value?.renter_id === session.userId)
const orderAmountLabel = computed(() => (isOwner.value ? '预计租金' : '支付租金'))
const orderRentDisplayAmount = computed(() => (order.value ? orderRentAmount(order.value) : 0))
const orderRentDisplayAmount = computed(() =>
order.value ? orderRentAmount(order.value, session.userId) : 0
)
const ownerIncomeDisplayAmount = computed(() =>
order.value ? ownerActualIncome(order.value) : null
order.value ? ownerActualIncome(order.value, session.userId) : null
)
const ownerIncomeLabel = computed(() =>
order.value?.status === 'completed' ? '实际到手' : '结账预计到手'
@@ -108,28 +122,15 @@ const isCheckoutDisputeStage = computed(() => {
['pending_checkout_confirm', 'pending_checkout_accept'].includes(order.value.status)
)
})
const checkoutResources = computed(() => {
const resources = readSnapshotResources()
return resources.filter(item => item.quantity > 0)
})
const resourceChargeAmount = computed(() => {
return roundMoney(
checkoutResources.value.reduce((sum, item) => {
if (!isChargedResource(item)) return sum
const used = readResourceUsage(item.key)
return sum + used * item.unitPrice
}, 0)
)
})
const snapshotHafCoinM = computed(() => {
const snapshot = readSnapshot()
return roundQuantity(readNumber(snapshot?.haf_coin_amount) / 1000000)
})
const remainingHafCoinM = computed(() => {
return roundQuantity(
Math.max(snapshotHafCoinM.value - Number(checkoutForm.value.coin_consumed_m || 0), 0)
)
})
const {
checkoutResources,
resourceChargeAmount,
snapshotHafCoinM,
remainingHafCoinM,
hydrateResourceUsage,
resourceLineAmount,
checkoutContentWithSummary,
} = useOrderCheckoutSnapshot({ order, checkoutForm, resourceUsage })
function getOrderStep(status: string) {
const stepMap: Record<string, number> = {
@@ -467,191 +468,17 @@ async function openOrderChat() {
}
}
function readError(error: unknown, fallback: string) {
if (typeof error === 'object' && error && 'response' in error) {
const response = (error as { response?: { data?: { message?: string } } }).response
return response?.data?.message || fallback
}
return fallback
function orderEstimatedEndAt() {
return readOrderEstimatedEndAt(order.value)
}
function orderRentedAt() {
return order.value?.rented_at
}
function orderEstimatedEndAt() {
if (!order.value) return undefined
const rentedAt = orderRentedAt()
const durationHours = Number(order.value.estimated_duration_hours || 0)
if (!rentedAt || durationHours <= 0) return undefined
return new Date(new Date(rentedAt).getTime() + durationHours * 60 * 60 * 1000).toISOString()
}
interface CheckoutResource {
key: string
label: string
price: string
mode: string
quantity: number
unitPrice: number
}
function readSnapshot() {
const snapshot = order.value?.account_snapshot
if (isRecord(snapshot)) return snapshot
return null
}
function readAssetSummary() {
const summary = readSnapshot()?.asset_summary
if (isRecord(summary)) return summary
return null
}
function readSnapshotResources(): CheckoutResource[] {
const resources = readAssetSummary()?.resources
if (!Array.isArray(resources)) return []
return resources
.filter(isRecord)
.map(item => {
const key = String(item.key || item.label || '')
const label = String(item.label || key || '额外消耗品')
const price = String(item.price || '')
return {
key,
label,
price,
mode: String(item.mode || '收费'),
quantity: readNumber(item.quantity),
unitPrice: readUnitPrice(price),
}
})
.filter(item => item.key && item.quantity > 0)
}
function hydrateResourceUsage() {
const next: Record<string, number> = {}
for (const item of checkoutResources.value) {
next[item.key] = Math.min(
Math.max(Number(resourceUsage.value[item.key] || 0), 0),
item.quantity
)
}
resourceUsage.value = next
}
function readResourceUsage(key: string) {
return Math.max(Number(resourceUsage.value[key] || 0), 0)
}
function isChargedResource(item: CheckoutResource) {
return item.mode !== '赠送'
}
function resourceLineAmount(item: CheckoutResource) {
return roundMoney(readResourceUsage(item.key) * item.unitPrice)
}
function checkoutContentWithSummary() {
const lines = [checkoutForm.value.content.trim()].filter(Boolean)
const usedResources = checkoutResources.value.filter(item => readResourceUsage(item.key) > 0)
if (usedResources.length) {
lines.push(
`额外消耗品:${usedResources
.map(
item =>
`${item.label} ${readResourceUsage(item.key)}/${item.quantity}${
isChargedResource(item) ? `,金额¥${money(resourceLineAmount(item))}` : ',赠送不扣款'
}`
)
.join('')}`
)
}
if (Number(checkoutForm.value.coin_consumed_m || 0) > 0) {
lines.push(
`哈夫币消耗:${quantity(Number(checkoutForm.value.coin_consumed_m))}M,预计剩余${quantity(
remainingHafCoinM.value
)}M`
)
}
if (lines.length === 0) {
lines.push('租客发起结账。')
}
return lines.join('\n')
}
function readUnitPrice(priceText: string) {
const normalized = priceText.replace(//g, ',').trim()
const fractionMatch = normalized.match(/(\d+(?:\.\d+)?)\s*元\s*\/\s*(\d+(?:\.\d+)?)/)
if (fractionMatch) {
const amount = Number(fractionMatch[1])
const count = Number(fractionMatch[2])
return count > 0 ? roundMoney(amount / count) : 0
}
const singleMatch = normalized.match(/(\d+(?:\.\d+)?)\s*元/)
if (singleMatch) return Number(singleMatch[1])
const fallback = normalized.match(/(\d+(?:\.\d+)?)/)
return fallback ? Number(fallback[1]) : 0
}
function roundMoney(value: number) {
return Math.round(Number(value || 0) * 10) / 10
}
function roundQuantity(value: number) {
return Math.round(value * 100) / 100
}
function money(value: unknown) {
return formatMoney(readNumber(value))
}
function amountYuan(cent: unknown) {
if (cent !== undefined && cent !== null) return centToYuan(readNumber(cent))
return 0
}
function orderRentAmount(item: Order) {
if (item.owner_id === session.userId) return amountYuan(item.owner_rent_amount_cent)
if (item.renter_id === session.userId) return amountYuan(item.rent_amount_cent)
return amountYuan(item.display_amount_cent)
}
function ownerActualIncome(item: Order) {
if (item.owner_id !== session.userId) return null
const value = item.checkout?.owner_income_amount_cent
if (typeof value === 'number') return centToYuan(value)
return null
}
function quantity(value: unknown) {
const rounded = roundQuantity(readNumber(value))
return Number.isInteger(rounded) ? `${rounded}` : rounded.toFixed(2)
}
function readNumber(value: unknown) {
const number = Number(value || 0)
return Number.isFinite(number) ? number : 0
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function hydrateCounterForm() {
if (!order.value?.checkout) return
const checkout = order.value.checkout
counterForm.value.consumableAmountYuan = amountYuan(checkout.consumable_amount_cent)
counterForm.value.coin_consumed_m = checkout.coin_consumed_m
counterForm.value.otherAmountYuan = amountYuan(checkout.other_amount_cent)
counterForm.value.depositDeductAmountYuan = amountYuan(checkout.deposit_deduct_amount_cent)
}
function linesToList(value: string) {
return value
.split('\n')
.map(item => item.trim())
.filter(Boolean)
counterForm.value = hydrateCounterFormFromCheckout(order.value.checkout)
}
function scrollToDispute() {
@@ -682,18 +509,6 @@ function scrollToRejectCheckout() {
}
}
function formatHandoffRecordType(type: string) {
const typeMap: Record<string, string> = {
owner_handoff: '卖家交接',
renter_checkout: '买家结账',
owner_counter_checkout: '卖家反驳结账',
renter_confirm_checkout: '买家确认结账',
owner_accept_checkout: '卖家接受结账',
admin_arbitration: '客服仲裁',
}
return typeMap[type] || type
}
async function copyListingCode() {
if (!order.value) return
try {
@@ -826,189 +641,31 @@ async function copyListingCode() {
</div>
</div>
<div v-if="order" class="timeline-section">
<div class="section-header">
<h2>交接记录</h2>
<span>商品编号 {{ listingCode }}</span>
</div>
<el-empty v-if="handoffRecords.length === 0" description="暂无交接记录" />
<el-timeline v-else>
<el-timeline-item
v-for="record in handoffRecords"
:key="record.id"
:timestamp="formatDateTime(record.created_at)"
placement="top"
>
<div class="timeline-content">
<div class="timeline-title">{{ formatHandoffRecordType(record.type) }}</div>
<div class="timeline-body">{{ record.content }}</div>
</div>
</el-timeline-item>
</el-timeline>
</div>
<OrderHandoffTimeline v-if="order" :records="handoffRecords" :listing-code="listingCode" />
<div
<OrderResourceUsageEditor
v-if="order && isRenter && ['renting', 'overdue'].includes(order.status)"
class="form-section checkout-form-section"
>
<div class="section-header">
<h2>发起结账</h2>
</div>
<div class="form-card">
<el-input
v-model="checkoutForm.content"
type="textarea"
:rows="4"
placeholder="填写结账说明、租后资产状态或注意事项"
/>
<div class="checkout-resource-panel">
<div class="checkout-resource-head">
<strong>额外消耗品</strong>
<span class="amount-highlight">已用金额¥{{ money(resourceChargeAmount) }}</span>
</div>
<el-empty
v-if="checkoutResources.length === 0"
description="订单快照中暂无额外消耗品"
/>
<div
v-for="item in checkoutResources"
v-else
:key="item.key"
class="checkout-resource-row"
>
<div class="checkout-resource-meta">
<strong>{{ item.label }}</strong>
<span
>库存 {{ item.quantity }}{{ item.mode }}{{
item.price || '未设置单价'
}}</span
>
</div>
<el-input-number
v-model="resourceUsage[item.key]"
:min="0"
:max="item.quantity"
:precision="0"
controls-position="right"
/>
<span class="checkout-resource-amount">¥{{ money(resourceLineAmount(item)) }}</span>
</div>
</div>
<el-form class="form-grid" label-position="top">
<el-form-item label="消耗哈夫币(M">
<el-input-number
v-model="checkoutForm.coin_consumed_m"
class="full-control"
:min="0"
:max="snapshotHafCoinM"
:precision="2"
controls-position="right"
/>
<span class="field-hint"
>订单快照 {{ quantity(snapshotHafCoinM) }}M预计剩余
{{ quantity(remainingHafCoinM) }}M</span
>
</el-form-item>
<el-form-item label="其他押金赔付(元)">
<el-input-number
v-model="checkoutForm.otherAmountYuan"
class="full-control"
:min="0"
:precision="0"
controls-position="right"
/>
<span class="field-hint"
>不含上方额外消耗品仅填写封禁违规资产损坏等需要从押金赔付的费用</span
>
</el-form-item>
</el-form>
<div class="checkout-deduct-preview">
<div>
<span>额外消耗品已用</span>
<strong>¥{{ money(resourceChargeAmount) }}</strong>
<em>按上方物资数量自动计算计入实际结算租金</em>
</div>
<div>
<span>其他押金赔付</span>
<strong>¥{{ money(checkoutForm.otherAmountYuan) }}</strong>
<em>作为押金赔付扣除和额外消耗品分开展示</em>
</div>
</div>
<el-input
v-model="checkoutForm.evidenceText"
type="textarea"
:rows="3"
placeholder="结账证据链接,一行一个。可填写截图地址或备注链接"
/>
<el-button
type="primary"
size="large"
:loading="returning"
@click="handleSubmitCheckout"
>发起结账</el-button
>
</div>
</div>
v-model:checkout-form="checkoutForm"
v-model:resource-usage="resourceUsage"
:resources="checkoutResources"
:resource-charge-amount="resourceChargeAmount"
:snapshot-haf-coin-m="snapshotHafCoinM"
:remaining-haf-coin-m="remainingHafCoinM"
:returning="returning"
:resource-line-amount="resourceLineAmount"
@submit="handleSubmitCheckout"
/>
<div
<OrderCheckoutSummary
v-if="
order &&
order.checkout &&
['pending_checkout_confirm', 'pending_checkout_accept'].includes(order.status)
"
class="info-section"
>
<div class="section-header">
<h2>结账明细</h2>
</div>
<div class="checkout-summary-card">
<div class="summary-row">
<span>实际结算租金</span>
<strong>¥{{ money(amountYuan(order.checkout.display_amount_cent)) }}</strong>
</div>
<div class="summary-row">
<span>预收押金</span>
<strong>
¥{{ money(amountYuan(order.checkout.deposit_amount_cent)) }}
<em v-if="amountYuan(order.deposit_waived_amount_cent) > 0"
>已免押 ¥{{ money(amountYuan(order.deposit_waived_amount_cent)) }}</em
>
</strong>
</div>
<div class="summary-row">
<span>额外消耗品已用</span>
<strong class="warning"
>¥{{ money(amountYuan(order.checkout.consumable_amount_cent)) }}</strong
>
</div>
<div class="summary-row">
<span>押金赔付扣除</span>
<strong class="warning"
>¥{{ money(amountYuan(order.checkout.deposit_deduct_amount_cent)) }}</strong
>
</div>
<div v-if="isRenter" class="summary-row highlight">
<span>退还租客(未使用租金 + 剩余押金)</span>
<strong class="amount"
>¥{{ money(amountYuan(order.checkout.renter_refund_amount_cent)) }}</strong
>
</div>
<div v-if="isOwner" class="summary-row highlight">
<span>号主最终收入(租金 + 押金赔付)</span>
<strong class="amount"
>¥{{ money(amountYuan(order.checkout.owner_income_amount_cent)) }}</strong
>
</div>
<div v-if="order.checkout.content" class="summary-note">
<label>说明:</label>
<p>{{ order.checkout.content }}</p>
</div>
<div v-if="order.checkout.owner_adjustment_reason" class="summary-note warning">
<label>修正原因:</label>
<p>{{ order.checkout.owner_adjustment_reason }}</p>
</div>
</div>
</div>
:order="order"
:is-owner="isOwner"
:is-renter="isRenter"
/>
<div
v-if="order && isOwner && order.status === 'pending_checkout_confirm'"
@@ -1558,35 +1215,6 @@ async function copyListingCode() {
margin: 0;
}
.timeline-section {
margin-bottom: 32px;
}
.timeline-section :deep(.el-timeline) {
padding: 24px;
background: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 12px;
}
.timeline-content {
display: grid;
gap: 8px;
}
.timeline-title {
font-size: 15px;
font-weight: 600;
color: #1f2937;
}
.timeline-body {
font-size: 14px;
color: #64748b;
line-height: 1.6;
white-space: pre-wrap;
}
.form-section {
margin-bottom: 32px;
}
@@ -1664,69 +1292,6 @@ async function copyListingCode() {
margin: 0 0 16px 0;
}
.checkout-resource-panel {
display: grid;
gap: 12px;
padding: 16px;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 8px;
}
.checkout-resource-head {
display: grid;
grid-template-columns: 1fr auto;
gap: 12px;
align-items: center;
padding-bottom: 12px;
border-bottom: 2px solid #e5e7eb;
}
.checkout-resource-head strong {
color: #1f2937;
font-size: 15px;
}
.amount-highlight {
color: #ff6a00;
font-weight: 700;
font-size: 14px;
}
.checkout-resource-row {
display: grid;
grid-template-columns: 1fr auto auto;
gap: 12px;
align-items: center;
padding: 12px;
background: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 6px;
}
.checkout-resource-meta {
display: grid;
gap: 4px;
}
.checkout-resource-meta strong {
color: #1f2937;
font-size: 14px;
}
.checkout-resource-meta span {
color: #6b7785;
font-size: 12px;
}
.checkout-resource-amount {
min-width: 80px;
text-align: right;
color: #ff6a00;
font-weight: 700;
font-size: 16px;
}
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
@@ -1740,126 +1305,6 @@ async function copyListingCode() {
font-size: 12px;
}
.checkout-deduct-preview {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.checkout-deduct-preview div {
display: grid;
gap: 6px;
padding: 12px;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #f9fafb;
}
.checkout-deduct-preview span {
color: #4b5563;
font-size: 13px;
font-weight: 700;
}
.checkout-deduct-preview strong {
color: #ff6a00;
font-size: 18px;
font-weight: 800;
}
.checkout-deduct-preview em {
color: #6b7280;
font-size: 12px;
font-style: normal;
line-height: 1.45;
}
.checkout-summary-card {
display: grid;
gap: 12px;
padding: 24px;
background: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 12px;
}
.summary-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
border-bottom: 1px solid #f3f4f6;
}
.summary-row:last-child {
border-bottom: none;
}
.summary-row.highlight {
padding: 16px;
background: #f0fdf4;
border: 1px solid #bbf7d0;
border-radius: 8px;
}
.summary-row span {
font-size: 14px;
color: #64748b;
}
.summary-row strong {
display: flex;
flex-direction: column;
align-items: flex-end;
font-size: 18px;
font-weight: 700;
color: #1f2937;
}
.summary-row strong em {
font-style: normal;
font-size: 12px;
font-weight: 500;
color: #2563eb;
}
.summary-row strong.amount {
color: #10b981;
font-size: 20px;
}
.summary-row strong.warning {
color: #f59e0b;
}
.summary-note {
padding: 16px;
background: #f8fafc;
border-left: 3px solid #94a3b8;
border-radius: 4px;
}
.summary-note.warning {
background: #fef3c7;
border-left-color: #f59e0b;
}
.summary-note label {
display: block;
margin-bottom: 8px;
color: #475569;
font-size: 13px;
font-weight: 600;
}
.summary-note p {
margin: 0;
color: #1f2937;
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
}
.dispute-section .form-card {
background: #fef2f2;
border-color: #fecaca;
@@ -2006,18 +1451,6 @@ async function copyListingCode() {
grid-template-columns: 1fr;
}
.checkout-resource-row {
grid-template-columns: 1fr;
}
.checkout-resource-amount {
text-align: left;
}
.checkout-deduct-preview {
grid-template-columns: 1fr;
}
.action-buttons {
flex-direction: column;
}