refactor(time):彻底重构time类型。

This commit is contained in:
徐涛 2023-06-05 22:09:42 +08:00
parent 1fd5e7b9aa
commit 8aa3a054b0
10 changed files with 79 additions and 73 deletions

View File

@ -37,7 +37,7 @@ func searchCharges(c *fiber.Ctx) error {
chargeLog.Error("无法解析查询结束时间。", zap.Error(err)) chargeLog.Error("无法解析查询结束时间。", zap.Error(err))
return result.Error(http.StatusInternalServerError, err.Error()) return result.Error(http.StatusInternalServerError, err.Error())
} }
charges, total, err := repository.ChargeRepository.FindCharges(uint(page), &beginTime.Time, &endTime.Time, &keyword) charges, total, err := repository.ChargeRepository.FindCharges(uint(page), &beginTime, &endTime, &keyword)
if err != nil { if err != nil {
chargeLog.Error("检索用户的充值记录列表失败。", zap.Error(err)) chargeLog.Error("检索用户的充值记录列表失败。", zap.Error(err))
return result.Error(http.StatusInternalServerError, err.Error()) return result.Error(http.StatusInternalServerError, err.Error())

View File

@ -133,21 +133,52 @@ func WithSugar(fields ...zap.Field) *zap.SugaredLogger {
return logger.With(fields...).Sugar() return logger.With(fields...).Sugar()
} }
func DecimalField(key string, val *decimal.Decimal) zap.Field { func DecimalField(key string, val decimal.Decimal) zap.Field {
return zap.String(key, val.String()) return zap.String(key, val.String())
} }
func NullDecimalField(key string, val *decimal.NullDecimal) zap.Field { func DecimalFieldp(key string, val *decimal.Decimal) zap.Field {
if val == nil {
return zap.String(key, "null")
}
return DecimalField(key, *val)
}
func NullDecimalField(key string, val decimal.NullDecimal) zap.Field {
if val.Valid { if val.Valid {
return DecimalField(key, &val.Decimal) return DecimalField(key, val.Decimal)
} }
return zap.String(key, "null") return zap.String(key, "null")
} }
func DateField(key string, val *types.Date) zap.Field { func NullDecimalFieldp(key string, val *decimal.NullDecimal) zap.Field {
if val == nil {
return zap.String(key, "null")
}
if val.Valid {
return DecimalField(key, val.Decimal)
}
return zap.String(key, "null")
}
func DateField(key string, val types.Date) zap.Field {
return val.Log(key) return val.Log(key)
} }
func DateTimeField(key string, val *types.DateTime) zap.Field { func DateFieldp(key string, val *types.Date) zap.Field {
if val == nil {
return zap.String(key, "null")
}
return DateField(key, *val)
}
func DateTimeField(key string, val types.DateTime) zap.Field {
return val.Log(key) return val.Log(key)
} }
func DateTimeFieldp(key string, val *types.DateTime) zap.Field {
if val == nil {
return zap.String(key, "null")
}
return DateTimeField(key, *val)
}

View File

@ -47,9 +47,9 @@ func (m ManagementAccountCreationForm) IntoUserDetail() *UserDetail {
Phone: m.Phone, Phone: m.Phone,
UnitServiceFee: decimal.Zero, UnitServiceFee: decimal.Zero,
ServiceExpiration: m.Expires, ServiceExpiration: m.Expires,
CreatedAt: time.Now(), CreatedAt: types.Now(),
CreatedBy: nil, CreatedBy: nil,
LastModifiedAt: time.Now(), LastModifiedAt: types.Now(),
LastModifiedBy: nil, LastModifiedBy: nil,
DeletedAt: nil, DeletedAt: nil,
DeletedBy: nil, DeletedBy: nil,
@ -85,11 +85,11 @@ type UserDetail struct {
Phone *string `json:"phone"` Phone *string `json:"phone"`
UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"` UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"`
ServiceExpiration types.Date `json:"serviceExpiration"` ServiceExpiration types.Date `json:"serviceExpiration"`
CreatedAt time.Time `json:"createdAt"` CreatedAt types.DateTime `json:"createdAt"`
CreatedBy *string `json:"createdBy"` CreatedBy *string `json:"createdBy"`
LastModifiedAt time.Time `json:"lastModifiedAt"` LastModifiedAt types.DateTime `json:"lastModifiedAt"`
LastModifiedBy *string `json:"lastModifiedBy"` LastModifiedBy *string `json:"lastModifiedBy"`
DeletedAt *time.Time `json:"deletedAt"` DeletedAt *types.DateTime `json:"deletedAt"`
DeletedBy *string `json:"deletedBy"` DeletedBy *string `json:"deletedBy"`
} }
@ -107,8 +107,8 @@ type UserWithDetail struct {
Phone *string `json:"phone"` Phone *string `json:"phone"`
UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"` UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"`
ServiceExpiration types.Date `json:"serviceExpiration"` ServiceExpiration types.Date `json:"serviceExpiration"`
CreatedAt time.Time `json:"createdAt"` CreatedAt types.DateTime `json:"createdAt"`
CreatedBy *string `json:"createdBy"` CreatedBy *string `json:"createdBy"`
LastModifiedAt time.Time `json:"lastModifiedAt"` LastModifiedAt types.DateTime `json:"lastModifiedAt"`
LastModifiedBy *string `json:"lastModifiedBy"` LastModifiedBy *string `json:"lastModifiedBy"`
} }

View File

@ -8,10 +8,8 @@ import (
"electricity_bill_calc/logger" "electricity_bill_calc/logger"
"electricity_bill_calc/model" "electricity_bill_calc/model"
"electricity_bill_calc/tools" "electricity_bill_calc/tools"
"electricity_bill_calc/tools/time"
"electricity_bill_calc/types" "electricity_bill_calc/types"
"fmt" "fmt"
st "time"
"github.com/doug-martin/goqu/v9" "github.com/doug-martin/goqu/v9"
_ "github.com/doug-martin/goqu/v9/dialect/postgres" _ "github.com/doug-martin/goqu/v9/dialect/postgres"
@ -33,13 +31,13 @@ var ChargeRepository = &_ChargeRepository{
} }
// 分页查询用户的充值记录 // 分页查询用户的充值记录
func (cr _ChargeRepository) FindCharges(page uint, beginTime, endTime *st.Time, keyword *string) ([]*model.UserChargeDetail, int64, error) { func (cr _ChargeRepository) FindCharges(page uint, beginTime, endTime *types.Date, keyword *string) ([]*model.UserChargeDetail, int64, error) {
cr.log.Info("查询用户的充值记录。", zap.Timep("beginTime", beginTime), zap.Timep("endTime", endTime), zap.Stringp("keyword", keyword), zap.Uint("page", page)) cr.log.Info("查询用户的充值记录。", logger.DateFieldp("beginTime", beginTime), logger.DateFieldp("endTime", endTime), zap.Stringp("keyword", keyword), zap.Uint("page", page))
cacheConditions := []string{ cacheConditions := []string{
fmt.Sprintf("%d", page), fmt.Sprintf("%d", page),
tools.DefaultTo(keyword, ""), tools.DefaultTo(keyword, ""),
tools.CondFn(func(t *st.Time) bool { return t != nil }, beginTime, beginTime.Format("2006-01-02"), "UNDEF"), tools.CondFn(func(t *types.Date) bool { return t != nil }, beginTime, beginTime.Format("2006-01-02"), "UNDEF"),
tools.CondFn(func(t *st.Time) bool { return t != nil }, endTime, endTime.Format("2006-01-02"), "UNDEF"), tools.CondFn(func(t *types.Date) bool { return t != nil }, endTime, endTime.Format("2006-01-02"), "UNDEF"),
} }
if charges, total, err := cache.RetrievePagedSearch[[]*model.UserChargeDetail]("charges", cacheConditions...); err == nil { if charges, total, err := cache.RetrievePagedSearch[[]*model.UserChargeDetail]("charges", cacheConditions...); err == nil {
cr.log.Info("从缓存中获取用户的充值记录成功。", zap.Int("count", len(*charges)), zap.Int64("total", total)) cr.log.Info("从缓存中获取用户的充值记录成功。", zap.Int("count", len(*charges)), zap.Int64("total", total))
@ -115,7 +113,7 @@ func (cr _ChargeRepository) CreateChargeRecord(tx pgx.Tx, ctx context.Context, u
createQuery, createArgs, _ := cr.ds. createQuery, createArgs, _ := cr.ds.
Insert(goqu.T("user_charge")). Insert(goqu.T("user_charge")).
Cols("user_id", "fee", "discount", "amount", "charge_to", "created_at"). Cols("user_id", "fee", "discount", "amount", "charge_to", "created_at").
Vals(goqu.Vals{uid, fee, discount, amount, chargeTo, time.Now()}). Vals(goqu.Vals{uid, fee, discount, amount, chargeTo, types.Now()}).
Prepared(true).ToSQL() Prepared(true).ToSQL()
rs, err := tx.Exec(ctx, createQuery, createArgs...) rs, err := tx.Exec(ctx, createQuery, createArgs...)
@ -130,7 +128,7 @@ func (cr _ChargeRepository) CreateChargeRecord(tx pgx.Tx, ctx context.Context, u
func (cr _ChargeRepository) CancelCharge(tx pgx.Tx, ctx context.Context, uid string, seq int64) (bool, error) { func (cr _ChargeRepository) CancelCharge(tx pgx.Tx, ctx context.Context, uid string, seq int64) (bool, error) {
updateQuerySql, updateArgs, _ := cr.ds. updateQuerySql, updateArgs, _ := cr.ds.
Update(goqu.T("user_charge")). Update(goqu.T("user_charge")).
Set(goqu.Record{"cancelled": true, "cancelled_at": time.Now()}). Set(goqu.Record{"cancelled": true, "cancelled_at": types.Now()}).
Where(goqu.I("user_id").Eq(uid), goqu.I("seq").Eq(seq)). Where(goqu.I("user_id").Eq(uid), goqu.I("seq").Eq(seq)).
Prepared(true).ToSQL() Prepared(true).ToSQL()

View File

@ -25,10 +25,10 @@ func (cs _ChargeService) RecordUserCharge(uid string, fee, discount, amount *dec
cs.log.Info( cs.log.Info(
"创建一条新的用户充值记录。", "创建一条新的用户充值记录。",
zap.String("uid", uid), zap.String("uid", uid),
logger.DecimalField("fee", fee), logger.DecimalFieldp("fee", fee),
logger.DecimalField("discount", discount), logger.DecimalFieldp("discount", discount),
logger.DecimalField("amount", amount), logger.DecimalFieldp("amount", amount),
logger.DateField("chargeTo", &chargeTo), logger.DateField("chargeTo", chargeTo),
zap.Bool("extendExpriationIgnoringSettle", extendExpriationIgnoringSettle), zap.Bool("extendExpriationIgnoringSettle", extendExpriationIgnoringSettle),
) )

View File

@ -9,7 +9,8 @@ import (
"electricity_bill_calc/repository" "electricity_bill_calc/repository"
"electricity_bill_calc/tools" "electricity_bill_calc/tools"
"electricity_bill_calc/tools/serial" "electricity_bill_calc/tools/serial"
"electricity_bill_calc/tools/time" "electricity_bill_calc/types"
"time"
"github.com/fufuok/utils" "github.com/fufuok/utils"
"github.com/google/uuid" "github.com/google/uuid"
@ -85,7 +86,7 @@ func (us _UserService) ProcessEnterpriseUserLogin(username, password string) (*m
Name: user.Username, Name: user.Username,
Type: user.UserType, Type: user.UserType,
Token: token.String(), Token: token.String(),
ExpiresAt: time.Now().Add(config.ServiceSettings.MaxSessionLife), ExpiresAt: types.Now().Add(config.ServiceSettings.MaxSessionLife),
} }
if userDetail != nil && userDetail.Name != nil { if userDetail != nil && userDetail.Name != nil {
userSession.Name = *userDetail.Name userSession.Name = *userDetail.Name

View File

@ -4,9 +4,9 @@ import (
"electricity_bill_calc/config" "electricity_bill_calc/config"
"electricity_bill_calc/global" "electricity_bill_calc/global"
"electricity_bill_calc/logger" "electricity_bill_calc/logger"
"electricity_bill_calc/tools/time" "electricity_bill_calc/types"
"fmt" "fmt"
stdTime "time" "time"
"github.com/rueian/rueidis" "github.com/rueian/rueidis"
"github.com/samber/lo" "github.com/samber/lo"
@ -18,7 +18,7 @@ var log = logger.Named("Algorithm", "Unique Serial")
// 在防止服务器时间回拨的情况下,生成一个用于生成唯一编号的精简时间戳,该时间戳的起始时间为`2022-02-22 22:22:22.000000 +0800`,时间戳精确到秒。 // 在防止服务器时间回拨的情况下,生成一个用于生成唯一编号的精简时间戳,该时间戳的起始时间为`2022-02-22 22:22:22.000000 +0800`,时间戳精确到秒。
func generateTimestamp() int64 { func generateTimestamp() int64 {
for { for {
timestamp := time.Timestamp() timestamp := types.Timestamp()
cmds := make(rueidis.Commands, 0, 2) cmds := make(rueidis.Commands, 0, 2)
cmds = append(cmds, global.Rd.B().Set().Key("LAST_TIMESTAMP").Value(fmt.Sprintf("%d", timestamp)).Nx().ExSeconds(1).Build()) cmds = append(cmds, global.Rd.B().Set().Key("LAST_TIMESTAMP").Value(fmt.Sprintf("%d", timestamp)).Nx().ExSeconds(1).Build())
cmds = append(cmds, global.Rd.B().Get().Key("LAST_TIMESTAMP").Build()) cmds = append(cmds, global.Rd.B().Get().Key("LAST_TIMESTAMP").Build())
@ -26,14 +26,14 @@ func generateTimestamp() int64 {
store_res, err := lo.Last(results) store_res, err := lo.Last(results)
if err != nil { if err != nil {
log.Error("从Redis缓存中获取上一次的时间戳失败。", zap.Error(err)) log.Error("从Redis缓存中获取上一次的时间戳失败。", zap.Error(err))
stdTime.Sleep(1 * stdTime.Second) time.Sleep(1 * time.Second)
continue continue
} }
if stored_timestamp, err := store_res.AsInt64(); err == nil && timestamp >= stored_timestamp { if stored_timestamp, err := store_res.AsInt64(); err == nil && timestamp >= stored_timestamp {
return timestamp return timestamp
} else { } else {
log.Error("转换从Redis缓存中获取的时间戳失败。", zap.Error(err)) log.Error("转换从Redis缓存中获取的时间戳失败。", zap.Error(err))
stdTime.Sleep(1 * stdTime.Second) time.Sleep(1 * time.Second)
continue continue
} }
} }
@ -50,14 +50,14 @@ func GenerateUniqueSerial() int64 {
store_res, err := lo.Last(results) store_res, err := lo.Last(results)
if err != nil { if err != nil {
log.Error("从Redis缓存中获取上一次的序列号失败。", zap.Error(err)) log.Error("从Redis缓存中获取上一次的序列号失败。", zap.Error(err))
stdTime.Sleep(1 * stdTime.Second) time.Sleep(1 * time.Second)
continue continue
} }
if stored_serial, err := store_res.AsInt64(); err == nil { if stored_serial, err := store_res.AsInt64(); err == nil {
return (timestamp << 20) | ((config.ServiceSettings.HostSerial & 0xffff) << 16) | (stored_serial & 0xffff_ffff) return (timestamp << 20) | ((config.ServiceSettings.HostSerial & 0xffff) << 16) | (stored_serial & 0xffff_ffff)
} else { } else {
log.Error("转换从Redis缓存中获取的序列号失败。", zap.Error(err)) log.Error("转换从Redis缓存中获取的序列号失败。", zap.Error(err))
stdTime.Sleep(1 * stdTime.Second) time.Sleep(1 * time.Second)
continue continue
} }
} }

View File

@ -1,31 +0,0 @@
package time
import (
"time"
)
var Loc *time.Location = time.FixedZone("+0800", 8*60*60)
func Now() time.Time {
return time.Now().In(Loc)
}
func Time(year int, month time.Month, date, hours, min, sec, nsec int) time.Time {
return time.Date(year, month, date, hours, min, sec, nsec, Loc)
}
func Timestamp() int64 {
startline := time.Date(2022, 2, 22, 22, 22, 22, 0, Loc).Unix()
return Now().Unix() - startline
}
func DifferenceInMonth(t1, t2 time.Time) int {
var differYear, differMonth int
differYear = t1.Year() - t2.Year()
differMonth = int(t1.Month() - t2.Month())
return differYear*12 + differMonth
}
func IsNextMonth(origin, t time.Time) bool {
return DifferenceInMonth(t, origin) == 1
}

View File

@ -70,6 +70,14 @@ func DefaultStrTo[T any](format string, originValue *T, defaultStr string) strin
return fmt.Sprintf(format, originValue) return fmt.Sprintf(format, originValue)
} }
// 判断指定字符串指针是否为`nil`或者字符串长度为空,如果是则返回给定的默认字符串,否则返回指针所指内容的字符串形式。
func DefaultOrEmptyStr(originValue *string, defaultStr string) string {
if originValue == nil || len(*originValue) == 0 {
return defaultStr
}
return *originValue
}
// 判断指定表达式的值,根据表达式的值返回指定的值。相当于其他语言中的三目运算符。 // 判断指定表达式的值,根据表达式的值返回指定的值。相当于其他语言中的三目运算符。
func Cond[T any](expr bool, trueValue, falseValue T) T { func Cond[T any](expr bool, trueValue, falseValue T) T {
if expr { if expr {

View File

@ -2,9 +2,8 @@ package vo
import ( import (
"electricity_bill_calc/model" "electricity_bill_calc/model"
"electricity_bill_calc/tools/time"
"electricity_bill_calc/types" "electricity_bill_calc/types"
st "time" "time"
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
) )
@ -38,10 +37,10 @@ func (u MGTAndOPSAccountCreationForm) IntoUserDetail() *model.UserDetail {
Contact: u.Contact, Contact: u.Contact,
Phone: u.Phone, Phone: u.Phone,
UnitServiceFee: decimal.Zero, UnitServiceFee: decimal.Zero,
ServiceExpiration: types.NewDate(2099, st.December, 31), ServiceExpiration: types.NewDate(2099, time.December, 31),
CreatedAt: time.Now(), CreatedAt: types.Now(),
CreatedBy: nil, CreatedBy: nil,
LastModifiedAt: time.Now(), LastModifiedAt: types.Now(),
LastModifiedBy: nil, LastModifiedBy: nil,
DeletedAt: nil, DeletedAt: nil,
DeletedBy: nil, DeletedBy: nil,
@ -82,10 +81,10 @@ func (u EnterpriseAccountCreationForm) IntoUserDetail() (*model.UserDetail, erro
Contact: u.Contact, Contact: u.Contact,
Phone: u.Phone, Phone: u.Phone,
UnitServiceFee: unitServiceFee, UnitServiceFee: unitServiceFee,
ServiceExpiration: types.NewDate(2000, st.January, 1), ServiceExpiration: types.NewDate(2000, time.January, 1),
CreatedAt: time.Now(), CreatedAt: types.Now(),
CreatedBy: nil, CreatedBy: nil,
LastModifiedAt: time.Now(), LastModifiedAt: types.Now(),
LastModifiedBy: nil, LastModifiedBy: nil,
DeletedAt: nil, DeletedAt: nil,
DeletedBy: nil, DeletedBy: nil,