diff --git a/controller/charge.go b/controller/charge.go index 2425588..f03750b 100644 --- a/controller/charge.go +++ b/controller/charge.go @@ -37,7 +37,7 @@ func searchCharges(c *fiber.Ctx) error { chargeLog.Error("无法解析查询结束时间。", zap.Error(err)) 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 { chargeLog.Error("检索用户的充值记录列表失败。", zap.Error(err)) return result.Error(http.StatusInternalServerError, err.Error()) diff --git a/logger/logger.go b/logger/logger.go index bf872da..ddf414d 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -133,21 +133,52 @@ func WithSugar(fields ...zap.Field) *zap.SugaredLogger { 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()) } -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 { - return DecimalField(key, &val.Decimal) + return DecimalField(key, val.Decimal) } 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) } -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) } + +func DateTimeFieldp(key string, val *types.DateTime) zap.Field { + if val == nil { + return zap.String(key, "null") + } + return DateTimeField(key, *val) +} diff --git a/model/user.go b/model/user.go index 672205e..7815c29 100644 --- a/model/user.go +++ b/model/user.go @@ -47,9 +47,9 @@ func (m ManagementAccountCreationForm) IntoUserDetail() *UserDetail { Phone: m.Phone, UnitServiceFee: decimal.Zero, ServiceExpiration: m.Expires, - CreatedAt: time.Now(), + CreatedAt: types.Now(), CreatedBy: nil, - LastModifiedAt: time.Now(), + LastModifiedAt: types.Now(), LastModifiedBy: nil, DeletedAt: nil, DeletedBy: nil, @@ -85,11 +85,11 @@ type UserDetail struct { Phone *string `json:"phone"` UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"` ServiceExpiration types.Date `json:"serviceExpiration"` - CreatedAt time.Time `json:"createdAt"` + CreatedAt types.DateTime `json:"createdAt"` CreatedBy *string `json:"createdBy"` - LastModifiedAt time.Time `json:"lastModifiedAt"` + LastModifiedAt types.DateTime `json:"lastModifiedAt"` LastModifiedBy *string `json:"lastModifiedBy"` - DeletedAt *time.Time `json:"deletedAt"` + DeletedAt *types.DateTime `json:"deletedAt"` DeletedBy *string `json:"deletedBy"` } @@ -107,8 +107,8 @@ type UserWithDetail struct { Phone *string `json:"phone"` UnitServiceFee decimal.Decimal `db:"unit_service_fee" json:"unitServiceFee"` ServiceExpiration types.Date `json:"serviceExpiration"` - CreatedAt time.Time `json:"createdAt"` + CreatedAt types.DateTime `json:"createdAt"` CreatedBy *string `json:"createdBy"` - LastModifiedAt time.Time `json:"lastModifiedAt"` + LastModifiedAt types.DateTime `json:"lastModifiedAt"` LastModifiedBy *string `json:"lastModifiedBy"` } diff --git a/repository/charge.go b/repository/charge.go index 1908913..eb1419a 100644 --- a/repository/charge.go +++ b/repository/charge.go @@ -8,10 +8,8 @@ import ( "electricity_bill_calc/logger" "electricity_bill_calc/model" "electricity_bill_calc/tools" - "electricity_bill_calc/tools/time" "electricity_bill_calc/types" "fmt" - st "time" "github.com/doug-martin/goqu/v9" _ "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) { - cr.log.Info("查询用户的充值记录。", zap.Timep("beginTime", beginTime), zap.Timep("endTime", endTime), zap.Stringp("keyword", keyword), zap.Uint("page", page)) +func (cr _ChargeRepository) FindCharges(page uint, beginTime, endTime *types.Date, keyword *string) ([]*model.UserChargeDetail, int64, error) { + cr.log.Info("查询用户的充值记录。", logger.DateFieldp("beginTime", beginTime), logger.DateFieldp("endTime", endTime), zap.Stringp("keyword", keyword), zap.Uint("page", page)) cacheConditions := []string{ fmt.Sprintf("%d", page), tools.DefaultTo(keyword, ""), - tools.CondFn(func(t *st.Time) 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 }, beginTime, beginTime.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 { 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. Insert(goqu.T("user_charge")). 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() 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) { updateQuerySql, updateArgs, _ := cr.ds. 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)). Prepared(true).ToSQL() diff --git a/service/charge.go b/service/charge.go index 4135a8a..4bf7b92 100644 --- a/service/charge.go +++ b/service/charge.go @@ -25,10 +25,10 @@ func (cs _ChargeService) RecordUserCharge(uid string, fee, discount, amount *dec cs.log.Info( "创建一条新的用户充值记录。", zap.String("uid", uid), - logger.DecimalField("fee", fee), - logger.DecimalField("discount", discount), - logger.DecimalField("amount", amount), - logger.DateField("chargeTo", &chargeTo), + logger.DecimalFieldp("fee", fee), + logger.DecimalFieldp("discount", discount), + logger.DecimalFieldp("amount", amount), + logger.DateField("chargeTo", chargeTo), zap.Bool("extendExpriationIgnoringSettle", extendExpriationIgnoringSettle), ) diff --git a/service/user.go b/service/user.go index 4dc36fc..09587bf 100644 --- a/service/user.go +++ b/service/user.go @@ -9,7 +9,8 @@ import ( "electricity_bill_calc/repository" "electricity_bill_calc/tools" "electricity_bill_calc/tools/serial" - "electricity_bill_calc/tools/time" + "electricity_bill_calc/types" + "time" "github.com/fufuok/utils" "github.com/google/uuid" @@ -85,7 +86,7 @@ func (us _UserService) ProcessEnterpriseUserLogin(username, password string) (*m Name: user.Username, Type: user.UserType, Token: token.String(), - ExpiresAt: time.Now().Add(config.ServiceSettings.MaxSessionLife), + ExpiresAt: types.Now().Add(config.ServiceSettings.MaxSessionLife), } if userDetail != nil && userDetail.Name != nil { userSession.Name = *userDetail.Name diff --git a/tools/serial/algorithm.go b/tools/serial/algorithm.go index 9ce2354..ed07449 100644 --- a/tools/serial/algorithm.go +++ b/tools/serial/algorithm.go @@ -4,9 +4,9 @@ import ( "electricity_bill_calc/config" "electricity_bill_calc/global" "electricity_bill_calc/logger" - "electricity_bill_calc/tools/time" + "electricity_bill_calc/types" "fmt" - stdTime "time" + "time" "github.com/rueian/rueidis" "github.com/samber/lo" @@ -18,7 +18,7 @@ var log = logger.Named("Algorithm", "Unique Serial") // 在防止服务器时间回拨的情况下,生成一个用于生成唯一编号的精简时间戳,该时间戳的起始时间为`2022-02-22 22:22:22.000000 +0800`,时间戳精确到秒。 func generateTimestamp() int64 { for { - timestamp := time.Timestamp() + timestamp := types.Timestamp() 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().Get().Key("LAST_TIMESTAMP").Build()) @@ -26,14 +26,14 @@ func generateTimestamp() int64 { store_res, err := lo.Last(results) if err != nil { log.Error("从Redis缓存中获取上一次的时间戳失败。", zap.Error(err)) - stdTime.Sleep(1 * stdTime.Second) + time.Sleep(1 * time.Second) continue } if stored_timestamp, err := store_res.AsInt64(); err == nil && timestamp >= stored_timestamp { return timestamp } else { log.Error("转换从Redis缓存中获取的时间戳失败。", zap.Error(err)) - stdTime.Sleep(1 * stdTime.Second) + time.Sleep(1 * time.Second) continue } } @@ -50,14 +50,14 @@ func GenerateUniqueSerial() int64 { store_res, err := lo.Last(results) if err != nil { log.Error("从Redis缓存中获取上一次的序列号失败。", zap.Error(err)) - stdTime.Sleep(1 * stdTime.Second) + time.Sleep(1 * time.Second) continue } if stored_serial, err := store_res.AsInt64(); err == nil { return (timestamp << 20) | ((config.ServiceSettings.HostSerial & 0xffff) << 16) | (stored_serial & 0xffff_ffff) } else { log.Error("转换从Redis缓存中获取的序列号失败。", zap.Error(err)) - stdTime.Sleep(1 * stdTime.Second) + time.Sleep(1 * time.Second) continue } } diff --git a/tools/time/time.go b/tools/time/time.go deleted file mode 100644 index b3c3fe4..0000000 --- a/tools/time/time.go +++ /dev/null @@ -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 -} diff --git a/tools/utils.go b/tools/utils.go index 544f904..4779a6a 100644 --- a/tools/utils.go +++ b/tools/utils.go @@ -70,6 +70,14 @@ func DefaultStrTo[T any](format string, originValue *T, defaultStr string) strin 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 { if expr { diff --git a/vo/user.go b/vo/user.go index 8c7d7e4..14f2724 100644 --- a/vo/user.go +++ b/vo/user.go @@ -2,9 +2,8 @@ package vo import ( "electricity_bill_calc/model" - "electricity_bill_calc/tools/time" "electricity_bill_calc/types" - st "time" + "time" "github.com/shopspring/decimal" ) @@ -38,10 +37,10 @@ func (u MGTAndOPSAccountCreationForm) IntoUserDetail() *model.UserDetail { Contact: u.Contact, Phone: u.Phone, UnitServiceFee: decimal.Zero, - ServiceExpiration: types.NewDate(2099, st.December, 31), - CreatedAt: time.Now(), + ServiceExpiration: types.NewDate(2099, time.December, 31), + CreatedAt: types.Now(), CreatedBy: nil, - LastModifiedAt: time.Now(), + LastModifiedAt: types.Now(), LastModifiedBy: nil, DeletedAt: nil, DeletedBy: nil, @@ -82,10 +81,10 @@ func (u EnterpriseAccountCreationForm) IntoUserDetail() (*model.UserDetail, erro Contact: u.Contact, Phone: u.Phone, UnitServiceFee: unitServiceFee, - ServiceExpiration: types.NewDate(2000, st.January, 1), - CreatedAt: time.Now(), + ServiceExpiration: types.NewDate(2000, time.January, 1), + CreatedAt: types.Now(), CreatedBy: nil, - LastModifiedAt: time.Now(), + LastModifiedAt: types.Now(), LastModifiedBy: nil, DeletedAt: nil, DeletedBy: nil,