496 lines
16 KiB
Go
496 lines
16 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/config"
|
|
"hfb_sys/backend/internal/database"
|
|
"hfb_sys/backend/internal/model"
|
|
"hfb_sys/backend/internal/modules/chat"
|
|
"hfb_sys/backend/internal/modules/order"
|
|
"hfb_sys/backend/internal/modules/payment"
|
|
"hfb_sys/backend/internal/modules/paymentconfig"
|
|
"hfb_sys/backend/internal/tenancy"
|
|
|
|
"go.uber.org/zap"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/datatypes"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
const (
|
|
demoPassword = "demo123456"
|
|
ownerDPhone = "13920000001"
|
|
renterDPhone = "13920000002"
|
|
ownerJPhone = "13920000003"
|
|
renterJPhone = "13920000004"
|
|
)
|
|
|
|
type demoEnv struct {
|
|
db *gorm.DB
|
|
dachui model.Tenant
|
|
jieyou model.Tenant
|
|
ownerD model.User
|
|
renterD model.User
|
|
ownerJ model.User
|
|
renterJ model.User
|
|
cashierD *payment.Repository
|
|
cashierJ *payment.Repository
|
|
orderRepo *order.Repository
|
|
paymentRepo *payment.Repository
|
|
orders []model.RentalOrder
|
|
}
|
|
|
|
func main() {
|
|
cfg := config.Load()
|
|
logger := zap.NewNop()
|
|
db, err := database.OpenMySQLWithOptions(cfg.MySQLDSN, cfg.Log.Level, logger, database.MySQLOptions{
|
|
MaxOpenConns: cfg.Database.MaxOpenConns,
|
|
MaxIdleConns: cfg.Database.MaxIdleConns,
|
|
ConnMaxLifetime: cfg.Database.ConnMaxLifetime,
|
|
ConnMaxIdleTime: cfg.Database.ConnMaxIdleTime,
|
|
SlowQueryThreshold: cfg.Database.SlowQueryThreshold,
|
|
})
|
|
if err != nil {
|
|
fail("连接 MySQL 失败", err)
|
|
}
|
|
if err := seed(context.Background(), db); err != nil {
|
|
fail("写入双站演示数据失败", err)
|
|
}
|
|
}
|
|
|
|
func seed(ctx context.Context, db *gorm.DB) error {
|
|
if db == nil {
|
|
return fmt.Errorf("数据库未连接")
|
|
}
|
|
env := &demoEnv{db: db}
|
|
if err := env.ensureTenants(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensureDomains(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensureAdmins(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensureUsers(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensureMerchants(ctx); err != nil {
|
|
return err
|
|
}
|
|
listingD, err := env.ensureListing(ctx, env.dachui, env.ownerD, "L-DEMO-DACHUI", "大锤演示·烽火账号", 10000, 80)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
listingJ, err := env.ensureListing(ctx, env.jieyou, env.ownerJ, "L-DEMO-JIEYOU", "解忧演示·烽火账号", 12000, 96)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := env.ensureListing(ctx, env.dachui, env.ownerD, "L-DEMO-DACHUI-FREE", "大锤演示·可下单账号", 15000, 120); err != nil {
|
|
return err
|
|
}
|
|
if _, err := env.ensureListing(ctx, env.jieyou, env.ownerJ, "L-DEMO-JIEYOU-FREE", "解忧演示·可下单账号", 13000, 104); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensurePaidOrder(ctx, env.dachui, env.renterD, *listingJ); err != nil {
|
|
return err
|
|
}
|
|
if err := env.ensurePaidOrder(ctx, env.jieyou, env.renterJ, *listingD); err != nil {
|
|
return err
|
|
}
|
|
env.printSummary()
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureTenants(ctx context.Context) error {
|
|
rows := []model.Tenant{
|
|
{Code: "dachui", Name: "大锤商行", Status: "active", ProfileJSON: jsonValue(map[string]any{"site_name": "大锤商行"}), FeaturesJSON: jsonValue(map[string]any{})},
|
|
{Code: "jieyou", Name: "解忧商行", Status: "active", ProfileJSON: jsonValue(map[string]any{"site_name": "解忧商行"}), FeaturesJSON: jsonValue(map[string]any{})},
|
|
}
|
|
for index := range rows {
|
|
if err := e.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "code"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"name", "status", "profile_json", "features_json", "updated_at"}),
|
|
}).Create(&rows[index]).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := e.db.WithContext(ctx).Where("code = ?", "dachui").First(&e.dachui).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := e.db.WithContext(ctx).Where("code = ?", "jieyou").First(&e.jieyou).Error; err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureDomains(ctx context.Context) error {
|
|
for _, item := range []struct {
|
|
tenantID uint64
|
|
host string
|
|
}{
|
|
{tenantID: e.dachui.ID, host: "dachui.localhost"},
|
|
{tenantID: e.jieyou.ID, host: "jieyou.localhost"},
|
|
} {
|
|
row := model.TenantDomain{
|
|
TenantID: item.tenantID,
|
|
Host: item.host,
|
|
DomainType: "storefront",
|
|
Status: "active",
|
|
}
|
|
if err := e.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "host"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"tenant_id", "domain_type", "status", "updated_at"}),
|
|
}).Create(&row).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureAdmins(ctx context.Context) error {
|
|
var role model.Role
|
|
if err := e.db.WithContext(ctx).Where("code = ?", "cs").First(&role).Error; err != nil {
|
|
if err != gorm.ErrRecordNotFound {
|
|
return err
|
|
}
|
|
role = model.Role{Code: "cs", Name: "客服", Description: "双站演示客服"}
|
|
if err := e.db.WithContext(ctx).Create(&role).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(demoPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, item := range []struct {
|
|
username string
|
|
nickname string
|
|
tenantID uint64
|
|
}{
|
|
{username: "demo_dachui_cs", nickname: "大锤演示客服", tenantID: e.dachui.ID},
|
|
{username: "demo_jieyou_cs", nickname: "解忧演示客服", tenantID: e.jieyou.ID},
|
|
} {
|
|
admin := model.AdminUser{}
|
|
err := e.db.WithContext(ctx).Where("username = ?", item.username).First(&admin).Error
|
|
if err == gorm.ErrRecordNotFound {
|
|
admin = model.AdminUser{
|
|
Username: item.username,
|
|
PasswordHash: string(hash),
|
|
Nickname: item.nickname,
|
|
Status: "active",
|
|
TokenVersion: 1,
|
|
}
|
|
if err := e.db.WithContext(ctx).Create(&admin).Error; err != nil {
|
|
return err
|
|
}
|
|
} else if err != nil {
|
|
return err
|
|
} else if err := e.db.WithContext(ctx).Model(&admin).Updates(map[string]any{
|
|
"password_hash": string(hash),
|
|
"nickname": item.nickname,
|
|
"status": "active",
|
|
}).Error; err != nil {
|
|
return err
|
|
}
|
|
binding := model.AdminUserRole{AdminID: admin.ID, RoleID: role.ID, TenantID: item.tenantID}
|
|
if err := e.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&binding).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureUsers(ctx context.Context) error {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(demoPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
e.ownerD = e.ensureUser(ctx, e.dachui.ID, ownerDPhone, "大锤演示号主", string(hash), &errs)
|
|
e.renterD = e.ensureUser(ctx, e.dachui.ID, renterDPhone, "大锤演示租客", string(hash), &errs)
|
|
e.ownerJ = e.ensureUser(ctx, e.jieyou.ID, ownerJPhone, "解忧演示号主", string(hash), &errs)
|
|
e.renterJ = e.ensureUser(ctx, e.jieyou.ID, renterJPhone, "解忧演示租客", string(hash), &errs)
|
|
for _, item := range errs {
|
|
if item != nil {
|
|
return item
|
|
}
|
|
}
|
|
for _, user := range []model.User{e.ownerD, e.renterD, e.ownerJ, e.renterJ} {
|
|
if err := e.ensureRealname(ctx, user); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureUser(ctx context.Context, tenantID uint64, phone, nickname, passwordHash string, errs *[]error) model.User {
|
|
var user model.User
|
|
err := e.db.WithContext(ctx).Where("tenant_id = ? AND phone = ?", tenantID, phone).First(&user).Error
|
|
if err == gorm.ErrRecordNotFound {
|
|
user = model.User{
|
|
TenantID: tenantID,
|
|
Phone: phone,
|
|
PasswordHash: passwordHash,
|
|
Nickname: nickname,
|
|
RealnameStatus: "verified",
|
|
RiskStatus: "normal",
|
|
CreditScore: 100,
|
|
Status: "active",
|
|
}
|
|
*errs = append(*errs, e.db.WithContext(ctx).Create(&user).Error)
|
|
return user
|
|
}
|
|
if err != nil {
|
|
*errs = append(*errs, err)
|
|
return user
|
|
}
|
|
*errs = append(*errs, e.db.WithContext(ctx).Model(&user).Updates(map[string]any{
|
|
"password_hash": passwordHash,
|
|
"nickname": nickname,
|
|
"realname_status": "verified",
|
|
"status": "active",
|
|
}).Error)
|
|
return user
|
|
}
|
|
|
|
func (e *demoEnv) ensureRealname(ctx context.Context, user model.User) error {
|
|
hashRaw := sha256.Sum256([]byte(fmt.Sprintf("%d:%s", user.TenantID, user.Phone)))
|
|
hash := hex.EncodeToString(hashRaw[:])
|
|
now := time.Now()
|
|
row := model.UserRealname{
|
|
TenantID: user.TenantID,
|
|
UserID: user.ID,
|
|
Provider: "mock",
|
|
ProviderOrderNo: fmt.Sprintf("DEMO-RN-%d", user.ID),
|
|
Status: "verified",
|
|
MaskedName: "演示**",
|
|
EncryptedName: user.Nickname,
|
|
MaskedIDNo: "110***********001",
|
|
EncryptedIDNo: "demo-id-" + user.Phone,
|
|
IDNoHash: &hash,
|
|
VerifiedAt: &now,
|
|
}
|
|
return e.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{
|
|
"provider", "provider_order_no", "status", "masked_name", "encrypted_name",
|
|
"masked_id_no", "encrypted_id_no", "id_no_hash", "verified_at", "updated_at",
|
|
}),
|
|
}).Create(&row).Error
|
|
}
|
|
|
|
func (e *demoEnv) ensureMerchants(ctx context.Context) error {
|
|
for _, item := range []struct {
|
|
tenantID uint64
|
|
merchant string
|
|
name string
|
|
}{
|
|
{tenantID: e.dachui.ID, merchant: "DACHUI-DEMO-MOCK", name: "大锤演示 Mock 支付"},
|
|
{tenantID: e.jieyou.ID, merchant: "JIEYOU-DEMO-MOCK", name: "解忧演示 Mock 支付"},
|
|
} {
|
|
var count int64
|
|
if err := e.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).
|
|
Where("owner_tenant_id = ? AND merchant_id = ?", item.tenantID, item.merchant).
|
|
Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
if count > 0 {
|
|
continue
|
|
}
|
|
if err := e.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).
|
|
Where("owner_tenant_id = ? AND pay_way = ?", item.tenantID, "ZFBZF").
|
|
Update("is_default", false).Error; err != nil {
|
|
return err
|
|
}
|
|
row := model.PaymentMerchantConfig{
|
|
OwnerTenantID: item.tenantID,
|
|
Name: item.name,
|
|
Provider: "mock",
|
|
MerchantID: item.merchant,
|
|
PayWay: "ZFBZF",
|
|
SignType: "MD5",
|
|
IsDefault: true,
|
|
Status: "active",
|
|
Environment: "sandbox",
|
|
BusinessTags: model.JSONArray{"order_pay"},
|
|
}
|
|
if err := e.db.WithContext(ctx).Create(&row).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensureListing(ctx context.Context, tenant model.Tenant, owner model.User, listingNo, title string, priceCent, sourcePriceYuan int64) (*model.RentalListing, error) {
|
|
var listing model.RentalListing
|
|
err := e.db.WithContext(ctx).Where("listing_no = ?", listingNo).First(&listing).Error
|
|
if err == nil {
|
|
if err := e.ensureListingGroup(listing); err != nil {
|
|
return nil, err
|
|
}
|
|
return &listing, e.ensureOffers(ctx, listing)
|
|
}
|
|
if err != gorm.ErrRecordNotFound {
|
|
return nil, err
|
|
}
|
|
summary, _ := json.Marshal(map[string]any{
|
|
"fire_level": 50,
|
|
"online_time": map[string]any{"start": "09:00", "end": "23:00"},
|
|
"price_breakdown": map[string]any{
|
|
"seller_total_price": sourcePriceYuan,
|
|
"buyer_total_price": priceCent / 100,
|
|
"consumable_price": 120,
|
|
},
|
|
})
|
|
account := model.GameAccount{
|
|
SourceTenantID: tenant.ID,
|
|
OwnerID: owner.ID,
|
|
ServerRegion: "烽火地带",
|
|
LoginPlatform: "QQ",
|
|
Title: title,
|
|
Description: "本地双站演示数据,可直接下单并用 mock 支付。",
|
|
RankLevel: "钻石",
|
|
HafCoinAmount: 100_000_000,
|
|
AssetSummary: datatypes.JSON(summary),
|
|
SeasonTags: datatypes.JSON([]byte(`["S7"]`)),
|
|
ScreenshotURLS: datatypes.JSON([]byte(`[]`)),
|
|
Status: "published",
|
|
}
|
|
if err := e.db.WithContext(ctx).Create(&account).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
publishedAt := time.Now()
|
|
listing = model.RentalListing{
|
|
SourceTenantID: tenant.ID,
|
|
ListingNo: listingNo,
|
|
AccountID: account.ID,
|
|
OwnerID: owner.ID,
|
|
PriceCent: priceCent,
|
|
DepositAmountCent: 5000,
|
|
Status: "published",
|
|
ReviewStatus: "approved",
|
|
HandoffMode: "owner",
|
|
SettlementMode: "owner_wallet",
|
|
PublishedAt: &publishedAt,
|
|
}
|
|
if err := e.db.WithContext(ctx).Create(&listing).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
if err := e.ensureListingGroup(listing); err != nil {
|
|
return nil, err
|
|
}
|
|
return &listing, e.ensureOffers(ctx, listing)
|
|
}
|
|
|
|
func (e *demoEnv) ensureListingGroup(listing model.RentalListing) error {
|
|
return e.db.Transaction(func(tx *gorm.DB) error {
|
|
_, err := chat.EnsureListingConversation(tx, listing, 0)
|
|
return err
|
|
})
|
|
}
|
|
|
|
func (e *demoEnv) ensureOffers(ctx context.Context, listing model.RentalListing) error {
|
|
for _, item := range []struct {
|
|
tenantID uint64
|
|
price *int64
|
|
}{
|
|
{tenantID: e.dachui.ID, price: nil},
|
|
{tenantID: e.jieyou.ID, price: nil},
|
|
} {
|
|
if listing.SourceTenantID == e.dachui.ID && item.tenantID == e.jieyou.ID {
|
|
price := listing.PriceCent + 2000
|
|
item.price = &price
|
|
}
|
|
if listing.SourceTenantID == e.jieyou.ID && item.tenantID == e.dachui.ID {
|
|
price := listing.PriceCent + 2000
|
|
item.price = &price
|
|
}
|
|
offer := model.TenantListingOffer{
|
|
TenantID: item.tenantID,
|
|
ListingID: listing.ID,
|
|
DisplayStatus: "enabled",
|
|
PriceCent: item.price,
|
|
}
|
|
if err := e.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "listing_id"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"display_status", "price_cent", "updated_at"}),
|
|
}).Create(&offer).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) ensurePaidOrder(ctx context.Context, buyerTenant model.Tenant, renter model.User, listing model.RentalListing) error {
|
|
if e.paymentRepo == nil {
|
|
configRepo := paymentconfig.NewRepository(e.db, &paymentconfig.MockEncryptor{})
|
|
chatRepo := chat.NewRepository(e.db, nil, nil)
|
|
e.orderRepo = order.NewRepository(e.db, order.Dependencies{
|
|
ChatNotifier: chatRepo,
|
|
ChatArchiver: chat.NewOrderChatArchiverAdapter(),
|
|
})
|
|
e.paymentRepo = payment.NewRepository(e.db, configRepo, e.orderRepo)
|
|
}
|
|
tenantCtx := tenancy.WithScope(ctx, tenancy.Scope{TenantID: buyerTenant.ID, TenantCode: buyerTenant.Code, TenantName: buyerTenant.Name})
|
|
var existing model.RentalOrder
|
|
err := e.db.WithContext(ctx).
|
|
Where("listing_id = ? AND buyer_tenant_id = ?", listing.ID, buyerTenant.ID).
|
|
Order("id DESC").
|
|
First(&existing).Error
|
|
if err == nil {
|
|
if existing.Status == "pending_payment" {
|
|
if _, err := e.paymentRepo.Start(tenantCtx, renter.ID, existing.ID, payment.StartPaymentRequest{PayWay: "ZFBZF"}, "127.0.0.1"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
e.orders = append(e.orders, existing)
|
|
return nil
|
|
}
|
|
if err != gorm.ErrRecordNotFound {
|
|
return err
|
|
}
|
|
created, err := e.orderRepo.Create(tenantCtx, renter.ID, order.CreateRequest{ListingID: listing.ID})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := e.paymentRepo.Start(tenantCtx, renter.ID, created.ID, payment.StartPaymentRequest{PayWay: "ZFBZF"}, "127.0.0.1"); err != nil {
|
|
return err
|
|
}
|
|
var paid model.RentalOrder
|
|
if err := e.db.WithContext(ctx).First(&paid, created.ID).Error; err != nil {
|
|
return err
|
|
}
|
|
e.orders = append(e.orders, paid)
|
|
return nil
|
|
}
|
|
|
|
func (e *demoEnv) printSummary() {
|
|
fmt.Println("双站本地演示数据已就绪")
|
|
fmt.Printf("大锤前台: http://dachui.localhost:5189 (账号 %s / %s,密码 %s)\n", ownerDPhone, renterDPhone, demoPassword)
|
|
fmt.Printf("解忧前台: http://jieyou.localhost:5189 (账号 %s / %s,密码 %s)\n", ownerJPhone, renterJPhone, demoPassword)
|
|
fmt.Printf("大锤后台: http://dachui.localhost:5189/admin/login (demo_dachui_cs / %s)\n", demoPassword)
|
|
fmt.Printf("解忧后台: http://jieyou.localhost:5189/admin/login (demo_jieyou_cs / %s)\n", demoPassword)
|
|
for _, row := range e.orders {
|
|
fmt.Printf("演示订单: %s buyer=%d source=%d status=%s\n", row.OrderNo, row.BuyerTenantID, row.SourceTenantID, row.Status)
|
|
}
|
|
}
|
|
|
|
func jsonValue(value any) datatypes.JSON {
|
|
raw, _ := json.Marshal(value)
|
|
return datatypes.JSON(raw)
|
|
}
|
|
|
|
func fail(message string, err error) {
|
|
fmt.Fprintf(os.Stderr, "%s: %v\n", message, err)
|
|
os.Exit(1)
|
|
}
|