add request id to sql query log

This commit is contained in:
MaysWind
2023-09-03 13:54:07 +08:00
parent 6b30a0aebc
commit 9221f3fc96
23 changed files with 432 additions and 360 deletions
+25 -24
View File
@@ -5,6 +5,7 @@ import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -31,30 +32,30 @@ var (
)
// GetTotalAccountCountByUid returns total account count of user
func (s *AccountService) GetTotalAccountCountByUid(uid int64) (int64, error) {
func (s *AccountService) GetTotalAccountCountByUid(c *core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
count, err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Count(&models.Account{})
count, err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Count(&models.Account{})
return count, err
}
// GetAllAccountsByUid returns all account models of user
func (s *AccountService) GetAllAccountsByUid(uid int64) ([]*models.Account, error) {
func (s *AccountService) GetAllAccountsByUid(c *core.Context, uid int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
var accounts []*models.Account
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).OrderBy("parent_account_id asc, display_order asc").Find(&accounts)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).OrderBy("parent_account_id asc, display_order asc").Find(&accounts)
return accounts, err
}
// GetAccountAndSubAccountsByAccountId returns account model and sub account models according to account id
func (s *AccountService) GetAccountAndSubAccountsByAccountId(uid int64, accountId int64) ([]*models.Account, error) {
func (s *AccountService) GetAccountAndSubAccountsByAccountId(c *core.Context, uid int64, accountId int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -64,13 +65,13 @@ func (s *AccountService) GetAccountAndSubAccountsByAccountId(uid int64, accountI
}
var accounts []*models.Account
err := s.UserDataDB(uid).Where("uid=? AND deleted=? AND (account_id=? OR parent_account_id=?)", uid, false, accountId, accountId).OrderBy("parent_account_id asc, display_order asc").Find(&accounts)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=? AND (account_id=? OR parent_account_id=?)", uid, false, accountId, accountId).OrderBy("parent_account_id asc, display_order asc").Find(&accounts)
return accounts, err
}
// GetSubAccountsByAccountId returns sub account models according to account id
func (s *AccountService) GetSubAccountsByAccountId(uid int64, accountId int64) ([]*models.Account, error) {
func (s *AccountService) GetSubAccountsByAccountId(c *core.Context, uid int64, accountId int64) ([]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -80,13 +81,13 @@ func (s *AccountService) GetSubAccountsByAccountId(uid int64, accountId int64) (
}
var accounts []*models.Account
err := s.UserDataDB(uid).Where("uid=? AND deleted=? AND parent_account_id=?", uid, false, accountId).OrderBy("display_order asc").Find(&accounts)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=? AND parent_account_id=?", uid, false, accountId).OrderBy("display_order asc").Find(&accounts)
return accounts, err
}
// GetAccountsByAccountIds returns account models according to account ids
func (s *AccountService) GetAccountsByAccountIds(uid int64, accountIds []int64) (map[int64]*models.Account, error) {
func (s *AccountService) GetAccountsByAccountIds(c *core.Context, uid int64, accountIds []int64) (map[int64]*models.Account, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -96,7 +97,7 @@ func (s *AccountService) GetAccountsByAccountIds(uid int64, accountIds []int64)
}
var accounts []*models.Account
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).In("account_id", accountIds).Find(&accounts)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).In("account_id", accountIds).Find(&accounts)
if err != nil {
return nil, err
@@ -107,13 +108,13 @@ func (s *AccountService) GetAccountsByAccountIds(uid int64, accountIds []int64)
}
// GetMaxDisplayOrder returns the max display order according to account category
func (s *AccountService) GetMaxDisplayOrder(uid int64, category models.AccountCategory) (int32, error) {
func (s *AccountService) GetMaxDisplayOrder(c *core.Context, uid int64, category models.AccountCategory) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
account := &models.Account{}
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.LevelOneAccountParentId, category).OrderBy("display_order desc").Limit(1).Get(account)
has, err := s.UserDataDB(uid).NewSession(c).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.LevelOneAccountParentId, category).OrderBy("display_order desc").Limit(1).Get(account)
if err != nil {
return 0, err
@@ -127,7 +128,7 @@ func (s *AccountService) GetMaxDisplayOrder(uid int64, category models.AccountCa
}
// GetMaxSubAccountDisplayOrder returns the max display order of sub account according to account category and parent account id
func (s *AccountService) GetMaxSubAccountDisplayOrder(uid int64, category models.AccountCategory, parentAccountId int64) (int32, error) {
func (s *AccountService) GetMaxSubAccountDisplayOrder(c *core.Context, uid int64, category models.AccountCategory, parentAccountId int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -137,7 +138,7 @@ func (s *AccountService) GetMaxSubAccountDisplayOrder(uid int64, category models
}
account := &models.Account{}
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, parentAccountId, category).OrderBy("display_order desc").Limit(1).Get(account)
has, err := s.UserDataDB(uid).NewSession(c).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, parentAccountId, category).OrderBy("display_order desc").Limit(1).Get(account)
if err != nil {
return 0, err
@@ -151,7 +152,7 @@ func (s *AccountService) GetMaxSubAccountDisplayOrder(uid int64, category models
}
// CreateAccounts saves a new account model to database
func (s *AccountService) CreateAccounts(mainAccount *models.Account, childrenAccounts []*models.Account, utcOffset int16) error {
func (s *AccountService) CreateAccounts(c *core.Context, mainAccount *models.Account, childrenAccounts []*models.Account, utcOffset int16) error {
if mainAccount.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -204,7 +205,7 @@ func (s *AccountService) CreateAccounts(mainAccount *models.Account, childrenAcc
}
}
return s.UserDataDB(mainAccount.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(mainAccount.Uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(allAccounts); i++ {
account := allAccounts[i]
_, err := sess.Insert(account)
@@ -228,7 +229,7 @@ func (s *AccountService) CreateAccounts(mainAccount *models.Account, childrenAcc
}
// ModifyAccounts saves an existed account model to database
func (s *AccountService) ModifyAccounts(uid int64, accounts []*models.Account) error {
func (s *AccountService) ModifyAccounts(c *core.Context, uid int64, accounts []*models.Account) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -239,7 +240,7 @@ func (s *AccountService) ModifyAccounts(uid int64, accounts []*models.Account) e
accounts[i].UpdatedUnixTime = now
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(accounts); i++ {
account := accounts[i]
updatedRows, err := sess.ID(account.AccountId).Cols("name", "category", "icon", "color", "comment", "hidden", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).Update(account)
@@ -256,7 +257,7 @@ func (s *AccountService) ModifyAccounts(uid int64, accounts []*models.Account) e
}
// HideAccount updates hidden field of given accounts
func (s *AccountService) HideAccount(uid int64, ids []int64, hidden bool) error {
func (s *AccountService) HideAccount(c *core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -268,7 +269,7 @@ func (s *AccountService) HideAccount(uid int64, ids []int64, hidden bool) error
UpdatedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.Cols("hidden", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).In("account_id", ids).Update(updateModel)
if err != nil {
@@ -282,7 +283,7 @@ func (s *AccountService) HideAccount(uid int64, ids []int64, hidden bool) error
}
// ModifyAccountDisplayOrders updates display order of given accounts
func (s *AccountService) ModifyAccountDisplayOrders(uid int64, accounts []*models.Account) error {
func (s *AccountService) ModifyAccountDisplayOrders(c *core.Context, uid int64, accounts []*models.Account) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -291,7 +292,7 @@ func (s *AccountService) ModifyAccountDisplayOrders(uid int64, accounts []*model
accounts[i].UpdatedUnixTime = time.Now().Unix()
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(accounts); i++ {
account := accounts[i]
updatedRows, err := sess.ID(account.AccountId).Cols("display_order", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).Update(account)
@@ -308,7 +309,7 @@ func (s *AccountService) ModifyAccountDisplayOrders(uid int64, accounts []*model
}
// DeleteAccount deletes an existed account from database
func (s *AccountService) DeleteAccount(uid int64, accountId int64) error {
func (s *AccountService) DeleteAccount(c *core.Context, uid int64, accountId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -321,7 +322,7 @@ func (s *AccountService) DeleteAccount(uid int64, accountId int64) error {
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
var accountAndSubAccounts []*models.Account
err := sess.Where("uid=? AND deleted=? AND (account_id=? OR parent_account_id=?)", uid, false, accountId, accountId).Find(&accountAndSubAccounts)
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"net/url"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/locales"
"github.com/mayswind/ezbookkeeping/pkg/mail"
@@ -34,7 +35,7 @@ var (
)
// SendPasswordResetEmail sends password reset email according to specified parameters
func (s *ForgetPasswordService) SendPasswordResetEmail(user *models.User, passwordResetToken string, backupLocale string) error {
func (s *ForgetPasswordService) SendPasswordResetEmail(c *core.Context, user *models.User, passwordResetToken string, backupLocale string) error {
if !s.CurrentConfig().EnableSMTP {
return errs.ErrSMTPServerNotEnabled
}
+25 -25
View File
@@ -38,19 +38,19 @@ var (
)
// GetAllTokensByUid returns all token models of given user
func (s *TokenService) GetAllTokensByUid(uid int64) ([]*models.TokenRecord, error) {
func (s *TokenService) GetAllTokensByUid(c *core.Context, uid int64) ([]*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
var tokenRecords []*models.TokenRecord
err := s.TokenDB(uid).Cols("uid", "user_token_id", "token_type", "user_agent", "created_unix_time", "expired_unix_time").Where("uid=?", uid).Find(&tokenRecords)
err := s.TokenDB(uid).NewSession(c).Cols("uid", "user_token_id", "token_type", "user_agent", "created_unix_time", "expired_unix_time").Where("uid=?", uid).Find(&tokenRecords)
return tokenRecords, err
}
// GetAllUnexpiredNormalTokensByUid returns all available token models of given user
func (s *TokenService) GetAllUnexpiredNormalTokensByUid(uid int64) ([]*models.TokenRecord, error) {
func (s *TokenService) GetAllUnexpiredNormalTokensByUid(c *core.Context, uid int64) ([]*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -58,7 +58,7 @@ func (s *TokenService) GetAllUnexpiredNormalTokensByUid(uid int64) ([]*models.To
now := time.Now().Unix()
var tokenRecords []*models.TokenRecord
err := s.TokenDB(uid).Cols("uid", "user_token_id", "token_type", "user_agent", "created_unix_time", "expired_unix_time").Where("uid=? AND token_type=? AND expired_unix_time>?", uid, core.USER_TOKEN_TYPE_NORMAL, now).Find(&tokenRecords)
err := s.TokenDB(uid).NewSession(c).Cols("uid", "user_token_id", "token_type", "user_agent", "created_unix_time", "expired_unix_time").Where("uid=? AND token_type=? AND expired_unix_time>?", uid, core.USER_TOKEN_TYPE_NORMAL, now).Find(&tokenRecords)
return tokenRecords, err
}
@@ -79,22 +79,22 @@ func (s *TokenService) ParseTokenByCookie(c *core.Context, tokenCookieName strin
}
// CreateToken generates a new normal token and saves to database
func (s *TokenService) CreateToken(user *models.User, ctx *core.Context) (string, *core.UserTokenClaims, error) {
return s.createToken(user, core.USER_TOKEN_TYPE_NORMAL, s.getUserAgent(ctx), s.CurrentConfig().TokenExpiredTimeDuration)
func (s *TokenService) CreateToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_NORMAL, s.getUserAgent(c), s.CurrentConfig().TokenExpiredTimeDuration)
}
// CreateRequire2FAToken generates a new token requiring user to verify 2fa passcode and saves to database
func (s *TokenService) CreateRequire2FAToken(user *models.User, ctx *core.Context) (string, *core.UserTokenClaims, error) {
return s.createToken(user, core.USER_TOKEN_TYPE_REQUIRE_2FA, s.getUserAgent(ctx), s.CurrentConfig().TemporaryTokenExpiredTimeDuration)
func (s *TokenService) CreateRequire2FAToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_REQUIRE_2FA, s.getUserAgent(c), s.CurrentConfig().TemporaryTokenExpiredTimeDuration)
}
// CreatePasswordResetToken generates a new password reset token and saves to database
func (s *TokenService) CreatePasswordResetToken(user *models.User, ctx *core.Context) (string, *core.UserTokenClaims, error) {
return s.createToken(user, core.USER_TOKEN_TYPE_PASSWORD_RESET, s.getUserAgent(ctx), s.CurrentConfig().PasswordResetTokenExpiredTimeDuration)
func (s *TokenService) CreatePasswordResetToken(c *core.Context, user *models.User) (string, *core.UserTokenClaims, error) {
return s.createToken(c, user, core.USER_TOKEN_TYPE_PASSWORD_RESET, s.getUserAgent(c), s.CurrentConfig().PasswordResetTokenExpiredTimeDuration)
}
// DeleteToken deletes given token from database
func (s *TokenService) DeleteToken(tokenRecord *models.TokenRecord) error {
func (s *TokenService) DeleteToken(c *core.Context, tokenRecord *models.TokenRecord) error {
if tokenRecord.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -103,7 +103,7 @@ func (s *TokenService) DeleteToken(tokenRecord *models.TokenRecord) error {
return errs.ErrInvalidUserTokenId
}
return s.TokenDB(tokenRecord.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.TokenDB(tokenRecord.Uid).DoTransaction(c, func(sess *xorm.Session) error {
deletedRows, err := sess.Where("uid=? AND user_token_id=? AND created_unix_time=?", tokenRecord.Uid, tokenRecord.UserTokenId, tokenRecord.CreatedUnixTime).Delete(&models.TokenRecord{})
if err != nil {
@@ -117,12 +117,12 @@ func (s *TokenService) DeleteToken(tokenRecord *models.TokenRecord) error {
}
// DeleteTokens deletes given tokens from database
func (s *TokenService) DeleteTokens(uid int64, tokenRecords []*models.TokenRecord) error {
func (s *TokenService) DeleteTokens(c *core.Context, uid int64, tokenRecords []*models.TokenRecord) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
return s.TokenDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.TokenDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(tokenRecords); i++ {
tokenRecord := tokenRecords[i]
deletedRows, err := sess.Where("uid=? AND user_token_id=? AND created_unix_time=?", uid, tokenRecord.UserTokenId, tokenRecord.CreatedUnixTime).Delete(&models.TokenRecord{})
@@ -139,14 +139,14 @@ func (s *TokenService) DeleteTokens(uid int64, tokenRecords []*models.TokenRecor
}
// DeleteTokenByClaims deletes given token from database
func (s *TokenService) DeleteTokenByClaims(claims *core.UserTokenClaims) error {
func (s *TokenService) DeleteTokenByClaims(c *core.Context, claims *core.UserTokenClaims) error {
userTokenId, err := utils.StringToInt64(claims.UserTokenId)
if err != nil {
return errs.ErrInvalidUserTokenId
}
return s.DeleteToken(&models.TokenRecord{
return s.DeleteToken(c, &models.TokenRecord{
Uid: claims.Uid,
UserTokenId: userTokenId,
CreatedUnixTime: claims.IssuedAt,
@@ -154,12 +154,12 @@ func (s *TokenService) DeleteTokenByClaims(claims *core.UserTokenClaims) error {
}
// DeleteTokensBeforeTime deletes tokens that is created before specific time
func (s *TokenService) DeleteTokensBeforeTime(uid int64, expireTime int64) error {
func (s *TokenService) DeleteTokensBeforeTime(c *core.Context, uid int64, expireTime int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
return s.TokenDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.TokenDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Where("uid=? AND created_unix_time<?", uid, expireTime).Delete(&models.TokenRecord{})
return err
})
@@ -218,7 +218,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
return nil, errs.ErrInvalidUserTokenId
}
tokenRecord, err := s.getTokenRecord(claims.Uid, userTokenId, claims.IssuedAt)
tokenRecord, err := s.getTokenRecord(c, claims.Uid, userTokenId, claims.IssuedAt)
if err != nil {
log.WarnfWithRequestId(c, "[tokens.ParseToken] token \"utid:%s\" of user \"uid:%d\" record not found, because %s", claims.UserTokenId, claims.Uid, err.Error())
@@ -261,7 +261,7 @@ func (s *TokenService) parseToken(c *core.Context, extractor request.Extractor)
return token, claims, err
}
func (s *TokenService) createToken(user *models.User, tokenType core.TokenType, userAgent string, expiryDate time.Duration) (string, *core.UserTokenClaims, error) {
func (s *TokenService) createToken(c *core.Context, user *models.User, tokenType core.TokenType, userAgent string, expiryDate time.Duration) (string, *core.UserTokenClaims, error) {
var err error
now := time.Now()
@@ -294,7 +294,7 @@ func (s *TokenService) createToken(user *models.User, tokenType core.TokenType,
return "", nil, err
}
err = s.createTokenRecord(tokenRecord)
err = s.createTokenRecord(c, tokenRecord)
if err != nil {
return "", nil, err
@@ -303,7 +303,7 @@ func (s *TokenService) createToken(user *models.User, tokenType core.TokenType,
return tokenString, claims, err
}
func (s *TokenService) getTokenRecord(uid int64, userTokenId int64, createUnixTime int64) (*models.TokenRecord, error) {
func (s *TokenService) getTokenRecord(c *core.Context, uid int64, userTokenId int64, createUnixTime int64) (*models.TokenRecord, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -313,7 +313,7 @@ func (s *TokenService) getTokenRecord(uid int64, userTokenId int64, createUnixTi
}
tokenRecord := &models.TokenRecord{}
has, err := s.TokenDB(uid).Where("uid=? AND user_token_id=? AND created_unix_time=?", uid, userTokenId, createUnixTime).Limit(1).Get(tokenRecord)
has, err := s.TokenDB(uid).NewSession(c).Where("uid=? AND user_token_id=? AND created_unix_time=?", uid, userTokenId, createUnixTime).Limit(1).Get(tokenRecord)
if err != nil {
return nil, err
@@ -326,7 +326,7 @@ func (s *TokenService) getTokenRecord(uid int64, userTokenId int64, createUnixTi
return tokenRecord, nil
}
func (s *TokenService) createTokenRecord(tokenRecord *models.TokenRecord) error {
func (s *TokenService) createTokenRecord(c *core.Context, tokenRecord *models.TokenRecord) error {
if tokenRecord.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -335,7 +335,7 @@ func (s *TokenService) createTokenRecord(tokenRecord *models.TokenRecord) error
return errs.ErrInvalidUserTokenId
}
return s.TokenDB(tokenRecord.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.TokenDB(tokenRecord.Uid).DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Insert(tokenRecord)
return err
})
+27 -26
View File
@@ -5,6 +5,7 @@ import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -30,18 +31,18 @@ var (
)
// GetTotalCategoryCountByUid returns total category count of user
func (s *TransactionCategoryService) GetTotalCategoryCountByUid(uid int64) (int64, error) {
func (s *TransactionCategoryService) GetTotalCategoryCountByUid(c *core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
count, err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Count(&models.TransactionCategory{})
count, err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Count(&models.TransactionCategory{})
return count, err
}
// GetAllCategoriesByUid returns all transaction category models of user
func (s *TransactionCategoryService) GetAllCategoriesByUid(uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) ([]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetAllCategoriesByUid(c *core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) ([]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -62,13 +63,13 @@ func (s *TransactionCategoryService) GetAllCategoriesByUid(uid int64, categoryTy
}
var categories []*models.TransactionCategory
err := s.UserDataDB(uid).Where(condition, conditionParams...).OrderBy("type asc, parent_category_id asc, display_order asc").Find(&categories)
err := s.UserDataDB(uid).NewSession(c).Where(condition, conditionParams...).OrderBy("type asc, parent_category_id asc, display_order asc").Find(&categories)
return categories, err
}
// GetCategoryByCategoryId returns a transaction category model according to transaction category id
func (s *TransactionCategoryService) GetCategoryByCategoryId(uid int64, categoryId int64) (*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetCategoryByCategoryId(c *core.Context, uid int64, categoryId int64) (*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -78,7 +79,7 @@ func (s *TransactionCategoryService) GetCategoryByCategoryId(uid int64, category
}
category := &models.TransactionCategory{}
has, err := s.UserDataDB(uid).ID(categoryId).Where("uid=? AND deleted=?", uid, false).Get(category)
has, err := s.UserDataDB(uid).NewSession(c).ID(categoryId).Where("uid=? AND deleted=?", uid, false).Get(category)
if err != nil {
return nil, err
@@ -90,7 +91,7 @@ func (s *TransactionCategoryService) GetCategoryByCategoryId(uid int64, category
}
// GetCategoriesByCategoryIds returns transaction category models according to transaction category ids
func (s *TransactionCategoryService) GetCategoriesByCategoryIds(uid int64, categoryIds []int64) (map[int64]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) GetCategoriesByCategoryIds(c *core.Context, uid int64, categoryIds []int64) (map[int64]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -100,7 +101,7 @@ func (s *TransactionCategoryService) GetCategoriesByCategoryIds(uid int64, categ
}
var categories []*models.TransactionCategory
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).In("category_id", categoryIds).Find(&categories)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).In("category_id", categoryIds).Find(&categories)
if err != nil {
return nil, err
@@ -111,13 +112,13 @@ func (s *TransactionCategoryService) GetCategoriesByCategoryIds(uid int64, categ
}
// GetMaxDisplayOrder returns the max display order according to transaction category type
func (s *TransactionCategoryService) GetMaxDisplayOrder(uid int64, categoryType models.TransactionCategoryType) (int32, error) {
func (s *TransactionCategoryService) GetMaxDisplayOrder(c *core.Context, uid int64, categoryType models.TransactionCategoryType) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
category := &models.TransactionCategory{}
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.LevelOneTransactionParentId).OrderBy("display_order desc").Limit(1).Get(category)
has, err := s.UserDataDB(uid).NewSession(c).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.LevelOneTransactionParentId).OrderBy("display_order desc").Limit(1).Get(category)
if err != nil {
return 0, err
@@ -131,7 +132,7 @@ func (s *TransactionCategoryService) GetMaxDisplayOrder(uid int64, categoryType
}
// GetMaxSubCategoryDisplayOrder returns the max display order of sub transaction category according to transaction category type and parent transaction category id
func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) (int32, error) {
func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(c *core.Context, uid int64, categoryType models.TransactionCategoryType, parentCategoryId int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -141,7 +142,7 @@ func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(uid int64, ca
}
category := &models.TransactionCategory{}
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, parentCategoryId).OrderBy("display_order desc").Limit(1).Get(category)
has, err := s.UserDataDB(uid).NewSession(c).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, parentCategoryId).OrderBy("display_order desc").Limit(1).Get(category)
if err != nil {
return 0, err
@@ -155,7 +156,7 @@ func (s *TransactionCategoryService) GetMaxSubCategoryDisplayOrder(uid int64, ca
}
// CreateCategory saves a new transaction category model to database
func (s *TransactionCategoryService) CreateCategory(category *models.TransactionCategory) error {
func (s *TransactionCategoryService) CreateCategory(c *core.Context, category *models.TransactionCategory) error {
if category.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -166,14 +167,14 @@ func (s *TransactionCategoryService) CreateCategory(category *models.Transaction
category.CreatedUnixTime = time.Now().Unix()
category.UpdatedUnixTime = time.Now().Unix()
return s.UserDataDB(category.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(category.Uid).DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Insert(category)
return err
})
}
// CreateCategories saves a few transaction category models to database
func (s *TransactionCategoryService) CreateCategories(uid int64, categories map[*models.TransactionCategory][]*models.TransactionCategory) ([]*models.TransactionCategory, error) {
func (s *TransactionCategoryService) CreateCategories(c *core.Context, uid int64, categories map[*models.TransactionCategory][]*models.TransactionCategory) ([]*models.TransactionCategory, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -206,7 +207,7 @@ func (s *TransactionCategoryService) CreateCategories(uid int64, categories map[
}
}
err := s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
err := s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(allCategories); i++ {
category := allCategories[i]
_, err := sess.Insert(category)
@@ -227,14 +228,14 @@ func (s *TransactionCategoryService) CreateCategories(uid int64, categories map[
}
// ModifyCategory saves an existed transaction category model to database
func (s *TransactionCategoryService) ModifyCategory(category *models.TransactionCategory) error {
func (s *TransactionCategoryService) ModifyCategory(c *core.Context, category *models.TransactionCategory) error {
if category.Uid <= 0 {
return errs.ErrUserIdInvalid
}
category.UpdatedUnixTime = time.Now().Unix()
return s.UserDataDB(category.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(category.Uid).DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.ID(category.CategoryId).Cols("name", "icon", "color", "comment", "hidden", "updated_unix_time").Where("uid=? AND deleted=?", category.Uid, false).Update(category)
if err != nil {
@@ -248,7 +249,7 @@ func (s *TransactionCategoryService) ModifyCategory(category *models.Transaction
}
// HideCategory updates hidden field of given transaction categories
func (s *TransactionCategoryService) HideCategory(uid int64, ids []int64, hidden bool) error {
func (s *TransactionCategoryService) HideCategory(c *core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -260,7 +261,7 @@ func (s *TransactionCategoryService) HideCategory(uid int64, ids []int64, hidden
UpdatedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.Cols("hidden", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).In("category_id", ids).Update(updateModel)
if err != nil {
@@ -274,7 +275,7 @@ func (s *TransactionCategoryService) HideCategory(uid int64, ids []int64, hidden
}
// ModifyCategoryDisplayOrders updates display order of given transaction categories
func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(uid int64, categories []*models.TransactionCategory) error {
func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(c *core.Context, uid int64, categories []*models.TransactionCategory) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -283,7 +284,7 @@ func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(uid int64, cate
categories[i].UpdatedUnixTime = time.Now().Unix()
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(categories); i++ {
category := categories[i]
updatedRows, err := sess.ID(category.CategoryId).Cols("display_order", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).Update(category)
@@ -300,7 +301,7 @@ func (s *TransactionCategoryService) ModifyCategoryDisplayOrders(uid int64, cate
}
// DeleteCategory deletes an existed transaction category from database
func (s *TransactionCategoryService) DeleteCategory(uid int64, categoryId int64) error {
func (s *TransactionCategoryService) DeleteCategory(c *core.Context, uid int64, categoryId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -312,7 +313,7 @@ func (s *TransactionCategoryService) DeleteCategory(uid int64, categoryId int64)
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
var categoryAndSubCategories []*models.TransactionCategory
err := sess.Where("uid=? AND deleted=? AND (category_id=? OR parent_category_id=?)", uid, false, categoryId, categoryId).Find(&categoryAndSubCategories)
@@ -349,7 +350,7 @@ func (s *TransactionCategoryService) DeleteCategory(uid int64, categoryId int64)
}
// DeleteAllCategories deletes all existed transaction categories from database
func (s *TransactionCategoryService) DeleteAllCategories(uid int64) error {
func (s *TransactionCategoryService) DeleteAllCategories(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -361,7 +362,7 @@ func (s *TransactionCategoryService) DeleteAllCategories(uid int64) error {
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
exists, err := sess.Cols("uid", "deleted", "category_id").Where("uid=? AND deleted=? AND category_id<>?", uid, false, 0).Limit(1).Exist(&models.Transaction{})
if err != nil {
+31 -30
View File
@@ -5,6 +5,7 @@ import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -30,30 +31,30 @@ var (
)
// GetTotalTagCountByUid returns total tag count of user
func (s *TransactionTagService) GetTotalTagCountByUid(uid int64) (int64, error) {
func (s *TransactionTagService) GetTotalTagCountByUid(c *core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
count, err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Count(&models.TransactionTag{})
count, err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Count(&models.TransactionTag{})
return count, err
}
// GetAllTagsByUid returns all transaction tag models of user
func (s *TransactionTagService) GetAllTagsByUid(uid int64) ([]*models.TransactionTag, error) {
func (s *TransactionTagService) GetAllTagsByUid(c *core.Context, uid int64) ([]*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
var tags []*models.TransactionTag
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Find(&tags)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Find(&tags)
return tags, err
}
// GetTagByTagId returns a transaction tag model according to transaction tag id
func (s *TransactionTagService) GetTagByTagId(uid int64, tagId int64) (*models.TransactionTag, error) {
func (s *TransactionTagService) GetTagByTagId(c *core.Context, uid int64, tagId int64) (*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -63,7 +64,7 @@ func (s *TransactionTagService) GetTagByTagId(uid int64, tagId int64) (*models.T
}
tag := &models.TransactionTag{}
has, err := s.UserDataDB(uid).ID(tagId).Where("uid=? AND deleted=?", uid, false).Get(tag)
has, err := s.UserDataDB(uid).NewSession(c).ID(tagId).Where("uid=? AND deleted=?", uid, false).Get(tag)
if err != nil {
return nil, err
@@ -75,7 +76,7 @@ func (s *TransactionTagService) GetTagByTagId(uid int64, tagId int64) (*models.T
}
// GetTagsByTagIds returns transaction tag models according to transaction tag ids
func (s *TransactionTagService) GetTagsByTagIds(uid int64, tagIds []int64) (map[int64]*models.TransactionTag, error) {
func (s *TransactionTagService) GetTagsByTagIds(c *core.Context, uid int64, tagIds []int64) (map[int64]*models.TransactionTag, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -85,7 +86,7 @@ func (s *TransactionTagService) GetTagsByTagIds(uid int64, tagIds []int64) (map[
}
var tags []*models.TransactionTag
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).In("tag_id", tagIds).Find(&tags)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).In("tag_id", tagIds).Find(&tags)
if err != nil {
return nil, err
@@ -96,13 +97,13 @@ func (s *TransactionTagService) GetTagsByTagIds(uid int64, tagIds []int64) (map[
}
// GetMaxDisplayOrder returns the max display order
func (s *TransactionTagService) GetMaxDisplayOrder(uid int64) (int32, error) {
func (s *TransactionTagService) GetMaxDisplayOrder(c *core.Context, uid int64) (int32, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
tag := &models.TransactionTag{}
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "display_order").Where("uid=? AND deleted=?", uid, false).OrderBy("display_order desc").Limit(1).Get(tag)
has, err := s.UserDataDB(uid).NewSession(c).Cols("uid", "deleted", "display_order").Where("uid=? AND deleted=?", uid, false).OrderBy("display_order desc").Limit(1).Get(tag)
if err != nil {
return 0, err
@@ -116,13 +117,13 @@ func (s *TransactionTagService) GetMaxDisplayOrder(uid int64) (int32, error) {
}
// GetAllTagIdsOfAllTransactions returns all transaction tag ids
func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(uid int64) (map[int64][]int64, error) {
func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(c *core.Context, uid int64) (map[int64][]int64, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
var tagIndexs []*models.TransactionTagIndex
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Find(&tagIndexs)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Find(&tagIndexs)
allTransactionTagIds := s.getGroupedTransactionTagIds(tagIndexs)
@@ -130,13 +131,13 @@ func (s *TransactionTagService) GetAllTagIdsOfAllTransactions(uid int64) (map[in
}
// GetAllTagIdsOfTransactions returns transaction tag ids for given transactions
func (s *TransactionTagService) GetAllTagIdsOfTransactions(uid int64, transactionIds []int64) (map[int64][]int64, error) {
func (s *TransactionTagService) GetAllTagIdsOfTransactions(c *core.Context, uid int64, transactionIds []int64) (map[int64][]int64, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
var tagIndexs []*models.TransactionTagIndex
err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).In("transaction_id", transactionIds).Find(&tagIndexs)
err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).In("transaction_id", transactionIds).Find(&tagIndexs)
allTransactionTagIds := s.getGroupedTransactionTagIds(tagIndexs)
@@ -144,12 +145,12 @@ func (s *TransactionTagService) GetAllTagIdsOfTransactions(uid int64, transactio
}
// CreateTag saves a new transaction tag model to database
func (s *TransactionTagService) CreateTag(tag *models.TransactionTag) error {
func (s *TransactionTagService) CreateTag(c *core.Context, tag *models.TransactionTag) error {
if tag.Uid <= 0 {
return errs.ErrUserIdInvalid
}
exists, err := s.ExistsTagName(tag.Uid, tag.Name)
exists, err := s.ExistsTagName(c, tag.Uid, tag.Name)
if err != nil {
return err
@@ -163,19 +164,19 @@ func (s *TransactionTagService) CreateTag(tag *models.TransactionTag) error {
tag.CreatedUnixTime = time.Now().Unix()
tag.UpdatedUnixTime = time.Now().Unix()
return s.UserDataDB(tag.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(tag.Uid).DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Insert(tag)
return err
})
}
// ModifyTag saves an existed transaction tag model to database
func (s *TransactionTagService) ModifyTag(tag *models.TransactionTag) error {
func (s *TransactionTagService) ModifyTag(c *core.Context, tag *models.TransactionTag) error {
if tag.Uid <= 0 {
return errs.ErrUserIdInvalid
}
exists, err := s.ExistsTagName(tag.Uid, tag.Name)
exists, err := s.ExistsTagName(c, tag.Uid, tag.Name)
if err != nil {
return err
@@ -185,7 +186,7 @@ func (s *TransactionTagService) ModifyTag(tag *models.TransactionTag) error {
tag.UpdatedUnixTime = time.Now().Unix()
return s.UserDataDB(tag.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(tag.Uid).DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.ID(tag.TagId).Cols("name", "updated_unix_time").Where("uid=? AND deleted=?", tag.Uid, false).Update(tag)
if err != nil {
@@ -199,7 +200,7 @@ func (s *TransactionTagService) ModifyTag(tag *models.TransactionTag) error {
}
// HideTag updates hidden field of given transaction tags
func (s *TransactionTagService) HideTag(uid int64, ids []int64, hidden bool) error {
func (s *TransactionTagService) HideTag(c *core.Context, uid int64, ids []int64, hidden bool) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -211,7 +212,7 @@ func (s *TransactionTagService) HideTag(uid int64, ids []int64, hidden bool) err
UpdatedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.Cols("hidden", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).In("tag_id", ids).Update(updateModel)
if err != nil {
@@ -225,7 +226,7 @@ func (s *TransactionTagService) HideTag(uid int64, ids []int64, hidden bool) err
}
// ModifyTagDisplayOrders updates display order of given transaction tags
func (s *TransactionTagService) ModifyTagDisplayOrders(uid int64, tags []*models.TransactionTag) error {
func (s *TransactionTagService) ModifyTagDisplayOrders(c *core.Context, uid int64, tags []*models.TransactionTag) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -234,7 +235,7 @@ func (s *TransactionTagService) ModifyTagDisplayOrders(uid int64, tags []*models
tags[i].UpdatedUnixTime = time.Now().Unix()
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
for i := 0; i < len(tags); i++ {
tag := tags[i]
updatedRows, err := sess.ID(tag.TagId).Cols("display_order", "updated_unix_time").Where("uid=? AND deleted=?", uid, false).Update(tag)
@@ -251,7 +252,7 @@ func (s *TransactionTagService) ModifyTagDisplayOrders(uid int64, tags []*models
}
// DeleteTag deletes an existed transaction tag from database
func (s *TransactionTagService) DeleteTag(uid int64, tagId int64) error {
func (s *TransactionTagService) DeleteTag(c *core.Context, uid int64, tagId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -263,7 +264,7 @@ func (s *TransactionTagService) DeleteTag(uid int64, tagId int64) error {
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
exists, err := sess.Cols("uid", "tag_id").Where("uid=? AND deleted=? AND tag_id=?", uid, false, tagId).Limit(1).Exist(&models.TransactionTagIndex{})
if err != nil {
@@ -285,7 +286,7 @@ func (s *TransactionTagService) DeleteTag(uid int64, tagId int64) error {
}
// DeleteAllTags deletes all existed transaction tags from database
func (s *TransactionTagService) DeleteAllTags(uid int64) error {
func (s *TransactionTagService) DeleteAllTags(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -297,7 +298,7 @@ func (s *TransactionTagService) DeleteAllTags(uid int64) error {
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
exists, err := sess.Cols("uid", "deleted").Where("uid=? AND deleted=?", uid, false).Limit(1).Exist(&models.TransactionTagIndex{})
if err != nil {
@@ -317,12 +318,12 @@ func (s *TransactionTagService) DeleteAllTags(uid int64) error {
}
// ExistsTagName returns whether the given tag name exists
func (s *TransactionTagService) ExistsTagName(uid int64, name string) (bool, error) {
func (s *TransactionTagService) ExistsTagName(c *core.Context, uid int64, name string) (bool, error) {
if name == "" {
return false, errs.ErrTransactionTagNameIsEmpty
}
return s.UserDataDB(uid).Cols("name").Where("uid=? AND deleted=? AND name=?", uid, false, name).Exist(&models.TransactionTag{})
return s.UserDataDB(uid).NewSession(c).Cols("name").Where("uid=? AND deleted=? AND name=?", uid, false, name).Exist(&models.TransactionTag{})
}
// GetTagMapByList returns a transaction tag map by a list
+33 -32
View File
@@ -7,6 +7,7 @@ import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -33,23 +34,23 @@ var (
)
// GetTotalTransactionCountByUid returns total transaction count of user
func (s *TransactionService) GetTotalTransactionCountByUid(uid int64) (int64, error) {
func (s *TransactionService) GetTotalTransactionCountByUid(c *core.Context, uid int64) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
count, err := s.UserDataDB(uid).Where("uid=? AND deleted=?", uid, false).Count(&models.Transaction{})
count, err := s.UserDataDB(uid).NewSession(c).Where("uid=? AND deleted=?", uid, false).Count(&models.Transaction{})
return count, err
}
// GetAllTransactions returns all transactions
func (s *TransactionService) GetAllTransactions(uid int64, pageCount int32, noDuplicated bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetAllTransactions(c *core.Context, uid int64, pageCount int32, noDuplicated bool) ([]*models.Transaction, error) {
maxTransactionTime := utils.GetMaxTransactionTimeFromUnixTime(time.Now().Unix())
var allTransactions []*models.Transaction
for maxTransactionTime > 0 {
transactions, err := s.GetAllTransactionsByMaxTime(uid, maxTransactionTime, pageCount, noDuplicated)
transactions, err := s.GetAllTransactionsByMaxTime(c, uid, maxTransactionTime, pageCount, noDuplicated)
if err != nil {
return nil, err
@@ -69,12 +70,12 @@ func (s *TransactionService) GetAllTransactions(uid int64, pageCount int32, noDu
}
// GetAllTransactionsByMaxTime returns all transactions before given time
func (s *TransactionService) GetAllTransactionsByMaxTime(uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) {
return s.GetTransactionsByMaxTime(uid, maxTransactionTime, 0, 0, nil, nil, "", 1, count, false, noDuplicated)
func (s *TransactionService) GetAllTransactionsByMaxTime(c *core.Context, uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) {
return s.GetTransactionsByMaxTime(c, uid, maxTransactionTime, 0, 0, nil, nil, "", 1, count, false, noDuplicated)
}
// GetTransactionsByMaxTime returns transactions before given time
func (s *TransactionService) GetTransactionsByMaxTime(uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string, page int32, count int32, needOneMoreItem bool, noDuplicated bool) ([]*models.Transaction, error) {
func (s *TransactionService) GetTransactionsByMaxTime(c *core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string, page int32, count int32, needOneMoreItem bool, noDuplicated bool) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -99,13 +100,13 @@ func (s *TransactionService) GetTransactionsByMaxTime(uid int64, maxTransactionT
}
condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, noDuplicated)
err = s.UserDataDB(uid).Where(condition, conditionParams...).Limit(int(actualCount), int(count*(page-1))).OrderBy("transaction_time desc").Find(&transactions)
err = s.UserDataDB(uid).NewSession(c).Where(condition, conditionParams...).Limit(int(actualCount), int(count*(page-1))).OrderBy("transaction_time desc").Find(&transactions)
return transactions, err
}
// GetTransactionsInMonthByPage returns all transactions in given year and month
func (s *TransactionService) GetTransactionsInMonthByPage(uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string) ([]*models.Transaction, error) {
func (s *TransactionService) GetTransactionsInMonthByPage(c *core.Context, uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -125,7 +126,7 @@ func (s *TransactionService) GetTransactionsInMonthByPage(uid int64, year int32,
var transactions []*models.Transaction
condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, true)
err = s.UserDataDB(uid).Where(condition, conditionParams...).OrderBy("transaction_time desc").Find(&transactions)
err = s.UserDataDB(uid).NewSession(c).Where(condition, conditionParams...).OrderBy("transaction_time desc").Find(&transactions)
transactionsInMonth := make([]*models.Transaction, 0, len(transactions))
@@ -143,7 +144,7 @@ func (s *TransactionService) GetTransactionsInMonthByPage(uid int64, year int32,
}
// GetTransactionByTransactionId returns a transaction model according to transaction id
func (s *TransactionService) GetTransactionByTransactionId(uid int64, transactionId int64) (*models.Transaction, error) {
func (s *TransactionService) GetTransactionByTransactionId(c *core.Context, uid int64, transactionId int64) (*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -153,7 +154,7 @@ func (s *TransactionService) GetTransactionByTransactionId(uid int64, transactio
}
transaction := &models.Transaction{}
has, err := s.UserDataDB(uid).ID(transactionId).Where("uid=? AND deleted=?", uid, false).Get(transaction)
has, err := s.UserDataDB(uid).NewSession(c).ID(transactionId).Where("uid=? AND deleted=?", uid, false).Get(transaction)
if err != nil {
return nil, err
@@ -165,12 +166,12 @@ func (s *TransactionService) GetTransactionByTransactionId(uid int64, transactio
}
// GetAllTransactionCount returns total count of transactions
func (s *TransactionService) GetAllTransactionCount(uid int64) (int64, error) {
return s.GetTransactionCount(uid, 0, 0, 0, nil, nil, "")
func (s *TransactionService) GetAllTransactionCount(c *core.Context, uid int64) (int64, error) {
return s.GetTransactionCount(c, uid, 0, 0, 0, nil, nil, "")
}
// GetMonthTransactionCount returns total count of transactions in given year and month
func (s *TransactionService) GetMonthTransactionCount(uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string, utcOffset int16) (int64, error) {
func (s *TransactionService) GetMonthTransactionCount(c *core.Context, uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string, utcOffset int16) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
@@ -186,21 +187,21 @@ func (s *TransactionService) GetMonthTransactionCount(uid int64, year int32, mon
minTransactionTime := utils.GetMinTransactionTimeFromUnixTime(startTime.Unix())
maxTransactionTime := utils.GetMinTransactionTimeFromUnixTime(endTime.Unix()) - 1
return s.GetTransactionCount(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword)
return s.GetTransactionCount(c, uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword)
}
// GetTransactionCount returns count of transactions
func (s *TransactionService) GetTransactionCount(uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string) (int64, error) {
func (s *TransactionService) GetTransactionCount(c *core.Context, uid int64, maxTransactionTime int64, minTransactionTime int64, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string) (int64, error) {
if uid <= 0 {
return 0, errs.ErrUserIdInvalid
}
condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, true)
return s.UserDataDB(uid).Where(condition, conditionParams...).Count(&models.Transaction{})
return s.UserDataDB(uid).NewSession(c).Where(condition, conditionParams...).Count(&models.Transaction{})
}
// CreateTransaction saves a new transaction to database
func (s *TransactionService) CreateTransaction(transaction *models.Transaction, tagIds []int64) error {
func (s *TransactionService) CreateTransaction(c *core.Context, transaction *models.Transaction, tagIds []int64) error {
if transaction.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -247,7 +248,7 @@ func (s *TransactionService) CreateTransaction(transaction *models.Transaction,
}
}
return s.UserDataDB(transaction.Uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(transaction.Uid).DoTransaction(c, func(sess *xorm.Session) error {
// Get and verify source and destination account
sourceAccount, destinationAccount, err := s.getAccountModels(sess, transaction)
@@ -411,7 +412,7 @@ func (s *TransactionService) CreateTransaction(transaction *models.Transaction,
}
// ModifyTransaction saves an existed transaction to database
func (s *TransactionService) ModifyTransaction(transaction *models.Transaction, addTagIds []int64, removeTagIds []int64) error {
func (s *TransactionService) ModifyTransaction(c *core.Context, transaction *models.Transaction, addTagIds []int64, removeTagIds []int64) error {
if transaction.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -441,7 +442,7 @@ func (s *TransactionService) ModifyTransaction(transaction *models.Transaction,
}
}
err := s.UserDataDB(transaction.Uid).DoTransaction(func(sess *xorm.Session) error {
err := s.UserDataDB(transaction.Uid).DoTransaction(c, func(sess *xorm.Session) error {
// Get and verify current transaction
oldTransaction := &models.Transaction{}
has, err := sess.ID(transaction.TransactionId).Where("uid=? AND deleted=?", transaction.Uid, false).Get(oldTransaction)
@@ -782,7 +783,7 @@ func (s *TransactionService) ModifyTransaction(transaction *models.Transaction,
}
// DeleteTransaction deletes an existed transaction from database
func (s *TransactionService) DeleteTransaction(uid int64, transactionId int64) error {
func (s *TransactionService) DeleteTransaction(c *core.Context, uid int64, transactionId int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -799,7 +800,7 @@ func (s *TransactionService) DeleteTransaction(uid int64, transactionId int64) e
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
// Get and verify current transaction
oldTransaction := &models.Transaction{}
has, err := sess.ID(transactionId).Where("uid=? AND deleted=?", uid, false).Get(oldTransaction)
@@ -902,7 +903,7 @@ func (s *TransactionService) DeleteTransaction(uid int64, transactionId int64) e
}
// DeleteAllTransactions deletes all existed transactions from database
func (s *TransactionService) DeleteAllTransactions(uid int64) error {
func (s *TransactionService) DeleteAllTransactions(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -925,7 +926,7 @@ func (s *TransactionService) DeleteAllTransactions(uid int64) error {
DeletedUnixTime: now,
}
return s.UserDataDB(uid).DoTransaction(func(sess *xorm.Session) error {
return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error {
// Update all transaction to deleted
_, err := sess.Cols("deleted", "deleted_unix_time").Where("uid=? AND deleted=?", uid, false).Update(updateModel)
@@ -992,7 +993,7 @@ func (s *TransactionService) GetRelatedTransferTransaction(originalTransaction *
}
// GetAccountsTotalIncomeAndExpense returns the every accounts total income and expense amount by specific date range
func (s *TransactionService) GetAccountsTotalIncomeAndExpense(uid int64, startUnixTime int64, endUnixTime int64) (map[int64]int64, map[int64]int64, error) {
func (s *TransactionService) GetAccountsTotalIncomeAndExpense(c *core.Context, uid int64, startUnixTime int64, endUnixTime int64) (map[int64]int64, map[int64]int64, error) {
if uid <= 0 {
return nil, nil, errs.ErrUserIdInvalid
}
@@ -1001,7 +1002,7 @@ func (s *TransactionService) GetAccountsTotalIncomeAndExpense(uid int64, startUn
endTransactionTime := utils.GetMaxTransactionTimeFromUnixTime(endUnixTime)
var transactionTotalAmounts []*models.Transaction
err := s.UserDataDB(uid).Select("type, account_id, SUM(amount) as amount").Where("uid=? AND deleted=? AND (type=? OR type=?) AND transaction_time>=? AND transaction_time<=?", uid, false, models.TRANSACTION_DB_TYPE_INCOME, models.TRANSACTION_DB_TYPE_EXPENSE, startTransactionTime, endTransactionTime).GroupBy("type, account_id").Find(&transactionTotalAmounts)
err := s.UserDataDB(uid).NewSession(c).Select("type, account_id, SUM(amount) as amount").Where("uid=? AND deleted=? AND (type=? OR type=?) AND transaction_time>=? AND transaction_time<=?", uid, false, models.TRANSACTION_DB_TYPE_INCOME, models.TRANSACTION_DB_TYPE_EXPENSE, startTransactionTime, endTransactionTime).GroupBy("type, account_id").Find(&transactionTotalAmounts)
if err != nil {
return nil, nil, err
@@ -1024,7 +1025,7 @@ func (s *TransactionService) GetAccountsTotalIncomeAndExpense(uid int64, startUn
}
// GetAccountsMonthTotalIncomeAndExpense returns the every accounts total income and expense amount in month by specific date range
func (s *TransactionService) GetAccountsMonthTotalIncomeAndExpense(uid int64, startUnixTime int64, endUnixTime int64, pageCount int) (map[string]models.TransactionAccountsAmount, error) {
func (s *TransactionService) GetAccountsMonthTotalIncomeAndExpense(c *core.Context, uid int64, startUnixTime int64, endUnixTime int64, pageCount int) (map[string]models.TransactionAccountsAmount, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -1039,7 +1040,7 @@ func (s *TransactionService) GetAccountsMonthTotalIncomeAndExpense(uid int64, st
for maxTransactionTime > 0 {
var transactions []*models.Transaction
err := s.UserDataDB(uid).Select("uid, type, account_id, transaction_time, timezone_utc_offset, amount").Where("uid=? AND deleted=? AND (type=? OR type=?) AND transaction_time>=? AND transaction_time<=?", uid, false, models.TRANSACTION_DB_TYPE_INCOME, models.TRANSACTION_DB_TYPE_EXPENSE, minTransactionTime, maxTransactionTime).Limit(pageCount, 0).OrderBy("transaction_time desc").Find(&transactions)
err := s.UserDataDB(uid).NewSession(c).Select("uid, type, account_id, transaction_time, timezone_utc_offset, amount").Where("uid=? AND deleted=? AND (type=? OR type=?) AND transaction_time>=? AND transaction_time<=?", uid, false, models.TRANSACTION_DB_TYPE_INCOME, models.TRANSACTION_DB_TYPE_EXPENSE, minTransactionTime, maxTransactionTime).Limit(pageCount, 0).OrderBy("transaction_time desc").Find(&transactions)
if err != nil {
return nil, err
@@ -1091,7 +1092,7 @@ func (s *TransactionService) GetAccountsMonthTotalIncomeAndExpense(uid int64, st
}
// GetAccountsAndCategoriesTotalIncomeAndExpense returns the every accounts and categories total income and expense amount by specific date range
func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(uid int64, startUnixTime int64, endUnixTime int64) ([]*models.Transaction, error) {
func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(c *core.Context, uid int64, startUnixTime int64, endUnixTime int64) ([]*models.Transaction, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
@@ -1114,7 +1115,7 @@ func (s *TransactionService) GetAccountsAndCategoriesTotalIncomeAndExpense(uid i
}
var transactionTotalAmounts []*models.Transaction
err := s.UserDataDB(uid).Select("category_id, account_id, SUM(amount) as amount").Where(condition, conditionParams...).GroupBy("category_id, account_id").Find(&transactionTotalAmounts)
err := s.UserDataDB(uid).NewSession(c).Select("category_id, account_id, SUM(amount) as amount").Where(condition, conditionParams...).GroupBy("category_id, account_id").Find(&transactionTotalAmounts)
if err != nil {
return nil, err
+17 -16
View File
@@ -7,6 +7,7 @@ import (
"github.com/pquerna/otp/totp"
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -45,13 +46,13 @@ var (
)
// GetUserTwoFactorSettingByUid returns the 2fa setting model according to user uid
func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(uid int64) (*models.TwoFactor, error) {
func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(c *core.Context, uid int64) (*models.TwoFactor, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
twoFactor := &models.TwoFactor{}
has, err := s.UserDB().Where("uid=?", uid).Get(twoFactor)
has, err := s.UserDB().NewSession(c).Where("uid=?", uid).Get(twoFactor)
if err != nil {
return nil, err
@@ -69,7 +70,7 @@ func (s *TwoFactorAuthorizationService) GetUserTwoFactorSettingByUid(uid int64)
}
// GenerateTwoFactorSecret generates a new 2fa secret
func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(user *models.User) (*otp.Key, error) {
func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(c *core.Context, user *models.User) (*otp.Key, error) {
if user == nil {
return nil, errs.ErrUserNotFound
}
@@ -85,7 +86,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(user *models.Use
}
// CreateTwoFactorSetting saves a new 2fa setting to database
func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(twoFactor *models.TwoFactor) error {
func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(c *core.Context, twoFactor *models.TwoFactor) error {
if twoFactor.Uid <= 0 {
return errs.ErrUserIdInvalid
}
@@ -99,19 +100,19 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(twoFactor *models
twoFactor.CreatedUnixTime = time.Now().Unix()
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Insert(twoFactor)
return err
})
}
// DeleteTwoFactorSetting deletes an existed 2fa setting from database
func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(uid int64) error {
func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
deletedRows, err := sess.Where("uid=?", uid).Delete(&models.TwoFactor{})
if err != nil {
@@ -125,22 +126,22 @@ func (s *TwoFactorAuthorizationService) DeleteTwoFactorSetting(uid int64) error
}
// ExistsTwoFactorSetting returns whether the given user has existed 2fa setting
func (s *TwoFactorAuthorizationService) ExistsTwoFactorSetting(uid int64) (bool, error) {
func (s *TwoFactorAuthorizationService) ExistsTwoFactorSetting(c *core.Context, uid int64) (bool, error) {
if uid <= 0 {
return false, errs.ErrUserIdInvalid
}
return s.UserDB().Cols("uid").Where("uid=?", uid).Exist(&models.TwoFactor{})
return s.UserDB().NewSession(c).Cols("uid").Where("uid=?", uid).Exist(&models.TwoFactor{})
}
// GetAndUseUserTwoFactorRecoveryCode checks whether the given 2fa recovery code exists and marks it used
func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(uid int64, recoveryCode string, salt string) error {
func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(c *core.Context, uid int64, recoveryCode string, salt string) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
recoveryCode = utils.EncodePassword(recoveryCode, salt)
exists, err := s.UserDB().Cols("uid", "recovery_code").Where("uid=? AND recovery_code=? AND used=?", uid, recoveryCode, false).Exist(&models.TwoFactorRecoveryCode{})
exists, err := s.UserDB().NewSession(c).Cols("uid", "recovery_code").Where("uid=? AND recovery_code=? AND used=?", uid, recoveryCode, false).Exist(&models.TwoFactorRecoveryCode{})
if err != nil {
return err
@@ -148,7 +149,7 @@ func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(uid i
return errs.ErrTwoFactorRecoveryCodeNotExist
}
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Cols("used", "used_unix_time").Where("uid=? AND recovery_code=?", uid, recoveryCode).Update(&models.TwoFactorRecoveryCode{Used: true, UsedUnixTime: time.Now().Unix()})
return err
})
@@ -172,7 +173,7 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]stri
}
// CreateTwoFactorRecoveryCodes saves new 2fa recovery codes to database
func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(uid int64, recoveryCodes []string, salt string) error {
func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(c *core.Context, uid int64, recoveryCodes []string, salt string) error {
twoFactorRecoveryCodes := make([]*models.TwoFactorRecoveryCode, len(recoveryCodes))
for i := 0; i < len(recoveryCodes); i++ {
@@ -184,7 +185,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(uid int64,
}
}
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Where("uid=?", uid).Delete(&models.TwoFactorRecoveryCode{})
if err != nil {
@@ -205,12 +206,12 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorRecoveryCodes(uid int64,
}
// DeleteTwoFactorRecoveryCodes deletes existed 2fa recovery codes from database
func (s *TwoFactorAuthorizationService) DeleteTwoFactorRecoveryCodes(uid int64) error {
func (s *TwoFactorAuthorizationService) DeleteTwoFactorRecoveryCodes(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Where("uid=?", uid).Delete(&models.TwoFactorRecoveryCode{})
return err
})
+33 -32
View File
@@ -5,6 +5,7 @@ import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
@@ -31,14 +32,14 @@ var (
)
// GetUserByUsernameOrEmailAndPassword returns the user model according to login name and password
func (s *UserService) GetUserByUsernameOrEmailAndPassword(loginname string, password string) (*models.User, error) {
func (s *UserService) GetUserByUsernameOrEmailAndPassword(c *core.Context, loginname string, password string) (*models.User, error) {
var user *models.User
var err error
if utils.IsValidUsername(loginname) {
user, err = s.GetUserByUsername(loginname)
user, err = s.GetUserByUsername(c, loginname)
} else if utils.IsValidEmail(loginname) {
user, err = s.GetUserByEmail(loginname)
user, err = s.GetUserByEmail(c, loginname)
} else {
err = errs.ErrLoginNameInvalid
}
@@ -55,13 +56,13 @@ func (s *UserService) GetUserByUsernameOrEmailAndPassword(loginname string, pass
}
// GetUserById returns the user model according to user uid
func (s *UserService) GetUserById(uid int64) (*models.User, error) {
func (s *UserService) GetUserById(c *core.Context, uid int64) (*models.User, error) {
if uid <= 0 {
return nil, errs.ErrUserIdInvalid
}
user := &models.User{}
has, err := s.UserDB().ID(uid).Where("deleted=?", false).Get(user)
has, err := s.UserDB().NewSession(c).ID(uid).Where("deleted=?", false).Get(user)
if err != nil {
return nil, err
@@ -73,13 +74,13 @@ func (s *UserService) GetUserById(uid int64) (*models.User, error) {
}
// GetUserByUsername returns the user model according to user name
func (s *UserService) GetUserByUsername(username string) (*models.User, error) {
func (s *UserService) GetUserByUsername(c *core.Context, username string) (*models.User, error) {
if username == "" {
return nil, errs.ErrUsernameIsEmpty
}
user := &models.User{}
has, err := s.UserDB().Where("username=? AND deleted=?", username, false).Get(user)
has, err := s.UserDB().NewSession(c).Where("username=? AND deleted=?", username, false).Get(user)
if err != nil {
return nil, err
@@ -91,13 +92,13 @@ func (s *UserService) GetUserByUsername(username string) (*models.User, error) {
}
// GetUserByEmail returns the user model according to user email
func (s *UserService) GetUserByEmail(email string) (*models.User, error) {
func (s *UserService) GetUserByEmail(c *core.Context, email string) (*models.User, error) {
if email == "" {
return nil, errs.ErrEmailIsEmpty
}
user := &models.User{}
has, err := s.UserDB().Where("email=? AND deleted=?", email, false).Get(user)
has, err := s.UserDB().NewSession(c).Where("email=? AND deleted=?", email, false).Get(user)
if err != nil {
return nil, err
@@ -109,8 +110,8 @@ func (s *UserService) GetUserByEmail(email string) (*models.User, error) {
}
// CreateUser saves a new user model to database
func (s *UserService) CreateUser(user *models.User) error {
exists, err := s.ExistsUsername(user.Username)
func (s *UserService) CreateUser(c *core.Context, user *models.User) error {
exists, err := s.ExistsUsername(c, user.Username)
if err != nil {
return err
@@ -118,7 +119,7 @@ func (s *UserService) CreateUser(user *models.User) error {
return errs.ErrUsernameAlreadyExists
}
exists, err = s.ExistsEmail(user.Email)
exists, err = s.ExistsEmail(c, user.Email)
if err != nil {
return err
@@ -143,14 +144,14 @@ func (s *UserService) CreateUser(user *models.User) error {
user.UpdatedUnixTime = time.Now().Unix()
user.LastLoginUnixTime = time.Now().Unix()
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.Insert(user)
return err
})
}
// UpdateUser saves an existed user model to database
func (s *UserService) UpdateUser(user *models.User, modifyUserLanguage bool) (keyProfileUpdated bool, err error) {
func (s *UserService) UpdateUser(c *core.Context, user *models.User, modifyUserLanguage bool) (keyProfileUpdated bool, err error) {
if user.Uid <= 0 {
return false, errs.ErrUserIdInvalid
}
@@ -161,7 +162,7 @@ func (s *UserService) UpdateUser(user *models.User, modifyUserLanguage bool) (ke
keyProfileUpdated = false
if user.Email != "" {
exists, err := s.ExistsEmail(user.Email)
exists, err := s.ExistsEmail(c, user.Email)
if err != nil {
return false, err
@@ -225,7 +226,7 @@ func (s *UserService) UpdateUser(user *models.User, modifyUserLanguage bool) (ke
user.UpdatedUnixTime = now
updateCols = append(updateCols, "updated_unix_time")
err = s.UserDB().DoTransaction(func(sess *xorm.Session) error {
err = s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
updatedRows, err := sess.ID(user.Uid).Cols(updateCols...).Where("deleted=?", false).Update(user)
if err != nil {
@@ -245,19 +246,19 @@ func (s *UserService) UpdateUser(user *models.User, modifyUserLanguage bool) (ke
}
// UpdateUserLastLoginTime updates the last login time field
func (s *UserService) UpdateUserLastLoginTime(uid int64) error {
func (s *UserService) UpdateUserLastLoginTime(c *core.Context, uid int64) error {
if uid <= 0 {
return errs.ErrUserIdInvalid
}
return s.UserDB().DoTransaction(func(sess *xorm.Session) error {
return s.UserDB().DoTransaction(c, func(sess *xorm.Session) error {
_, err := sess.ID(uid).Cols("last_login_unix_time").Where("deleted=?", false).Update(&models.User{LastLoginUnixTime: time.Now().Unix()})
return err
})
}
// EnableUser sets user enabled
func (s *UserService) EnableUser(username string) error {
func (s *UserService) EnableUser(c *core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -269,7 +270,7 @@ func (s *UserService) EnableUser(username string) error {
UpdatedUnixTime: now,
}
updatedRows, err := s.UserDB().Cols("disabled", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
updatedRows, err := s.UserDB().NewSession(c).Cols("disabled", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
if err != nil {
return err
@@ -280,7 +281,7 @@ func (s *UserService) EnableUser(username string) error {
}
// DisableUser sets user disabled
func (s *UserService) DisableUser(username string) error {
func (s *UserService) DisableUser(c *core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -292,7 +293,7 @@ func (s *UserService) DisableUser(username string) error {
UpdatedUnixTime: now,
}
updatedRows, err := s.UserDB().Cols("disabled", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
updatedRows, err := s.UserDB().NewSession(c).Cols("disabled", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
if err != nil {
return err
@@ -303,7 +304,7 @@ func (s *UserService) DisableUser(username string) error {
}
// SetUserEmailVerified sets user email address verified
func (s *UserService) SetUserEmailVerified(username string) error {
func (s *UserService) SetUserEmailVerified(c *core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -315,7 +316,7 @@ func (s *UserService) SetUserEmailVerified(username string) error {
UpdatedUnixTime: now,
}
updatedRows, err := s.UserDB().Cols("email_verified", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
updatedRows, err := s.UserDB().NewSession(c).Cols("email_verified", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
if err != nil {
return err
@@ -326,7 +327,7 @@ func (s *UserService) SetUserEmailVerified(username string) error {
}
// SetUserEmailUnverified sets user email address unverified
func (s *UserService) SetUserEmailUnverified(username string) error {
func (s *UserService) SetUserEmailUnverified(c *core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -338,7 +339,7 @@ func (s *UserService) SetUserEmailUnverified(username string) error {
UpdatedUnixTime: now,
}
updatedRows, err := s.UserDB().Cols("email_verified", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
updatedRows, err := s.UserDB().NewSession(c).Cols("email_verified", "updated_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
if err != nil {
return err
@@ -349,7 +350,7 @@ func (s *UserService) SetUserEmailUnverified(username string) error {
}
// DeleteUser deletes an existed user from database
func (s *UserService) DeleteUser(username string) error {
func (s *UserService) DeleteUser(c *core.Context, username string) error {
if username == "" {
return errs.ErrUsernameIsEmpty
}
@@ -361,7 +362,7 @@ func (s *UserService) DeleteUser(username string) error {
DeletedUnixTime: now,
}
deletedRows, err := s.UserDB().Cols("deleted", "deleted_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
deletedRows, err := s.UserDB().NewSession(c).Cols("deleted", "deleted_unix_time").Where("username=? AND deleted=?", username, false).Update(updateModel)
if err != nil {
return err
@@ -372,21 +373,21 @@ func (s *UserService) DeleteUser(username string) error {
}
// ExistsUsername returns whether the given user name exists
func (s *UserService) ExistsUsername(username string) (bool, error) {
func (s *UserService) ExistsUsername(c *core.Context, username string) (bool, error) {
if username == "" {
return false, errs.ErrUsernameIsEmpty
}
return s.UserDB().Cols("username").Where("username=? AND deleted=?", username, false).Exist(&models.User{})
return s.UserDB().NewSession(c).Cols("username").Where("username=? AND deleted=?", username, false).Exist(&models.User{})
}
// ExistsEmail returns whether the given user email exists
func (s *UserService) ExistsEmail(email string) (bool, error) {
func (s *UserService) ExistsEmail(c *core.Context, email string) (bool, error) {
if email == "" {
return false, errs.ErrEmailIsEmpty
}
return s.UserDB().Cols("email").Where("email=? AND deleted=?", email, false).Exist(&models.User{})
return s.UserDB().NewSession(c).Cols("email").Where("email=? AND deleted=?", email, false).Exist(&models.User{})
}
// IsPasswordEqualsUserPassword returns whether the given password is correct