feat(#67): add Shopee order snapshots to purchase tasks

This commit is contained in:
QiuSW
2026-08-22 10:41:05 +08:00
parent 0ceb248233
commit 9490bddf8f
17 changed files with 173 additions and 30 deletions
@@ -0,0 +1,43 @@
package version_local
import (
"runtime"
goautomigrations "go-admin/app/goauto/migrations"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
"gorm.io/gorm"
)
// This additive #67 migration records the Shopee order number that explains
// each purchase task. Existing tasks are backfilled from their immutable SYB
// product relation when it is still available; unresolved legacy rows stay
// empty instead of receiving a fabricated identifier.
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), migratePurchaseShopeeOrderSnapshot)
}
func migratePurchaseShopeeOrderSnapshot(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
if err := goautomigrations.Migrate(tx); err != nil {
return err
}
if err := backfillPurchaseShopeeOrderSnapshot(tx); err != nil {
return err
}
return tx.Create(&common.Migration{Version: version}).Error
})
}
func backfillPurchaseShopeeOrderSnapshot(db *gorm.DB) error {
return db.Exec(`UPDATE purchase_task
SET shopee_order_no_snapshot = COALESCE((
SELECT syb_product.order_code
FROM syb_product
WHERE syb_product.id = purchase_task.syb_product_id
), '')
WHERE shopee_order_no_snapshot = ''
AND syb_product_id IS NOT NULL`).Error
}
@@ -0,0 +1,38 @@
package version_local
import (
"testing"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestBackfillPurchaseShopeeOrderSnapshot(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:purchase-order-snapshot?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
for _, statement := range []string{
`CREATE TABLE syb_product (id INTEGER PRIMARY KEY, order_code TEXT NOT NULL)`,
`CREATE TABLE purchase_task (id INTEGER PRIMARY KEY, syb_product_id INTEGER, shopee_order_no_snapshot TEXT NOT NULL DEFAULT '')`,
`INSERT INTO syb_product (id, order_code) VALUES (1, '260728TB95MJTQ')`,
`INSERT INTO purchase_task (id, syb_product_id, shopee_order_no_snapshot) VALUES (1, 1, ''), (2, NULL, ''), (3, 1, 'IMMUTABLE')`,
} {
if err = db.Exec(statement).Error; err != nil {
t.Fatal(err)
}
}
if err = backfillPurchaseShopeeOrderSnapshot(db); err != nil {
t.Fatal(err)
}
var rows []struct {
ID uint64
Snapshot string `gorm:"column:shopee_order_no_snapshot"`
}
if err = db.Table("purchase_task").Select("id, shopee_order_no_snapshot").Order("id").Scan(&rows).Error; err != nil {
t.Fatal(err)
}
if len(rows) != 3 || rows[0].Snapshot != "260728TB95MJTQ" || rows[1].Snapshot != "" || rows[2].Snapshot != "IMMUTABLE" {
t.Fatalf("unexpected backfill rows: %+v", rows)
}
}