From f2d0fe407b630c4702a442e41a70b55a49cfc74e Mon Sep 17 00:00:00 2001 From: MaysWind Date: Thu, 21 Aug 2025 00:01:25 +0800 Subject: [PATCH] support deleting all transactions (#202) --- cmd/webserver.go | 3 +- pkg/api/data_managements.go | 62 +++++++++-- pkg/services/transactions.go | 10 +- src/lib/services.ts | 7 +- src/locales/de.json | 6 ++ src/locales/en.json | 6 ++ src/locales/es.json | 6 ++ src/locales/it.json | 6 ++ src/locales/ja.json | 6 ++ src/locales/nl.json | 6 ++ src/locales/pt_BR.json | 6 ++ src/locales/ru.json | 6 ++ src/locales/uk.json | 6 ++ src/locales/vi.json | 6 ++ src/locales/zh_Hans.json | 6 ++ src/locales/zh_Hant.json | 6 ++ src/stores/index.ts | 46 +++++++- .../tabs/UserDataManagementSettingTab.vue | 100 ++++++++++++------ src/views/mobile/users/DataManagementPage.vue | 62 +++++++++-- 19 files changed, 301 insertions(+), 61 deletions(-) diff --git a/cmd/webserver.go b/cmd/webserver.go index d0208d23..424c77da 100644 --- a/cmd/webserver.go +++ b/cmd/webserver.go @@ -323,7 +323,8 @@ func startWebServer(c *core.CliContext) error { // Data apiV1Route.GET("/data/statistics.json", bindApi(api.DataManagements.DataStatisticsHandler)) - apiV1Route.POST("/data/clear.json", bindApi(api.DataManagements.ClearDataHandler)) + apiV1Route.POST("/data/clear/all.json", bindApi(api.DataManagements.ClearAllDataHandler)) + apiV1Route.POST("/data/clear/transactions.json", bindApi(api.DataManagements.ClearAllTransactionsHandler)) if config.EnableDataExport { apiV1Route.GET("/data/export.csv", bindCsv(api.DataManagements.ExportDataToEzbookkeepingCSVHandler)) diff --git a/pkg/api/data_managements.go b/pkg/api/data_managements.go index f15b193e..e14aca94 100644 --- a/pkg/api/data_managements.go +++ b/pkg/api/data_managements.go @@ -124,13 +124,13 @@ func (a *DataManagementsApi) DataStatisticsHandler(c *core.WebContext) (any, *er return dataStatisticsResp, nil } -// ClearDataHandler deletes all user data -func (a *DataManagementsApi) ClearDataHandler(c *core.WebContext) (any, *errs.Error) { +// ClearAllDataHandler deletes all user data +func (a *DataManagementsApi) ClearAllDataHandler(c *core.WebContext) (any, *errs.Error) { var clearDataReq models.ClearDataRequest err := c.ShouldBindJSON(&clearDataReq) if err != nil { - log.Warnf(c, "[data_managements.ClearDataHandler] parse request failed, because %s", err.Error()) + log.Warnf(c, "[data_managements.ClearAllDataHandler] parse request failed, because %s", err.Error()) return nil, errs.NewIncompleteOrIncorrectSubmissionError(err) } @@ -139,7 +139,7 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.WebContext) (any, *errs.Er if err != nil { if !errs.IsCustomError(err) { - log.Warnf(c, "[data_managements.ClearDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error()) + log.Warnf(c, "[data_managements.ClearAllDataHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error()) } return nil, errs.ErrUserNotFound @@ -156,39 +156,79 @@ func (a *DataManagementsApi) ClearDataHandler(c *core.WebContext) (any, *errs.Er err = a.templates.DeleteAllTemplates(c, uid) if err != nil { - log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction templates, because %s", err.Error()) + log.Errorf(c, "[data_managements.ClearAllDataHandler] failed to delete all transaction templates, because %s", err.Error()) return nil, errs.Or(err, errs.ErrOperationFailed) } - err = a.transactions.DeleteAllTransactions(c, uid) + err = a.transactions.DeleteAllTransactions(c, uid, true) if err != nil { - log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transactions, because %s", err.Error()) + log.Errorf(c, "[data_managements.ClearAllDataHandler] failed to delete all transactions, because %s", err.Error()) return nil, errs.Or(err, errs.ErrOperationFailed) } err = a.categories.DeleteAllCategories(c, uid) if err != nil { - log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction categories, because %s", err.Error()) + log.Errorf(c, "[data_managements.ClearAllDataHandler] failed to delete all transaction categories, because %s", err.Error()) return nil, errs.Or(err, errs.ErrOperationFailed) } err = a.tags.DeleteAllTags(c, uid) if err != nil { - log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all transaction tags, because %s", err.Error()) + log.Errorf(c, "[data_managements.ClearAllDataHandler] failed to delete all transaction tags, because %s", err.Error()) return nil, errs.Or(err, errs.ErrOperationFailed) } err = a.userCustomExchangeRates.DeleteAllCustomExchangeRates(c, uid) if err != nil { - log.Errorf(c, "[data_managements.ClearDataHandler] failed to delete all user custom exchange rates, because %s", err.Error()) + log.Errorf(c, "[data_managements.ClearAllDataHandler] failed to delete all user custom exchange rates, because %s", err.Error()) return nil, errs.Or(err, errs.ErrOperationFailed) } - log.Infof(c, "[data_managements.ClearDataHandler] user \"uid:%d\" has cleared all data", uid) + log.Infof(c, "[data_managements.ClearAllDataHandler] user \"uid:%d\" has cleared all data", uid) + return true, nil +} + +// ClearAllTransactionsHandler deletes all transactions +func (a *DataManagementsApi) ClearAllTransactionsHandler(c *core.WebContext) (any, *errs.Error) { + var clearDataReq models.ClearDataRequest + err := c.ShouldBindJSON(&clearDataReq) + + if err != nil { + log.Warnf(c, "[data_managements.ClearAllTransactionsHandler] parse request failed, because %s", err.Error()) + return nil, errs.NewIncompleteOrIncorrectSubmissionError(err) + } + + uid := c.GetCurrentUid() + user, err := a.users.GetUserById(c, uid) + + if err != nil { + if !errs.IsCustomError(err) { + log.Warnf(c, "[data_managements.ClearAllTransactionsHandler] failed to get user for user \"uid:%d\", because %s", uid, err.Error()) + } + + return nil, errs.ErrUserNotFound + } + + if !a.users.IsPasswordEqualsUserPassword(clearDataReq.Password, user) { + return nil, errs.ErrUserPasswordWrong + } + + if user.FeatureRestriction.Contains(core.USER_FEATURE_RESTRICTION_TYPE_CLEAR_ALL_DATA) { + return nil, errs.ErrNotPermittedToPerformThisAction + } + + err = a.transactions.DeleteAllTransactions(c, uid, false) + + if err != nil { + log.Errorf(c, "[data_managements.ClearAllTransactionsHandler] failed to delete all transactions, because %s", err.Error()) + return nil, errs.Or(err, errs.ErrOperationFailed) + } + + log.Infof(c, "[data_managements.ClearAllTransactionsHandler] user \"uid:%d\" has cleared all transactions", uid) return true, nil } diff --git a/pkg/services/transactions.go b/pkg/services/transactions.go index 032cdea7..c2d14dc9 100644 --- a/pkg/services/transactions.go +++ b/pkg/services/transactions.go @@ -1320,7 +1320,7 @@ func (s *TransactionService) DeleteTransaction(c core.Context, uid int64, transa } // DeleteAllTransactions deletes all existed transactions from database -func (s *TransactionService) DeleteAllTransactions(c core.Context, uid int64) error { +func (s *TransactionService) DeleteAllTransactions(c core.Context, uid int64, deleteAccount bool) error { if uid <= 0 { return errs.ErrUserIdInvalid } @@ -1344,12 +1344,12 @@ func (s *TransactionService) DeleteAllTransactions(c core.Context, uid int64) er accountUpdateModel := &models.Account{ Balance: 0, - Deleted: true, + Deleted: deleteAccount, DeletedUnixTime: now, } return s.UserDataDB(uid).DoTransaction(c, func(sess *xorm.Session) error { - // Update all transaction to deleted + // Update all transactions to deleted _, err := sess.Cols("deleted", "deleted_unix_time").Where("uid=? AND deleted=?", uid, false).Update(updateModel) if err != nil { @@ -1363,14 +1363,14 @@ func (s *TransactionService) DeleteAllTransactions(c core.Context, uid int64) er return err } - // Update all transaction picture to deleted + // Update all transaction pictures to deleted _, err = sess.Cols("deleted", "deleted_unix_time").Where("uid=? AND deleted=?", uid, false).Update(pictureUpdateModel) if err != nil { return err } - // Update all account table to deleted + // Update all accounts to deleted or set amount to zero _, err = sess.Cols("balance", "deleted", "deleted_unix_time").Where("uid=? AND deleted=?", uid, false).Update(accountUpdateModel) if err != nil { diff --git a/src/lib/services.ts b/src/lib/services.ts index 3b426a1e..a0c941a1 100644 --- a/src/lib/services.ts +++ b/src/lib/services.ts @@ -378,8 +378,11 @@ export default { return Promise.reject('Parameter Invalid'); } }, - clearData: (req: ClearDataRequest): ApiResponsePromise => { - return axios.post>('v1/data/clear.json', req); + clearAllData: (req: ClearDataRequest): ApiResponsePromise => { + return axios.post>('v1/data/clear/all.json', req); + }, + clearAllTransactions: (req: ClearDataRequest): ApiResponsePromise => { + return axios.post>('v1/data/clear/transactions.json', req); }, getAllAccounts: ({ visibleOnly }: { visibleOnly: boolean }): ApiResponsePromise => { return axios.get>('v1/accounts/list.json?visible_only=' + visibleOnly); diff --git a/src/locales/de.json b/src/locales/de.json index bf6616c0..70c84f55 100644 --- a/src/locales/de.json +++ b/src/locales/de.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Benutzerdaten löschen", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Alle Transaktionsdaten in Datei exportieren.", "Are you sure you want to export all transaction data to file?": "Sind Sie sicher, dass Sie alle Transaktionsdaten in eine Datei exportieren möchten?", "It may take a long time, please wait for a few minutes.": "Es kann lange dauern, bitte warten Sie ein paar Minuten.", "Unable to retrieve exported user data": "Exportierte Benutzerdaten können nicht abgerufen werden", "Save Data": "Daten speichern", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Sind Sie sicher, dass Sie alle Daten löschen möchten?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Diese Aktion kann NICHT rückgängig gemacht werden. Dies wird Ihre Konten, Kategorien, Tags und Transaktionsdaten löschen. Bitte geben Sie Ihr aktuelles Passwort ein, um zu bestätigen.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Alle Benutzerdaten wurden gelöscht", "Unable to clear user data": "Benutzerdaten können nicht gelöscht werden", "Device & Sessions": "Geräte & Sitzungen", diff --git a/src/locales/en.json b/src/locales/en.json index 210f19d2..28fddc89 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Clear User Data", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Export all transaction data to file.", "Are you sure you want to export all transaction data to file?": "Are you sure you want to export all transaction data to file?", "It may take a long time, please wait for a few minutes.": "It may take a long time, please wait for a few minutes.", "Unable to retrieve exported user data": "Unable to retrieve exported user data", "Save Data": "Save Data", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Are you sure you want to clear all data?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "All user data has been cleared", "Unable to clear user data": "Unable to clear user data", "Device & Sessions": "Device & Sessions", diff --git a/src/locales/es.json b/src/locales/es.json index e41ec312..5f9d8332 100644 --- a/src/locales/es.json +++ b/src/locales/es.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Borrar datos de usuario", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Exportar todos los datos de la transacción a un archivo.", "Are you sure you want to export all transaction data to file?": "¿Está seguro de que desea exportar todos los datos de la transacción al archivo?", "It may take a long time, please wait for a few minutes.": "Puede que tarde mucho tiempo, espere unos minutos.", "Unable to retrieve exported user data": "No se pueden recuperar los datos de usuario exportados", "Save Data": "Guardar datos", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "¿Está seguro de que desea borrar todos los datos?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "NO PUEDE deshacer esta acción. Esto borrará sus cuentas, categorías, etiquetas y datos de transacciones. Por favor ingrese su contraseña actual para confirmar.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Todos los datos del usuario han sido borrados.", "Unable to clear user data": "No se pueden borrar los datos del usuario", "Device & Sessions": "Dispositivo y sesiones", diff --git a/src/locales/it.json b/src/locales/it.json index 015c9197..b8e5a97b 100644 --- a/src/locales/it.json +++ b/src/locales/it.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Cancella dati utente", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Esporta tutti i dati delle transazioni in un file.", "Are you sure you want to export all transaction data to file?": "Sei sicuro di voler esportare tutti i dati delle transazioni in un file?", "It may take a long time, please wait for a few minutes.": "Potrebbe richiedere molto tempo, attendi qualche minuto.", "Unable to retrieve exported user data": "Impossibile recuperare i dati utente esportati", "Save Data": "Salva dati", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Sei sicuro di voler cancellare tutti i dati?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "NON PUOI annullare questa azione. Questo cancellerà i tuoi account, categorie, tag e dati delle transazioni. Inserisci la tua password attuale per confermare.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Tutti i dati utente sono stati cancellati", "Unable to clear user data": "Impossibile cancellare i dati utente", "Device & Sessions": "Dispositivo e sessioni", diff --git a/src/locales/ja.json b/src/locales/ja.json index e78c2283..92096cb1 100644 --- a/src/locales/ja.json +++ b/src/locales/ja.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "ユーザーデータをクリア", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "すべての取引データをファイルにエクスポートします。", "Are you sure you want to export all transaction data to file?": "取引データをファイルにエクスポートしますか?", "It may take a long time, please wait for a few minutes.": "時間がかかる場合がありますので数分お待ちください。", "Unable to retrieve exported user data": "エクスポートされたユーザーデータを取得できません", "Save Data": "データの保存", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "データをすべてクリアしますか?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "このアクションを元に戻すことはできません。これにより、口座、カテゴリ、タグ、および取引データがクリアされます。確認のため現在のパスワードを入力してください。", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "ユーザーデータがすべてクリアされました", "Unable to clear user data": "ユーザーデータをクリアできません", "Device & Sessions": "デバイスとセッション", diff --git a/src/locales/nl.json b/src/locales/nl.json index f8f955bf..8fd48523 100644 --- a/src/locales/nl.json +++ b/src/locales/nl.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Exporteren naar TSV-bestand (tab-gescheiden waarden)", "Markdown File": "Markdown-bestand", "Clear User Data": "Gebruikersgegevens wissen", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Alle transactiegegevens naar een bestand exporteren.", "Are you sure you want to export all transaction data to file?": "Weet je zeker dat je alle transactiegegevens wilt exporteren?", "It may take a long time, please wait for a few minutes.": "Dit kan lang duren; een paar minuten geduld alstublieft.", "Unable to retrieve exported user data": "Kan geëxporteerde gebruikersgegevens niet ophalen", "Save Data": "Gegevens opslaan", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Weet je zeker dat je alle gegevens wilt wissen?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Dit kan NIET ongedaan worden gemaakt. Je rekeningen, categorieën, tags en transacties worden gewist. Voer je huidige wachtwoord in ter bevestiging.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Alle gebruikersgegevens zijn gewist", "Unable to clear user data": "Kan gebruikersgegevens niet wissen", "Device & Sessions": "Apparaten & Sessies", diff --git a/src/locales/pt_BR.json b/src/locales/pt_BR.json index 5d7cd564..f0279a1f 100644 --- a/src/locales/pt_BR.json +++ b/src/locales/pt_BR.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Arquivo Markdown", "Clear User Data": "Limpar Dados do Usuário", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Exportar todos os dados de transação para arquivo.", "Are you sure you want to export all transaction data to file?": "Você tem certeza de que deseja exportar todos os dados de transação para arquivo?", "It may take a long time, please wait for a few minutes.": "Pode levar algum tempo, por favor, aguarde alguns minutos.", "Unable to retrieve exported user data": "Não foi possível recuperar os dados de usuário exportados", "Save Data": "Salvar Dados", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Você tem certeza de que deseja limpar todos os dados?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Você NÃO PODE desfazer esta ação. Isto apagará seus dados de contas, categorias, tags e transações. Por favor, insira sua senha atual para confirmar.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Todos os dados de usuário foram apagados", "Unable to clear user data": "Não foi possível limpar os dados de usuário", "Device & Sessions": "Dispositivo e Sessões", diff --git a/src/locales/ru.json b/src/locales/ru.json index 19df334b..0e286f37 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Очистить данные пользователя", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Экспортировать все данные о транзакциях в файл.", "Are you sure you want to export all transaction data to file?": "Вы уверены, что хотите экспортировать все данные о транзакциях в файл?", "It may take a long time, please wait for a few minutes.": "Это может занять много времени, пожалуйста, подождите несколько минут.", "Unable to retrieve exported user data": "Не удалось получить экспортированные данные пользователя", "Save Data": "Сохранить данные", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Вы уверены, что хотите очистить все данные?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Вы НЕ сможете отменить это действие. Это очистит данные ваших счетов, категорий, тегов и транзакций. Пожалуйста, введите текущий пароль для подтверждения.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Все данные пользователя были очищены", "Unable to clear user data": "Не удалось очистить данные пользователя", "Device & Sessions": "Устройства и сессии", diff --git a/src/locales/uk.json b/src/locales/uk.json index a6b0e505..ec292087 100644 --- a/src/locales/uk.json +++ b/src/locales/uk.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Очистити дані користувача", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Експортувати всі транзакції у файл.", "Are you sure you want to export all transaction data to file?": "Ви впевнені, що хочете експортувати всі транзакції?", "It may take a long time, please wait for a few minutes.": "Це може зайняти певний час, зачекайте кілька хвилин.", "Unable to retrieve exported user data": "Не вдалося отримати експортовані дані користувача", "Save Data": "Зберегти дані", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Ви впевнені, що хочете очистити всі дані?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Цю дію не можна скасувати. Будуть видалені рахунки, категорії, теги та транзакції. Введіть поточний пароль для підтвердження.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Усі дані користувача очищено", "Unable to clear user data": "Не вдалося очистити дані", "Device & Sessions": "Пристрої та сесії", diff --git a/src/locales/vi.json b/src/locales/vi.json index 5fbd85c8..286856f4 100644 --- a/src/locales/vi.json +++ b/src/locales/vi.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "Export to TSV (Tab-separated values) File", "Markdown File": "Markdown File", "Clear User Data": "Xóa dữ liệu người dùng", + "Clear All Transactions": "Clear All Transactions", + "Clear All Data": "Clear All Data", "Export all transaction data to file.": "Xuất tất cả dữ liệu giao dịch sang tệp.", "Are you sure you want to export all transaction data to file?": "Bạn có chắc chắn muốn xuất tất cả dữ liệu giao dịch sang tệp không?", "It may take a long time, please wait for a few minutes.": "Có thể mất nhiều thời gian, vui lòng đợi vài phút.", "Unable to retrieve exported user data": "Không thể lấy dữ liệu người dùng đã xuất", "Save Data": "Lưu dữ liệu", + "Are you sure you want to clear all transactions?": "Are you sure you want to clear all transactions?", "Are you sure you want to clear all data?": "Bạn có chắc chắn muốn xóa tất cả dữ liệu không?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "Bạn KHÔNG THỂ hoàn tác hành động này. Thao tác này sẽ xóa dữ liệu tài khoản, danh mục, thẻ và giao dịch của bạn. Vui lòng nhập mật khẩu hiện tại của bạn để xác nhận.", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.", + "All transactions has been cleared": "All transactions has been cleared", "All user data has been cleared": "Tất cả dữ liệu người dùng đã bị xóa", "Unable to clear user data": "Không thể xóa dữ liệu người dùng", "Device & Sessions": "Thiết bị & Phiên", diff --git a/src/locales/zh_Hans.json b/src/locales/zh_Hans.json index df6fa0f2..29da90d2 100644 --- a/src/locales/zh_Hans.json +++ b/src/locales/zh_Hans.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "导出到 TSV (制表符分隔的值) 文件", "Markdown File": "Markdown 文件", "Clear User Data": "清除用户数据", + "Clear All Transactions": "清除所有交易", + "Clear All Data": "清除所有数据", "Export all transaction data to file.": "导出所有交易数据到文件。", "Are you sure you want to export all transaction data to file?": "您确定要导出所有交易数据到文件?", "It may take a long time, please wait for a few minutes.": "这可能花费一些时间,请稍等几分钟。", "Unable to retrieve exported user data": "无法获取导出的用户数据", "Save Data": "保存数据", + "Are you sure you want to clear all transactions?": "您确定要清除所有交易?", "Are you sure you want to clear all data?": "您确定要清除所有数据?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "您不能撤销该操作。该操作将会清除您的交易数据。请输入您当前的密码以确认。", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "您不能撤销该操作。该操作将会清除您的账户、分类、标签以及交易数据。请输入您当前的密码以确认。", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "您不能撤销该操作。\"清除所有交易\" 将会清除您的所有交易数据,以及 \"清除所有数据\" 将会清除您的账户、分类、标签以及交易数据。请输入您当前的密码以确认。", + "All transactions has been cleared": "所有交易已经清空", "All user data has been cleared": "用户所有数据已经清空", "Unable to clear user data": "无法清除用户数据", "Device & Sessions": "设备和会话", diff --git a/src/locales/zh_Hant.json b/src/locales/zh_Hant.json index e6946e5a..c0be5009 100644 --- a/src/locales/zh_Hant.json +++ b/src/locales/zh_Hant.json @@ -2005,13 +2005,19 @@ "Export to TSV (Tab-separated values) File": "匯出為 TSV (定位點分隔的值) 檔案", "Markdown File": "Markdown 檔案", "Clear User Data": "清除使用者資料", + "Clear All Transactions": "清除所有交易", + "Clear All Data": "清除所有資料", "Export all transaction data to file.": "匯出所有交易資料到檔案。", "Are you sure you want to export all transaction data to file?": "您確定要匯出所有交易資料到檔案?", "It may take a long time, please wait for a few minutes.": "這可能需要一些時間,請稍等幾分鐘。", "Unable to retrieve exported user data": "無法取得匯出的使用者資料", "Save Data": "儲存資料", + "Are you sure you want to clear all transactions?": "您確定要清除所有交易?", "Are you sure you want to clear all data?": "您確定要清除所有資料?", + "You CANNOT undo this action. This will clear your transactions data. Please enter your current password to confirm.": "您不能還原此操作。此操作將會清除您的交易資料。請輸入您目前的密碼以確認。", "You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "您不能還原此操作。此操作將會清除您的帳戶、分類、標籤以及交易資料。請輸入您目前的密碼以確認。", + "You CANNOT undo this action. \"Clear All Transactions\" will clear all your transactions data, and \"Clear All Data\" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.": "您不能還原此操作。\"清除所有交易\" 將會清除您的所有交易資料,以及 \"清除所有資料\" 將會清除您的帳戶、分類、標籤以及交易資料。請輸入您目前的密碼以確認。", + "All transactions has been cleared": "所有交易已經清空", "All user data has been cleared": "使用者所有資料已經清空", "Unable to clear user data": "無法清除使用者資料", "Device & Sessions": "裝置和會話", diff --git a/src/stores/index.ts b/src/stores/index.ts index 2d471f3d..7cf5e9d1 100644 --- a/src/stores/index.ts +++ b/src/stores/index.ts @@ -457,9 +457,48 @@ export const useRootStore = defineStore('root', () => { }); } - function clearUserData({ password }: { password: string }): Promise { + function clearAllUserTransactions({ password }: { password: string }): Promise { return new Promise((resolve, reject) => { - services.clearData({ + services.clearAllTransactions({ + password: password + }).then(response => { + const data = response.data; + + if (!data || !data.success || !data.result) { + reject({ message: 'Unable to clear user data' }); + return; + } + + if (!accountsStore.accountListStateInvalid) { + accountsStore.updateAccountListInvalidState(true); + } + + if (!overviewStore.transactionOverviewStateInvalid) { + overviewStore.updateTransactionOverviewInvalidState(true); + } + + if (!statisticsStore.transactionStatisticsStateInvalid) { + statisticsStore.updateTransactionStatisticsInvalidState(true); + } + + resolve(data.result); + }).catch(error => { + logger.error('failed to clear user data', error); + + if (error && error.processed) { + reject(error); + } else if (error.response && error.response.data && error.response.data.errorMessage) { + reject({ error: error.response.data }); + } else { + reject({ message: 'Unable to clear user data' }); + } + }); + }); + } + + function clearAllUserData({ password }: { password: string }): Promise { + return new Promise((resolve, reject) => { + services.clearAllData({ password: password }).then(response => { const data = response.data; @@ -521,6 +560,7 @@ export const useRootStore = defineStore('root', () => { resetPassword, updateUserProfile, resendVerifyEmailByLoginedUser, - clearUserData + clearAllUserData, + clearAllUserTransactions }; }); diff --git a/src/views/desktop/user/settings/tabs/UserDataManagementSettingTab.vue b/src/views/desktop/user/settings/tabs/UserDataManagementSettingTab.vue index f2de00c0..0fa822f0 100644 --- a/src/views/desktop/user/settings/tabs/UserDataManagementSettingTab.vue +++ b/src/views/desktop/user/settings/tabs/UserDataManagementSettingTab.vue @@ -114,39 +114,46 @@ {{ tt('Danger Zone') }} - - + - - {{ tt('You CANNOT undo this action. This will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.') }} + + {{ tt('You CANNOT undo this action. "Clear All Transactions" will clear all your transactions data, and "Clear All Data" will clear your accounts, categories, tags and transactions data. Please enter your current password to confirm.') }} - + - - - - - - - + + + + + + + - - - {{ tt('Clear User Data') }} - - - - + + + {{ tt('Clear User Data') }} + + + + + {{ tt('Clear All Transactions') }} + + + {{ tt('Clear All Data') }} + + + + + @@ -242,7 +249,38 @@ function exportData(fileType: string): void { }); } -function clearData(): void { +function clearAllTransactions(): void { + if (!currentPasswordForClearData.value) { + snackbar.value?.showMessage('Current password cannot be blank'); + return; + } + + if (clearingData.value) { + return; + } + + confirmDialog.value?.open('Are you sure you want to clear all transactions?', { color: 'error' }).then(() => { + clearingData.value = true; + + rootStore.clearAllUserTransactions({ + password: currentPasswordForClearData.value + }).then(() => { + clearingData.value = false; + currentPasswordForClearData.value = ''; + + snackbar.value?.showMessage('All transactions has been cleared'); + reloadUserDataStatistics(false); + }).catch(error => { + clearingData.value = false; + + if (!error.processed) { + snackbar.value?.showError(error); + } + }); + }); +} + +function clearAllData(): void { if (!currentPasswordForClearData.value) { snackbar.value?.showMessage('Current password cannot be blank'); return; @@ -255,7 +293,7 @@ function clearData(): void { confirmDialog.value?.open('Are you sure you want to clear all data?', { color: 'error' }).then(() => { clearingData.value = true; - rootStore.clearUserData({ + rootStore.clearAllUserData({ password: currentPasswordForClearData.value }).then(() => { clearingData.value = false; diff --git a/src/views/mobile/users/DataManagementPage.vue b/src/views/mobile/users/DataManagementPage.vue index 0f430ebb..84ecc9ee 100644 --- a/src/views/mobile/users/DataManagementPage.vue +++ b/src/views/mobile/users/DataManagementPage.vue @@ -26,7 +26,11 @@ {{ tt('Export Data') }} - {{ tt('Clear User Data') }} + + + + {{ tt('Clear All Transactions') }} + {{ tt('Clear All Data') }} + + + + @password:confirm="clearAllData"> @@ -105,7 +119,8 @@ const exportedData = ref(null); const currentPasswordForClearData = ref(''); const clearingData = ref(false); const showExportDataSheet = ref(false); -const showInputPasswordSheetForClearData = ref(false); +const showInputPasswordSheetForClearAllTransactions = ref(false); +const showInputPasswordSheetForClearAllData = ref(false); const exportFileName = computed(() => getExportFileName(exportFileType.value)); @@ -144,24 +159,55 @@ function exportData(): void { }); } -function clearData(password: string | null): void { +function clearAllTransactions(password: string | null): void { if (!password) { currentPasswordForClearData.value = ''; - showInputPasswordSheetForClearData.value = true; + showInputPasswordSheetForClearAllTransactions.value = true; return; } clearingData.value = true; showLoading(() => clearingData.value); - rootStore.clearUserData({ + rootStore.clearAllUserTransactions({ password: password }).then(() => { clearingData.value = false; currentPasswordForClearData.value = ''; hideLoading(); - showInputPasswordSheetForClearData.value = false; + showInputPasswordSheetForClearAllTransactions.value = false; + showToast('All transactions has been cleared'); + + reloadUserDataStatistics(); + }).catch(error => { + clearingData.value = false; + hideLoading(); + + if (!error.processed) { + showToast(error.message || error); + } + }); +} + +function clearAllData(password: string | null): void { + if (!password) { + currentPasswordForClearData.value = ''; + showInputPasswordSheetForClearAllData.value = true; + return; + } + + clearingData.value = true; + showLoading(() => clearingData.value); + + rootStore.clearAllUserData({ + password: password + }).then(() => { + clearingData.value = false; + currentPasswordForClearData.value = ''; + hideLoading(); + + showInputPasswordSheetForClearAllData.value = false; showToast('All user data has been cleared'); reloadUserDataStatistics();