migrate account edit page to composition API and typescript

This commit is contained in:
MaysWind
2025-01-24 00:42:37 +08:00
parent eca0574e41
commit 8fce3f2bcc
4 changed files with 666 additions and 704 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ const props = defineProps<{
class?: string;
color?: string;
density?: string;
currency: string;
currency?: string;
showCurrency?: boolean;
label?: string;
placeholder?: string;
@@ -0,0 +1,182 @@
import { ref, computed, watch } from 'vue';
import { useI18n } from '@/locales/helpers.ts';
import { useAccountsStore } from '@/stores/account.ts';
import type { TypeAndDisplayName } from '@/core/base.ts';
import { AccountCategory, AccountType } from '@/core/account.ts';
import type { LocalizedCurrencyInfo } from '@/core/currency.ts';
import type { LocalizedAccountCategory } from '@/core/account.ts';
import type { Account } from '@/models/account.ts';
import { setAccountSuitableIcon } from '@/lib/account.ts';
export interface DayAndDisplayName {
readonly day: number;
readonly displayName: string;
}
export function useAccountEditPageBaseBase() {
const { tt, getAllCurrencies, getAllAccountCategories, getAllAccountTypes, getMonthdayShortName } = useI18n();
const accountsStore = useAccountsStore();
const editAccountId = ref<string | null>(null);
const clientSessionId = ref<string>('');
const loading = ref<boolean>(false);
const submitting = ref<boolean>(false);
const account = ref<Account>(accountsStore.generateNewAccountModel());
const subAccounts = ref<Account[]>([]);
const title = computed<string>(() => {
if (!editAccountId.value) {
return 'Add Account';
} else {
return 'Edit Account';
}
});
const saveButtonTitle = computed<string>(() => {
if (!editAccountId.value) {
return 'Add';
} else {
return 'Save';
}
});
const allAccountCategories = computed<LocalizedAccountCategory[]>(() => getAllAccountCategories());
const allAccountTypes = computed<TypeAndDisplayName[]>(() => getAllAccountTypes());
const allCurrencies = computed<LocalizedCurrencyInfo[]>(() => getAllCurrencies());
const allAvailableMonthDays = computed<DayAndDisplayName[]>(() => {
const allAvailableDays: DayAndDisplayName[] = [];
allAvailableDays.push({
day: 0,
displayName: tt('Not set'),
});
for (let i = 1; i <= 28; i++) {
allAvailableDays.push({
day: i,
displayName: getMonthdayShortName(i),
});
}
return allAvailableDays;
});
const isAccountSupportCreditCardStatementDate = computed<boolean>(() => account.value && account.value.category === AccountCategory.CreditCard.type);
function getAccountCreditCardStatementDate(statementDate?: number): string | null {
for (const item of allAvailableMonthDays.value) {
if (item.day === statementDate) {
return item.displayName;
}
}
return null;
}
function getInputEmptyProblemMessage(account: Account, isSubAccount: boolean): string | null {
if (!isSubAccount && !account.category) {
return 'Account category cannot be blank';
} else if (!isSubAccount && !account.type) {
return 'Account type cannot be blank';
} else if (!account.name) {
return 'Account name cannot be blank';
} else if (account.type === AccountType.SingleAccount.type && !account.currency) {
return 'Account currency cannot be blank';
} else {
return null;
}
}
function isInputEmpty(): boolean {
const isAccountEmpty = !!getInputEmptyProblemMessage(account.value, false);
if (isAccountEmpty) {
return true;
}
if (account.value.type === AccountType.MultiSubAccounts.type) {
for (let i = 0; i < subAccounts.value.length; i++) {
const isSubAccountEmpty = !!getInputEmptyProblemMessage(subAccounts.value[i], true);
if (isSubAccountEmpty) {
return true;
}
}
}
return false;
}
function getAccountOrSubAccountProblemMessage(): string | null {
let problemMessage = getInputEmptyProblemMessage(account.value, false);
if (!problemMessage && account.value.type === AccountType.MultiSubAccounts.type) {
for (let i = 0; i < subAccounts.value.length; i++) {
problemMessage = getInputEmptyProblemMessage(subAccounts.value[i], true);
if (problemMessage) {
break;
}
}
}
return problemMessage;
}
function addSubAccount(): boolean {
if (account.value.type !== AccountType.MultiSubAccounts.type) {
return false;
}
const subAccount = accountsStore.generateNewSubAccountModel(account.value);
subAccounts.value.push(subAccount);
return true;
}
function setAccount(newAccount: Account): void {
account.value.from(newAccount);
subAccounts.value = [];
if (newAccount.childrenAccounts && newAccount.childrenAccounts.length > 0) {
for (let i = 0; i < newAccount.childrenAccounts.length; i++) {
const subAccount = accountsStore.generateNewSubAccountModel(account.value);
subAccount.from(newAccount.childrenAccounts[i]);
subAccounts.value.push(subAccount);
}
}
}
watch(() => account.value.category, (newValue, oldValue) => {
setAccountSuitableIcon(account.value, oldValue, newValue);
});
return {
// states
editAccountId,
clientSessionId,
loading,
submitting,
account,
subAccounts,
// computed states
title,
saveButtonTitle,
allAccountCategories,
allAccountTypes,
allCurrencies,
allAvailableMonthDays,
isAccountSupportCreditCardStatementDate,
// functions
getAccountCreditCardStatementDate,
isInputEmpty,
getAccountOrSubAccountProblemMessage,
addSubAccount,
setAccount
};
}
@@ -1,19 +1,19 @@
<template>
<v-dialog :width="account.type === allAccountTypes.MultiSubAccounts.type ? 1000 : 800" :persistent="!!persistent" v-model="showState">
<v-dialog :width="account.type === AccountType.MultiSubAccounts.type ? 1000 : 800" :persistent="!!persistent" v-model="showState">
<v-card class="pa-2 pa-sm-4 pa-md-8">
<template #title>
<div class="d-flex align-center justify-center">
<div class="d-flex w-100 align-center justify-center">
<h4 class="text-h4">{{ $t(title) }}</h4>
<h4 class="text-h4">{{ tt(title) }}</h4>
<v-progress-circular indeterminate size="22" class="ml-2" v-if="loading"></v-progress-circular>
</div>
<v-btn density="comfortable" color="default" variant="text" class="ml-2" :icon="true"
:disabled="loading || submitting || !!editAccountId || account.type !== allAccountTypes.MultiSubAccounts.type">
:disabled="loading || submitting || !!editAccountId || account.type !== AccountType.MultiSubAccounts.type">
<v-icon :icon="icons.more" />
<v-menu activator="parent">
<v-list>
<v-list-item :prepend-icon="icons.add"
:title="$t('Add Sub-account')"
:title="tt('Add Sub-account')"
@click="addSubAccount"></v-list-item>
</v-list>
</v-menu>
@@ -21,14 +21,14 @@
</div>
</template>
<v-card-text class="d-flex flex-column flex-md-row mt-md-4 pt-0">
<div class="mb-4" v-if="account.type === allAccountTypes.MultiSubAccounts.type">
<div class="mb-4" v-if="account.type === AccountType.MultiSubAccounts.type">
<v-tabs direction="vertical" :disabled="loading || submitting" v-model="currentAccountIndex">
<v-tab :value="-1">
<span>{{ $t('Main Account') }}</span>
<span>{{ tt('Main Account') }}</span>
</v-tab>
<template v-if="account.type === allAccountTypes.MultiSubAccounts.type">
<template v-if="account.type === AccountType.MultiSubAccounts.type">
<v-tab :key="idx" :value="idx" v-for="(subAccount, idx) in subAccounts">
<span>{{ $t('Sub Account') + ' #' + (idx + 1) }}</span>
<span>{{ tt('Sub Account') + ' #' + (idx + 1) }}</span>
<v-btn class="ml-2" color="error" size="24" variant="text"
:icon="icons.delete" v-if="!editAccountId"
@click="removeSubAccount(subAccount)"></v-btn>
@@ -38,21 +38,21 @@
</div>
<v-window class="d-flex flex-grow-1 disable-tab-transition w-100-window-container"
:class="{ 'ml-md-5': account.type === allAccountTypes.MultiSubAccounts.type }"
:class="{ 'ml-md-5': account.type === AccountType.MultiSubAccounts.type }"
v-model="activeTab">
<v-window-item value="account">
<v-form class="mt-2">
<v-row>
<v-col cols="12" md="12" v-if="account.type === allAccountTypes.SingleAccount.type || currentAccountIndex < 0">
<v-col cols="12" md="12" v-if="account.type === AccountType.SingleAccount.type || currentAccountIndex < 0">
<v-select
item-title="displayName"
item-value="type"
persistent-placeholder
:disabled="loading || submitting"
:label="$t('Account Category')"
:placeholder="$t('Account Category')"
:label="tt('Account Category')"
:placeholder="tt('Account Category')"
:items="allAccountCategories"
:no-data-text="$t('No results')"
:no-data-text="tt('No results')"
v-model="selectedAccount.category"
>
<template #item="{ props, item }">
@@ -71,16 +71,16 @@
</template>
</v-select>
</v-col>
<v-col cols="12" md="12" v-if="account.type === allAccountTypes.SingleAccount.type || currentAccountIndex < 0">
<v-col cols="12" md="12" v-if="account.type === AccountType.SingleAccount.type || currentAccountIndex < 0">
<v-select
item-title="displayName"
item-value="type"
persistent-placeholder
:disabled="loading || submitting || !!editAccountId"
:label="$t('Account Type')"
:placeholder="$t('Account Type')"
:items="allAccountTypesArray"
:no-data-text="$t('No results')"
:label="tt('Account Type')"
:placeholder="tt('Account Type')"
:items="allAccountTypes"
:no-data-text="tt('No results')"
v-model="selectedAccount.type"
/>
</v-col>
@@ -89,36 +89,36 @@
type="text"
persistent-placeholder
:disabled="loading || submitting"
:label="currentAccountIndex < 0 ? $t('Account Name') : $t('Sub-account Name')"
:placeholder="currentAccountIndex < 0 ? $t('Your account name') : $t('Your sub-account name')"
:label="currentAccountIndex < 0 ? tt('Account Name') : tt('Sub-account Name')"
:placeholder="currentAccountIndex < 0 ? tt('Your account name') : tt('Your sub-account name')"
v-model="selectedAccount.name"
/>
</v-col>
<v-col cols="12" md="6">
<icon-select icon-type="account"
:all-icon-infos="allAccountIcons"
:label="currentAccountIndex < 0 ? $t('Account Icon') : $t('Sub-account Icon')"
:all-icon-infos="ALL_ACCOUNT_ICONS"
:label="currentAccountIndex < 0 ? tt('Account Icon') : tt('Sub-account Icon')"
:color="selectedAccount.color"
:disabled="loading || submitting"
v-model="selectedAccount.icon" />
</v-col>
<v-col cols="12" md="6">
<color-select :all-color-infos="allAccountColors"
:label="currentAccountIndex < 0 ? $t('Account Color') : $t('Sub-account Color')"
<color-select :all-color-infos="ALL_ACCOUNT_COLORS"
:label="currentAccountIndex < 0 ? tt('Account Color') : tt('Sub-account Color')"
:disabled="loading || submitting"
v-model="selectedAccount.color" />
</v-col>
<v-col cols="12" :md="currentAccountIndex < 0 && isAccountSupportCreditCardStatementDate() ? 6 : 12" v-if="account.type === allAccountTypes.SingleAccount.type || currentAccountIndex >= 0">
<v-col cols="12" :md="currentAccountIndex < 0 && isAccountSupportCreditCardStatementDate ? 6 : 12" v-if="account.type === AccountType.SingleAccount.type || currentAccountIndex >= 0">
<v-autocomplete
item-title="displayName"
item-value="currencyCode"
auto-select-first
persistent-placeholder
:disabled="loading || submitting || !!editAccountId"
:label="$t('Currency')"
:placeholder="$t('Currency')"
:label="tt('Currency')"
:placeholder="tt('Currency')"
:items="allCurrencies"
:no-data-text="$t('No results')"
:no-data-text="tt('No results')"
v-model="selectedAccount.currency"
>
<template #append-inner>
@@ -126,37 +126,37 @@
</template>
</v-autocomplete>
</v-col>
<v-col cols="12" :md="account.type === allAccountTypes.SingleAccount.type || currentAccountIndex >= 0 ? 6 : 12" v-if="currentAccountIndex < 0 && isAccountSupportCreditCardStatementDate()">
<v-col cols="12" :md="account.type === AccountType.SingleAccount.type || currentAccountIndex >= 0 ? 6 : 12" v-if="currentAccountIndex < 0 && isAccountSupportCreditCardStatementDate">
<v-autocomplete
item-title="displayName"
item-value="day"
auto-select-first
persistent-placeholder
:disabled="loading || submitting"
:label="$t('Statement Date')"
:placeholder="$t('Statement Date')"
:label="tt('Statement Date')"
:placeholder="tt('Statement Date')"
:items="allAvailableMonthDays"
:no-data-text="$t('No results')"
:no-data-text="tt('No results')"
v-model="account.creditCardStatementDate"
></v-autocomplete>
</v-col>
<v-col cols="12" :md="!editAccountId && selectedAccount.balance ? 6 : 12"
v-if="account.type === allAccountTypes.SingleAccount.type || currentAccountIndex >= 0">
v-if="account.type === AccountType.SingleAccount.type || currentAccountIndex >= 0">
<amount-input :disabled="loading || submitting || !!editAccountId"
:persistent-placeholder="true"
:currency="selectedAccount.currency"
:show-currency="true"
:label="currentAccountIndex < 0 ? $t('Account Balance') : $t('Sub-account Balance')"
:placeholder="currentAccountIndex < 0 ? $t('Account Balance') : $t('Sub-account Balance')"
:label="currentAccountIndex < 0 ? tt('Account Balance') : tt('Sub-account Balance')"
:placeholder="currentAccountIndex < 0 ? tt('Account Balance') : tt('Sub-account Balance')"
v-model="selectedAccount.balance"/>
</v-col>
<v-col cols="12" md="6" v-show="selectedAccount.balance"
v-if="!editAccountId && (account.type === allAccountTypes.SingleAccount.type || currentAccountIndex >= 0)">
v-if="!editAccountId && (account.type === AccountType.SingleAccount.type || currentAccountIndex >= 0)">
<date-time-select
:disabled="loading || submitting"
:label="$t('Balance Time')"
:label="tt('Balance Time')"
v-model="selectedAccount.balanceTime"
@error="showDateTimeError" />
@error="onShowDateTimeError" />
</v-col>
<v-col cols="12" md="12">
<v-textarea
@@ -164,14 +164,14 @@
persistent-placeholder
rows="3"
:disabled="loading || submitting"
:label="$t('Description')"
:placeholder="currentAccountIndex < 0 ? $t('Your account description (optional)') : $t('Your sub-account description (optional)')"
:label="tt('Description')"
:placeholder="currentAccountIndex < 0 ? tt('Your account description (optional)') : tt('Your sub-account description (optional)')"
v-model="selectedAccount.comment"
/>
</v-col>
<v-col class="py-0" cols="12" md="12" v-if="editAccountId">
<v-switch :disabled="loading || submitting"
:label="$t('Visible')" v-model="selectedAccount.visible"/>
:label="tt('Visible')" v-model="selectedAccount.visible"/>
</v-col>
</v-row>
</v-form>
@@ -181,11 +181,11 @@
<v-card-text class="overflow-y-visible">
<div class="w-100 d-flex justify-center mt-2 mt-sm-4 mt-md-6 gap-4">
<v-btn :disabled="isInputEmpty() || loading || submitting" @click="save">
{{ $t(saveButtonTitle) }}
{{ tt(saveButtonTitle) }}
<v-progress-circular indeterminate size="22" class="ml-2" v-if="submitting"></v-progress-circular>
</v-btn>
<v-btn color="secondary" variant="tonal"
:disabled="loading || submitting" @click="cancel">{{ $t('Cancel') }}</v-btn>
:disabled="loading || submitting" @click="cancel">{{ tt('Cancel') }}</v-btn>
</div>
</v-card-text>
</v-card>
@@ -195,14 +195,21 @@
<snack-bar ref="snackbar" />
</template>
<script>
import { mapStores } from 'pinia';
import { useSettingsStore } from '@/stores/setting.ts';
<script setup lang="ts">
import ConfirmDialog from '@/components/desktop/ConfirmDialog.vue';
import SnackBar from '@/components/desktop/SnackBar.vue';
import { ref, computed, useTemplateRef, watch } from 'vue';
import { useI18n } from '@/locales/helpers.ts';
import { useAccountEditPageBaseBase } from '@/views/base/accounts/AccountEditPageBase.ts';
import { useAccountsStore } from '@/stores/account.ts';
import { AccountType, AccountCategory } from '@/core/account.ts';
import { AccountType } from '@/core/account.ts';
import { ALL_ACCOUNT_ICONS } from '@/consts/icon.ts';
import { ALL_ACCOUNT_COLORS } from '@/consts/color.ts';
import type { Account } from '@/models/account.ts';
import { isNumber } from '@/lib/common.ts';
import { generateRandomUUID } from '@/lib/misc.ts';
@@ -214,290 +221,176 @@ import {
mdiDeleteOutline
} from '@mdi/js';
export default {
props: [
'persistent',
'show'
],
expose: [
'open'
],
data() {
const accountsStore = useAccountsStore();
const newAccount = accountsStore.generateNewAccountModel();
return {
showState: false,
activeTab: 'account',
editAccountId: null,
clientSessionId: '',
loading: false,
account: newAccount,
subAccounts: [],
currentAccountIndex: -1,
submitting: false,
resolve: null,
reject: null,
icons: {
more: mdiDotsVertical,
add: mdiCreditCardPlusOutline,
delete: mdiDeleteOutline
}
};
},
computed: {
...mapStores(useSettingsStore, useAccountsStore),
title() {
if (!this.editAccountId) {
return 'Add Account';
} else {
return 'Edit Account';
}
},
saveButtonTitle() {
if (!this.editAccountId) {
return 'Add';
} else {
return 'Save';
}
},
allAccountTypes() {
return AccountType.all();
},
allAccountCategories() {
return this.$locale.getAllAccountCategories();
},
allAccountTypesArray() {
return this.$locale.getAllAccountTypes();
},
allAccountIcons() {
return ALL_ACCOUNT_ICONS;
},
allAccountColors() {
return ALL_ACCOUNT_COLORS;
},
allCurrencies() {
return this.$locale.getAllCurrencies();
},
allAvailableMonthDays() {
const allAvailableDays = [];
allAvailableDays.push({
day: 0,
displayName: this.$t('Not set'),
});
for (let i = 1; i <= 28; i++) {
allAvailableDays.push({
day: i,
displayName: this.$locale.getMonthdayShortName(i),
});
}
return allAvailableDays;
},
selectedAccount() {
if (this.currentAccountIndex < 0) {
return this.account;
}
return this.subAccounts[this.currentAccountIndex];
}
},
watch: {
'account.category': function (newValue, oldValue) {
this.chooseSuitableIcon(oldValue, newValue);
},
'account.type': function () {
if (this.subAccounts.length < 1) {
this.addSubAccount();
}
}
},
methods: {
open(options) {
const self = this;
self.showState = true;
self.loading = true;
self.submitting = false;
const newAccount = self.accountsStore.generateNewAccountModel();
self.account.from(newAccount);
self.subAccounts = [];
self.currentAccountIndex = -1;
if (options && options.id) {
if (options.currentAccount) {
self.setAccount(options.currentAccount);
}
self.editAccountId = options.id;
self.accountsStore.getAccount({
accountId: self.editAccountId
}).then(account => {
self.setAccount(account);
self.loading = false;
}).catch(error => {
self.loading = false;
self.showState = false;
if (!error.processed) {
if (self.reject) {
self.reject(error);
}
}
});
} else {
if (isNumber(options.category)) {
self.account.category = options.category;
self.chooseSuitableIcon(1, options.category);
}
self.editAccountId = null;
self.clientSessionId = generateRandomUUID();
self.loading = false;
}
return new Promise((resolve, reject) => {
self.resolve = resolve;
self.reject = reject;
});
},
addSubAccount() {
if (this.account.type !== this.allAccountTypes.MultiSubAccounts.type) {
return;
}
const subAccount = this.accountsStore.generateNewSubAccountModel(this.account);
this.subAccounts.push(subAccount);
},
removeSubAccount(subAccount) {
const self = this;
self.$refs.confirmDialog.open('Are you sure you want to remove this sub-account?').then(() => {
for (let i = 0; i < self.subAccounts.length; i++) {
if (self.subAccounts[i] === subAccount) {
self.subAccounts.splice(i, 1);
if (self.currentAccountIndex >= self.subAccounts.length) {
self.currentAccountIndex = self.subAccounts.length - 1;
}
}
}
});
},
save() {
const self = this;
let problemMessage = self.getInputEmptyProblemMessage(self.account, false);
if (!problemMessage && self.account.type === self.allAccountTypes.MultiSubAccounts.type) {
for (let i = 0; i < self.subAccounts.length; i++) {
problemMessage = self.getInputEmptyProblemMessage(self.subAccounts[i], true);
if (problemMessage) {
break;
}
}
}
if (problemMessage) {
self.$refs.snackbar.showMessage(problemMessage);
return;
}
self.submitting = true;
self.accountsStore.saveAccount({
account: self.account,
subAccounts: self.subAccounts,
isEdit: !!self.editAccountId,
clientSessionId: self.clientSessionId
}).then(() => {
self.submitting = false;
let message = 'You have saved this account';
if (!self.editAccountId) {
message = 'You have added a new account';
}
if (self.resolve) {
self.resolve({
message: message
});
}
self.showState = false;
}).catch(error => {
self.submitting = false;
if (!error.processed) {
self.$refs.snackbar.showError(error);
}
});
},
cancel() {
if (this.reject) {
this.reject();
}
this.showState = false;
},
isAccountSupportCreditCardStatementDate() {
return this.account && this.account.category === AccountCategory.CreditCard.type;
},
chooseSuitableIcon(oldCategory, newCategory) {
setAccountSuitableIcon(this.account, oldCategory, newCategory);
},
isInputEmpty() {
const isAccountEmpty = !!this.getInputEmptyProblemMessage(this.account, false);
if (isAccountEmpty) {
return true;
}
if (this.account.type === this.allAccountTypes.MultiSubAccounts.type) {
for (let i = 0; i < this.subAccounts.length; i++) {
const isSubAccountEmpty = !!this.getInputEmptyProblemMessage(this.subAccounts[i], true);
if (isSubAccountEmpty) {
return true;
}
}
}
return false;
},
getInputEmptyProblemMessage(account, isSubAccount) {
if (!isSubAccount && !account.category) {
return 'Account category cannot be blank';
} else if (!isSubAccount && !account.type) {
return 'Account type cannot be blank';
} else if (!account.name) {
return 'Account name cannot be blank';
} else if (account.type === this.allAccountTypes.SingleAccount.type && !account.currency) {
return 'Account currency cannot be blank';
} else {
return null;
}
},
setAccount(account) {
this.account.from(account);
this.subAccounts = [];
if (account.childrenAccounts && account.childrenAccounts.length > 0) {
for (let i = 0; i < account.childrenAccounts.length; i++) {
const subAccount = this.accountsStore.generateNewSubAccountModel(this.account);
subAccount.from(account.childrenAccounts[i]);
this.subAccounts.push(subAccount);
}
}
},
showDateTimeError(error) {
this.$refs.snackbar.showError(error);
}
}
interface AccountEditResponse {
message: string;
}
type ConfirmDialogType = InstanceType<typeof ConfirmDialog>;
type SnackBarType = InstanceType<typeof SnackBar>;
defineProps<{
persistent?: boolean;
show?: boolean;
}>();
const { tt } = useI18n();
const {
editAccountId,
clientSessionId,
loading,
submitting,
account,
subAccounts,
title,
saveButtonTitle,
allAccountCategories,
allAccountTypes,
allCurrencies,
allAvailableMonthDays,
isAccountSupportCreditCardStatementDate,
isInputEmpty,
getAccountOrSubAccountProblemMessage,
addSubAccount,
setAccount
} = useAccountEditPageBaseBase();
const accountsStore = useAccountsStore();
const icons = {
more: mdiDotsVertical,
add: mdiCreditCardPlusOutline,
delete: mdiDeleteOutline
};
const confirmDialog = useTemplateRef<ConfirmDialogType>('confirmDialog');
const snackbar = useTemplateRef<SnackBarType>('snackbar');
const showState = ref<boolean>(false);
const activeTab = ref<string>('account');
const currentAccountIndex = ref<number>(-1);
const selectedAccount = computed<Account>(() => {
if (currentAccountIndex.value < 0) {
return account.value;
}
return subAccounts.value[currentAccountIndex.value];
});
let resolveFunc: ((value: AccountEditResponse) => void) | null = null;
let rejectFunc: ((reason?: unknown) => void) | null = null;
function open(options?: { id?: string, currentAccount?: Account, category?: number }): Promise<AccountEditResponse> {
showState.value = true;
loading.value = true;
submitting.value = false;
const newAccount = accountsStore.generateNewAccountModel();
account.value.from(newAccount);
subAccounts.value = [];
currentAccountIndex.value = -1;
if (options && options.id) {
if (options.currentAccount) {
setAccount(options.currentAccount);
}
editAccountId.value = options.id;
accountsStore.getAccount({
accountId: editAccountId.value
}).then(response => {
setAccount(response);
loading.value = false;
}).catch(error => {
loading.value = false;
showState.value = false;
if (!error.processed) {
snackbar.value?.showError(error);
}
});
} else {
if (options && isNumber(options.category)) {
account.value.category = options.category;
setAccountSuitableIcon(account.value, 1, options.category);
}
editAccountId.value = null;
clientSessionId.value = generateRandomUUID();
loading.value = false;
}
return new Promise<AccountEditResponse>((resolve, reject) => {
resolveFunc = resolve;
rejectFunc = reject;
});
}
function save(): void {
const problemMessage = getAccountOrSubAccountProblemMessage();
if (problemMessage) {
snackbar.value?.showMessage(problemMessage);
return;
}
submitting.value = true;
accountsStore.saveAccount({
account: account.value,
subAccounts: subAccounts.value,
isEdit: !!editAccountId.value,
clientSessionId: clientSessionId.value
}).then(() => {
submitting.value = false;
let message = 'You have saved this account';
if (!editAccountId.value) {
message = 'You have added a new account';
}
resolveFunc?.({ message });
showState.value = false;
}).catch(error => {
submitting.value = false;
if (!error.processed) {
snackbar.value?.showError(error);
}
});
}
function removeSubAccount(subAccount: Account): void {
confirmDialog.value?.open('Are you sure you want to remove this sub-account?').then(() => {
for (let i = 0; i < subAccounts.value.length; i++) {
if (subAccounts.value[i] === subAccount) {
subAccounts.value.splice(i, 1);
if (currentAccountIndex.value >= subAccounts.value.length) {
currentAccountIndex.value = subAccounts.value.length - 1;
}
}
}
});
}
function cancel(): void {
rejectFunc?.();
showState.value = false;
}
function onShowDateTimeError(error: string): void {
snackbar.value?.showError(error);
}
watch(() => account.value.type, () => {
if (subAccounts.value.length < 1) {
addSubAccount();
}
});
defineExpose({
open
});
</script>
+258 -371
View File
@@ -1,11 +1,11 @@
<template>
<f7-page @page:afterin="onPageAfterIn">
<f7-navbar>
<f7-nav-left :back-link="$t('Back')"></f7-nav-left>
<f7-nav-title :title="$t(title)"></f7-nav-title>
<f7-nav-left :back-link="tt('Back')"></f7-nav-left>
<f7-nav-title :title="tt(title)"></f7-nav-title>
<f7-nav-right>
<f7-link icon-f7="ellipsis" :class="{ 'disabled': editAccountId || account.type !== allAccountTypes.MultiSubAccounts.type }" @click="showMoreActionSheet = true"></f7-link>
<f7-link :class="{ 'disabled': isInputEmpty() || submitting }" :text="$t(saveButtonTitle)" @click="save"></f7-link>
<f7-link icon-f7="ellipsis" :class="{ 'disabled': editAccountId || account.type !== AccountType.MultiSubAccounts.type }" @click="showMoreActionSheet = true"></f7-link>
<f7-link :class="{ 'disabled': isInputEmpty() || submitting }" :text="tt(saveButtonTitle)" @click="save"></f7-link>
</f7-nav-right>
</f7-navbar>
@@ -18,8 +18,8 @@
<f7-list-item
link="#" no-chevron
class="list-item-with-header-and-title"
:header="$t('Account Category')"
:title="getAccountCategoryName(account.category)"
:header="tt('Account Category')"
:title="findDisplayNameByType(allAccountCategories, account.category)"
@click="showAccountCategorySheet = true"
>
<list-item-selection-sheet value-type="item"
@@ -35,13 +35,13 @@
link="#" no-chevron
class="list-item-with-header-and-title"
:class="{ 'disabled': editAccountId }"
:header="$t('Account Type')"
:title="getAccountTypeName(account.type)"
:header="tt('Account Type')"
:title="findDisplayNameByType(allAccountTypes, account.type)"
@click="showAccountTypeSheet = true"
>
<list-item-selection-sheet value-type="item"
key-field="type" value-field="type" title-field="displayName"
:items="allAccountTypesArray"
:items="allAccountTypes"
v-model:show="showAccountTypeSheet"
v-model="account.type">
</list-item-selection-sheet>
@@ -94,12 +94,12 @@
<f7-list-input label="Description" type="textarea" placeholder="Your account description (optional)"></f7-list-input>
</f7-list>
<f7-list form strong inset dividers class="margin-vertical" v-else-if="!loading && account.type === allAccountTypes.SingleAccount.type">
<f7-list form strong inset dividers class="margin-vertical" v-else-if="!loading && account.type === AccountType.SingleAccount.type">
<f7-list-input
type="text"
clear-button
:label="$t('Account Name')"
:placeholder="$t('Your account name')"
:label="tt('Account Name')"
:placeholder="tt('Your account name')"
v-model:value="account.name"
></f7-list-input>
@@ -107,11 +107,11 @@
<template #default>
<div class="grid grid-cols-2">
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="account.showIconSelectionSheet = true">
<a class="item-link" href="#" @click="accountContext.showIconSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Account Icon') }}</span>
<span>{{ tt('Account Icon') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -122,18 +122,18 @@
</div>
</a>
<icon-selection-sheet :all-icon-infos="allAccountIcons"
<icon-selection-sheet :all-icon-infos="ALL_ACCOUNT_ICONS"
:color="account.color"
v-model:show="account.showIconSelectionSheet"
v-model:show="accountContext.showIconSelectionSheet"
v-model="account.icon"
></icon-selection-sheet>
</div>
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="account.showColorSelectionSheet = true">
<a class="item-link" href="#" @click="accountContext.showColorSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Account Color') }}</span>
<span>{{ tt('Account Color') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -144,8 +144,8 @@
</div>
</a>
<color-selection-sheet :all-color-infos="allAccountColors"
v-model:show="account.showColorSelectionSheet"
<color-selection-sheet :all-color-infos="ALL_ACCOUNT_COLORS"
v-model:show="accountContext.showColorSelectionSheet"
v-model="account.color"
></color-selection-sheet>
</div>
@@ -156,9 +156,9 @@
<f7-list-item
class="list-item-with-header-and-title list-item-no-item-after"
:class="{ 'disabled': editAccountId }"
:header="$t('Currency')"
:header="tt('Currency')"
:no-chevron="!!editAccountId"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: $t('Currency Name'), searchbarDisableText: $t('Cancel'), appendSearchbarNotFound: $t('No results'), pageTitle: $t('Currency Name'), popupCloseLinkText: $t('Done') }"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: tt('Currency Name'), searchbarDisableText: tt('Cancel'), appendSearchbarNotFound: tt('No results'), pageTitle: tt('Currency Name'), popupCloseLinkText: tt('Done') }"
>
<template #title>
<div class="no-padding no-margin">
@@ -175,10 +175,10 @@
<f7-list-item
class="list-item-with-header-and-title list-item-no-item-after"
:header="$t('Statement Date')"
:header="tt('Statement Date')"
:title="getAccountCreditCardStatementDate(account.creditCardStatementDate)"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: $t('Statement Date'), searchbarDisableText: $t('Cancel'), appendSearchbarNotFound: $t('No results'), pageTitle: $t('Statement Date'), popupCloseLinkText: $t('Done') }"
v-if="isAccountSupportCreditCardStatementDate()"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: tt('Statement Date'), searchbarDisableText: tt('Cancel'), appendSearchbarNotFound: tt('No results'), pageTitle: tt('Statement Date'), popupCloseLinkText: tt('Done') }"
v-if="isAccountSupportCreditCardStatementDate"
>
<select v-model="account.creditCardStatementDate">
<option :value="monthDay.day"
@@ -191,14 +191,14 @@
link="#" no-chevron
class="list-item-with-header-and-title"
:class="{ 'disabled': editAccountId }"
:header="$t('Account Balance')"
:title="getAccountBalance(account)"
@click="account.showBalanceSheet = true"
:header="tt('Account Balance')"
:title="formatAmountWithCurrency(account.balance, account.currency)"
@click="accountContext.showBalanceSheet = true"
>
<number-pad-sheet :min-value="allowedMinAmount"
:max-value="allowedMaxAmount"
<number-pad-sheet :min-value="TRANSACTION_MIN_AMOUNT"
:max-value="TRANSACTION_MAX_AMOUNT"
:currency="account.currency"
v-model:show="account.showBalanceSheet"
v-model:show="accountContext.showBalanceSheet"
v-model="account.balance"
></number-pad-sheet>
</f7-list-item>
@@ -210,39 +210,39 @@
v-if="!editAccountId"
>
<template #header>
<div class="account-edit-balancetime-header" @click="showDateTimeDialog(account, 'time')">{{ $t('Balance Time') }}</div>
<div class="account-edit-balancetime-header" @click="showDateTimeDialog(accountContext, 'time')">{{ tt('Balance Time') }}</div>
</template>
<template #title>
<div class="account-edit-balancetime-title">
<div @click="showDateTimeDialog(account, 'date')">{{ getAccountBalanceDate(account.balanceTime) }}</div>&nbsp;<div class="account-edit-balancetime-time" @click="showDateTimeDialog(account, 'time')">{{ getAccountBalanceTime(account.balanceTime) }}</div>
<div @click="showDateTimeDialog(accountContext, 'date')">{{ getAccountBalanceDate(account.balanceTime as number) }}</div>&nbsp;<div class="account-edit-balancetime-time" @click="showDateTimeDialog(accountContext, 'time')">{{ getAccountBalanceTime(account.balanceTime as number) }}</div>
</div>
</template>
<date-time-selection-sheet :init-mode="account.balanceDateTimeSheetMode"
v-model:show="account.showBalanceDateTimeSheet"
<date-time-selection-sheet :init-mode="accountContext.balanceDateTimeSheetMode"
v-model:show="accountContext.showBalanceDateTimeSheet"
v-model="account.balanceTime">
</date-time-selection-sheet>
</f7-list-item>
<f7-list-item :title="$t('Visible')" v-if="editAccountId">
<f7-list-item :title="tt('Visible')" v-if="editAccountId">
<f7-toggle :checked="account.visible" @toggle:change="account.visible = $event"></f7-toggle>
</f7-list-item>
<f7-list-input
type="textarea"
style="height: auto"
:label="$t('Description')"
:placeholder="$t('Your account description (optional)')"
:label="tt('Description')"
:placeholder="tt('Your account description (optional)')"
v-textarea-auto-size
v-model:value="account.comment"
></f7-list-input>
</f7-list>
<f7-list form strong inset dividers class="margin-vertical" v-else-if="!loading && account.type === allAccountTypes.MultiSubAccounts.type">
<f7-list form strong inset dividers class="margin-vertical" v-else-if="!loading && account.type === AccountType.MultiSubAccounts.type">
<f7-list-input
type="text"
clear-button
:label="$t('Account Name')"
:placeholder="$t('Your account name')"
:label="tt('Account Name')"
:placeholder="tt('Your account name')"
v-model:value="account.name"
></f7-list-input>
@@ -250,11 +250,11 @@
<template #default>
<div class="grid grid-cols-2">
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="account.showIconSelectionSheet = true">
<a class="item-link" href="#" @click="accountContext.showIconSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Account Icon') }}</span>
<span>{{ tt('Account Icon') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -265,18 +265,18 @@
</div>
</a>
<icon-selection-sheet :all-icon-infos="allAccountIcons"
<icon-selection-sheet :all-icon-infos="ALL_ACCOUNT_ICONS"
:color="account.color"
v-model:show="account.showIconSelectionSheet"
v-model:show="accountContext.showIconSelectionSheet"
v-model="account.icon"
></icon-selection-sheet>
</div>
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="account.showColorSelectionSheet = true">
<a class="item-link" href="#" @click="accountContext.showColorSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Account Color') }}</span>
<span>{{ tt('Account Color') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -287,8 +287,8 @@
</div>
</a>
<color-selection-sheet :all-color-infos="allAccountColors"
v-model:show="account.showColorSelectionSheet"
<color-selection-sheet :all-color-infos="ALL_ACCOUNT_COLORS"
v-model:show="accountContext.showColorSelectionSheet"
v-model="account.color"
></color-selection-sheet>
</div>
@@ -298,10 +298,10 @@
<f7-list-item
class="list-item-with-header-and-title list-item-no-item-after"
:header="$t('Statement Date')"
:header="tt('Statement Date')"
:title="getAccountCreditCardStatementDate(account.creditCardStatementDate)"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: $t('Statement Date'), searchbarDisableText: $t('Cancel'), appendSearchbarNotFound: $t('No results'), pageTitle: $t('Statement Date'), popupCloseLinkText: $t('Done') }"
v-if="isAccountSupportCreditCardStatementDate()"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: tt('Statement Date'), searchbarDisableText: tt('Cancel'), appendSearchbarNotFound: tt('No results'), pageTitle: tt('Statement Date'), popupCloseLinkText: tt('Done') }"
v-if="isAccountSupportCreditCardStatementDate"
>
<select v-model="account.creditCardStatementDate">
<option :value="monthDay.day"
@@ -310,28 +310,28 @@
</select>
</f7-list-item>
<f7-list-item :title="$t('Visible')" v-if="editAccountId">
<f7-list-item :title="tt('Visible')" v-if="editAccountId">
<f7-toggle :checked="account.visible" @toggle:change="account.visible = $event"></f7-toggle>
</f7-list-item>
<f7-list-input
type="textarea"
style="height: auto"
:label="$t('Description')"
:placeholder="$t('Your account description (optional)')"
:label="tt('Description')"
:placeholder="tt('Your account description (optional)')"
v-textarea-auto-size
v-model:value="account.comment"
></f7-list-input>
</f7-list>
<f7-block class="no-padding no-margin" v-if="!loading && account.type === allAccountTypes.MultiSubAccounts.type">
<f7-block class="no-padding no-margin" v-if="!loading && account.type === AccountType.MultiSubAccounts.type">
<f7-list strong inset dividers class="subaccount-edit-list margin-vertical"
:key="idx"
v-for="(subAccount, idx) in subAccounts">
<f7-list-item group-title>
<small>{{ $t('Sub Account') + ' #' + (idx + 1) }}</small>
<small>{{ tt('Sub Account') + ' #' + (idx + 1) }}</small>
<f7-button rasied fill class="subaccount-delete-button" color="red" icon-f7="trash" icon-size="16px"
:tooltip="$t('Remove Sub-account')"
:tooltip="tt('Remove Sub-account')"
v-if="!editAccountId"
@click="removeSubAccount(subAccount, false)">
</f7-button>
@@ -340,8 +340,8 @@
<f7-list-input
type="text"
clear-button
:label="$t('Sub-account Name')"
:placeholder="$t('Your sub-account name')"
:label="tt('Sub-account Name')"
:placeholder="tt('Your sub-account name')"
v-model:value="subAccount.name"
></f7-list-input>
@@ -349,11 +349,11 @@
<template #default>
<div class="grid grid-cols-2">
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="subAccount.showIconSelectionSheet = true">
<a class="item-link" href="#" @click="subAccountContexts[idx].showIconSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Sub-account Icon') }}</span>
<span>{{ tt('Sub-account Icon') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -364,18 +364,18 @@
</div>
</a>
<icon-selection-sheet :all-icon-infos="allAccountIcons"
<icon-selection-sheet :all-icon-infos="ALL_ACCOUNT_ICONS"
:color="subAccount.color"
v-model:show="subAccount.showIconSelectionSheet"
v-model:show="subAccountContexts[idx].showIconSelectionSheet"
v-model="subAccount.icon"
></icon-selection-sheet>
</div>
<div class="list-item-subitem no-chevron">
<a class="item-link" href="#" @click="subAccount.showColorSelectionSheet = true">
<a class="item-link" href="#" @click="subAccountContexts[idx].showColorSelectionSheet = true">
<div class="item-content">
<div class="item-inner">
<div class="item-header">
<span>{{ $t('Sub-account Color') }}</span>
<span>{{ tt('Sub-account Color') }}</span>
</div>
<div class="item-title">
<div class="list-item-custom-title no-padding">
@@ -386,8 +386,8 @@
</div>
</a>
<color-selection-sheet :all-color-infos="allAccountColors"
v-model:show="subAccount.showColorSelectionSheet"
<color-selection-sheet :all-color-infos="ALL_ACCOUNT_COLORS"
v-model:show="subAccountContexts[idx].showColorSelectionSheet"
v-model="subAccount.color"
></color-selection-sheet>
</div>
@@ -398,9 +398,9 @@
<f7-list-item
class="list-item-with-header-and-title list-item-no-item-after"
:class="{ 'disabled': editAccountId }"
:header="$t('Currency')"
:header="tt('Currency')"
:no-chevron="!!editAccountId"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: $t('Currency Name'), searchbarDisableText: $t('Cancel'), appendSearchbarNotFound: $t('No results'), pageTitle: $t('Currency Name'), popupCloseLinkText: $t('Done') }"
smart-select :smart-select-params="{ openIn: 'popup', popupPush: true, closeOnSelect: true, scrollToSelectedItem: true, searchbar: true, searchbarPlaceholder: tt('Currency Name'), searchbarDisableText: tt('Cancel'), appendSearchbarNotFound: tt('No results'), pageTitle: tt('Currency Name'), popupCloseLinkText: tt('Done') }"
>
<template #title>
<div class="no-padding no-margin">
@@ -419,14 +419,14 @@
link="#" no-chevron
class="list-item-with-header-and-title"
:class="{ 'disabled': editAccountId }"
:header="$t('Sub-account Balance')"
:title="getAccountBalance(subAccount)"
@click="subAccount.showBalanceSheet = true"
:header="tt('Sub-account Balance')"
:title="formatAmountWithCurrency(subAccount.balance, subAccount.currency)"
@click="subAccountContexts[idx].showBalanceSheet = true"
>
<number-pad-sheet :min-value="allowedMinAmount"
:max-value="allowedMaxAmount"
<number-pad-sheet :min-value="TRANSACTION_MIN_AMOUNT"
:max-value="TRANSACTION_MAX_AMOUNT"
:currency="subAccount.currency"
v-model:show="subAccount.showBalanceSheet"
v-model:show="subAccountContexts[idx].showBalanceSheet"
v-model="subAccount.balance"
></number-pad-sheet>
</f7-list-item>
@@ -438,28 +438,28 @@
v-if="!editAccountId"
>
<template #header>
<div class="account-edit-balancetime-header" @click="showDateTimeDialog(subAccount, 'time')">{{ $t('Sub-account Balance Time') }}</div>
<div class="account-edit-balancetime-header" @click="showDateTimeDialog(subAccountContexts[idx], 'time')">{{ tt('Sub-account Balance Time') }}</div>
</template>
<template #title>
<div class="account-edit-balancetime-title">
<div @click="showDateTimeDialog(subAccount, 'date')">{{ getAccountBalanceDate(subAccount.balanceTime) }}</div>&nbsp;<div class="account-edit-balancetime-time" @click="showDateTimeDialog(subAccount, 'time')">{{ getAccountBalanceTime(subAccount.balanceTime) }}</div>
<div @click="showDateTimeDialog(subAccountContexts[idx], 'date')">{{ getAccountBalanceDate(subAccount.balanceTime as number) }}</div>&nbsp;<div class="account-edit-balancetime-time" @click="showDateTimeDialog(subAccountContexts[idx], 'time')">{{ getAccountBalanceTime(subAccount.balanceTime as number) }}</div>
</div>
</template>
<date-time-selection-sheet :init-mode="subAccount.balanceDateTimeSheetMode"
v-model:show="subAccount.showBalanceDateTimeSheet"
<date-time-selection-sheet :init-mode="subAccountContexts[idx].balanceDateTimeSheetMode"
v-model:show="subAccountContexts[idx].showBalanceDateTimeSheet"
v-model="subAccount.balanceTime">
</date-time-selection-sheet>
</f7-list-item>
<f7-list-item :title="$t('Visible')" v-if="editAccountId">
<f7-list-item :title="tt('Visible')" v-if="editAccountId">
<f7-toggle :checked="subAccount.visible" @toggle:change="subAccount.visible = $event"></f7-toggle>
</f7-list-item>
<f7-list-input
type="textarea"
style="height: auto"
:label="$t('Description')"
:placeholder="$t('Your sub-account description (optional)')"
:label="tt('Description')"
:placeholder="tt('Your sub-account description (optional)')"
v-textarea-auto-size
v-model:value="subAccount.comment"
></f7-list-input>
@@ -468,341 +468,228 @@
<f7-actions close-by-outside-click close-on-escape :opened="showMoreActionSheet" @actions:closed="showMoreActionSheet = false">
<f7-actions-group>
<f7-actions-button @click="addSubAccount">{{ $t('Add Sub-account') }}</f7-actions-button>
<f7-actions-button @click="addSubAccountAndContext">{{ tt('Add Sub-account') }}</f7-actions-button>
</f7-actions-group>
<f7-actions-group>
<f7-actions-button bold close>{{ $t('Cancel') }}</f7-actions-button>
<f7-actions-button bold close>{{ tt('Cancel') }}</f7-actions-button>
</f7-actions-group>
</f7-actions>
<f7-actions close-by-outside-click close-on-escape :opened="showDeleteActionSheet" @actions:closed="showDeleteActionSheet = false">
<f7-actions-group>
<f7-actions-label>{{ $t('Are you sure you want to remove this sub-account?') }}</f7-actions-label>
<f7-actions-button color="red" @click="removeSubAccount(subAccountToDelete, true)">{{ $t('Remove') }}</f7-actions-button>
<f7-actions-label>{{ tt('Are you sure you want to remove this sub-account?') }}</f7-actions-label>
<f7-actions-button color="red" @click="removeSubAccount(subAccountToDelete, true)">{{ tt('Remove') }}</f7-actions-button>
</f7-actions-group>
<f7-actions-group>
<f7-actions-button bold close>{{ $t('Cancel') }}</f7-actions-button>
<f7-actions-button bold close>{{ tt('Cancel') }}</f7-actions-button>
</f7-actions-group>
</f7-actions>
</f7-page>
</template>
<script>
import { mapStores } from 'pinia';
import { useSettingsStore } from '@/stores/setting.ts';
import { useUserStore } from '@/stores/user.ts';
<script setup lang="ts">
import { ref, watch } from 'vue';
import type { Router } from 'framework7/types';
import { useI18n } from '@/locales/helpers.ts';
import { useI18nUIComponents, showLoading, hideLoading } from '@/lib/ui/mobile.ts';
import { useAccountEditPageBaseBase } from '@/views/base/accounts/AccountEditPageBase.ts';
import { useAccountsStore } from '@/stores/account.ts';
import { AccountType, AccountCategory } from '@/core/account.ts';
import { AccountType } from '@/core/account.ts';
import { ALL_ACCOUNT_ICONS } from '@/consts/icon.ts';
import { ALL_ACCOUNT_COLORS } from '@/consts/color.ts';
import { TRANSACTION_MIN_AMOUNT, TRANSACTION_MAX_AMOUNT } from '@/consts/transaction.ts';
import type { Account } from '@/models/account.ts';
import { getNameByKeyValue } from '@/lib/common.ts';
import { findDisplayNameByType } from '@/lib/common.ts';
import { generateRandomUUID } from '@/lib/misc.ts';
import { setAccountSuitableIcon } from '@/lib/account.ts';
import {
getTimezoneOffsetMinutes,
getBrowserTimezoneOffsetMinutes,
getActualUnixTimeForStore
} from '@/lib/datetime.ts';
export default {
props: [
'f7route',
'f7router'
],
data() {
const accountsStore = useAccountsStore();
const newAccount = accountsStore.generateNewAccountModel();
newAccount.showIconSelectionSheet = false;
newAccount.showColorSelectionSheet = false;
newAccount.showBalanceSheet = false;
newAccount.showBalanceDateTimeSheet = false;
newAccount.balanceDateTimeSheetMode = 'time';
interface AccountContext {
showIconSelectionSheet: boolean;
showColorSelectionSheet: boolean;
showBalanceSheet: boolean;
showBalanceDateTimeSheet: boolean;
balanceDateTimeSheetMode: string;
}
return {
editAccountId: null,
clientSessionId: '',
loading: false,
loadingError: null,
account: newAccount,
subAccounts: [],
subAccountToDelete: null,
submitting: false,
showAccountCategorySheet: false,
showAccountTypeSheet: false,
showMoreActionSheet: false,
showDeleteActionSheet: false
};
},
computed: {
...mapStores(useSettingsStore, useUserStore, useAccountsStore),
title() {
if (!this.editAccountId) {
return 'Add Account';
const props = defineProps<{
f7route: Router.Route;
f7router: Router.Router;
}>();
const { tt, getCurrencyName, formatUnixTimeToLongDate, formatUnixTimeToLongTime, formatAmountWithCurrency } = useI18n();
const { showAlert, showToast, routeBackOnError } = useI18nUIComponents();
const {
editAccountId,
clientSessionId,
loading,
submitting,
account,
subAccounts,
title,
saveButtonTitle,
allAccountCategories,
allAccountTypes,
allCurrencies,
allAvailableMonthDays,
isAccountSupportCreditCardStatementDate,
getAccountCreditCardStatementDate,
isInputEmpty,
getAccountOrSubAccountProblemMessage,
addSubAccount,
setAccount
} = useAccountEditPageBaseBase();
const accountsStore = useAccountsStore();
const DEFAULT_ACCOUNT_CONTEXT: AccountContext = {
showIconSelectionSheet: false,
showColorSelectionSheet: false,
showBalanceSheet: false,
showBalanceDateTimeSheet: false,
balanceDateTimeSheetMode: 'time'
};
const accountContext = ref<AccountContext>(Object.assign({}, DEFAULT_ACCOUNT_CONTEXT));
const subAccountContexts = ref<AccountContext[]>([]);
const subAccountToDelete = ref<Account | null>(null);
const loadingError = ref<unknown | null>(null);
const showAccountCategorySheet = ref<boolean>(false);
const showAccountTypeSheet = ref<boolean>(false);
const showMoreActionSheet = ref<boolean>(false);
const showDeleteActionSheet = ref<boolean>(false);
function getAccountBalanceDate(balanceTime: number): string {
return formatUnixTimeToLongDate(getActualUnixTimeForStore(balanceTime, getTimezoneOffsetMinutes(), getBrowserTimezoneOffsetMinutes()));
}
function getAccountBalanceTime(balanceTime: number): string {
return formatUnixTimeToLongTime(getActualUnixTimeForStore(balanceTime, getTimezoneOffsetMinutes(), getBrowserTimezoneOffsetMinutes()));
}
function init(): void {
const query = props.f7route.query;
if (query['id']) {
loading.value = true;
editAccountId.value = query['id'];
accountsStore.getAccount({
accountId: editAccountId.value
}).then(response => {
setAccount(response);
subAccountContexts.value = [];
for (let i = 0; i < subAccounts.value.length; i++) {
subAccountContexts.value.push(Object.assign({}, DEFAULT_ACCOUNT_CONTEXT));
}
loading.value = false;
}).catch(error => {
if (error.processed) {
loading.value = false;
} else {
return 'Edit Account';
loadingError.value = error;
showToast(error.message || error);
}
},
saveButtonTitle() {
if (!this.editAccountId) {
return 'Add';
} else {
return 'Save';
}
},
allAccountTypes() {
return AccountType.all();
},
allAccountCategories() {
return this.$locale.getAllAccountCategories();
},
allAccountTypesArray() {
return this.$locale.getAllAccountTypes();
},
allAccountIcons() {
return ALL_ACCOUNT_ICONS;
},
allAccountColors() {
return ALL_ACCOUNT_COLORS;
},
allCurrencies() {
return this.$locale.getAllCurrencies();
},
allAvailableMonthDays() {
const allAvailableDays = [];
});
} else {
clientSessionId.value = generateRandomUUID();
loading.value = false;
}
}
allAvailableDays.push({
day: 0,
displayName: this.$t('Not set'),
});
function save(): void {
const router = props.f7router;
const problemMessage = getAccountOrSubAccountProblemMessage();
for (let i = 1; i <= 28; i++) {
allAvailableDays.push({
day: i,
displayName: this.$locale.getMonthdayShortName(i),
});
}
if (problemMessage) {
showAlert(problemMessage);
return;
}
return allAvailableDays;
},
allowedMinAmount() {
return TRANSACTION_MIN_AMOUNT;
},
allowedMaxAmount() {
return TRANSACTION_MAX_AMOUNT;
}
},
watch: {
'account.category': function (newValue, oldValue) {
this.chooseSuitableIcon(oldValue, newValue);
},
'account.type': function () {
if (this.subAccounts.length < 1) {
this.addSubAccount();
}
}
},
created() {
const self = this;
const query = self.f7route.query;
submitting.value = true;
showLoading(() => submitting.value);
if (query.id) {
self.loading = true;
accountsStore.saveAccount({
account: account.value,
subAccounts: subAccounts.value,
isEdit: !!editAccountId.value,
clientSessionId: clientSessionId.value
}).then(() => {
submitting.value = false;
hideLoading();
self.editAccountId = query.id;
self.accountsStore.getAccount({
accountId: self.editAccountId
}).then(account => {
self.account.from(account);
self.subAccounts = [];
if (account.childrenAccounts && account.childrenAccounts.length > 0) {
for (let i = 0; i < account.childrenAccounts.length; i++) {
const subAccount = self.accountsStore.generateNewSubAccountModel(self.account);
subAccount.from(account.childrenAccounts[i]);
subAccount.showIconSelectionSheet = false;
subAccount.showColorSelectionSheet = false;
subAccount.showBalanceSheet = false;
subAccount.showBalanceDateTimeSheet = false;
subAccount.balanceDateTimeSheetMode = 'time';
self.subAccounts.push(subAccount);
}
}
self.loading = false;
}).catch(error => {
if (error.processed) {
self.loading = false;
} else {
self.loadingError = error;
self.$toast(error.message || error);
}
});
if (!editAccountId.value) {
showToast('You have added a new account');
} else {
self.clientSessionId = generateRandomUUID();
self.loading = false;
showToast('You have saved this account');
}
},
methods: {
onPageAfterIn() {
this.$routeBackOnError(this.f7router, 'loadingError');
},
addSubAccount() {
if (this.account.type !== this.allAccountTypes.MultiSubAccounts.type) {
return;
}
const subAccount = this.accountsStore.generateNewSubAccountModel(this.account);
subAccount.showIconSelectionSheet = false;
subAccount.showColorSelectionSheet = false;
subAccount.showBalanceSheet = false;
subAccount.showBalanceDateTimeSheet = false;
subAccount.balanceDateTimeSheetMode = 'time';
router.back();
}).catch(error => {
submitting.value = false;
hideLoading();
this.subAccounts.push(subAccount);
},
removeSubAccount(subAccount, confirm) {
if (!subAccount) {
this.$alert('An error occurred');
return;
}
if (!error.processed) {
showToast(error.message || error);
}
});
}
if (!confirm) {
this.subAccountToDelete = subAccount;
this.showDeleteActionSheet = true;
return;
}
function addSubAccountAndContext(): void {
if (addSubAccount()) {
subAccountContexts.value.push(Object.assign({}, DEFAULT_ACCOUNT_CONTEXT));
}
}
this.showDeleteActionSheet = false;
this.subAccountToDelete = null;
function removeSubAccount(subAccount: Account | null, confirm: boolean): void {
if (!subAccount) {
showAlert('An error occurred');
return;
}
for (let i = 0; i < this.subAccounts.length; i++) {
if (this.subAccounts[i] === subAccount) {
this.subAccounts.splice(i, 1);
}
}
},
save() {
const self = this;
const router = self.f7router;
if (!confirm) {
subAccountToDelete.value = subAccount;
showDeleteActionSheet.value = true;
return;
}
let problemMessage = self.getInputEmptyProblemMessage(self.account, false);
showDeleteActionSheet.value = false;
subAccountToDelete.value = null;
if (!problemMessage && self.account.type === self.allAccountTypes.MultiSubAccounts.type) {
for (let i = 0; i < self.subAccounts.length; i++) {
problemMessage = self.getInputEmptyProblemMessage(self.subAccounts[i], true);
if (problemMessage) {
break;
}
}
}
if (problemMessage) {
self.$alert(problemMessage);
return;
}
self.submitting = true;
self.$showLoading(() => self.submitting);
self.accountsStore.saveAccount({
account: self.account,
subAccounts: self.subAccounts,
isEdit: !!self.editAccountId,
clientSessionId: self.clientSessionId
}).then(() => {
self.submitting = false;
self.$hideLoading();
if (!self.editAccountId) {
self.$toast('You have added a new account');
} else {
self.$toast('You have saved this account');
}
router.back();
}).catch(error => {
self.submitting = false;
self.$hideLoading();
if (!error.processed) {
self.$toast(error.message || error);
}
});
},
showDateTimeDialog(account, sheetMode) {
account.balanceDateTimeSheetMode = sheetMode;
account.showBalanceDateTimeSheet = true;
},
getCurrencyName(currencyCode) {
return this.$locale.getCurrencyName(currencyCode);
},
getAccountTypeName(accountType) {
return getNameByKeyValue(this.allAccountTypesArray, accountType, 'type', 'displayName');
},
getAccountCategoryName(accountCategory) {
return getNameByKeyValue(this.allAccountCategories, accountCategory, 'type', 'displayName');
},
getAccountCreditCardStatementDate(statementDate) {
return getNameByKeyValue(this.allAvailableMonthDays, statementDate, 'day', 'displayName');
},
getAccountBalance(account) {
return this.getDisplayCurrency(account.balance, account.currency);
},
getAccountBalanceDate(balanceTime) {
return this.$locale.formatUnixTimeToLongDate(this.userStore, getActualUnixTimeForStore(balanceTime, getTimezoneOffsetMinutes(), getBrowserTimezoneOffsetMinutes()));
},
getAccountBalanceTime(balanceTime) {
return this.$locale.formatUnixTimeToLongTime(this.userStore, getActualUnixTimeForStore(balanceTime, getTimezoneOffsetMinutes(), getBrowserTimezoneOffsetMinutes()));
},
getDisplayCurrency(value, currencyCode) {
return this.$locale.formatAmountWithCurrency(this.settingsStore, this.userStore, value, currencyCode);
},
isAccountSupportCreditCardStatementDate() {
return this.account && this.account.category === AccountCategory.CreditCard.type;
},
chooseSuitableIcon(oldCategory, newCategory) {
setAccountSuitableIcon(this.account, oldCategory, newCategory);
},
isInputEmpty() {
const isAccountEmpty = !!this.getInputEmptyProblemMessage(this.account, false);
if (isAccountEmpty) {
return true;
}
if (this.account.type === this.allAccountTypes.MultiSubAccounts.type) {
for (let i = 0; i < this.subAccounts.length; i++) {
const isSubAccountEmpty = !!this.getInputEmptyProblemMessage(this.subAccounts[i], true);
if (isSubAccountEmpty) {
return true;
}
}
}
return false;
},
getInputEmptyProblemMessage(account, isSubAccount) {
if (!isSubAccount && !account.category) {
return 'Account category cannot be blank';
} else if (!isSubAccount && !account.type) {
return 'Account type cannot be blank';
} else if (!account.name) {
return 'Account name cannot be blank';
} else if (account.type === this.allAccountTypes.SingleAccount.type && !account.currency) {
return 'Account currency cannot be blank';
} else {
return null;
}
for (let i = 0; i < subAccounts.value.length; i++) {
if (subAccounts.value[i] === subAccount) {
subAccounts.value.splice(i, 1);
subAccountContexts.value.splice(i, 1);
}
}
}
function showDateTimeDialog(accountContext: AccountContext, sheetMode: string): void {
accountContext.balanceDateTimeSheetMode = sheetMode;
accountContext.showBalanceDateTimeSheet = true;
}
function onPageAfterIn(): void {
routeBackOnError(props.f7router, loadingError);
}
watch(() => account.value.type, () => {
if (subAccounts.value.length < 1) {
addSubAccountAndContext();
}
});
init();
</script>
<style>