code refactor, modify style

This commit is contained in:
MaysWind
2023-07-29 23:05:02 +08:00
parent a9c511eb2e
commit d3e1acddc5
8 changed files with 329 additions and 226 deletions
+19 -11
View File
@@ -118,7 +118,18 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (interface{},
return nil, errs.Or(err, errs.ErrOperationFailed) return nil, errs.Or(err, errs.ErrOperationFailed)
} }
transactions, err := a.transactions.GetTransactionsByMaxTime(uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword, transactionListReq.Count+1, true) var totalCount int64
if transactionListReq.WithCount {
totalCount, err = a.transactions.GetTransactionCount(uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get transaction count for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
}
transactions, err := a.transactions.GetTransactionsByMaxTime(uid, transactionListReq.MaxTime, transactionListReq.MinTime, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword, transactionListReq.Page, transactionListReq.Count, true, true)
if err != nil { if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get transactions earlier than \"%d\" for user \"uid:%d\", because %s", transactionListReq.MaxTime, uid, err.Error()) log.ErrorfWithRequestId(c, "[transactions.TransactionListHandler] failed to get transactions earlier than \"%d\" for user \"uid:%d\", because %s", transactionListReq.MaxTime, uid, err.Error())
@@ -149,10 +160,14 @@ func (a *TransactionsApi) TransactionListHandler(c *core.Context) (interface{},
transactionResps.NextTimeSequenceId = nextTimeSequenceId transactionResps.NextTimeSequenceId = nextTimeSequenceId
} }
if transactionListReq.WithCount {
transactionResps.TotalCount = &totalCount
}
return transactionResps, nil return transactionResps, nil
} }
// TransactionMonthListHandler returns transaction list of current user by month // TransactionMonthListHandler returns all transaction list of current user by month
func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (interface{}, *errs.Error) { func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (interface{}, *errs.Error) {
var transactionListReq models.TransactionListInMonthByPageRequest var transactionListReq models.TransactionListInMonthByPageRequest
err := c.ShouldBindQuery(&transactionListReq) err := c.ShouldBindQuery(&transactionListReq)
@@ -194,20 +209,13 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (interfac
return nil, errs.Or(err, errs.ErrOperationFailed) return nil, errs.Or(err, errs.ErrOperationFailed)
} }
transactions, err := a.transactions.GetTransactionsInMonthByPage(uid, transactionListReq.Year, transactionListReq.Month, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword, transactionListReq.Page, transactionListReq.Count, utcOffset) transactions, err := a.transactions.GetTransactionsInMonthByPage(uid, transactionListReq.Year, transactionListReq.Month, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword)
if err != nil { if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to get transactions in month \"%d-%d\" for user \"uid:%d\", because %s", transactionListReq.Year, transactionListReq.Month, uid, err.Error()) log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to get transactions in month \"%d-%d\" for user \"uid:%d\", because %s", transactionListReq.Year, transactionListReq.Month, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed) return nil, errs.Or(err, errs.ErrOperationFailed)
} }
totalCount, err := a.transactions.GetMonthTransactionCount(uid, transactionListReq.Year, transactionListReq.Month, transactionListReq.Type, allCategoryIds, allAccountIds, transactionListReq.Keyword, utcOffset)
if err != nil {
log.ErrorfWithRequestId(c, "[transactions.TransactionMonthListHandler] failed to get transaction count in month \"%d-%d\" for user \"uid:%d\", because %s", transactionListReq.Year, transactionListReq.Month, uid, err.Error())
return nil, errs.Or(err, errs.ErrOperationFailed)
}
transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag) transactionResult, err := a.getTransactionListResult(c, user, transactions, utcOffset, transactionListReq.TrimAccount, transactionListReq.TrimCategory, transactionListReq.TrimTag)
if err != nil { if err != nil {
@@ -217,7 +225,7 @@ func (a *TransactionsApi) TransactionMonthListHandler(c *core.Context) (interfac
transactionResps := &models.TransactionInfoPageWrapperResponse2{ transactionResps := &models.TransactionInfoPageWrapperResponse2{
Items: transactionResult, Items: transactionResult,
TotalCount: totalCount, TotalCount: int64(transactionResult.Len()),
} }
return transactionResps, nil return transactionResps, nil
+3 -2
View File
@@ -112,7 +112,9 @@ type TransactionListByMaxTimeRequest struct {
Keyword string `form:"keyword"` Keyword string `form:"keyword"`
MaxTime int64 `form:"max_time" binding:"min=0"` MaxTime int64 `form:"max_time" binding:"min=0"`
MinTime int64 `form:"min_time" binding:"min=0"` MinTime int64 `form:"min_time" binding:"min=0"`
Page int32 `form:"page" binding:"min=0"`
Count int32 `form:"count" binding:"required,min=1,max=50"` Count int32 `form:"count" binding:"required,min=1,max=50"`
WithCount bool `form:"with_count"`
TrimAccount bool `form:"trim_account"` TrimAccount bool `form:"trim_account"`
TrimCategory bool `form:"trim_category"` TrimCategory bool `form:"trim_category"`
TrimTag bool `form:"trim_tag"` TrimTag bool `form:"trim_tag"`
@@ -126,8 +128,6 @@ type TransactionListInMonthByPageRequest struct {
CategoryId int64 `form:"category_id" binding:"min=0"` CategoryId int64 `form:"category_id" binding:"min=0"`
AccountId int64 `form:"account_id" binding:"min=0"` AccountId int64 `form:"account_id" binding:"min=0"`
Keyword string `form:"keyword"` Keyword string `form:"keyword"`
Page int32 `form:"page" binding:"min=0"`
Count int32 `form:"count" binding:"min=0,max=50"`
TrimAccount bool `form:"trim_account"` TrimAccount bool `form:"trim_account"`
TrimCategory bool `form:"trim_category"` TrimCategory bool `form:"trim_category"`
TrimTag bool `form:"trim_tag"` TrimTag bool `form:"trim_tag"`
@@ -218,6 +218,7 @@ type TransactionCountResponse struct {
type TransactionInfoPageWrapperResponse struct { type TransactionInfoPageWrapperResponse struct {
Items TransactionInfoResponseSlice `json:"items"` Items TransactionInfoResponseSlice `json:"items"`
NextTimeSequenceId *int64 `json:"nextTimeSequenceId,string"` NextTimeSequenceId *int64 `json:"nextTimeSequenceId,string"`
TotalCount *int64 `json:"totalCount,omitempty"`
} }
// TransactionInfoPageWrapperResponse2 represents a response of transaction which contains items and count // TransactionInfoPageWrapperResponse2 represents a response of transaction which contains items and count
+34 -23
View File
@@ -70,15 +70,21 @@ func (s *TransactionService) GetAllTransactions(uid int64, pageCount int32, noDu
// GetAllTransactionsByMaxTime returns all transactions before given time // GetAllTransactionsByMaxTime returns all transactions before given time
func (s *TransactionService) GetAllTransactionsByMaxTime(uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) { func (s *TransactionService) GetAllTransactionsByMaxTime(uid int64, maxTransactionTime int64, count int32, noDuplicated bool) ([]*models.Transaction, error) {
return s.GetTransactionsByMaxTime(uid, maxTransactionTime, 0, 0, nil, nil, "", count, noDuplicated) return s.GetTransactionsByMaxTime(uid, maxTransactionTime, 0, 0, nil, nil, "", 1, count, false, noDuplicated)
} }
// GetTransactionsByMaxTime returns transactions before given time // 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, count int32, noDuplicated bool) ([]*models.Transaction, error) { 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) {
if uid <= 0 { if uid <= 0 {
return nil, errs.ErrUserIdInvalid return nil, errs.ErrUserIdInvalid
} }
if page < 0 {
return nil, errs.ErrPageIndexInvalid
} else if page == 0 {
page = 1
}
if count < 1 { if count < 1 {
return nil, errs.ErrPageCountInvalid return nil, errs.ErrPageCountInvalid
} }
@@ -86,49 +92,54 @@ func (s *TransactionService) GetTransactionsByMaxTime(uid int64, maxTransactionT
var transactions []*models.Transaction var transactions []*models.Transaction
var err error var err error
actualCount := count
if needOneMoreItem {
actualCount++
}
condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, noDuplicated) condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, noDuplicated)
err = s.UserDataDB(uid).Where(condition, conditionParams...).Limit(int(count), 0).OrderBy("transaction_time desc").Find(&transactions) err = s.UserDataDB(uid).Where(condition, conditionParams...).Limit(int(actualCount), int(count*(page-1))).OrderBy("transaction_time desc").Find(&transactions)
return transactions, err return transactions, err
} }
// GetTransactionsInMonthByPage returns transactions in given year and month // 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, page int32, count int32, utcOffset int16) ([]*models.Transaction, error) { func (s *TransactionService) GetTransactionsInMonthByPage(uid int64, year int32, month int32, transactionType models.TransactionDbType, categoryIds []int64, accountIds []int64, keyword string) ([]*models.Transaction, error) {
if uid <= 0 { if uid <= 0 {
return nil, errs.ErrUserIdInvalid return nil, errs.ErrUserIdInvalid
} }
if page < 0 || (count > 0 && page < 1) { startMinUnixTime, err := utils.ParseFromLongDateTimeToMinUnixTime(fmt.Sprintf("%d-%02d-01 00:00:00", year, month))
return nil, errs.ErrPageIndexInvalid startMaxUnixTime, err := utils.ParseFromLongDateTimeToMaxUnixTime(fmt.Sprintf("%d-%02d-01 00:00:00", year, month))
}
if count < 0 {
return nil, errs.ErrPageCountInvalid
}
startTime, err := utils.ParseFromLongDateTime(fmt.Sprintf("%d-%02d-01 00:00:00", year, month), utcOffset)
if err != nil { if err != nil {
return nil, errs.ErrSystemError return nil, errs.ErrSystemError
} }
endTime := startTime.AddDate(0, 1, 0) endMaxUnixTime := startMaxUnixTime.AddDate(0, 1, 0)
minTransactionTime := utils.GetMinTransactionTimeFromUnixTime(startTime.Unix()) minTransactionTime := utils.GetMinTransactionTimeFromUnixTime(startMinUnixTime.Unix())
maxTransactionTime := utils.GetMinTransactionTimeFromUnixTime(endTime.Unix()) - 1 maxTransactionTime := utils.GetMinTransactionTimeFromUnixTime(endMaxUnixTime.Unix()) - 1
var transactions []*models.Transaction var transactions []*models.Transaction
condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, true) condition, conditionParams := s.getTransactionQueryCondition(uid, maxTransactionTime, minTransactionTime, transactionType, categoryIds, accountIds, keyword, true)
sess := s.UserDataDB(uid).Where(condition, conditionParams...) err = s.UserDataDB(uid).Where(condition, conditionParams...).OrderBy("transaction_time desc").Find(&transactions)
if count > 0 { transactionsInMonth := make([]*models.Transaction, 0, len(transactions))
sess = sess.Limit(int(count), int(count*(page-1)))
for i := 0; i < len(transactions); i++ {
transaction := transactions[i]
transactionUnixTime := utils.GetUnixTimeFromTransactionTime(transaction.TransactionTime)
transactionTimeZone := time.FixedZone("Transaction Timezone", int(transaction.TimezoneUtcOffset)*60)
if utils.IsUnixTimeEqualsYearAndMonth(transactionUnixTime, transactionTimeZone, year, month) {
transactionsInMonth = append(transactionsInMonth, transaction)
}
} }
err = sess.OrderBy("transaction_time desc").Find(&transactions) return transactionsInMonth, err
return transactions, err
} }
// GetTransactionByTransactionId returns a transaction model according to transaction id // GetTransactionByTransactionId returns a transaction model according to transaction id
+20
View File
@@ -13,6 +13,8 @@ const (
longDateTimeWithoutSecondFormat = "2006-01-02 15:04" longDateTimeWithoutSecondFormat = "2006-01-02 15:04"
shortDateTimeFormat = "2006-1-2 15:4:5" shortDateTimeFormat = "2006-1-2 15:4:5"
yearMonthDateTimeFormat = "2006-01" yearMonthDateTimeFormat = "2006-01"
westernmostTimezoneUtcOffset = -720 // Etc/GMT+12 (UTC-12:00)
easternmostTimezoneUtcOffset = 840 // Pacific/Kiritimati (UTC+14:00)
) )
// FormatUnixTimeToLongDateTimeInServerTimezone returns a textual representation of the unix time formatted by long date time format // FormatUnixTimeToLongDateTimeInServerTimezone returns a textual representation of the unix time formatted by long date time format
@@ -42,6 +44,18 @@ func FormatUnixTimeToYearMonth(unixTime int64, timezone *time.Location) string {
return t.Format(yearMonthDateTimeFormat) return t.Format(yearMonthDateTimeFormat)
} }
// ParseFromLongDateTimeToMinUnixTime parses a formatted string in long date time format to minimal unix time (the westernmost timezone)
func ParseFromLongDateTimeToMinUnixTime(t string) (time.Time, error) {
timezone := time.FixedZone("Timezone", easternmostTimezoneUtcOffset*60)
return time.ParseInLocation(longDateTimeFormat, t, timezone)
}
// ParseFromLongDateTimeToMaxUnixTime parses a formatted string in long date time format to maximal unix time (the easternmost timezone)
func ParseFromLongDateTimeToMaxUnixTime(t string) (time.Time, error) {
timezone := time.FixedZone("Timezone", westernmostTimezoneUtcOffset*60)
return time.ParseInLocation(longDateTimeFormat, t, timezone)
}
// ParseFromLongDateTime parses a formatted string in long date time format // ParseFromLongDateTime parses a formatted string in long date time format
func ParseFromLongDateTime(t string, utcOffset int16) (time.Time, error) { func ParseFromLongDateTime(t string, utcOffset int16) (time.Time, error) {
timezone := time.FixedZone("Timezone", int(utcOffset)*60) timezone := time.FixedZone("Timezone", int(utcOffset)*60)
@@ -59,6 +73,12 @@ func ParseFromShortDateTime(t string, utcOffset int16) (time.Time, error) {
return time.ParseInLocation(shortDateTimeFormat, t, timezone) return time.ParseInLocation(shortDateTimeFormat, t, timezone)
} }
// IsUnixTimeEqualsYearAndMonth returns whether year and month of the unix time are equals to the specified year and month
func IsUnixTimeEqualsYearAndMonth(unixTime int64, timezone *time.Location, year int32, month int32) bool {
date := parseFromUnixTime(unixTime).In(timezone)
return date.Year() == int(year) && int(date.Month()) == int(month)
}
// GetTimezoneOffsetMinutes returns offset minutes according specified timezone // GetTimezoneOffsetMinutes returns offset minutes according specified timezone
func GetTimezoneOffsetMinutes(timezone *time.Location) int16 { func GetTimezoneOffsetMinutes(timezone *time.Location) int16 {
_, tzOffset := time.Now().In(timezone).Zone() _, tzOffset := time.Now().In(timezone).Zone()
+11
View File
@@ -414,3 +414,14 @@ export function isDateRangeMatchFullMonths(minTime, maxTime) {
return firstDayOfMonth.unix() === minDateTime.unix() && lastDayOfMonth.unix() === maxDateTime.unix(); return firstDayOfMonth.unix() === minDateTime.unix() && lastDayOfMonth.unix() === maxDateTime.unix();
} }
export function isDateRangeMatchOneMonth(minTime, maxTime) {
const minDateTime = parseDateFromUnixTime(minTime);
const maxDateTime = parseDateFromUnixTime(maxTime);
if (getYear(minDateTime) !== getYear(maxDateTime) || getMonth(minDateTime) !== getMonth(maxDateTime)) {
return false;
}
return isDateRangeMatchFullMonths(minTime, maxTime);
}
+2 -2
View File
@@ -237,9 +237,9 @@ export default {
id id
}); });
}, },
getTransactions: ({ maxTime, minTime, type, categoryId, accountId, keyword }) => { getTransactions: ({ maxTime, minTime, count, page, withCount, type, categoryId, accountId, keyword }) => {
keyword = encodeURIComponent(keyword); keyword = encodeURIComponent(keyword);
return axios.get(`v1/transactions/list.json?max_time=${maxTime}&min_time=${minTime}&type=${type}&category_id=${categoryId}&account_id=${accountId}&keyword=${keyword}&count=50&trim_account=true&trim_category=true&trim_tag=true`); return axios.get(`v1/transactions/list.json?max_time=${maxTime}&min_time=${minTime}&type=${type}&category_id=${categoryId}&account_id=${accountId}&keyword=${keyword}&count=${count}&page=${page}&with_count=${withCount}&trim_account=true&trim_category=true&trim_tag=true`);
}, },
getAllTransactionsByMonth: ({ year, month, type, categoryId, accountId, keyword }) => { getAllTransactionsByMonth: ({ year, month, type, categoryId, accountId, keyword }) => {
keyword = encodeURIComponent(keyword); keyword = encodeURIComponent(keyword);
+80 -24
View File
@@ -401,7 +401,7 @@ export const useTransactionsStore = defineStore('transactions', {
return querys.join('&'); return querys.join('&');
}, },
loadTransactions({ reload, yearMonth, autoExpand, defaultCurrency }) { loadTransactions({ reload, count, page, withCount, autoExpand, defaultCurrency }) {
const self = this; const self = this;
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
const exchangeRatesStore = useExchangeRatesStore(); const exchangeRatesStore = useExchangeRatesStore();
@@ -414,29 +414,17 @@ export const useTransactionsStore = defineStore('transactions', {
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let promise = null; services.getTransactions({
maxTime: actualMaxTime,
if (yearMonth) { minTime: self.transactionsFilter.minTime * 1000,
promise = services.getAllTransactionsByMonth({ count: count || 50,
year: yearMonth.year, page: page || 1,
month: yearMonth.month, withCount: (!!withCount) || false,
type: self.transactionsFilter.type, type: self.transactionsFilter.type,
categoryId: self.transactionsFilter.categoryId, categoryId: self.transactionsFilter.categoryId,
accountId: self.transactionsFilter.accountId, accountId: self.transactionsFilter.accountId,
keyword: self.transactionsFilter.keyword keyword: self.transactionsFilter.keyword
}); }).then(response => {
} else {
promise = services.getTransactions({
maxTime: actualMaxTime,
minTime: self.transactionsFilter.minTime * 1000,
type: self.transactionsFilter.type,
categoryId: self.transactionsFilter.categoryId,
accountId: self.transactionsFilter.accountId,
keyword: self.transactionsFilter.keyword
});
}
promise.then(response => {
const data = response.data; const data = response.data;
if (!data || !data.success || !data.result) { if (!data || !data.success || !data.result) {
@@ -497,6 +485,74 @@ export const useTransactionsStore = defineStore('transactions', {
}); });
}); });
}, },
loadMonthlyAllTransactions({ year, month, autoExpand, defaultCurrency }) {
const self = this;
const settingsStore = useSettingsStore();
const exchangeRatesStore = useExchangeRatesStore();
return new Promise((resolve, reject) => {
services.getAllTransactionsByMonth({
year: year,
month: month,
type: self.transactionsFilter.type,
categoryId: self.transactionsFilter.categoryId,
accountId: self.transactionsFilter.accountId,
keyword: self.transactionsFilter.keyword
}).then(response => {
const data = response.data;
if (!data || !data.success || !data.result) {
loadTransactionList(self, settingsStore, exchangeRatesStore, {
transactions: emptyTransactionResult,
reload: true,
autoExpand: autoExpand,
defaultCurrency: defaultCurrency
});
if (!self.transactionListStateInvalid) {
self.updateTransactionListInvalidState(true);
}
reject({ message: 'Unable to get transaction list' });
return;
}
loadTransactionList(self, settingsStore, exchangeRatesStore, {
transactions: data.result,
reload: true,
autoExpand: autoExpand,
defaultCurrency: defaultCurrency
});
if (self.transactionListStateInvalid) {
self.updateTransactionListInvalidState(false);
}
resolve(data.result);
}).catch(error => {
logger.error('failed to load monthly all transaction list', error);
loadTransactionList(self, settingsStore, exchangeRatesStore, {
transactions: emptyTransactionResult,
reload: true,
autoExpand: autoExpand,
defaultCurrency: defaultCurrency
});
if (!self.transactionListStateInvalid) {
self.updateTransactionListInvalidState(true);
}
if (error.response && error.response.data && error.response.data.errorMessage) {
reject({ error: error.response.data });
} else if (!error.processed) {
reject({ message: 'Unable to get transaction list' });
} else {
reject(error);
}
});
});
},
getTransaction({ transactionId }) { getTransaction({ transactionId }) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
services.getTransaction({ services.getTransaction({
+160 -164
View File
@@ -79,20 +79,20 @@
<span v-else-if="this.query.minTime || this.query.maxTime">{{ `${queryMinTime} - ${queryMaxTime}` }}</span> <span v-else-if="this.query.minTime || this.query.maxTime">{{ `${queryMinTime} - ${queryMaxTime}` }}</span>
</span> </span>
<v-spacer/> <v-spacer/>
<div class="transaction-list-total-amount-text d-flex align-center" v-if="showTotalAmountInTransactionListPage && monthlyDataTotalAmount"> <div class="transaction-list-total-amount-text d-flex align-center" v-if="showTotalAmountInTransactionListPage && currentMonthTotalAmount">
<span class="ml-2 text-subtitle-1">{{ $t('Total Income') }}</span> <span class="ml-2 text-subtitle-1">{{ $t('Total Income') }}</span>
<span class="text-income ml-2" v-if="loading"> <span class="text-income ml-2" v-if="loading">
<v-skeleton-loader type="text" style="width: 60px" :loading="true"></v-skeleton-loader> <v-skeleton-loader type="text" style="width: 60px" :loading="true"></v-skeleton-loader>
</span> </span>
<span class="text-income ml-2" v-else-if="!loading"> <span class="text-income ml-2" v-else-if="!loading">
{{ monthlyDataTotalAmount.income }} {{ currentMonthTotalAmount.income }}
</span> </span>
<span class="text-subtitle-1 ml-3">{{ $t('Total Expense') }}</span> <span class="text-subtitle-1 ml-3">{{ $t('Total Expense') }}</span>
<span class="text-income ml-2" v-if="loading"> <span class="text-income ml-2" v-if="loading">
<v-skeleton-loader type="text" style="width: 60px" :loading="true"></v-skeleton-loader> <v-skeleton-loader type="text" style="width: 60px" :loading="true"></v-skeleton-loader>
</span> </span>
<span class="text-expense ml-2" v-else-if="!loading"> <span class="text-expense ml-2" v-else-if="!loading">
{{ monthlyDataTotalAmount.expense }} {{ currentMonthTotalAmount.expense }}
</span> </span>
</div> </div>
</div> </div>
@@ -234,7 +234,7 @@
</tr> </tr>
</thead> </thead>
<tbody v-if="loading"> <tbody v-if="loading && (!transactions || !transactions.length || transactions.length < 1)">
<tr :key="itemIdx" v-for="itemIdx in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]"> <tr :key="itemIdx" v-for="itemIdx in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]">
<td class="px-0" colspan="5"> <td class="px-0" colspan="5">
<v-skeleton-loader type="text" :loading="true"></v-skeleton-loader> <v-skeleton-loader type="text" :loading="true"></v-skeleton-loader>
@@ -242,79 +242,76 @@
</tr> </tr>
</tbody> </tbody>
<tbody v-if="!loading && noTransaction"> <tbody v-if="!loading && (!transactions || !transactions.length || transactions.length < 1)">
<tr> <tr>
<td colspan="5">{{ $t('No transaction data') }}</td> <td colspan="5">{{ $t('No transaction data') }}</td>
</tr> </tr>
</tbody> </tbody>
<template :key="transactionMonthList.yearMonth" <tbody :key="transaction.id"
v-for="(transactionMonthList, monthIdx) in transactions"> :class="{ 'disabled': loading, 'has-bottom-border': idx < transactions.length - 1 }"
<tbody :class="{ 'has-bottom-border': monthIdx < transactions.length - 1 }" v-if="shouldShowMonthlyData(transactionMonthList)"> v-for="(transaction, idx) in transactions">
<template :key="transaction.id" v-for="(transaction, idx) in transactionMonthList.items"> <tr class="transaction-list-row-date no-hover text-sm"
<template v-if="monthlyDatePageFirstIndex <= idx && idx < monthlyDatePageLastIndex"> v-if="idx === 0 || (idx > 0 && (transaction.day !== transactions[idx - 1].day))">
<tr class="transaction-list-row-date no-hover text-sm" <td colspan="5" class="font-weight-bold">
v-if="idx === 0 || monthlyDatePageFirstIndex === idx || (idx > 0 && (transaction.day !== transactionMonthList.items[idx - 1].day))"> <div class="d-flex align-center">
<td colspan="5" class="font-weight-bold"> <span>{{ getLongDate(transaction) }}</span>
<div class="d-flex align-center"> <v-chip class="ml-1" color="default" size="x-small">
<span>{{ getLongDate(transaction) }}</span> {{ getWeekdayLongName(transaction) }}
<v-chip class="ml-1" color="default" size="x-small"> </v-chip>
{{ getWeekdayLongName(transaction) }} </div>
</v-chip> </td>
</div> </tr>
</td> <tr class="transaction-table-row-data text-sm cursor-pointer"
</tr> @click="show(transaction)">
<tr class="transaction-table-row-data text-sm cursor-pointer" <td class="transaction-table-column-time">
@click="show(transaction)"> <div class="d-flex flex-column">
<td class="transaction-table-column-time"> <span>{{ getDisplayTime(transaction) }}</span>
<div class="d-flex flex-column"> <span class="text-caption" v-if="transaction.utcOffset !== currentTimezoneOffsetMinutes">{{ getDisplayTimezone(transaction) }}</span>
<span>{{ getDisplayTime(transaction) }}</span> </div>
<span class="text-caption" v-if="transaction.utcOffset !== currentTimezoneOffsetMinutes">{{ getDisplayTimezone(transaction) }}</span> </td>
</div> <td class="transaction-table-column-category">
</td> <div class="d-flex align-center">
<td class="transaction-table-column-category"> <ItemIcon size="24px" icon-type="category"
<div class="d-flex align-center"> :icon-id="transaction.category.icon"
<ItemIcon size="24px" icon-type="category" :color="transaction.category.color"
:icon-id="transaction.category.icon" v-if="transaction.category && transaction.category.color"></ItemIcon>
:color="transaction.category.color" <v-icon size="24" :icon="icons.modifyBalance" v-else-if="!transaction.category || !transaction.category.color" />
v-if="transaction.category && transaction.category.color"></ItemIcon> <span class="ml-2" v-if="transaction.type === allTransactionTypes.ModifyBalance">
<v-icon size="24" :icon="icons.modifyBalance" v-else-if="!transaction.category || !transaction.category.color" /> {{ $t('Modify Balance') }}
<span class="ml-2" v-if="transaction.type === allTransactionTypes.ModifyBalance"> </span>
{{ $t('Modify Balance') }} <span class="ml-2" v-else-if="transaction.type !== allTransactionTypes.ModifyBalance && transaction.category">
</span> {{ transaction.category.name }}
<span class="ml-2" v-else-if="transaction.type !== allTransactionTypes.ModifyBalance && transaction.category"> </span>
{{ transaction.category.name }} <span class="ml-2" v-else-if="transaction.type !== allTransactionTypes.ModifyBalance && !transaction.category">
</span> {{ getTransactionTypeName(transaction.type, 'Transaction') }}
<span class="ml-2" v-else-if="transaction.type !== allTransactionTypes.ModifyBalance && !transaction.category"> </span>
{{ getTransactionTypeName(transaction.type, 'Transaction') }} </div>
</span> </td>
</div> <td class="transaction-table-column-amount" :class="{ 'text-expense': transaction.type === allTransactionTypes.Expense, 'text-income': transaction.type === allTransactionTypes.Income }">
</td> <div v-if="transaction.sourceAccount">
<td class="transaction-table-column-amount" :class="{ 'text-expense': transaction.type === allTransactionTypes.Expense, 'text-income': transaction.type === allTransactionTypes.Income }"> <span v-if="!query.accountId || query.accountId === '0' || (transaction.sourceAccount && (transaction.sourceAccount.id === query.accountId || transaction.sourceAccount.parentId === query.accountId))">{{ getDisplayAmount(transaction.sourceAmount, transaction.sourceAccount.currency, transaction.hideAmount) }}</span>
<div v-if="transaction.sourceAccount"> <span v-else-if="query.accountId && query.accountId !== '0' && transaction.destinationAccount && (transaction.destinationAccount.id === query.accountId || transaction.destinationAccount.parentId === query.accountId)">{{ getDisplayAmount(transaction.destinationAmount, transaction.destinationAccount.currency, transaction.hideAmount) }}</span>
<span v-if="!query.accountId || query.accountId === '0' || (transaction.sourceAccount && (transaction.sourceAccount.id === query.accountId || transaction.sourceAccount.parentId === query.accountId))">{{ getDisplayAmount(transaction.sourceAmount, transaction.sourceAccount.currency, transaction.hideAmount) }}</span> <span v-else></span>
<span v-else-if="query.accountId && query.accountId !== '0' && transaction.destinationAccount && (transaction.destinationAccount.id === query.accountId || transaction.destinationAccount.parentId === query.accountId)">{{ getDisplayAmount(transaction.destinationAmount, transaction.destinationAccount.currency, transaction.hideAmount) }}</span> </div>
<span v-else></span> </td>
</div> <td class="transaction-table-column-account">
</td> <div class="d-flex align-center">
<td class="transaction-table-column-account"> <span v-if="transaction.sourceAccount">{{ transaction.sourceAccount.name }}</span>
<span v-if="transaction.sourceAccount">{{ transaction.sourceAccount.name }}</span> <v-icon class="mx-1" size="13" :icon="icons.arrowRight" v-if="transaction.sourceAccount && transaction.type === allTransactionTypes.Transfer && transaction.destinationAccount && transaction.sourceAccount.id !== transaction.destinationAccount.id"></v-icon>
<v-icon :icon="icons.arrowRight" v-if="transaction.sourceAccount && transaction.type === allTransactionTypes.Transfer && transaction.destinationAccount && transaction.sourceAccount.id !== transaction.destinationAccount.id"></v-icon> <span v-if="transaction.sourceAccount && transaction.type === allTransactionTypes.Transfer && transaction.destinationAccount && transaction.sourceAccount.id !== transaction.destinationAccount.id">{{ transaction.destinationAccount.name }}</span>
<span v-if="transaction.sourceAccount && transaction.type === allTransactionTypes.Transfer && transaction.destinationAccount && transaction.sourceAccount.id !== transaction.destinationAccount.id">{{ transaction.destinationAccount.name }}</span> </div>
</td> </td>
<td class="transaction-table-column-description text-truncate"> <td class="transaction-table-column-description text-truncate">
{{ transaction.comment }} {{ transaction.comment }}
</td> </td>
</tr> </tr>
</template> </tbody>
</template>
</tbody>
</template>
</v-table> </v-table>
<div class="mt-2 mb-4" v-if="isShowMonthlyData"> <div class="mt-2 mb-4">
<v-pagination :total-visible="5" :length="monthlyDatePageCount" <v-pagination :total-visible="6" :length="totalPageCount"
v-model="currentPage"></v-pagination> v-model="paginationCurrentPage"></v-pagination>
</div> </div>
</v-card> </v-card>
</v-window-item> </v-window-item>
@@ -324,7 +321,7 @@
</v-col> </v-col>
</v-row> </v-row>
<date-range-selection-dialog :title="$t('Custom Date Range')" :persistent="true" <date-range-selection-dialog :title="$t('Custom Date Range')"
:min-time="query.minTime" :min-time="query.minTime"
:max-time="query.maxTime" :max-time="query.maxTime"
v-model:show="showCustomDateRangeDialog" v-model:show="showCustomDateRangeDialog"
@@ -350,6 +347,8 @@ import { getNameByKeyValue } from '@/lib/common.js';
import { import {
getCurrentUnixTime, getCurrentUnixTime,
parseDateFromUnixTime, parseDateFromUnixTime,
getYear,
getMonth,
getUnixTime, getUnixTime,
getSpecifiedDayFirstUnixTime, getSpecifiedDayFirstUnixTime,
getUtcOffsetByUtcOffsetMinutes, getUtcOffsetByUtcOffsetMinutes,
@@ -357,7 +356,8 @@ import {
getBrowserTimezoneOffsetMinutes, getBrowserTimezoneOffsetMinutes,
getActualUnixTimeForStore, getActualUnixTimeForStore,
getDateRangeByDateType, getDateRangeByDateType,
getRecentDateRangeType getRecentDateRangeType,
isDateRangeMatchOneMonth
} from '@/lib/datetime.js'; } from '@/lib/datetime.js';
import { import {
categoryTypeToTransactionType, categoryTypeToTransactionType,
@@ -372,7 +372,7 @@ import {
mdiRefresh, mdiRefresh,
mdiMenuDown, mdiMenuDown,
mdiPencilBoxOutline, mdiPencilBoxOutline,
mdiArrowRightThin, mdiArrowRight,
mdiDeleteOutline, mdiDeleteOutline,
mdiDotsVertical mdiDotsVertical
} from '@mdi/js'; } from '@mdi/js';
@@ -394,6 +394,8 @@ export default {
currentPage: 1, currentPage: 1,
countPerPage: 15, countPerPage: 15,
searchKeyword: '', searchKeyword: '',
currentPageTransactions: [],
totalPageCount: 1,
showCustomDateRangeDialog: false, showCustomDateRangeDialog: false,
transactionRemoving: {}, transactionRemoving: {},
icons: { icons: {
@@ -403,7 +405,7 @@ export default {
refresh: mdiRefresh, refresh: mdiRefresh,
dropdownMenu: mdiMenuDown, dropdownMenu: mdiMenuDown,
modifyBalance: mdiPencilBoxOutline, modifyBalance: mdiPencilBoxOutline,
arrowRight: mdiArrowRightThin, arrowRight: mdiArrowRight,
remove: mdiDeleteOutline, remove: mdiDeleteOutline,
more: mdiDotsVertical more: mdiDotsVertical
} }
@@ -466,84 +468,72 @@ export default {
queryAccountName() { queryAccountName() {
return getNameByKeyValue(this.allAccounts, this.query.accountId, null, 'name', this.$t('Account')); return getNameByKeyValue(this.allAccounts, this.query.accountId, null, 'name', this.$t('Account'));
}, },
transactions() { queryMonthlyData() {
if (this.loading) { return isDateRangeMatchOneMonth(this.query.minTime, this.query.maxTime);
return [];
}
return this.transactionsStore.transactions;
}, },
noTransaction() { paginationCurrentPage: {
return this.transactionsStore.noTransaction; get: function () {
}, return this.currentPage;
hasMoreTransaction() { },
return this.transactionsStore.hasMoreTransaction; set: function (value) {
}, this.currentPage = value;
isShowMonthlyData() {
const recentDateRange = this.recentMonthDateRanges[this.recentDateRangeType];
return recentDateRange.year && recentDateRange.month;
},
monthlyDatePageCount() {
const recentDateRange = this.recentMonthDateRanges[this.recentDateRangeType];
if (!recentDateRange || !recentDateRange.year || !recentDateRange.month) { if (!this.queryMonthlyData) {
return 1; this.reload(false);
}
if (!this.transactions || !this.transactions.length) {
return 1;
}
for (let i = 0; i < this.transactions.length; i++) {
if (this.transactions[i].year === recentDateRange.year &&
this.transactions[i].month === recentDateRange.month) {
return Math.ceil(this.transactions[i].items.length / this.countPerPage);
} }
} }
return 1;
}, },
monthlyDatePageFirstIndex() { currentMonthTransactionData() {
const currentPage = this.currentPage >= 1 ? this.currentPage : 1; const allTransactions = this.transactionsStore.transactions;
if (this.isShowMonthlyData) { if (!allTransactions || !allTransactions.length) {
return (currentPage - 1) * this.countPerPage;
} else {
return 0;
}
},
monthlyDatePageLastIndex() {
const currentPage = this.currentPage >= 1 ? this.currentPage : 1;
if (this.isShowMonthlyData) {
return currentPage * this.countPerPage;
} else {
return Number.MAX_SAFE_INTEGER;
}
},
monthlyDataTotalAmount() {
const recentDateRange = this.recentMonthDateRanges[this.recentDateRangeType];
if (!recentDateRange || !recentDateRange.year || !recentDateRange.month) {
return null; return null;
} }
if (!this.transactions || !this.transactions.length) { const currentMonthMinDate = parseDateFromUnixTime(this.query.minTime);
return null; const currentYear = getYear(currentMonthMinDate);
} const currentMonth = getMonth(currentMonthMinDate);
for (let i = 0; i < this.transactions.length; i++) { for (let i = 0; i < allTransactions.length; i++) {
if (this.transactions[i].year === recentDateRange.year && if (allTransactions[i].year === currentYear && allTransactions[i].month === currentMonth) {
this.transactions[i].month === recentDateRange.month) { return allTransactions[i];
return {
income: this.getDisplayMonthTotalAmount(this.transactions[i].totalAmount.income, this.defaultCurrency, '', this.transactions[i].totalAmount.incompleteIncome),
expense: this.getDisplayMonthTotalAmount(this.transactions[i].totalAmount.expense, this.defaultCurrency, '', this.transactions[i].totalAmount.incompleteExpense)
};
} }
} }
return null; return null;
}, },
transactions() {
if (this.queryMonthlyData) {
const transactionData = this.currentMonthTransactionData;
if (!transactionData || !transactionData.items) {
return [];
}
const firstIndex = (this.currentPage - 1) * this.countPerPage;
const lastIndex = this.currentPage * this.countPerPage;
return transactionData.items.slice(firstIndex, lastIndex);
} else {
return this.currentPageTransactions;
}
},
currentMonthTotalAmount() {
if (this.queryMonthlyData) {
const transactionData = this.currentMonthTransactionData;
if (!transactionData) {
return null;
}
return {
income: this.getDisplayMonthTotalAmount(transactionData.totalAmount.income, this.defaultCurrency, '', transactionData.totalAmount.incompleteIncome),
expense: this.getDisplayMonthTotalAmount(transactionData.totalAmount.expense, this.defaultCurrency, '', transactionData.totalAmount.incompleteExpense)
};
} else {
return null;
}
},
allTransactionTypes() { allTransactionTypes() {
return transactionConstants.allTransactionTypes; return transactionConstants.allTransactionTypes;
}, },
@@ -623,6 +613,7 @@ export default {
keyword: this.searchKeyword keyword: this.searchKeyword
}); });
this.currentPage = 1;
this.reload(false); this.reload(false);
}, },
reload(force) { reload(force) {
@@ -630,37 +621,50 @@ export default {
self.loading = true; self.loading = true;
const page = self.currentPage;
Promise.all([ Promise.all([
self.accountsStore.loadAllAccounts({ force: false }), self.accountsStore.loadAllAccounts({ force: false }),
self.transactionCategoriesStore.loadAllCategories({ force: false }) self.transactionCategoriesStore.loadAllCategories({ force: false })
]).then(() => { ]).then(() => {
const recentDateRange = this.recentMonthDateRanges[this.recentDateRangeType]; if (this.queryMonthlyData) {
let yearMonth = null; const currentMonthMinDate = parseDateFromUnixTime(this.query.minTime);
const currentYear = getYear(currentMonthMinDate);
const currentMonth = getMonth(currentMonthMinDate);
if (recentDateRange.year && recentDateRange.month) { return self.transactionsStore.loadMonthlyAllTransactions({
yearMonth = { year: currentYear,
year: recentDateRange.year, month: currentMonth,
month: recentDateRange.month force: force,
}; autoExpand: true,
defaultCurrency: self.defaultCurrency
});
} else {
return self.transactionsStore.loadTransactions({
reload: true,
force: force,
count: self.countPerPage,
page: page,
withCount: page <= 1,
autoExpand: true,
defaultCurrency: self.defaultCurrency
});
} }
}).then(data => {
return self.transactionsStore.loadTransactions({
reload: true,
yearMonth: yearMonth,
force: force,
autoExpand: true,
defaultCurrency: self.defaultCurrency
});
}).then(() => {
self.loading = false; self.loading = false;
self.currentPage = 1; self.currentPageTransactions = data && data.items && data.items.length ? data.items : [];
if (page <= 1) {
self.totalPageCount = data && data.totalCount ? Math.ceil(data.totalCount / this.countPerPage) : 1;
}
if (force) { if (force) {
self.$refs.snackbar.showMessage('Data has been updated'); self.$refs.snackbar.showMessage('Data has been updated');
} }
}).catch(error => { }).catch(error => {
self.loading = false; self.loading = false;
self.currentPage = 1; self.currentPageTransactions = [];
self.totalPageCount = 1;
if (!error.processed) { if (!error.processed) {
self.$refs.snackbar.showError(error); self.$refs.snackbar.showError(error);
@@ -756,6 +760,7 @@ export default {
keyword: keyword keyword: keyword
}); });
this.currentPage = 1;
this.reload(false); this.reload(false);
}, },
add() { add() {
@@ -793,15 +798,6 @@ export default {
}); });
}); });
}, },
shouldShowMonthlyData(transactionMonthList) {
const recentDateRange = this.recentMonthDateRanges[this.recentDateRangeType];
if (!recentDateRange || !recentDateRange.year || !recentDateRange.month) {
return true;
}
return transactionMonthList.year === recentDateRange.year && transactionMonthList.month === recentDateRange.month;
},
scrollCategoryMenuToSelectedItem(opened) { scrollCategoryMenuToSelectedItem(opened) {
if (opened) { if (opened) {
this.scrollMenuToSelectedItem(this.$refs.categoryFilterMenu); this.scrollMenuToSelectedItem(this.$refs.categoryFilterMenu);