feat(region):加入服务启动时同步行政区划。

This commit is contained in:
徐涛 2022-08-12 16:39:49 +08:00
parent dd38fd6d6f
commit b213b32325
5 changed files with 3869 additions and 2 deletions

53
main.go
View File

@ -5,8 +5,13 @@ import (
"electricity_bill_calc/global"
"electricity_bill_calc/model"
"electricity_bill_calc/router"
"electricity_bill_calc/utils"
"encoding/csv"
"fmt"
"io"
"log"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
@ -47,6 +52,54 @@ func init() {
log.Fatalf("Main Cache Database connect failed: %v", err)
}
log.Println("Main Cache Database connected!")
err = initializeRegions()
if err != nil {
log.Fatalf("Regions initialize failed: %v", err)
}
log.Println("Regions synchronized.")
}
func initializeRegions() error {
log.Println("Synchronize regions...")
regionCsvFile, err := os.Open("regions.csv")
if err != nil {
return fmt.Errorf("region initialize file is not found: %w", err)
}
defer regionCsvFile.Close()
var existRegions = make([]string, 0)
err = global.DBConn.Table("region").Cols("code").Find(&existRegions)
if err != nil {
return fmt.Errorf("unable to retreive regions from database: %w", err)
}
regionCsv := csv.NewReader(regionCsvFile)
transaction := global.DBConn.NewSession()
defer transaction.Close()
if err = transaction.Begin(); err != nil {
return fmt.Errorf("unable to intiate database transaction: %w", err)
}
for {
record, err := regionCsv.Read()
if err == io.EOF {
break
}
if utils.Contains(record[0], existRegions) {
continue
}
level, err := strconv.Atoi(record[2])
if err != nil {
continue
}
if _, err = transaction.Insert(&model.Region{Code: record[0], Name: record[1], Level: level, Parent: record[3]}); err != nil {
return fmt.Errorf("region synchronize in failed: %v, %w", record, err)
}
}
if err = transaction.Commit(); err != nil {
return fmt.Errorf("synchronize regions to database failed: %w", err)
}
return nil
}
func DBConnectionKeepLive() {

View File

@ -3,7 +3,7 @@ package model
type Region struct {
Code string `xorm:"varchar(15) pk not null" json:"code"`
Name string `xorm:"varchar(50) not null" json:"name"`
Level int8 `xorm:"smallint not null default 0" json:"level"`
Level int `xorm:"int not null default 0" json:"level"`
Parent string `xorm:"varchar(15) not null default '0'" json:"parent"`
}

View File

@ -9,7 +9,6 @@ import (
type UserCharge struct {
Created `xorm:"extends"`
Seq int64 `xorm:"bigint pk not null " json:"seq"`
CreatedAt time.Time `xorm:"timestampz not null" json:"createdAt"`
UserId string `xorm:"varchar(120) not null" json:"userId"`
Fee decimal.Decimal `xorm:"numeric(12,2) not null" json:"fee"`
Discount decimal.Decimal `xorm:"numeric(5,4) not null" json:"discount"`

3805
regions.csv Normal file

File diff suppressed because it is too large Load Diff

10
utils/utils.go Normal file
View File

@ -0,0 +1,10 @@
package utils
func Contains[T string | int | uint](element T, slice []T) bool {
for _, v := range slice {
if v == element {
return true
}
}
return false
}