第 4 阶段:订单、交接与账务--1

This commit is contained in:
yml
2026-05-22 16:05:40 +08:00
parent 9ac65ffad9
commit edda1fbc7b
16 changed files with 1102 additions and 5 deletions
+52
View File
@@ -0,0 +1,52 @@
package order
import (
"time"
"gorm.io/datatypes"
)
type OrderDTO struct {
ID uint64 `json:"id"`
OrderNo string `json:"order_no"`
ListingID uint64 `json:"listing_id"`
AccountID uint64 `json:"account_id"`
OwnerID uint64 `json:"owner_id"`
RenterID uint64 `json:"renter_id"`
Title string `json:"title"`
ServerRegion string `json:"server_region"`
LoginPlatform string `json:"login_platform"`
RentStartAt *time.Time `json:"rent_start_at"`
RentEndAt *time.Time `json:"rent_end_at"`
RentHours int `json:"rent_hours"`
RentAmount float64 `json:"rent_amount"`
DepositAmount float64 `json:"deposit_amount"`
PlatformFee float64 `json:"platform_fee"`
AccountSnapshot datatypes.JSON `json:"account_snapshot"`
Status string `json:"status"`
HandoffStatus string `json:"handoff_status"`
SettlementStatus string `json:"settlement_status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CreateRequest struct {
ListingID uint64 `json:"listing_id" binding:"required"`
RentHours int `json:"rent_hours" binding:"required"`
}
type SubmitHandoffRequest struct {
Content string `json:"content" binding:"required"`
}
type HandoffRecordDTO struct {
ID uint64 `json:"id"`
OrderID uint64 `json:"order_id"`
FromUserID uint64 `json:"from_user_id"`
ToUserID uint64 `json:"to_user_id"`
Type string `json:"type"`
Content string `json:"content"`
ConfirmedByRenterAt *time.Time `json:"confirmed_by_renter_at"`
ConfirmedByOwnerAt *time.Time `json:"confirmed_by_owner_at"`
CreatedAt time.Time `json:"created_at"`
}
+189
View File
@@ -0,0 +1,189 @@
package order
import (
"errors"
"net/http"
"strconv"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) Create(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
var req CreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "订单信息不完整")
return
}
item, err := h.service.Create(userID, req)
if err != nil {
writeOrderError(c, err)
return
}
response.Created(c, item)
}
func (h *Handler) List(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
items, err := h.service.ListForUser(userID)
if err != nil {
writeOrderError(c, err)
return
}
response.OK(c, gin.H{"items": items})
}
func (h *Handler) Detail(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
item, err := h.service.FindForUser(userID, id)
if err != nil {
writeOrderError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) Cancel(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
if err := h.service.Cancel(userID, id); err != nil {
writeOrderError(c, err)
return
}
response.OK(c, gin.H{"cancelled": true})
}
func (h *Handler) SubmitHandoff(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
var req SubmitHandoffRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "交接说明不能为空")
return
}
record, err := h.service.SubmitHandoff(userID, id, req)
if err != nil {
writeOrderError(c, err)
return
}
response.Created(c, record)
}
func (h *Handler) ConfirmReceive(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
if err := h.service.ConfirmReceive(userID, id); err != nil {
writeOrderError(c, err)
return
}
response.OK(c, gin.H{"received": true})
}
func (h *Handler) HandoffRecords(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
id, ok := parseID(c)
if !ok {
return
}
items, err := h.service.HandoffRecords(userID, id)
if err != nil {
writeOrderError(c, err)
return
}
response.OK(c, gin.H{"items": items})
}
func currentUserID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextUserID)
if !ok {
return 0, false
}
userID, ok := value.(uint64)
return userID, ok
}
func parseID(c *gin.Context) (uint64, bool) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
response.BadRequest(c, "ID 不正确")
return 0, false
}
return id, true
}
func writeOrderError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrDependencyUnavailable):
response.ServiceUnavailable(c, "数据库未连接")
case errors.Is(err, ErrInvalidRentHours):
response.BadRequest(c, "租期不符合规则")
case errors.Is(err, ErrListingUnavailable):
response.Error(c, http.StatusConflict, "listing_unavailable", "该账号暂不可租")
case errors.Is(err, ErrCannotRentOwnListing):
response.BadRequest(c, "不能租用自己发布的账号")
case errors.Is(err, ErrOrderCannotCancel):
response.Error(c, http.StatusConflict, "order_cannot_cancel", "当前订单不能取消")
case errors.Is(err, ErrOrderCannotHandoff):
response.Error(c, http.StatusConflict, "order_cannot_handoff", "当前订单不能交接")
case errors.Is(err, ErrOrderCannotReceive):
response.Error(c, http.StatusConflict, "order_cannot_receive", "当前订单不能确认收号")
case errors.Is(err, ErrPermissionDenied):
response.Error(c, http.StatusForbidden, "permission_denied", "无权操作该订单")
case IsNotFound(err):
response.Error(c, http.StatusNotFound, "not_found", "订单不存在")
default:
response.Error(c, http.StatusInternalServerError, "internal_error", "订单服务暂时不可用")
}
}
@@ -0,0 +1,324 @@
package order
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"hfb_sys/backend/internal/model"
"gorm.io/datatypes"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) Create(renterID uint64, req CreateRequest) (*OrderDTO, error) {
var createdID uint64
err := r.db.Transaction(func(tx *gorm.DB) error {
var listing model.RentalListing
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&listing, req.ListingID).Error; err != nil {
return err
}
if listing.Status != "published" || listing.ReviewStatus != "approved" {
return ErrListingUnavailable
}
if listing.OwnerID == renterID {
return ErrCannotRentOwnListing
}
if req.RentHours < listing.MinRentHours || req.RentHours > listing.MaxRentHours {
return ErrInvalidRentHours
}
var account model.GameAccount
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&account, listing.AccountID).Error; err != nil {
return err
}
snapshot, err := makeAccountSnapshot(account)
if err != nil {
return err
}
orderNo, err := newOrderNo()
if err != nil {
return err
}
now := time.Now()
rentEnd := now.Add(time.Duration(req.RentHours) * time.Hour)
order := model.RentalOrder{
OrderNo: orderNo,
ListingID: listing.ID,
AccountID: listing.AccountID,
OwnerID: listing.OwnerID,
RenterID: renterID,
RentStartAt: &now,
RentEndAt: &rentEnd,
RentHours: req.RentHours,
RentAmount: listing.PriceHourly * float64(req.RentHours),
DepositAmount: listing.DepositAmount,
PlatformFee: 0,
AccountSnapshot: snapshot,
Status: "pending_handoff",
HandoffStatus: "pending_owner",
SettlementStatus: "unsettled",
}
if err := tx.Create(&order).Error; err != nil {
return err
}
listing.Status = "rented"
account.Status = "rented"
if err := tx.Save(&listing).Error; err != nil {
return err
}
if err := tx.Save(&account).Error; err != nil {
return err
}
createdID = order.ID
return nil
})
if err != nil {
return nil, err
}
return r.FindForUser(renterID, createdID)
}
func (r *Repository) Cancel(userID uint64, orderID uint64) error {
return r.db.Transaction(func(tx *gorm.DB) error {
var order model.RentalOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ? AND renter_id = ?", orderID, userID).
First(&order).Error; err != nil {
return err
}
if order.Status != "pending_handoff" {
return ErrOrderCannotCancel
}
var listing model.RentalListing
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&listing, order.ListingID).Error; err != nil {
return err
}
var account model.GameAccount
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&account, order.AccountID).Error; err != nil {
return err
}
order.Status = "cancelled"
order.HandoffStatus = "cancelled"
listing.Status = "published"
account.Status = "published"
if err := tx.Save(&order).Error; err != nil {
return err
}
if err := tx.Save(&listing).Error; err != nil {
return err
}
return tx.Save(&account).Error
})
}
func (r *Repository) SubmitHandoff(userID uint64, orderID uint64, req SubmitHandoffRequest) (*HandoffRecordDTO, error) {
var recordID uint64
err := r.db.Transaction(func(tx *gorm.DB) error {
var order model.RentalOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
return err
}
if order.OwnerID != userID {
return ErrPermissionDenied
}
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_owner" {
return ErrOrderCannotHandoff
}
record := model.HandoffRecord{
OrderID: order.ID,
FromUserID: order.OwnerID,
ToUserID: order.RenterID,
Type: "owner_handoff",
Content: req.Content,
}
if err := tx.Create(&record).Error; err != nil {
return err
}
order.HandoffStatus = "pending_renter_confirm"
if err := tx.Save(&order).Error; err != nil {
return err
}
recordID = record.ID
return nil
})
if err != nil {
return nil, err
}
return r.findHandoffRecord(recordID)
}
func (r *Repository) ConfirmReceive(userID uint64, orderID uint64) error {
return r.db.Transaction(func(tx *gorm.DB) error {
var order model.RentalOrder
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
return err
}
if order.RenterID != userID {
return ErrPermissionDenied
}
if order.Status != "pending_handoff" || order.HandoffStatus != "pending_renter_confirm" {
return ErrOrderCannotReceive
}
now := time.Now()
if err := tx.Model(&model.HandoffRecord{}).
Where("order_id = ? AND type = ?", order.ID, "owner_handoff").
Update("confirmed_by_renter_at", now).Error; err != nil {
return err
}
order.Status = "renting"
order.HandoffStatus = "received"
order.RentStartAt = &now
rentEnd := now.Add(time.Duration(order.RentHours) * time.Hour)
order.RentEndAt = &rentEnd
return tx.Save(&order).Error
})
}
func (r *Repository) HandoffRecords(userID uint64, orderID uint64) ([]HandoffRecordDTO, error) {
var order model.RentalOrder
if err := r.db.Where("id = ? AND (renter_id = ? OR owner_id = ?)", orderID, userID, userID).First(&order).Error; err != nil {
return nil, err
}
var records []model.HandoffRecord
if err := r.db.Where("order_id = ?", orderID).Order("id ASC").Find(&records).Error; err != nil {
return nil, err
}
items := make([]HandoffRecordDTO, 0, len(records))
for _, record := range records {
items = append(items, toHandoffDTO(record))
}
return items, nil
}
func (r *Repository) ListForUser(userID uint64) ([]OrderDTO, error) {
var rows []orderRow
err := r.baseQuery().
Where("o.renter_id = ?", userID).
Order("o.id DESC").
Scan(&rows).Error
if err != nil {
return nil, err
}
items := make([]OrderDTO, 0, len(rows))
for _, row := range rows {
items = append(items, row.toDTO())
}
return items, nil
}
func (r *Repository) FindForUser(userID uint64, orderID uint64) (*OrderDTO, error) {
var row orderRow
if err := r.baseQuery().
Where("o.id = ? AND (o.renter_id = ? OR o.owner_id = ?)", orderID, userID, userID).
First(&row).Error; err != nil {
return nil, err
}
dto := row.toDTO()
return &dto, nil
}
func (r *Repository) findHandoffRecord(id uint64) (*HandoffRecordDTO, error) {
var record model.HandoffRecord
if err := r.db.First(&record, id).Error; err != nil {
return nil, err
}
dto := toHandoffDTO(record)
return &dto, nil
}
func (r *Repository) baseQuery() *gorm.DB {
return r.db.Table("rental_orders AS o").
Select("o.*, a.title, a.server_region, a.login_platform").
Joins("JOIN game_accounts AS a ON a.id = o.account_id")
}
type orderRow struct {
model.RentalOrder
Title string
ServerRegion string
LoginPlatform string
}
func (row orderRow) toDTO() OrderDTO {
return OrderDTO{
ID: row.ID,
OrderNo: row.OrderNo,
ListingID: row.ListingID,
AccountID: row.AccountID,
OwnerID: row.OwnerID,
RenterID: row.RenterID,
Title: row.Title,
ServerRegion: row.ServerRegion,
LoginPlatform: row.LoginPlatform,
RentStartAt: row.RentStartAt,
RentEndAt: row.RentEndAt,
RentHours: row.RentHours,
RentAmount: row.RentAmount,
DepositAmount: row.DepositAmount,
PlatformFee: row.PlatformFee,
AccountSnapshot: row.AccountSnapshot,
Status: row.Status,
HandoffStatus: row.HandoffStatus,
SettlementStatus: row.SettlementStatus,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
}
func toHandoffDTO(record model.HandoffRecord) HandoffRecordDTO {
return HandoffRecordDTO{
ID: record.ID,
OrderID: record.OrderID,
FromUserID: record.FromUserID,
ToUserID: record.ToUserID,
Type: record.Type,
Content: record.Content,
ConfirmedByRenterAt: record.ConfirmedByRenterAt,
ConfirmedByOwnerAt: record.ConfirmedByOwnerAt,
CreatedAt: record.CreatedAt,
}
}
func makeAccountSnapshot(account model.GameAccount) (datatypes.JSON, error) {
payload := map[string]any{
"account_id": account.ID,
"title": account.Title,
"game_name": account.GameName,
"server_region": account.ServerRegion,
"login_platform": account.LoginPlatform,
"rank_level": account.RankLevel,
"haf_coin_amount": account.HafCoinAmount,
"asset_summary": account.AssetSummary,
"season_tags": account.SeasonTags,
"screenshot_urls": account.ScreenshotURLS,
"snapshot_version": 1,
}
raw, err := json.Marshal(payload)
return datatypes.JSON(raw), err
}
func newOrderNo() (string, error) {
buf := make([]byte, 4)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return fmt.Sprintf("RO%d%s", time.Now().UnixNano(), hex.EncodeToString(buf)), nil
}
func IsNotFound(err error) bool {
return errors.Is(err, gorm.ErrRecordNotFound)
}
+77
View File
@@ -0,0 +1,77 @@
package order
import "errors"
var (
ErrDependencyUnavailable = errors.New("dependency unavailable")
ErrInvalidRentHours = errors.New("invalid rent hours")
ErrListingUnavailable = errors.New("listing unavailable")
ErrCannotRentOwnListing = errors.New("cannot rent own listing")
ErrOrderCannotCancel = errors.New("order cannot cancel")
ErrOrderCannotHandoff = errors.New("order cannot handoff")
ErrOrderCannotReceive = errors.New("order cannot receive")
ErrPermissionDenied = errors.New("permission denied")
)
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Create(userID uint64, req CreateRequest) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if req.ListingID == 0 || req.RentHours <= 0 {
return nil, ErrInvalidRentHours
}
return s.repo.Create(userID, req)
}
func (s *Service) Cancel(userID uint64, orderID uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.Cancel(userID, orderID)
}
func (s *Service) SubmitHandoff(userID uint64, orderID uint64, req SubmitHandoffRequest) (*HandoffRecordDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if orderID == 0 || req.Content == "" {
return nil, ErrOrderCannotHandoff
}
return s.repo.SubmitHandoff(userID, orderID, req)
}
func (s *Service) ConfirmReceive(userID uint64, orderID uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.ConfirmReceive(userID, orderID)
}
func (s *Service) HandoffRecords(userID uint64, orderID uint64) ([]HandoffRecordDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.HandoffRecords(userID, orderID)
}
func (s *Service) ListForUser(userID uint64) ([]OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListForUser(userID)
}
func (s *Service) FindForUser(userID uint64, orderID uint64) (*OrderDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.FindForUser(userID, orderID)
}