feat(order): 统一网站自交接订单24小时自动完成倒计时

This commit is contained in:
yml
2026-11-30 17:05:49 +08:00
parent 295c88dd2f
commit 2992885a6d
32 changed files with 996 additions and 23 deletions
+155 -10
View File
@@ -13,6 +13,8 @@ import (
"hfb_sys/backend/internal/modules/adminnotification"
"hfb_sys/backend/internal/modules/chat"
"hfb_sys/backend/internal/modules/notification"
ordermodule "hfb_sys/backend/internal/modules/order"
"hfb_sys/backend/internal/processlog"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
@@ -48,6 +50,7 @@ type thresholds struct {
PendingPaymentTimeoutMinutes int
OwnerSubmitTimeoutMinutes int
RenterConfirmTimeoutMinutes int
AutoCompleteHandoffTimeoutMinutes int
ReturnOverdueGraceMinutes int
OwnerReturnConfirmTimeoutMinutes int
RenterRetentionDaysAfterOrderEnd int
@@ -177,6 +180,7 @@ func (j *Job) run(ctx context.Context) {
run func(context.Context, time.Time, thresholds) (int, error)
}{
{name: "pending_payment", run: j.handlePendingPaymentTimeout},
{name: "auto_complete_handoff", run: j.handleAutoCompleteHandoff},
{name: "owner_submit", run: j.handleOwnerSubmitTimeout},
{name: "renter_confirm", run: j.handleRenterConfirmTimeout},
{name: "return_overdue", run: j.handleReturnOverdue},
@@ -226,18 +230,20 @@ func (j *Job) run(ctx context.Context) {
func (j *Job) loadThresholds(ctx context.Context) (thresholds, error) {
cfg := thresholds{
PendingPaymentTimeoutMinutes: 15,
OwnerSubmitTimeoutMinutes: 30,
RenterConfirmTimeoutMinutes: 30,
ReturnOverdueGraceMinutes: 10,
OwnerReturnConfirmTimeoutMinutes: 120,
RenterRetentionDaysAfterOrderEnd: defaultRenterRetentionDaysAfterOrderEnd,
PendingPaymentTimeoutMinutes: 15,
OwnerSubmitTimeoutMinutes: 30,
RenterConfirmTimeoutMinutes: 30,
AutoCompleteHandoffTimeoutMinutes: 1440,
ReturnOverdueGraceMinutes: 10,
OwnerReturnConfirmTimeoutMinutes: 120,
RenterRetentionDaysAfterOrderEnd: defaultRenterRetentionDaysAfterOrderEnd,
}
var rows []model.SystemConfig
query := j.db.WithContext(ctx).
Where("`key` IN ?", []string{
"handoff.owner_submit_timeout_minutes",
"handoff.renter_confirm_timeout_minutes",
"handoff.auto_complete_timeout_minutes",
"order.pending_payment_timeout_minutes",
"order.return_overdue_grace_minutes",
"handoff.owner_return_confirm_timeout_minutes",
@@ -260,6 +266,8 @@ func (j *Job) loadThresholds(ctx context.Context) (thresholds, error) {
cfg.OwnerSubmitTimeoutMinutes = value
case "handoff.renter_confirm_timeout_minutes":
cfg.RenterConfirmTimeoutMinutes = value
case "handoff.auto_complete_timeout_minutes":
cfg.AutoCompleteHandoffTimeoutMinutes = value
case "order.pending_payment_timeout_minutes":
cfg.PendingPaymentTimeoutMinutes = value
case "order.return_overdue_grace_minutes":
@@ -414,13 +422,150 @@ func closePendingOrderPayments(tx *gorm.DB, orderID uint64, source string) error
}).Error
}
func (j *Job) handleAutoCompleteHandoff(ctx context.Context, now time.Time, cfg thresholds) (int, error) {
if cfg.AutoCompleteHandoffTimeoutMinutes <= 0 {
return 0, nil
}
var rows []model.RentalOrder
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status IN ? AND handoff_deadline_at IS NOT NULL AND handoff_deadline_at <= ?",
"pending_handoff",
[]string{"pending_owner", "owner_timeout", "pending_renter_confirm"},
now,
).
Where("COALESCE(NULLIF(handoff_mode, ''), 'owner') <> ? AND COALESCE(NULLIF(settlement_mode, ''), 'owner_wallet') <> ?",
"platform",
"platform_managed",
).
Where("COALESCE(NULLIF(refund_status, ''), 'none') <> ?", "pending_review").
Order("id ASC").
Limit(100)
query = applyOrderTenantScope(ctx, query, "buyer_tenant_id")
if err := query.Find(&rows).Error; err != nil {
return 0, err
}
count := 0
for _, row := range rows {
updated := false
if err := j.updateOrder(ctx, row.ID, "order.timeout.auto_handoff", func(tx *gorm.DB, order *model.RentalOrder) (string, error) {
if order.Status != "pending_handoff" || isPlatformManagedOrder(order) || order.RefundStatus == "pending_review" {
return "", nil
}
if order.HandoffStatus != "pending_owner" && order.HandoffStatus != "owner_timeout" && order.HandoffStatus != "pending_renter_confirm" {
return "", nil
}
if order.HandoffDeadlineAt == nil || order.HandoffDeadlineAt.After(now) {
return "", nil
}
var activeDisputeCount int64
if err := tx.Model(&model.Dispute{}).
Where("order_id = ? AND status IN ?", order.ID, []string{"open", "processing"}).
Count(&activeDisputeCount).Error; err != nil {
return "", err
}
if activeDisputeCount > 0 {
return "", nil
}
before := snapshot(order)
stateBefore := map[string]any{
"order_status": order.Status,
"handoff_status": order.HandoffStatus,
"settlement_status": order.SettlementStatus,
}
if err := tx.Model(&model.HandoffRecord{}).
Where("order_id = ? AND type = ? AND confirmed_by_renter_at IS NULL", order.ID, "owner_handoff").
Update("confirmed_by_renter_at", now).Error; err != nil {
return "", err
}
var ownerRecordCount int64
if err := tx.Model(&model.HandoffRecord{}).
Where("order_id = ? AND type = ?", order.ID, "owner_handoff").
Count(&ownerRecordCount).Error; err != nil {
return "", err
}
if ownerRecordCount == 0 {
record := model.HandoffRecord{
OrderID: order.ID,
FromUserID: order.OwnerID,
ToUserID: order.RenterID,
Type: "system_auto_handoff",
Content: "自动交接倒计时到期,系统已自动完成交接并进入租用阶段。",
ConfirmedByRenterAt: &now,
}
if err := tx.Create(&record).Error; err != nil {
return "", err
}
}
order.Status = "renting"
order.HandoffStatus = "received"
order.EstimatedDurationHours = ordermodule.EstimateOrderDurationHours(order.AccountSnapshot)
order.RentedAt = &now
stateAfter := map[string]any{
"order_status": order.Status,
"handoff_status": order.HandoffStatus,
"settlement_status": order.SettlementStatus,
}
targetID := order.OwnerID
if err := processlog.Append(tx, processlog.Entry{
BusinessType: "order",
BusinessID: order.ID,
Stage: "handoff",
Action: "system_auto_handoff",
ActorType: processlog.ActorSystem,
ActorID: 0,
TargetType: processlog.ActorUser,
TargetID: &targetID,
Content: "交接倒计时到期,系统自动完成交接并进入使用中。",
StateBefore: stateBefore,
StateAfter: stateAfter,
}); err != nil {
return "", err
}
orderID := order.ID
if err := notification.Append(tx,
notification.Entry{
UserID: order.RenterID,
Type: "handoff",
Title: "订单已自动完成交接",
Content: "交接倒计时到期,系统已自动完成交接并进入使用中。",
BizType: "order",
BizID: &orderID,
},
notification.Entry{
UserID: order.OwnerID,
Type: "handoff",
Title: "订单已自动完成交接",
Content: "交接倒计时到期,系统已自动完成交接,订单已进入使用中。",
BizType: "order",
BizID: &orderID,
},
); err != nil {
return "", err
}
updated = true
return before, nil
}); err != nil {
return count, err
}
if updated {
count++
}
}
return count, nil
}
func (j *Job) handleOwnerSubmitTimeout(ctx context.Context, now time.Time, cfg thresholds) (int, error) {
if cfg.OwnerSubmitTimeoutMinutes <= 0 {
return 0, nil
}
var rows []model.RentalOrder
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status = ? AND COALESCE(handoff_started_at, created_at) <= ?", "pending_handoff", "pending_owner", now.Add(-time.Duration(cfg.OwnerSubmitTimeoutMinutes)*time.Minute)).
Where("status = ? AND handoff_status = ? AND handoff_deadline_at IS NULL AND COALESCE(handoff_started_at, created_at) <= ?", "pending_handoff", "pending_owner", now.Add(-time.Duration(cfg.OwnerSubmitTimeoutMinutes)*time.Minute)).
Order("id ASC").
Limit(100)
query = applyOrderTenantScope(ctx, query, "source_tenant_id")
@@ -431,7 +576,7 @@ func (j *Job) handleOwnerSubmitTimeout(ctx context.Context, now time.Time, cfg t
count := 0
for _, row := range rows {
if err := j.updateOrder(ctx, row.ID, "order.timeout.owner_submit", func(tx *gorm.DB, order *model.RentalOrder) (string, error) {
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_owner" {
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_owner" || order.HandoffDeadlineAt != nil {
return "", nil
}
before := snapshot(order)
@@ -490,7 +635,7 @@ func (j *Job) handleRenterConfirmTimeout(ctx context.Context, now time.Time, cfg
var rows []model.RentalOrder
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status = ?", "pending_handoff", "pending_renter_confirm").
Where("status = ? AND handoff_status = ? AND handoff_deadline_at IS NULL", "pending_handoff", "pending_renter_confirm").
Order("id ASC").
Limit(100)
query = applyOrderTenantScope(ctx, query, "buyer_tenant_id")
@@ -537,7 +682,7 @@ func (j *Job) handleRenterConfirmTimeout(ctx context.Context, now time.Time, cfg
continue
}
if err := j.updateOrder(ctx, row.ID, "order.timeout.renter_confirm", func(tx *gorm.DB, order *model.RentalOrder) (string, error) {
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_renter_confirm" {
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_renter_confirm" || order.HandoffDeadlineAt != nil {
return "", nil
}
before := snapshot(order)
@@ -9,6 +9,7 @@ import (
"hfb_sys/backend/internal/modules/chat"
"go.uber.org/zap"
"gorm.io/datatypes"
"gorm.io/gorm"
)
@@ -25,6 +26,8 @@ func setupOrderTimeoutTestDB(t *testing.T) *gorm.DB {
&model.ChatMessage{},
&model.SystemConfig{},
&model.AuditLog{},
&model.Dispute{},
&model.ProcessEvent{},
); err != nil {
t.Fatalf("数据库迁移失败: %v", err)
}
@@ -281,3 +284,245 @@ func TestClampRenterRetentionDays(t *testing.T) {
}
}
}
func TestHandleAutoCompleteHandoffPendingOwnerAndRenterConfirm(t *testing.T) {
db := setupOrderTimeoutTestDB(t)
job := New(db, nil, zap.NewNop(), nil)
now := time.Date(2026, 6, 18, 12, 0, 0, 0, time.UTC)
expiredAt := now.Add(-time.Minute)
futureAt := now.Add(2 * time.Hour)
snapshot := datatypes.JSON([]byte(`{"haf_coin_amount":100000000,"daily_loss_m":50}`))
// 1. 新单 pending_owner 到期:应自动交接并进入 renting/received,补记 system_auto_handoff 记录
ownerPendingExpired := model.RentalOrder{
OrderNo: "ORD-AUTO-OWNER-EXPIRED",
ListingID: 1,
AccountID: 1,
OwnerID: 101,
RenterID: 201,
Status: "pending_handoff",
HandoffStatus: "pending_owner",
HandoffMode: "owner",
SettlementMode: "owner_wallet",
HandoffDeadlineAt: &expiredAt,
AccountSnapshot: snapshot,
}
// 2. 新单 pending_renter_confirm 到期:已有 owner_handoff,应补写 confirmed_by_renter_at 并进入 renting/received
renterConfirmExpired := model.RentalOrder{
OrderNo: "ORD-AUTO-RENTER-EXPIRED",
ListingID: 2,
AccountID: 2,
OwnerID: 102,
RenterID: 202,
Status: "pending_handoff",
HandoffStatus: "pending_renter_confirm",
HandoffMode: "owner",
SettlementMode: "owner_wallet",
HandoffDeadlineAt: &expiredAt,
AccountSnapshot: snapshot,
}
// 3. 新单未到期:保持 pending_handoff
notExpired := model.RentalOrder{
OrderNo: "ORD-AUTO-NOT-EXPIRED",
ListingID: 3,
AccountID: 3,
OwnerID: 103,
RenterID: 203,
Status: "pending_handoff",
HandoffStatus: "pending_owner",
HandoffMode: "owner",
HandoffDeadlineAt: &futureAt,
}
// 4. 平台代管订单:即使设置截止时间也不自动完成
platformOrder := model.RentalOrder{
OrderNo: "ORD-AUTO-PLATFORM",
ListingID: 4,
AccountID: 4,
OwnerID: 104,
RenterID: 204,
Status: "pending_handoff",
HandoffStatus: "pending_renter_confirm",
HandoffMode: "platform",
SettlementMode: "platform_managed",
HandoffDeadlineAt: &expiredAt,
}
// 5. 历史旧单(handoff_deadline_at = nil):不触发自动完成
legacyOrder := model.RentalOrder{
OrderNo: "ORD-AUTO-LEGACY",
ListingID: 5,
AccountID: 5,
OwnerID: 105,
RenterID: 205,
Status: "pending_handoff",
HandoffStatus: "pending_owner",
HandoffMode: "owner",
}
// 6. 有进行中申诉或待审核退款的订单:不自动完成
disputedOrder := model.RentalOrder{
OrderNo: "ORD-AUTO-DISPUTED",
ListingID: 6,
AccountID: 6,
OwnerID: 106,
RenterID: 206,
Status: "pending_handoff",
HandoffStatus: "pending_renter_confirm",
HandoffMode: "owner",
HandoffDeadlineAt: &expiredAt,
}
for _, item := range []*model.RentalOrder{
&ownerPendingExpired,
&renterConfirmExpired,
&notExpired,
&platformOrder,
&legacyOrder,
&disputedOrder,
} {
if err := db.Create(item).Error; err != nil {
t.Fatalf("创建订单 %s 失败: %v", item.OrderNo, err)
}
}
ownerHandoff := model.HandoffRecord{
OrderID: renterConfirmExpired.ID,
FromUserID: renterConfirmExpired.OwnerID,
ToUserID: renterConfirmExpired.RenterID,
Type: "owner_handoff",
Content: "已发登录二维码",
}
if err := db.Create(&ownerHandoff).Error; err != nil {
t.Fatalf("创建交接记录失败: %v", err)
}
dispute := model.Dispute{
OrderID: disputedOrder.ID,
InitiatorID: disputedOrder.RenterID,
Type: "cannot_login",
Description: "无法登录",
Status: "open",
}
if err := db.Create(&dispute).Error; err != nil {
t.Fatalf("创建申诉失败: %v", err)
}
count, err := job.handleAutoCompleteHandoff(t.Context(), now, thresholds{
AutoCompleteHandoffTimeoutMinutes: 1440,
})
if err != nil {
t.Fatalf("handleAutoCompleteHandoff() error = %v", err)
}
if count != 2 {
t.Fatalf("auto-completed count = %d, want 2", count)
}
var saved1, saved2, saved3, saved4, saved5, saved6 model.RentalOrder
_ = db.First(&saved1, ownerPendingExpired.ID)
_ = db.First(&saved2, renterConfirmExpired.ID)
_ = db.First(&saved3, notExpired.ID)
_ = db.First(&saved4, platformOrder.ID)
_ = db.First(&saved5, legacyOrder.ID)
_ = db.First(&saved6, disputedOrder.ID)
if saved1.Status != "renting" || saved1.HandoffStatus != "received" || saved1.RentedAt == nil || saved1.EstimatedDurationHours != 48 {
t.Fatalf("saved1 = %s/%s rented=%v hours=%d, want renting/received/set/48",
saved1.Status, saved1.HandoffStatus, saved1.RentedAt, saved1.EstimatedDurationHours)
}
if saved2.Status != "renting" || saved2.HandoffStatus != "received" || saved2.RentedAt == nil {
t.Fatalf("saved2 = %s/%s rented=%v, want renting/received/set", saved2.Status, saved2.HandoffStatus, saved2.RentedAt)
}
if saved3.Status != "pending_handoff" || saved4.Status != "pending_handoff" || saved5.Status != "pending_handoff" || saved6.Status != "pending_handoff" {
t.Fatalf("non-eligible orders modified: %s, %s, %s, %s", saved3.Status, saved4.Status, saved5.Status, saved6.Status)
}
var autoRecord model.HandoffRecord
if err := db.Where("order_id = ? AND type = ?", ownerPendingExpired.ID, "system_auto_handoff").First(&autoRecord).Error; err != nil {
t.Fatalf("expected system_auto_handoff record for ownerPendingExpired: %v", err)
}
var updatedOwnerHandoff model.HandoffRecord
if err := db.First(&updatedOwnerHandoff, ownerHandoff.ID).Error; err != nil {
t.Fatalf("load ownerHandoff failed: %v", err)
}
if updatedOwnerHandoff.ConfirmedByRenterAt == nil {
t.Fatal("expected confirmed_by_renter_at to be populated on existing owner_handoff record")
}
var processCount int64
if err := db.Model(&model.ProcessEvent{}).
Where("business_type = ? AND business_id IN ? AND action = ?", "order", []uint64{ownerPendingExpired.ID, renterConfirmExpired.ID}, "system_auto_handoff").
Count(&processCount).Error; err != nil {
t.Fatalf("count process events failed: %v", err)
}
if processCount != 2 {
t.Fatalf("process event count = %d, want 2", processCount)
}
}
func TestNewOrdersWithHandoffDeadlineSkipLegacy30MinTimeouts(t *testing.T) {
db := setupOrderTimeoutTestDB(t)
job := New(db, nil, zap.NewNop(), nil)
now := time.Date(2026, 6, 18, 12, 0, 0, 0, time.UTC)
startedAt := now.Add(-2 * time.Hour)
futureDeadline := now.Add(22 * time.Hour)
pendingOwnerNew := model.RentalOrder{
OrderNo: "ORD-NEW-PENDING-OWNER",
ListingID: 11,
AccountID: 11,
OwnerID: 301,
RenterID: 401,
Status: "pending_handoff",
HandoffStatus: "pending_owner",
HandoffMode: "owner",
HandoffStartedAt: &startedAt,
HandoffDeadlineAt: &futureDeadline,
}
pendingRenterNew := model.RentalOrder{
OrderNo: "ORD-NEW-PENDING-RENTER",
ListingID: 12,
AccountID: 12,
OwnerID: 302,
RenterID: 402,
Status: "pending_handoff",
HandoffStatus: "pending_renter_confirm",
HandoffMode: "owner",
HandoffStartedAt: &startedAt,
HandoffDeadlineAt: &futureDeadline,
}
if err := db.Create(&pendingOwnerNew).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&pendingRenterNew).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.HandoffRecord{
OrderID: pendingRenterNew.ID,
FromUserID: pendingRenterNew.OwnerID,
ToUserID: pendingRenterNew.RenterID,
Type: "owner_handoff",
Content: "已提交交接",
CreatedAt: startedAt,
}).Error; err != nil {
t.Fatal(err)
}
c1, err := job.handleOwnerSubmitTimeout(t.Context(), now, thresholds{OwnerSubmitTimeoutMinutes: 30})
if err != nil {
t.Fatalf("handleOwnerSubmitTimeout() error = %v", err)
}
c2, err := job.handleRenterConfirmTimeout(t.Context(), now, thresholds{RenterConfirmTimeoutMinutes: 30})
if err != nil {
t.Fatalf("handleRenterConfirmTimeout() error = %v", err)
}
if c1 != 0 || c2 != 0 {
t.Fatalf("legacy 30m handlers touched new unified-countdown orders: owner=%d renter=%d", c1, c2)
}
var savedOwner, savedRenter model.RentalOrder
_ = db.First(&savedOwner, pendingOwnerNew.ID)
_ = db.First(&savedRenter, pendingRenterNew.ID)
if savedOwner.Status != "pending_handoff" || savedOwner.HandoffStatus != "pending_owner" {
t.Fatalf("pendingOwnerNew altered to %s/%s", savedOwner.Status, savedOwner.HandoffStatus)
}
if savedRenter.Status != "pending_handoff" || savedRenter.HandoffStatus != "pending_renter_confirm" {
t.Fatalf("pendingRenterNew altered to %s/%s", savedRenter.Status, savedRenter.HandoffStatus)
}
}
+1
View File
@@ -19,6 +19,7 @@ type RentalOrder struct {
RenterID uint64 `gorm:"not null;index" json:"renter_id"`
RentedAt *time.Time `json:"rented_at"`
HandoffStartedAt *time.Time `json:"handoff_started_at"`
HandoffDeadlineAt *time.Time `gorm:"index:idx_rental_orders_handoff_deadline" json:"handoff_deadline_at"`
EstimatedDurationHours int `gorm:"not null;default:24" json:"estimated_duration_hours"`
RentAmountCent int64 `gorm:"not null;default:0" json:"-"`
OwnerRentAmountCent int64 `gorm:"not null;default:0" json:"-"`
@@ -231,6 +231,12 @@ func (r *Repository) AdminResetHandoff(ctx context.Context, adminID uint64, orde
order.HandoffStatus = target.HandoffStatus
if target.RefreshStageTime {
order.HandoffStartedAt = &now
if !isPlatformHandoffOrder(order) && !isPlatformSettlementOrder(order) && order.HandoffDeadlineAt != nil {
if timeoutMinutes := autoCompleteHandoffTimeoutMinutesForOrder(tx, order); timeoutMinutes > 0 {
deadline := now.Add(time.Duration(timeoutMinutes) * time.Minute)
order.HandoffDeadlineAt = &deadline
}
}
}
if target.RecalculateEnd {
durationHours := estimateOrderDurationHours(order.AccountSnapshot)
@@ -503,6 +509,13 @@ func (r *Repository) AdminRejectRefund(ctx context.Context, orderID uint64, acti
if order.HandoffStatus == handoffStatusCancelled || order.HandoffStatus == handoffStatusRenterConfirmTimeout {
order.HandoffStatus = handoffStatusPendingOwner
}
if !isPlatformHandoffOrder(*order) && !isPlatformSettlementOrder(*order) && order.HandoffDeadlineAt != nil {
if timeoutMinutes := autoCompleteHandoffTimeoutMinutesForOrder(tx, *order); timeoutMinutes > 0 {
now := time.Now()
deadline := now.Add(time.Duration(timeoutMinutes) * time.Minute)
order.HandoffDeadlineAt = &deadline
}
}
order.SettlementStatus = settlementStatusUnsettled
order.SettledAt = nil
reserveListingForOrder(listing)
+5 -2
View File
@@ -97,6 +97,7 @@ type OrderDTO struct {
Checkout *CheckoutDTO `json:"checkout,omitempty"`
AdminActions *AdminActionsDTO `json:"admin_actions,omitempty"`
PaymentDeadlineAt *time.Time `json:"payment_deadline_at,omitempty"`
HandoffDeadlineAt *time.Time `json:"handoff_deadline_at,omitempty"`
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
SourceTrackCode string `json:"source_track_code,omitempty"`
CreatedAt time.Time `json:"created_at"`
@@ -122,6 +123,7 @@ type UserOrderListItemDTO struct {
HandoffStatus string `json:"handoff_status"`
CanHide bool `json:"can_hide,omitempty"`
PaymentDeadlineAt *time.Time `json:"payment_deadline_at,omitempty"`
HandoffDeadlineAt *time.Time `json:"handoff_deadline_at,omitempty"`
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
@@ -147,8 +149,9 @@ type AdminOrderListItemDTO struct {
HandoffStatus string `json:"handoff_status"`
HandoffMode string `json:"handoff_mode"`
SettlementMode string `json:"settlement_mode"`
SettlementStatus string `json:"settlement_status"`
CreatedAt time.Time `json:"created_at"`
SettlementStatus string `json:"settlement_status"`
HandoffDeadlineAt *time.Time `json:"handoff_deadline_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
// OwnerIncomeAmountCent 为号主实际到手金额(分),仅在已结账/已仲裁订单上返回;
// 用指针区分「未结账(null)」与「到手 0 元」。平台代管订单取线下结算金额,
// 其他订单取号主钱包最终入账合计。
@@ -415,6 +415,12 @@ func (r *Repository) ConfirmPaidFromChannelTx(tx *gorm.DB, orderID uint64) (uint
order.Status = orderStatusPendingHandoff
order.HandoffStatus = handoffStatusPendingOwner
order.HandoffStartedAt = &now
if !isPlatformHandoffOrder(*order) && !isPlatformSettlementOrder(*order) {
if timeoutMinutes := autoCompleteHandoffTimeoutMinutesForOrder(tx, *order); timeoutMinutes > 0 {
deadline := now.Add(time.Duration(timeoutMinutes) * time.Minute)
order.HandoffDeadlineAt = &deadline
}
}
if err := markAssetsRented(tx, listing, account); err != nil {
return 0, err
}
@@ -151,6 +151,7 @@ func (row orderRow) toAdminDTO() OrderDTO {
DepositHeldAt: row.DepositHeldAt,
DepositHoldReleasedAt: row.DepositHoldReleasedAt,
AdminActions: adminActionsForOrder(row.RentalOrder),
HandoffDeadlineAt: effectiveHandoffDeadlineAt(row.RentalOrder),
DistributionSiteID: row.DistributionSiteID,
SourceTrackCode: row.SourceTrackCode,
CreatedAt: row.CreatedAt,
@@ -215,6 +216,7 @@ func (row orderRow) toUserListItem(userID uint64, paymentDeadlineAt *time.Time)
Status: row.Status,
HandoffStatus: row.HandoffStatus,
PaymentDeadlineAt: paymentDeadlineAt,
HandoffDeadlineAt: effectiveHandoffDeadlineAt(row.RentalOrder),
DistributionSiteID: row.DistributionSiteID,
CreatedAt: row.CreatedAt,
}
@@ -241,10 +243,22 @@ func (row orderRow) toAdminListItem() AdminOrderListItemDTO {
HandoffMode: effectiveHandoffMode(row.RentalOrder),
SettlementMode: effectiveSettlementMode(row.RentalOrder),
SettlementStatus: row.SettlementStatus,
HandoffDeadlineAt: effectiveHandoffDeadlineAt(row.RentalOrder),
CreatedAt: row.CreatedAt,
}
}
func effectiveHandoffDeadlineAt(order model.RentalOrder) *time.Time {
if order.Status != orderStatusPendingHandoff || order.HandoffDeadlineAt == nil {
return nil
}
if isPlatformHandoffOrder(order) || isPlatformSettlementOrder(order) {
return nil
}
deadline := *order.HandoffDeadlineAt
return &deadline
}
func effectiveHandoffMode(order model.RentalOrder) string {
if order.HandoffMode != "" {
return order.HandoffMode
@@ -144,6 +144,10 @@ func orderListingTerms(snapshot datatypes.JSON) (days int, dailyLossM float64) {
return days, roundQuantity(dailyLossM)
}
func EstimateOrderDurationHours(snapshot datatypes.JSON) int {
return estimateOrderDurationHours(snapshot)
}
func estimateOrderDurationHours(snapshot datatypes.JSON) int {
hafCoinM := readOrderSnapshotCoinM(snapshot)
if hafCoinM <= 0 {
+24
View File
@@ -462,6 +462,30 @@ func pendingPaymentTimeoutMinutes(tx *gorm.DB) int {
return value
}
func autoCompleteHandoffTimeoutMinutesForOrder(tx *gorm.DB, order model.RentalOrder) int {
var row model.SystemConfig
query := tx.Where("`key` = ?", "handoff.auto_complete_timeout_minutes")
tenantID := order.BuyerTenantID
if tenantID == 0 && tx.Statement != nil && tx.Statement.Context != nil {
tenantID = tenancy.IDFromContext(tx.Statement.Context)
}
if tenantID == 0 {
tenantID = order.SourceTenantID
}
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
err := query.First(&row).Error
if err != nil {
return defaultAutoCompleteHandoffTimeoutMinutes
}
value, err := strconv.Atoi(row.Value)
if err != nil || value < 0 {
return defaultAutoCompleteHandoffTimeoutMinutes
}
return value
}
func applyPaymentDeadline(dto *OrderDTO, order model.RentalOrder, timeoutMinutes int) {
if dto == nil || order.Status != orderStatusPendingPayment || timeoutMinutes <= 0 {
return
+4 -1
View File
@@ -64,7 +64,10 @@ type Repository struct {
paymentProbe ChannelPaymentProbe
}
const defaultPendingPaymentTimeoutMinutes = 15
const (
defaultPendingPaymentTimeoutMinutes = 15
defaultAutoCompleteHandoffTimeoutMinutes = 1440
)
func NewRepository(db *gorm.DB, deps ...Dependencies) *Repository {
repo := &Repository{db: db}
@@ -3127,3 +3127,153 @@ func TestCheckoutInvitationRebateUsesActualPlatformProfit(t *testing.T) {
})
}
}
func TestConfirmPaidSetsUnifiedHandoffDeadlineForOwnerAndSkipsPlatform(t *testing.T) {
db := setupOrderTestDB(t)
repo := NewRepository(db)
if err := db.Create(&model.SystemConfig{
TenantID: 1,
Key: "handoff.auto_complete_timeout_minutes",
Value: "720",
}).Error; err != nil {
t.Fatalf("写入系统配置失败: %v", err)
}
owner := model.User{Phone: "13800009101", TenantID: 1}
renter := model.User{Phone: "13900009101", TenantID: 1}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&renter).Error; err != nil {
t.Fatal(err)
}
makeOrder := func(suffix, handoffMode string) model.RentalOrder {
acc := model.GameAccount{
OwnerID: owner.ID,
Status: accountStatusPublished,
ServerRegion: "国服",
LoginPlatform: "steam",
Title: "自动交接测试账号-" + suffix,
}
if err := db.Create(&acc).Error; err != nil {
t.Fatal(err)
}
lst := model.RentalListing{
ListingNo: "LST-DL-" + suffix,
OwnerID: owner.ID,
AccountID: acc.ID,
Status: listingStatusPublished,
ReviewStatus: listingReviewStatusApproved,
InTransaction: true,
PriceCent: 1000,
HandoffMode: handoffMode,
}
if err := db.Create(&lst).Error; err != nil {
t.Fatal(err)
}
ord := model.RentalOrder{
BuyerTenantID: 1,
SourceTenantID: 1,
OrderNo: "ORD-DL-" + suffix,
ListingID: lst.ID,
AccountID: acc.ID,
OwnerID: owner.ID,
RenterID: renter.ID,
RentAmountCent: 1000,
Status: orderStatusPendingPayment,
HandoffStatus: handoffStatusNone,
HandoffMode: handoffMode,
}
if err := db.Create(&ord).Error; err != nil {
t.Fatal(err)
}
return ord
}
ownerOrder := makeOrder("OWN", handoffModeOwner)
platformOrder := makeOrder("PLT", handoffModePlatform)
beforePaid := time.Now()
if _, err := repo.ConfirmPaidFromChannelTx(db, ownerOrder.ID); err != nil {
t.Fatalf("ConfirmPaidFromChannelTx(owner) error = %v", err)
}
if _, err := repo.ConfirmPaidFromChannelTx(db, platformOrder.ID); err != nil {
t.Fatalf("ConfirmPaidFromChannelTx(platform) error = %v", err)
}
var savedOwner, savedPlatform model.RentalOrder
_ = db.First(&savedOwner, ownerOrder.ID)
_ = db.First(&savedPlatform, platformOrder.ID)
if savedOwner.HandoffDeadlineAt == nil {
t.Fatal("owner order HandoffDeadlineAt should be set after payment")
}
expectedMin := beforePaid.Add(719 * time.Minute)
expectedMax := time.Now().Add(721 * time.Minute)
if savedOwner.HandoffDeadlineAt.Before(expectedMin) || savedOwner.HandoffDeadlineAt.After(expectedMax) {
t.Fatalf("HandoffDeadlineAt = %v, want within ~720m [%v, %v]", savedOwner.HandoffDeadlineAt, expectedMin, expectedMax)
}
if savedPlatform.HandoffDeadlineAt != nil {
t.Fatalf("platform order HandoffDeadlineAt = %v, want nil", savedPlatform.HandoffDeadlineAt)
}
// 号主提交交接后,统一倒计时不重置(沿用原 HandoffDeadlineAt)
initialDeadline := *savedOwner.HandoffDeadlineAt
if _, err := repo.SubmitHandoff(t.Context(), owner.ID, ownerOrder.ID, SubmitHandoffRequest{Content: "已提交账号"}); err != nil {
t.Fatalf("SubmitHandoff() error = %v", err)
}
_ = db.First(&savedOwner, ownerOrder.ID)
if savedOwner.HandoffDeadlineAt == nil || !savedOwner.HandoffDeadlineAt.Equal(initialDeadline) {
t.Fatalf("HandoffDeadlineAt changed after SubmitHandoff: got %v, want %v", savedOwner.HandoffDeadlineAt, initialDeadline)
}
// 详情和列表在待交接阶段透出 handoff_deadline_at,平台代管订单与已收号订单不透出
userDTO, err := repo.FindForUser(t.Context(), renter.ID, ownerOrder.ID)
if err != nil {
t.Fatalf("FindForUser() error = %v", err)
}
if userDTO.HandoffDeadlineAt == nil {
t.Fatal("expected FindForUser to expose handoff_deadline_at during pending_handoff")
}
platformDTO, err := repo.FindForUser(t.Context(), renter.ID, platformOrder.ID)
if err != nil {
t.Fatalf("FindForUser(platform) error = %v", err)
}
if platformDTO.HandoffDeadlineAt != nil {
t.Fatalf("expected platform order DTO handoff_deadline_at nil, got %v", platformDTO.HandoffDeadlineAt)
}
// 列表接口也应在待交接阶段透出 handoff_deadline_at,平台代管订单不透出
listResult, err := repo.ListForUser(t.Context(), renter.ID, 1, 20)
if err != nil {
t.Fatalf("ListForUser() error = %v", err)
}
foundOwnerInList := false
for _, item := range listResult.Items {
if item.ID == ownerOrder.ID {
foundOwnerInList = true
if item.HandoffDeadlineAt == nil {
t.Fatal("expected ListForUser to expose handoff_deadline_at during pending_handoff")
}
}
if item.ID == platformOrder.ID && item.HandoffDeadlineAt != nil {
t.Fatalf("expected platform order list item handoff_deadline_at nil, got %v", item.HandoffDeadlineAt)
}
}
if !foundOwnerInList {
t.Fatal("expected ownerOrder in ListForUser result")
}
if err := repo.ConfirmReceive(t.Context(), renter.ID, ownerOrder.ID); err != nil {
t.Fatalf("ConfirmReceive() error = %v", err)
}
afterReceiveDTO, err := repo.FindForUser(t.Context(), renter.ID, ownerOrder.ID)
if err != nil {
t.Fatalf("FindForUser() after receive error = %v", err)
}
if afterReceiveDTO.HandoffDeadlineAt != nil {
t.Fatalf("expected handoff_deadline_at cleared from DTO once renting, got %v", afterReceiveDTO.HandoffDeadlineAt)
}
}
@@ -26,11 +26,16 @@ func ParseDistributionSettlementHoldDays(raw string) int {
return days
}
// AutoCompleteHandoffTimeoutKey 是「网站自交接订单自动完成倒计时(分钟)」的系统配置键。
const AutoCompleteHandoffTimeoutKey = "handoff.auto_complete_timeout_minutes"
// validateConfigValue 按配置键分发校验逻辑,未注册校验的键直接放行。
func validateConfigValue(key, value string) error {
switch key {
case DistributionSettlementHoldDaysKey:
return validateDistributionSettlementHoldDays(value)
case AutoCompleteHandoffTimeoutKey:
return validateNonNegativeMinutes(value, 30*24*60)
case smsnode.ConfigKey:
if _, err := smsnode.ParseConfigValue(value); err != nil {
return ErrInvalidConfig
@@ -48,3 +53,11 @@ func validateDistributionSettlementHoldDays(value string) error {
}
return nil
}
func validateNonNegativeMinutes(value string, maxMinutes int) error {
minutes, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || minutes < 0 || minutes > maxMinutes {
return ErrInvalidConfig
}
return nil
}
@@ -64,3 +64,41 @@ func TestValidateConfigValueDistributionSettlementHoldDays(t *testing.T) {
t.Fatalf("无关配置键应放行, got %v", err)
}
}
func TestAutoCompleteHandoffTimeoutConfig(t *testing.T) {
visible := false
for _, key := range adminVisibleConfigKeys {
if key == AutoCompleteHandoffTimeoutKey {
visible = true
break
}
}
if !visible {
t.Fatalf("adminVisibleConfigKeys 缺少 %s", AutoCompleteHandoffTimeoutKey)
}
foundDefault := false
for _, item := range defaultConfigs {
if item.Key == AutoCompleteHandoffTimeoutKey {
foundDefault = true
if item.Value != "1440" {
t.Fatalf("default %s = %q, want 1440", AutoCompleteHandoffTimeoutKey, item.Value)
}
break
}
}
if !foundDefault {
t.Fatalf("defaultConfigs 缺少 %s", AutoCompleteHandoffTimeoutKey)
}
for _, value := range []string{"0", "60", "1440", "43200"} {
if err := validateConfigValue(AutoCompleteHandoffTimeoutKey, value); err != nil {
t.Fatalf("validateConfigValue(%q) = %v, want nil", value, err)
}
}
for _, value := range []string{"-1", "43201", "", "abc"} {
if err := validateConfigValue(AutoCompleteHandoffTimeoutKey, value); err != ErrInvalidConfig {
t.Fatalf("validateConfigValue(%q) = %v, want ErrInvalidConfig", value, err)
}
}
}
@@ -36,6 +36,7 @@ type defaultConfig struct {
var defaultConfigs = []defaultConfig{
{Key: "handoff.owner_submit_timeout_minutes", Value: "30", Description: "号主待交接超时分钟数"},
{Key: "handoff.renter_confirm_timeout_minutes", Value: "30", Description: "租客待确认收号超时分钟数"},
{Key: "handoff.auto_complete_timeout_minutes", Value: "1440", Description: "网站自交接订单自动完成倒计时分钟数(0 表示关闭)"},
{Key: "handoff.owner_return_confirm_timeout_minutes", Value: "120", Description: "号主待确认结账超时分钟数"},
{Key: "order.pending_payment_timeout_minutes", Value: "15", Description: "订单待支付超时取消分钟数"},
{Key: "order.return_overdue_grace_minutes", Value: "10", Description: "预计截止后结账宽限分钟数"},
@@ -74,6 +75,7 @@ var adminVisibleConfigKeys = []string{
"chat.listing_group_welcome",
"chat.renter_retention_days_after_order_end",
"distribution.default_settlement_hold_days",
"handoff.auto_complete_timeout_minutes",
"handoff.owner_return_confirm_timeout_minutes",
"handoff.owner_submit_timeout_minutes",
"handoff.renter_confirm_timeout_minutes",
@@ -0,0 +1,12 @@
-- +goose Up
-- 新增网站自交接订单统一自动交接截止时间;仅对功能上线后的新付款非代管订单写入,历史订单保持 NULL 不受影响。
ALTER TABLE rental_orders
ADD COLUMN handoff_deadline_at DATETIME NULL COMMENT '统一自动交接截止时间' AFTER handoff_started_at,
ADD INDEX idx_rental_orders_handoff_deadline (status, handoff_deadline_at);
-- +goose Down
ALTER TABLE rental_orders
DROP INDEX idx_rental_orders_handoff_deadline,
DROP COLUMN handoff_deadline_at;
@@ -28,6 +28,7 @@ const actionLabels: Record<string, string> = {
owner_handoff_submitted: '号主提交交接',
platform_handoff_submitted: '客服代交接',
admin_force_handoff: '客服确认交接',
system_auto_handoff: '系统自动完成交接',
renter_received_confirmed: '租客确认收号',
checkout_submitted: '租客发起结账',
checkout_countered: '修改结账方案',
@@ -112,6 +112,8 @@ export function formatHandoffRecordType(type: string) {
const typeMap: Record<string, string> = {
owner_handoff: '卖家交接',
platform_handoff: '客服代交接',
admin_force_handoff: '客服一键交接',
system_auto_handoff: '系统自动交接',
renter_checkout: '买家结账',
owner_counter_checkout: '卖家反驳结账',
platform_checkout_counter: '客服修改结账',
@@ -50,7 +50,8 @@ import {
refundStatusLabel,
settlementStatusLabel,
} from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateTime, formatHandoffCountdownDetail } from '@/shared/utils/time'
import { formatGameName, formatListingNo } from '@/shared/utils/listingDisplay'
import { useAdminSessionStore } from '@/stores/adminSession'
import AdminOrderMetrics, { type AdminOrderMetric } from '../components/AdminOrderMetrics.vue'
@@ -73,6 +74,17 @@ const adminSession = useAdminSessionStore()
const loading = ref(false)
const submitting = ref(false)
const order = ref<Order | null>(null)
const nowMs = useNowTick(1000)
const handoffCountdownText = computed(() => {
if (
!order.value ||
order.value.status !== 'pending_handoff' ||
!order.value.handoff_deadline_at
) {
return null
}
return formatHandoffCountdownDetail(order.value.handoff_deadline_at, nowMs.value)
})
const handoffRecords = ref<HandoffRecord[]>([])
const processEvents = ref<ProcessEvent[]>([])
const paymentRecords = ref<AdminPayment[]>([])
@@ -1218,6 +1230,13 @@ function formatRatioNumber(value: number) {
<dt>支付截止</dt>
<dd>{{ formatDateTime(order.payment_deadline_at, '未设置') }}</dd>
</div>
<div v-if="order.handoff_deadline_at">
<dt>自动交接截止</dt>
<dd>
{{ formatDateTime(order.handoff_deadline_at) }}
<template v-if="handoffCountdownText">({{ handoffCountdownText }})</template>
</dd>
</div>
<div>
<dt>开始租用</dt>
<dd>{{ formatDateTime(orderRentedAt(), '未开始') }}</dd>
@@ -92,6 +92,7 @@ export interface Order {
checkout?: Checkout
admin_actions?: AdminActions
payment_deadline_at?: string
handoff_deadline_at?: string
created_at: string
updated_at: string
}
@@ -115,6 +116,7 @@ export interface UserOrderListItem {
handoff_status: HandoffStatus
can_hide?: boolean
payment_deadline_at?: string
handoff_deadline_at?: string
created_at: string
}
@@ -140,6 +142,7 @@ export interface AdminOrderListItem {
handoff_mode: string
settlement_mode: string
settlement_status: SettlementStatus
handoff_deadline_at?: string
created_at: string
// 已结账/已仲裁时返回号主实际到手金额(分);未结账为 undefined,与到手 0 元可区分。
owner_income_amount_cent?: number
@@ -4,6 +4,7 @@ import type { Order } from '../api/orders'
import {
buildCheckoutContentWithSummary,
CHECKOUT_SYSTEM_SUMMARY_MARKER,
formatHandoffRecordType,
orderListRentalTerms,
orderRentalTerms,
parseCheckoutSystemSummary,
@@ -40,6 +41,12 @@ describe('orderListRentalTerms', () => {
})
})
describe('formatHandoffRecordType', () => {
it('formats system_auto_handoff cleanly', () => {
expect(formatHandoffRecordType('system_auto_handoff')).toBe('系统自动交接')
})
})
const ammoResource: CheckoutResource = {
key: 'ammo6',
label: '6级弹',
@@ -468,6 +468,7 @@ export function formatHandoffRecordType(type: string) {
owner_handoff: '卖家交接',
platform_handoff: '客服代交接',
admin_force_handoff: '客服一键交接',
system_auto_handoff: '系统自动交接',
renter_checkout: '买家结账',
owner_counter_checkout: '卖家反驳结账',
platform_checkout_counter: '客服修改结账',
@@ -419,3 +419,23 @@
.empty-wrap {
padding: 60px 0;
}
.handoff-countdown-card {
border: 1px solid #fcd34d;
background: linear-gradient(180deg, #fffbeb 0%, #fef3c7 100%);
}
.handoff-countdown-title {
display: block;
margin-bottom: 4px;
color: #92400e;
font-size: 14px;
font-weight: 700;
}
.handoff-countdown-desc {
margin: 0;
color: #b45309;
font-size: 12px;
line-height: 1.5;
}
@@ -18,7 +18,8 @@ import {
OrderResourceUsageEditor,
} from '@/features/orders'
import { orderHandoffStatusLabel, orderStatusLabel } from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateTime, formatHandoffCountdownDetail } from '@/shared/utils/time'
// 移动端支付收银台(基于通用 useOrderPaymentCashier 的薄封装:注入 vant toast + App 浏览器跳转)。
const cashier = useMobilePaymentCashier()
@@ -129,6 +130,17 @@ const {
})
const rentalTerms = computed(() => orderRentalTerms(order.value))
const nowMs = useNowTick(1000)
const handoffCountdownText = computed(() => {
if (
!order.value ||
order.value.status !== 'pending_handoff' ||
!order.value.handoff_deadline_at
) {
return null
}
return formatHandoffCountdownDetail(order.value.handoff_deadline_at, nowMs.value)
})
// Mobile 独有 UI 状态:各类 popup 显隐。
const showDisputePopup = ref(false)
@@ -315,6 +327,18 @@ async function copyListingCode() {
</van-cell-group>
</section>
<section
v-if="handoffCountdownText && order.handoff_deadline_at"
class="card-section handoff-countdown-card"
>
<strong class="handoff-countdown-title">自动交接倒计时:{{ handoffCountdownText }}</strong>
<p class="handoff-countdown-desc">
将于
{{ formatDateTime(order.handoff_deadline_at) }}
自动完成交接并进入使用中;号主交接与租客确认共用此倒计时。
</p>
</section>
<!-- Renter Action: Pay / Cancel -->
<section v-if="order.status === 'pending_payment'" class="card-section action-card">
<p class="action-hint">订单已创建,请确认并在有效期内完成支付。过期订单将自动关闭。</p>
@@ -23,7 +23,8 @@ import {
type MohongOrder,
} from '@/features/mohong/api/mohong'
import { centToYuan, formatCent, formatMoney } from '@/shared/utils/money'
import { formatDateMinute } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateMinute, formatHandoffCountdownCompact } from '@/shared/utils/time'
import { formatListingNo } from '@/shared/utils/listingDisplay'
import { useDistributionSiteStore } from '@/stores/distributionSite'
@@ -57,6 +58,7 @@ const hidingOrderId = ref<number | null>(null)
const rentalTotal = ref(0)
const rentalPage = ref(1)
const rentalPageSize = 20
const nowMs = useNowTick(15000)
const {
paymentPopupVisible,
activePayment,
@@ -310,6 +312,11 @@ function formatListingCode(order: UserOrderListItem) {
return formatListingNo(order.listing_no, order.listing_id)
}
function getHandoffCountdownText(order: UserOrderListItem) {
if (order.status !== 'pending_handoff' || !order.handoff_deadline_at) return null
return formatHandoffCountdownCompact(order.handoff_deadline_at, nowMs.value)
}
async function copyListingCode(order: UserOrderListItem) {
try {
await navigator.clipboard.writeText(formatListingCode(order))
@@ -407,6 +414,10 @@ async function copyListingCode(order: UserOrderListItem) {
<span class="info-tag">{{ item.rental.server_region }}</span>
<span class="info-tag">{{ item.rental.login_platform }}</span>
</div>
<div v-if="getHandoffCountdownText(item.rental)" class="handoff-countdown-pill">
<van-icon name="clock-o" :size="12" />
<span>{{ getHandoffCountdownText(item.rental) }}</span>
</div>
</div>
<div class="rental-price-panel">
@@ -863,6 +874,19 @@ async function copyListingCode(order: UserOrderListItem) {
margin-bottom: 0;
}
.handoff-countdown-pill {
display: inline-flex;
align-items: center;
gap: 4px;
margin-top: 7px;
padding: 2px 8px;
border-radius: 4px;
background: #fef3c7;
color: #b45309;
font-size: 11px;
font-weight: 600;
}
.info-tag {
position: relative;
padding: 0;
@@ -385,6 +385,35 @@
line-height: 1.45;
}
.handoff-countdown-strip {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 14px;
padding: 14px 16px;
border: 1px solid #fcd34d;
border-radius: 8px;
background: linear-gradient(180deg, #fffbeb 0%, #fef3c7 100%);
}
.handoff-countdown-strip div {
display: grid;
gap: 4px;
flex: 1;
min-width: 0;
}
.handoff-countdown-strip strong {
color: #92400e;
font-size: 14px;
}
.handoff-countdown-strip span {
color: #b45309;
font-size: 12px;
line-height: 1.45;
}
.secondary-actions {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
@@ -19,7 +19,8 @@ import { useOrderActions } from '@/features/orders/composables/useOrderActions'
import { useOrderPaymentCashier } from '@/features/orders/composables/useOrderPaymentCashier'
import { formatCent } from '@/shared/utils/money'
import { orderHandoffStatusLabel, orderStatusLabel } from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateTime, formatHandoffCountdownDetail } from '@/shared/utils/time'
import type { PaymentPayWay } from '@/features/orders/api/orders'
// 支付收银台:二维码渲染 + 轮询查询。PC 不做 App 浏览器跳转,直接渲染二维码弹窗。
@@ -123,6 +124,17 @@ const {
})
const rentalTerms = computed(() => orderRentalTerms(order.value))
const nowMs = useNowTick(1000)
const handoffCountdownText = computed(() => {
if (
!order.value ||
order.value.status !== 'pending_handoff' ||
!order.value.handoff_deadline_at
) {
return null
}
return formatHandoffCountdownDetail(order.value.handoff_deadline_at, nowMs.value)
})
// 支付弹窗别名:保持 template 字段名不变。
const paymentDialogVisible = cashier.paymentPopupVisible
@@ -352,6 +364,20 @@ watch([() => route.query.focus, order, loading], () => {
</el-steps>
</div>
<div
v-if="handoffCountdownText && order?.handoff_deadline_at"
class="handoff-countdown-strip"
>
<div>
<strong>统一自动交接倒计时:{{ handoffCountdownText }}</strong>
<span>
将于
{{ formatDateTime(order.handoff_deadline_at) }}
自动完成交接并进入使用中;号主交接与租客确认共用此倒计时。
</span>
</div>
</div>
<div
v-if="
isOwner &&
@@ -18,7 +18,8 @@ import {
} from '@/features/mohong/api/mohong'
import { centToYuan, formatCent, formatMoney } from '@/shared/utils/money'
import { orderStatusLabel } from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateTime, formatHandoffCountdownCompact } from '@/shared/utils/time'
import { formatListingNo } from '@/shared/utils/listingDisplay'
import { useDistributionSiteStore } from '@/stores/distributionSite'
@@ -53,6 +54,7 @@ const siteStore = useDistributionSiteStore()
const rentalTotal = ref(0)
const rentalPage = ref(1)
const rentalPageSize = 20
const nowMs = useNowTick(15000)
const statusTabs = [
{ key: 'all', label: '全部' },
@@ -330,11 +332,15 @@ function getPaymentDeadline(order: UserOrderListItem) {
function getCountdownMinutes(order: UserOrderListItem) {
const deadline = getPaymentDeadline(order)
if (!deadline) return 0
const now = new Date()
const diff = deadline.getTime() - now.getTime()
const diff = deadline.getTime() - nowMs.value
return Math.max(0, Math.ceil(diff / 60000))
}
function getHandoffCountdownText(order: UserOrderListItem) {
if (order.status !== 'pending_handoff' || !order.handoff_deadline_at) return null
return formatHandoffCountdownCompact(order.handoff_deadline_at, nowMs.value)
}
function statusText(item: UnifiedOrderItem) {
if (item.bizType === 'crash') return mohongOrderStatusLabel(item.status)
return orderStatusLabel(item.status)
@@ -509,6 +515,14 @@ function bizTypeLabel(bizType: BizType) {
>
{{ getCountdownMinutes(row.rental) }}分钟后超时
</span>
<span
v-else-if="
row.bizType === 'rental' && row.rental && getHandoffCountdownText(row.rental)
"
class="countdown-badge"
>
{{ getHandoffCountdownText(row.rental) }}
</span>
</div>
</template>
</el-table-column>
@@ -622,6 +636,9 @@ function bizTypeLabel(bizType: BizType) {
>
{{ getCountdownMinutes(item.rental) }}分钟后超时
</span>
<span v-else-if="getHandoffCountdownText(item.rental)" class="countdown-badge">
{{ getHandoffCountdownText(item.rental) }}
</span>
</div>
<el-button
v-if="item.rental.can_hide"
@@ -8,7 +8,8 @@ import {
type UserOrderListItem,
} from '@/features/orders'
import { handoffStatusLabel, orderStatusLabel } from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'
import { useNowTick } from '@/shared/composables/useNowTick'
import { formatDateTime, formatHandoffCountdownCompact } from '@/shared/utils/time'
import { centToYuan, formatMoney } from '@/shared/utils/money'
import { formatListingNo } from '@/shared/utils/listingDisplay'
@@ -23,6 +24,7 @@ const metrics = ref<SellerHandoffMetrics>({
pending_checkout: 0,
abnormal: 0,
})
const nowMs = useNowTick(15000)
onMounted(loadOrders)
@@ -69,6 +71,11 @@ function money(value: unknown) {
function sellerAmount(order: UserOrderListItem) {
return centToYuan(order.display_amount_cent)
}
function getHandoffCountdownText(order: UserOrderListItem) {
if (order.status !== 'pending_handoff' || !order.handoff_deadline_at) return null
return formatHandoffCountdownCompact(order.handoff_deadline_at, nowMs.value)
}
</script>
<template>
@@ -129,8 +136,19 @@ function sellerAmount(order: UserOrderListItem) {
<el-table-column label="订单状态" width="150">
<template #default="{ row }">{{ orderStatusLabel(row.status) }}</template>
</el-table-column>
<el-table-column label="交接状态" width="180">
<template #default="{ row }">{{ handoffStatusLabel(row.handoff_status) }}</template>
<el-table-column label="交接状态" width="210">
<template #default="{ row }">
<div>{{ handoffStatusLabel(row.handoff_status) }}</div>
<el-tag
v-if="getHandoffCountdownText(row)"
size="small"
type="warning"
effect="plain"
style="margin-top: 4px"
>
{{ getHandoffCountdownText(row) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="创建时间" min-width="180">
<template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
@@ -0,0 +1,22 @@
import { onMounted, onUnmounted, ref } from 'vue'
export function useNowTick(intervalMs = 1000) {
const nowMs = ref(Date.now())
let timer: ReturnType<typeof setInterval> | null = null
onMounted(() => {
nowMs.value = Date.now()
timer = setInterval(() => {
nowMs.value = Date.now()
}, intervalMs)
})
onUnmounted(() => {
if (timer !== null) {
clearInterval(timer)
timer = null
}
})
return nowMs
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { formatHandoffCountdownCompact, formatHandoffCountdownDetail } from '../time'
describe('handoff countdown helpers', () => {
const base = Date.UTC(2026, 10, 30, 12, 0, 0)
it('returns null for empty or invalid deadline', () => {
expect(formatHandoffCountdownDetail(undefined, base)).toBeNull()
expect(formatHandoffCountdownDetail('', base)).toBeNull()
expect(formatHandoffCountdownDetail('invalid-date', base)).toBeNull()
expect(formatHandoffCountdownCompact(null, base)).toBeNull()
})
it('formats remaining hours, minutes and seconds for detail banner', () => {
const deadline23h = new Date(base + (23 * 3600 + 5 * 60 + 9) * 1000).toISOString()
expect(formatHandoffCountdownDetail(deadline23h, base)).toBe('23小时05分09秒')
const deadline12m = new Date(base + (12 * 60 + 3) * 1000).toISOString()
expect(formatHandoffCountdownDetail(deadline12m, base)).toBe('12分03秒')
const deadline20s = new Date(base + 20 * 1000).toISOString()
expect(formatHandoffCountdownDetail(deadline20s, base)).toBe('20秒')
})
it('formats compact countdown for order lists', () => {
const deadline24h = new Date(base + 24 * 3600 * 1000).toISOString()
expect(formatHandoffCountdownCompact(deadline24h, base)).toBe('24小时后自动交接')
const deadline2h15m = new Date(base + (2 * 3600 + 15 * 60) * 1000).toISOString()
expect(formatHandoffCountdownCompact(deadline2h15m, base)).toBe('2小时15分后自动交接')
const deadline45m = new Date(base + 45 * 60 * 1000).toISOString()
expect(formatHandoffCountdownCompact(deadline45m, base)).toBe('45分钟后自动交接')
})
it('shows expiring message once deadline has passed', () => {
const expired = new Date(base - 1000).toISOString()
expect(formatHandoffCountdownDetail(expired, base)).toBe('倒计时已到期,系统正在自动完成交接')
expect(formatHandoffCountdownCompact(expired, base)).toBe('即将自动交接')
})
})
@@ -36,6 +36,7 @@ const booleanOptions: SystemConfigOption[] = [
export const systemConfigSelectOptions: Record<string, SystemConfigOption[]> = {
'handoff.owner_submit_timeout_minutes': shortTimeoutOptions,
'handoff.renter_confirm_timeout_minutes': shortTimeoutOptions,
'handoff.auto_complete_timeout_minutes': longTimeoutOptions,
'handoff.owner_return_confirm_timeout_minutes': longTimeoutOptions,
'order.pending_payment_timeout_minutes': shortTimeoutOptions,
'order.return_overdue_grace_minutes': [
+44
View File
@@ -23,6 +23,50 @@ export function formatInputDate(value: Date = new Date()) {
return [value.getFullYear(), pad(value.getMonth() + 1), pad(value.getDate())].join('-')
}
export function formatHandoffCountdownDetail(
deadlineAt: DateInput,
nowMs: number = Date.now()
): string | null {
if (!deadlineAt) return null
const deadline = deadlineAt instanceof Date ? deadlineAt : new Date(deadlineAt)
if (Number.isNaN(deadline.getTime())) return null
const diffMs = deadline.getTime() - nowMs
if (diffMs <= 0) {
return '倒计时已到期,系统正在自动完成交接'
}
const totalSeconds = Math.ceil(diffMs / 1000)
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
if (hours > 0) {
return `${hours}小时${pad(minutes)}分${pad(seconds)}秒`
}
if (minutes > 0) {
return `${minutes}分${pad(seconds)}秒`
}
return `${seconds}秒`
}
export function formatHandoffCountdownCompact(
deadlineAt: DateInput,
nowMs: number = Date.now()
): string | null {
if (!deadlineAt) return null
const deadline = deadlineAt instanceof Date ? deadlineAt : new Date(deadlineAt)
if (Number.isNaN(deadline.getTime())) return null
const diffMs = deadline.getTime() - nowMs
if (diffMs <= 0) {
return '即将自动交接'
}
const totalMinutes = Math.ceil(diffMs / 60000)
if (totalMinutes >= 60) {
const hours = Math.floor(totalMinutes / 60)
const minutes = totalMinutes % 60
return minutes > 0 ? `${hours}小时${minutes}分后自动交接` : `${hours}小时后自动交接`
}
return `${totalMinutes}分钟后自动交接`
}
function pad(value: number) {
return String(value).padStart(2, '0')
}