Skip to content

Open source personal finance application

feat(wallets): integrate Zod for wallet item validation and refactor wallet handling

Ilya Komichevfe57da72015c
diff --git a/app/components/wallets/Form.vue b/app/components/wallets/Form.vue
index 20e5390f..1a2a0c00 100644
--- a/app/components/wallets/Form.vue
+++ b/app/components/wallets/Form.vue
@@ -2,13 +2,12 @@
import { generateId } from '~~/utils/generateId'
import type { CurrencyCode } from '~/components/currencies/types'
-import type { WalletForm, WalletId, WalletItem, WalletType } from '~/components/wallets/types'
+import type { WalletId, WalletItem, WalletType } from '~/components/wallets/types'
import { errorEmo, random } from '~/assets/js/emo'
import UiToastContent from '~/components/ui/ToastContent.vue'
-import { icons, types } from '~/components/wallets/types'
+import { icons, types, walletItemSchema } from '~/components/wallets/types'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import { normalizeWalletItem } from '~/components/wallets/utils'
const props = defineProps<{
walletForm: WalletItem
@@ -44,7 +43,7 @@ const walletPlaceholder = computed(() => ({
/**
* Validate
*/
-function validate(values: WalletForm) {
+function validate(values: WalletItem) {
// name
if (!values.name) {
$toast(UiToastContent, {
@@ -98,7 +97,7 @@ async function onSave() {
await walletsStore.createOrUpdateWallet({
id: editWalletId,
- values: normalizeWalletItem(props.walletForm),
+ values: walletItemSchema.parse(props.walletForm),
})
emit('afterSave')
}
diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vue
index 15270fed..5d67e180 100644
--- a/app/components/wallets/page/List.vue
+++ b/app/components/wallets/page/List.vue
@@ -64,7 +64,7 @@ const selectedWalletsIds = computed<WalletId[]>(() => {
if (walletViewType.value === 'total')
return !wallet.isArchived && !wallet.isExcludeInTotal
- return wallet.type === walletViewType.value && !wallet.isArchived
+ return wallet.type === walletViewType.value
})
})
diff --git a/app/components/wallets/page/New.vue b/app/components/wallets/page/New.vue
index 49b3ae9a..9d486ad3 100644
--- a/app/components/wallets/page/New.vue
+++ b/app/components/wallets/page/New.vue
@@ -1,11 +1,11 @@
<script setup lang="ts">
-import type { WalletForm, WalletItem } from '~/components/wallets/types'
+import type { WalletItem } from '~/components/wallets/types'
-import { normalizeWalletItem } from '~/components/wallets/utils'
+import { walletItemSchema } from '~/components/wallets/types'
const { t } = useI18n()
const router = useRouter()
-const walletForm = ref(normalizeWalletItem())
+const walletForm = ref(walletItemSchema.parse({ type: 'cash' }))
useHead({
title: `${t('base.add')}: ${walletForm.value.name ? walletForm.value.name : t('wallets.form.name.label')}`,
@@ -21,7 +21,7 @@ useHead({
<WalletsForm
:walletForm="walletForm"
@afterSave="() => router.replace('/wallets')"
- @updateValue="(id: keyof WalletForm, value: WalletItem[keyof WalletItem]) => walletForm[id] = value"
+ @updateValue="(id: keyof WalletItem, value: WalletItem[keyof WalletItem]) => walletForm[id] = value"
/>
</UiPage>
</template>
diff --git a/app/components/wallets/page/id/Edit.vue b/app/components/wallets/page/id/Edit.vue
index 326f6e67..25719e59 100644
--- a/app/components/wallets/page/id/Edit.vue
+++ b/app/components/wallets/page/id/Edit.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
-import type { WalletForm, WalletId, WalletItem } from '~/components/wallets/types'
+import type { WalletId, WalletItem } from '~/components/wallets/types'
+import { walletItemSchema } from '~/components/wallets/types'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import { normalizeWalletItem } from '~/components/wallets/utils'
const { t } = useI18n()
const route = useRoute()
@@ -11,7 +11,7 @@ const walletsStore = useWalletsStore()
const walletId = computed(() => route.params.id) as Ref<WalletId>
const wallet = computed(() => walletsStore.items?.[walletId.value])
-const walletForm = ref(normalizeWalletItem(wallet.value))
+const walletForm = ref(walletItemSchema.parse(wallet.value))
useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form.name.label')}` })
</script>
@@ -32,7 +32,7 @@ useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form
:walletId
:walletForm
@afterSave="() => router.replace(`/wallets/${walletId}`)"
- @updateValue="(key: keyof WalletForm, value: WalletItem[keyof WalletItem]) => walletForm[key] = value"
+ @updateValue="(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) => walletForm[key] = value"
/>
</UiPage>
</template>
diff --git a/app/components/wallets/types.ts b/app/components/wallets/types.ts
index 820ee290..1f623b5c 100644
--- a/app/components/wallets/types.ts
+++ b/app/components/wallets/types.ts
@@ -1,7 +1,10 @@
-import type { DeepPartial } from '~~/utils/types'
+import { z } from 'zod/v4'
import type { CurrencyCode } from '~/components/currencies/types'
+import { random } from '~/assets/js/emo'
+import { colorsArray } from '~/components/color/colors'
+
export const types = [
'cash',
'credit',
@@ -33,56 +36,65 @@ export const icons: Record<WalletType, string> = {
deposit: 'lucide:diamond-percent',
} as const
-export type WalletItemBase = {
- color: string
- currency: CurrencyCode
- desc?: string
- editedAt: number
- isArchived?: boolean
- isExcludeInTotal?: boolean
- isWithdrawal?: boolean
- name: string
- order: number
-}
-
-export type WalletItemSimple = WalletItemBase & {
- type: Exclude<WalletType, 'credit'>
-}
-
-type WalletItemCredit = WalletItemBase & {
- creditLimit: number
- type: 'credit'
-}
-
-export type WalletItem = WalletItemSimple | WalletItemCredit
-
-export type WalletItemDirty = WalletItem & Partial<{
- archived: boolean
- creditLimit: number
- description: string
- edited: number
- isCash: boolean
- isCashless: boolean
- isCredit: boolean
- isDebt: boolean
- isDeposit: boolean
- isExcludeTotal: boolean
- withdrawal: boolean
-}>
-
-export type WalletForm = DeepPartial<WalletItem> & {
- creditLimit?: number | null
- description?: string | null
-}
-
-export type Wallets = Record<WalletId, WalletItem>
-export type WalletsDirty = Record<WalletId, WalletItemDirty>
-
+export const walletBaseSchema = z.object({
+ color: z.string().default(() => random(colorsArray)),
+ currency: z.string().default('USD'),
+ desc: z.string().default(''),
+ editedAt: z.number().default(() => new Date().getTime()),
+ isArchived: z.boolean().default(false),
+ isExcludeInTotal: z.boolean().default(false),
+ isWithdrawal: z.boolean().default(false),
+ name: z.string().default(''),
+ order: z.number().default(1),
+})
+
+export const walletTypeSchema = z.enum(types)
+
+export const walletItemSchema = z.discriminatedUnion('type', [
+ z.object({
+ ...walletBaseSchema.shape,
+ creditLimit: z.number().default(0),
+ type: z.literal(types.find(t => t === 'credit')),
+ }),
+ z.object({
+ ...walletBaseSchema.shape,
+ type: z.enum(types.filter(t => t !== 'credit')),
+ }),
+])
+
+// TODO: Deprecate this
+export const walletDirtySchema = z.object({
+ archived: z.boolean().optional(),
+ color: z.string(),
+ creditLimit: z.union([z.string(), z.number()]).transform(val => Number(val)).optional(),
+ currency: z.string(),
+ desc: z.string().optional(),
+ description: z.string().optional(),
+ edited: z.number().optional(),
+ editedAt: z.number().optional(),
+ isArchived: z.boolean().optional(),
+ isCash: z.boolean().optional(),
+ isCashless: z.boolean().optional(),
+ isCredit: z.boolean().optional(),
+ isDebt: z.boolean().optional(),
+ isDeposit: z.boolean().optional(),
+ isExcludeInTotal: z.boolean().optional(),
+ isWithdrawal: z.boolean().optional(),
+ name: z.string(),
+ order: z.number(),
+ type: walletTypeSchema.optional(),
+ withdrawal: z.boolean().optional(),
+})
+
+export type WalletItem = z.infer<typeof walletItemSchema>
+export type WalletItemDirty = z.infer<typeof walletDirtySchema>
export type WalletItemComputed = WalletItem & {
amount: number
rate?: number
}
+export type Wallets = Record<WalletId, WalletItem>
+export type WalletsDirty = Record<WalletId, WalletItemDirty>
export type WalletsComputed = Record<WalletId, WalletItemComputed>
export type WalletsGroupedBy = 'type' | 'currency' | 'none'
diff --git a/app/components/wallets/useWalletsStore.ts b/app/components/wallets/useWalletsStore.ts
index fadae09c..da505824 100644
--- a/app/components/wallets/useWalletsStore.ts
+++ b/app/components/wallets/useWalletsStore.ts
@@ -5,14 +5,14 @@ import { uniqueElementsBy } from '~~/utils/simple'
import type { CurrencyCode } from '~/components/currencies/types'
import type { TrnId } from '~/components/trns/types'
-import type { WalletId, WalletItem, WalletItemComputed, Wallets, WalletsComputed } from '~/components/wallets/types'
+import type { WalletId, WalletItem, WalletItemComputed, Wallets, WalletsComputed, WalletsDirty } from '~/components/wallets/types'
import { getAmountInRate, getTotal } from '~/components/amount/getTotal'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
import { useDemo } from '~/components/demo/useDemo'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useUserStore } from '~/components/user/useUserStore'
-import { normalizeWallets } from '~/components/wallets/utils'
+import { normalizeWalletItem } from '~/components/wallets/utils'
export const useWalletsStore = defineStore('wallets', () => {
const trnsStore = useTrnsStore()
@@ -28,6 +28,20 @@ export const useWalletsStore = defineStore('wallets', () => {
}
function setWallets(values: Wallets | null) {
+ const normalizeWallets = (items: WalletsDirty): Wallets => {
+ return Object.entries(items).reduce((acc, [walletId, wallet]) => {
+ const normalizedWallet = normalizeWalletItem(wallet)
+ acc[walletId] = normalizedWallet.values
+ if (normalizedWallet.error && !isDemo) {
+ createOrUpdateWallet({
+ id: walletId,
+ values: normalizedWallet.values as WalletItem,
+ })
+ }
+ return acc
+ }, {} as Wallets)
+ }
+
const wallets = values ? normalizeWallets(values) : null
items.value = wallets
localforage.setItem('finapp.wallets', deepUnref(wallets))
@@ -52,7 +66,7 @@ export const useWalletsStore = defineStore('wallets', () => {
async function saveWalletsOrder(ids: WalletId[]) {
if (isDemo.value) {
- return await sortDemoWallets(ids, items.value ?? {})
+ return await sortDemoWallets(ids, items.value || {})
}
const updates = ids.reduce(
@@ -79,9 +93,9 @@ export const useWalletsStore = defineStore('wallets', () => {
const { sum, sumTransfers } = getTotal({
trnsIds,
- trnsItems: trnsStore.items ?? {},
+ trnsItems: trnsStore.items || {},
walletsIds: [walletId],
- walletsItems: items.value ?? {},
+ walletsItems: items.value || {},
})
return sum + sumTransfers
diff --git a/app/components/wallets/utils.ts b/app/components/wallets/utils.ts
index 2c6e835a..681c6de6 100644
--- a/app/components/wallets/utils.ts
+++ b/app/components/wallets/utils.ts
@@ -1,41 +1,70 @@
-import type { WalletForm, WalletItem, WalletItemBase, WalletItemDirty, Wallets, WalletsDirty } from '~/components/wallets/types'
-
-import { random } from '~/assets/js/emo'
-import { colorsArray } from '~/components/color/colors'
-
-export function normalizeWalletItem(wallet?: WalletItemDirty | WalletForm) {
- const walletBase: WalletItemBase = {
- color: wallet?.color ?? random(colorsArray),
- currency: wallet?.currency ?? 'USD',
- desc: wallet?.desc ?? wallet?.description ?? '',
- editedAt: wallet?.editedAt ?? wallet?.edited ?? new Date().getTime(),
- isArchived: wallet?.isArchived ?? wallet?.archived ?? false,
- isExcludeInTotal: wallet?.isExcludeInTotal ?? false,
- isWithdrawal: wallet?.isWithdrawal ?? wallet?.withdrawal ?? false,
- name: wallet?.name ?? '',
- order: wallet?.order ?? 1,
+import type { WalletItemDirty } from '~/components/wallets/types'
+
+import { walletBaseSchema, walletDirtySchema, walletItemSchema } from '~/components/wallets/types'
+
+export function normalizeWalletItem(wallet: WalletItemDirty) {
+ const parsedGood = walletItemSchema.safeParse(wallet)
+ const parsed = walletDirtySchema.safeParse(wallet)
+
+ if (parsedGood.success) {
+ return {
+ error: false,
+ values: wallet,
+ }
}
- const walletItem: WalletItem = (wallet?.isCredit || wallet?.type === 'credit')
- ? { ...walletBase, creditLimit: +(wallet?.creditLimit ?? 0), type: 'credit' }
- : { ...walletBase, type: wallet?.type ?? 'cash' }
-
- // Set type based on the wallet type property
- if (wallet?.type === 'cash' || wallet?.isCash)
- walletItem.type = 'cash'
- else if (wallet?.type === 'cashless' || wallet?.isCashless)
- walletItem.type = 'cashless'
- else if (wallet?.type === 'debt' || wallet?.isDebt)
- walletItem.type = 'debt'
- else if (wallet?.type === 'deposit' || wallet?.isDeposit)
- walletItem.type = 'deposit'
-
- return walletItem
-}
+ if (!parsed.success) {
+ return {
+ error: false,
+ values: walletItemSchema.parse({ type: 'cash' }),
+ }
+ }
+
+ const data = parsed.data
+ const base = walletBaseSchema.parse({
+ color: data.color,
+ currency: data.currency,
+ desc: data.desc ?? data.description,
+ editedAt: data.editedAt ?? data.edited,
+ isArchived: data.isArchived ?? data.archived,
+ isExcludeInTotal: data.isExcludeInTotal,
+ isWithdrawal: data.isWithdrawal ?? data.withdrawal,
+ name: data.name,
+ order: data.order,
+ })
-export function normalizeWallets(items: WalletsDirty): Wallets {
- return Object.entries(items).reduce((acc, [walletId, wallet]) => {
- acc[walletId] = normalizeWalletItem(wallet)
- return acc
- }, {} as Wallets)
+ let type = data.type
+ if (!type) {
+ if (data.isCredit)
+ type = 'credit'
+ else if (data.isCash)
+ type = 'cash'
+ else if (data.isCashless)
+ type = 'cashless'
+ else if (data.isDebt)
+ type = 'debt'
+ else if (data.isDeposit)
+ type = 'deposit'
+ else type = 'cash'
+ }
+
+ const normalizeWalletItem = walletItemSchema.parse({
+ ...base,
+ ...(type === 'credit'
+ ? { creditLimit: +(data.creditLimit ?? 0) }
+ : { type }
+ ),
+ })
+
+ if (!parsedGood.success) {
+ return {
+ error: true,
+ values: normalizeWalletItem,
+ }
+ }
+
+ return {
+ error: false,
+ values: normalizeWalletItem,
+ }
}