Skip to content

Open source personal finance application

refactor: optimize date, amount, stat, trns, and categories modules

Ilya Komichev5098c2bce0b1
diff --git a/CLAUDE.md b/CLAUDE.md
index ccd3daf4..79fef8a7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,15 +9,15 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Conve
## Commands
-- `pnpm dev` — Nuxt dev server on port 3050
-- `pnpm dev:convex` — Convex backend (watches and auto-deploys changes)
+- `pnpm dev` - Nuxt dev server on port 3050
+- `pnpm dev:convex` - Convex backend (watches and auto-deploys changes)
- Both must run simultaneously in separate terminals
-- `pnpm build` — SPA build (`nuxt build`)
-- `pnpm generate` — static generation (`nuxt generate`)
-- `pnpm lint` / `pnpm lint:fix` — ESLint
-- `pnpm test` — Vitest
-- `pnpm docs:dev` — docs dev server
-- `pnpm docs:build` — build docs site
+- `pnpm build` - SPA build (`nuxt build`)
+- `pnpm generate` - static generation (`nuxt generate`)
+- `pnpm lint` / `pnpm lint:fix` - ESLint
+- `pnpm test` - Vitest
+- `pnpm docs:dev` - docs dev server
+- `pnpm docs:build` - build docs site
## Project Structure
@@ -37,18 +37,18 @@ See [Architecture](../docs/content/en/3.technical/1.architecture.md) for detaile
- @nuxt/ui defines CSS vars in `@layer theme`
- Dynamic theme (radius, colors) is applied via `useHead()` in `app.vue` with `tagPriority: -2`
-- **Do NOT** set `--ui-radius` or `--ui-primary` in `theme.css` — non-layered CSS loads after `useHead()` and overrides it
+- **Do NOT** set `--ui-radius` or `--ui-primary` in `theme.css` - non-layered CSS loads after `useHead()` and overrides it
- Radius uses `??` (not `||`) to allow `0`: `${appConfig.theme.radius ?? 0.375}`
## Store Pattern
All Pinia stores (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`) follow the same pattern:
-- `items: shallowRef` — reactive state (shallow for performance)
-- `init()` — fetch from Convex → `mergeOfflineOps` → `set`
-- `set(data)` — `items.value = data` + `debouncedPersist` (300ms)
-- `save({ id, values })` — optimistic UI → `pushSaveOp` → fire mutation (no await)
-- `delete(id)` — optimistic UI → `pushDeleteOp` → fire mutation (no await)
+- `items: shallowRef` - reactive state (shallow for performance)
+- `init()` - fetch from Convex → `mergeOfflineOps` → `set`
+- `set(data)` - `items.value = data` + `debouncedPersist` (300ms)
+- `save({ id, values })` - optimistic UI → `pushSaveOp` → fire mutation (no await)
+- `delete(id)` - optimistic UI → `pushDeleteOp` → fire mutation (no await)
Mutation result: `.then()` removes offline op + remaps frontend ID → `.catch()` shows error toast.
@@ -62,7 +62,7 @@ New entities get temporary IDs with `local_` prefix (e.g., `local_a1b2c3`). `isL
- `TrnType` enum in `convex/validators.ts` (re-exported from `convex/shared.ts`): Expense (0), Income (1), Transfer (2)
- Adjustment is determined by `categoryId === 'adjustment'`, NOT by `TrnType`. It uses Expense or Income type, excluded from income/expense statistics
- Auth: `@convex-dev/better-auth` with `cors: true` in `http.ts`
-- Generated types in `convex/_generated/` — do not edit
+- Generated types in `convex/_generated/` - do not edit
- `convex/tsconfig.json` is separate from the app tsconfig
### Convex Client Access
@@ -79,27 +79,27 @@ New entities get temporary IDs with `local_` prefix (e.g., `local_a1b2c3`). `isL
Auth uses Better Auth with `convexClient()` and `crossDomainClient()` plugins (`composables/useAuth.ts`).
**Convex auth lifecycle** (`plugins/convex.ts`):
-1. Eagerly call `client.setAuth(fetchToken)` if `hasAuthCookie()` && online — starts token fetch in parallel with session resolution
-2. `fetchToken` calls `authClient.convex.token()` — the `crossDomainClient` plugin handles cookie forwarding automatically
+1. Eagerly call `client.setAuth(fetchToken)` if `hasAuthCookie()` && online - starts token fetch in parallel with session resolution
+2. `fetchToken` calls `authClient.convex.token()` - the `crossDomainClient` plugin handles cookie forwarding automatically
3. `authReadyPromise` resolves when the first token fetch completes (success or failure); consumers (`loadDataFromDB`) await this before issuing queries
-4. Session watch acts only on definitive results — ignores `isPending` and `error` states to prevent logout on network failures
+4. Session watch acts only on definitive results - ignores `isPending` and `error` states to prevent logout on network failures
5. `online` event re-creates `authReadyPromise` and calls `setAuth()` for fresh token
-6. `ensureConvexAuth()` — called from callback page to set auth BEFORE SPA navigation
+6. `ensureConvexAuth()` - called from callback page to set auth BEFORE SPA navigation
-**Auth cookie** (`composables/useAuthCookie.ts`): `finapp.localAuthUid` cookie (document.cookie, 1yr max-age) — fast synchronous check for auth state. Not a security token, just a hint for middleware and plugin to skip network calls.
+**Auth cookie** (`composables/useAuthCookie.ts`): `finapp.localAuthUid` cookie (document.cookie, 1yr max-age) - fast synchronous check for auth state. Not a security token, just a hint for middleware and plugin to skip network calls.
### Convex CLI Notes
-- **Targeting prod**: always use the `--prod` flag (`npx convex run --prod`, `npx convex export --prod`). Do NOT use `CONVEX_DEPLOYMENT` env var — `.env.local` overrides env vars, so the CLI silently hits dev instead of prod
+- **Targeting prod**: always use the `--prod` flag (`npx convex run --prod`, `npx convex export --prod`). Do NOT use `CONVEX_DEPLOYMENT` env var - `.env.local` overrides env vars, so the CLI silently hits dev instead of prod
- Convex rejects hyphens in directory names (use underscores: `test_utils/`)
-- Files with multiple dots (e.g., `setup.helper.ts`) are auto-skipped by Convex bundler — useful for test helpers
+- Files with multiple dots (e.g., `setup.helper.ts`) are auto-skipped by Convex bundler - useful for test helpers
- Deploy with `--typecheck=disable` if there are pre-existing TS errors in Convex functions
## Local Development Setup
1. Install dependencies: `pnpm install`
-2. Start Convex backend: `pnpm dev:convex` — connects to dev deployment, watches and auto-deploys changes
-3. Start Nuxt frontend: `pnpm dev` — runs on http://localhost:3050
+2. Start Convex backend: `pnpm dev:convex` - connects to dev deployment, watches and auto-deploys changes
+3. Start Nuxt frontend: `pnpm dev` - runs on http://localhost:3050
4. Both servers must run simultaneously (in separate terminals)
### First-time setup
@@ -118,24 +118,24 @@ npx convex env set OPENEXCHANGERATES_APP_ID <value>
### Env files
-- `.env` — dev deployment values, read by Nuxt (default `--dotenv`)
-- `.env.local` — auto-created by `convex dev`, used by Convex CLI (gitignored)
-- `.env.prod` — prod deployment values, used by `pnpm dev:prod`
+- `.env` - dev deployment values, read by Nuxt (default `--dotenv`)
+- `.env.local` - auto-created by `convex dev`, used by Convex CLI (gitignored)
+- `.env.prod` - prod deployment values, used by `pnpm dev:prod`
All `.env*` files are gitignored except `.env.example`.
### Nuxt env vars (in `.env` / `.env.prod`)
-- `CONVEX_DEPLOYMENT` — deployment identifier (used by Convex CLI)
-- `VITE_CONVEX_URL` — Convex deployment URL (Nuxt frontend)
-- `VITE_CONVEX_SITE_URL` — Convex site URL (Nuxt auth client)
+- `CONVEX_DEPLOYMENT` - deployment identifier (used by Convex CLI)
+- `VITE_CONVEX_URL` - Convex deployment URL (Nuxt frontend)
+- `VITE_CONVEX_SITE_URL` - Convex site URL (Nuxt auth client)
### Convex backend env vars (set via `npx convex env set`)
-- `BETTER_AUTH_SECRET` — secret key for Better Auth (**required** — without it all auth endpoints including CORS preflight will fail)
-- `APP_URL` — app URL for cross-domain auth and CORS/trustedOrigins
-- `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` — Google OAuth
-- `OPENEXCHANGERATES_APP_ID` — exchange rates API
+- `BETTER_AUTH_SECRET` - secret key for Better Auth (**required** - without it all auth endpoints including CORS preflight will fail)
+- `APP_URL` - app URL for cross-domain auth and CORS/trustedOrigins
+- `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` - Google OAuth
+- `OPENEXCHANGERATES_APP_ID` - exchange rates API
## Key Files
diff --git a/app/components/amount/getTotal.ts b/app/components/amount/getTotal.ts
index 4850ad0a..e9c39829 100644
--- a/app/components/amount/getTotal.ts
+++ b/app/components/amount/getTotal.ts
@@ -19,13 +19,13 @@ export function getAmountInRate({
return amount
if (baseCurrencyCode !== currencyCode)
- return amount / (rates[currencyCode] || 1) * (rates[baseCurrencyCode] || 1)
+ return amount / (rates[currencyCode] ?? 1) * (rates[baseCurrencyCode] ?? 1)
return amount
}
type TotalProps = {
- baseCurrencyCode?: string
+ baseCurrencyCode?: CurrencyCode
rates?: Rates
trnsIds?: TrnId[]
trnsItems: Record<TrnId, TrnItem>
@@ -69,15 +69,14 @@ export function getTotal(props: TotalProps): TotalReturns {
// Transaction
if (trn.type === TrnType.Income || trn.type === TrnType.Expense) {
- // Adjustment: affects wallet balance but not income/expense statistics
if (trn.categoryId === 'adjustment') {
const wallet = walletsItems[trn.walletId]
- const amount = getAmount(trn.amount, wallet?.currency || 'USD')
+ const amount = getAmount(trn.amount, wallet?.currency ?? 'USD')
adjustment += trn.type === TrnType.Income ? amount : -amount
continue
}
const wallet = walletsItems[trn.walletId]
- const sum = getAmount(trn.amount, wallet?.currency || 'USD')
+ const sum = getAmount(trn.amount, wallet?.currency ?? 'USD')
if (trn.type === TrnType.Income)
income += sum
@@ -130,7 +129,7 @@ export function getTotal(props: TotalProps): TotalReturns {
* For each wallet, returns: income - expense + transfers + adjustments.
*/
export function getWalletsTotals(props: {
- baseCurrencyCode?: string
+ baseCurrencyCode?: CurrencyCode
rates?: Rates
trnsItems: Trns
walletsItems: Wallets
diff --git a/app/components/amount/useAmount.ts b/app/components/amount/useAmount.ts
index aa5fa035..cb74e701 100644
--- a/app/components/amount/useAmount.ts
+++ b/app/components/amount/useAmount.ts
@@ -13,25 +13,18 @@ export function useAmount() {
const walletsStore = useWalletsStore()
const trnsStore = useTrnsStore()
- function getAmountInBaseRate({ amount, currencyCode, noFormat }: {
+ function getAmountInBaseRate({ amount, currencyCode }: {
amount: number
currencyCode: CurrencyCode
- noFormat?: boolean
}, { precision }: { precision?: number } = {}) {
- const rates = currenciesStore.rates
- const baseCurrencyCode = currenciesStore.base
-
const amountInBaseRate = getAmountInRate({
amount,
- baseCurrencyCode,
+ baseCurrencyCode: currenciesStore.base,
currencyCode,
- rates,
+ rates: currenciesStore.rates,
})
- if (noFormat)
- return `${amountInBaseRate}`
-
- return formatAmount(+amountInBaseRate, baseCurrencyCode, { precision })
+ return formatAmount(amountInBaseRate, currenciesStore.base, { precision })
}
const baseCurrencyCode = computed(() => currenciesStore.base)
diff --git a/app/components/categories/useCategoriesStore.ts b/app/components/categories/useCategoriesStore.ts
index f4b64a85..5e04ca85 100644
--- a/app/components/categories/useCategoriesStore.ts
+++ b/app/components/categories/useCategoriesStore.ts
@@ -66,8 +66,8 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value)
return []
- return Object.keys(items.value)
- .filter(id => items.value?.[id]?.parentId === 0 && id !== 'transfer' && id !== 'adjustment')
+ return categoriesIds.value
+ .filter(id => items.value[id]?.parentId === 0 && id !== 'transfer' && id !== 'adjustment')
.sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
})
@@ -97,19 +97,9 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value)
return []
- return Object.keys(items.value)
+ return categoriesIds.value
.filter(id => items.value[id]?.showInQuickSelector)
- .sort((a, b) => {
- const catA = items.value[a]!
- const catB = items.value[b]!
- const parentNameA = items.value[catA.parentId]?.name || ''
- const parentNameB = items.value[catB.parentId]?.name || ''
-
- if (parentNameA !== parentNameB)
- return parentNameA.localeCompare(parentNameB)
-
- return catA.name.localeCompare(catB.name)
- })
+ .sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
})
const recentCategoriesIds = computed(() => {
@@ -122,8 +112,8 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
// Track most recent date per category (single pass)
const latestDateByCategory = new Map<CategoryId, number>()
- for (const trnId of Object.keys(trnsItems ?? {})) {
- const trn = trnsItems?.[trnId]
+ for (const trnId in trnsItems) {
+ const trn = trnsItems[trnId]
if (!trn || trn.type === TrnType.Transfer || trn.categoryId === 'adjustment')
continue
@@ -134,31 +124,27 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
}
// Filter valid categories and pick top N by most recent usage
- const sortedEntries: [CategoryId, number][] = [...latestDateByCategory.entries()].toSorted(([, dateA], [, dateB]) => dateB - dateA)
+ const sortedEntries = [...latestDateByCategory.entries()].toSorted(([, dateA], [, dateB]) => dateB - dateA)
- const recentIds = sortedEntries.reduce<CategoryId[]>((acc, [categoryId]) => {
- if (acc.length >= maxCategories)
- return acc
+ const recentIds: CategoryId[] = []
+ for (const [categoryId] of sortedEntries) {
+ if (recentIds.length >= maxCategories)
+ break
const category = items.value[categoryId]
if (!category || !category.showInLastUsed || categoryId === 'transfer' || favoriteIds.has(categoryId))
- return acc
+ continue
- acc.push(categoryId)
- return acc
- }, [])
+ recentIds.push(categoryId)
+ }
return recentIds
.sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
})
- const categoriesIdsForTrnValues = computed<CategoryId[]>(() => {
- return categoriesIds.value.filter((id) => {
- if (id === 'transfer')
- return false
- return !hasChildren(id)
- })
- })
+ const categoriesIdsForTrnValues = computed<CategoryId[]>(() =>
+ transactibleIds.value.filter(id => id !== 'transfer'),
+ )
const debouncedPersist = createDebouncedPersist<Categories>(STORAGE_KEYS.categories)
@@ -199,27 +185,18 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value)
return []
- const children = Object.keys(items.value)
+ return Object.keys(items.value)
.filter(id => items.value[id]?.parentId === categoryId)
-
- if (!children.length)
- return []
-
- return children
.sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
}
function getChildrenIdsOrParent(categoryId: CategoryId) {
- if (!hasItems.value)
- return []
-
- const children = Object.keys(items.value)
- .filter(id => items.value[id]?.parentId === categoryId)
+ const children = getChildrenIds(categoryId)
return children.length ? children : [categoryId]
}
function getTransactibleIds(ids?: CategoryId[]) {
- return getTransactibleCategoriesIds(items.value ?? {}, ids)
+ return getTransactibleCategoriesIds(items.value, ids)
}
function isTransactible(categoryId: CategoryId) {
@@ -228,7 +205,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
function applyOptimisticUpdate(id: CategoryId, categoryValues: CategoryItem, isUpdateChildCategoriesColor: boolean, categoryChildIds: CategoryId[]) {
const updatedItems: Categories = {
- ...(items.value ?? {}),
+ ...items.value,
[id]: categoryValues,
}
@@ -295,7 +272,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
return
// Optimistic UI
- const categories = { ...(items.value ?? {}) }
+ const categories = { ...items.value }
delete categories[id]
setCategories(categories)
diff --git a/app/components/categories/utils.ts b/app/components/categories/utils.ts
index b621dbe7..40505b48 100644
--- a/app/components/categories/utils.ts
+++ b/app/components/categories/utils.ts
@@ -1,8 +1,11 @@
import type { Categories, CategoryId, CategoryItem } from '~/components/categories/types'
export function getTransactibleCategoriesIds(items: Categories, ids?: CategoryId[]) {
+ if (!items)
+ return []
+
const childrenMap = new Map<CategoryId, CategoryId[]>()
- for (const id of Object.keys(items ?? {})) {
+ for (const id of Object.keys(items)) {
const parentId = items[id]?.parentId
if (parentId) {
const pid = String(parentId)
@@ -15,8 +18,8 @@ export function getTransactibleCategoriesIds(items: Categories, ids?: CategoryId
const seen = new Set<CategoryId>()
const result: CategoryId[] = []
- for (const id of ids ?? Object.keys(items ?? [])) {
- const category = items?.[id]
+ for (const id of ids ?? Object.keys(items)) {
+ const category = items[id]
const children = childrenMap.get(id)
if (category?.parentId === 0 && children?.length) {
for (const childId of children) {
@@ -48,7 +51,7 @@ export function getParentCategoryIdOrUndefined(items: Categories, categoryId: Ca
}
export function compareCategoriesByParentAndName(a: CategoryItem, b: CategoryItem, items: Categories): number {
- const parentNameA = items[a.parentId]?.name || ''
- const parentNameB = items[b.parentId]?.name || ''
+ const parentNameA = items[a.parentId]?.name ?? ''
+ const parentNameB = items[b.parentId]?.name ?? ''
return parentNameA.localeCompare(parentNameB) || a.name.localeCompare(b.name)
}
diff --git a/app/components/date/statDateParams.test.ts b/app/components/date/statDateParams.test.ts
index 09110ce7..e26d979e 100644
--- a/app/components/date/statDateParams.test.ts
+++ b/app/components/date/statDateParams.test.ts
@@ -79,13 +79,12 @@ describe('parseStatDateQueryParams', () => {
expect(result).toEqual(base)
})
- it('skips zero values for numeric fields', () => {
+ it('applies zero values for numeric fields', () => {
const result = parseStatDateQueryParams(
{ rangeDuration: '0' },
base,
)
- // 0 is falsy, so the if-check skips it
- expect(result.rangeDuration).toBe(base.rangeDuration)
+ expect(result.rangeDuration).toBe(0)
})
})
diff --git a/app/components/date/statDateParams.ts b/app/components/date/statDateParams.ts
index 40ae45f5..b4b54af2 100644
--- a/app/components/date/statDateParams.ts
+++ b/app/components/date/statDateParams.ts
@@ -43,17 +43,17 @@ export function parseStatDateQueryParams(
const data = parsed.data
const result = { ...currentParams }
- if (data.intervalsBy)
+ if (data.intervalsBy !== undefined)
result.intervalsBy = data.intervalsBy
- if (data.intervalsDuration)
+ if (data.intervalsDuration !== undefined)
result.intervalsDuration = data.intervalsDuration
- if (data.intervalSelected)
+ if (data.intervalSelected !== undefined)
result.intervalSelected = data.intervalSelected
- if (data.rangeBy)
+ if (data.rangeBy !== undefined)
result.rangeBy = data.rangeBy
- if (data.rangeDuration)
+ if (data.rangeDuration !== undefined)
result.rangeDuration = data.rangeDuration
- if (data.rangeOffset)
+ if (data.rangeOffset !== undefined)
result.rangeOffset = data.rangeOffset
if (data.isShowMaxRange !== undefined)
result.isShowMaxRange = data.isShowMaxRange
@@ -76,15 +76,10 @@ export function computeDateRange(
return params.customDate
}
- if (params.isShowMaxRange && params.isSkipEmpty) {
- return { ...maxRange }
- }
-
- if (params.isShowMaxRange && !params.isSkipEmpty) {
- return {
- end: getEndOf(new Date(now), params.rangeBy).getTime(),
- start: maxRange.start,
- }
+ if (params.isShowMaxRange) {
+ return params.isSkipEmpty
+ ? { ...maxRange }
+ : { end: getEndOf(new Date(now), params.rangeBy).getTime(), start: maxRange.start }
}
return calculateIntervalInRange({
diff --git a/app/components/date/types.ts b/app/components/date/types.ts
index be10070f..4c8109d3 100644
--- a/app/components/date/types.ts
+++ b/app/components/date/types.ts
@@ -36,7 +36,8 @@ export type StatDateParamsQuery = {
export type IntervalsInRangeProps = Pick<StatDateParams, 'intervalsBy' | 'intervalsDuration'> & {
range: Range
-} & Pick<StatDateParams, 'rangeOffset'>
+ rangeOffset?: number
+}
type Interval = Pick<StatDateParams, 'rangeDuration' | 'rangeBy'>
export type Grouped = Pick<StatDateParams, 'intervalsBy' | 'intervalsDuration'>
diff --git a/app/components/date/useDateFormats.ts b/app/components/date/useDateFormats.ts
index f71a3108..68923649 100644
--- a/app/components/date/useDateFormats.ts
+++ b/app/components/date/useDateFormats.ts
@@ -14,10 +14,10 @@ export function useDateFormats() {
return
const filterDate = new Date(date)
- const from = getStartOf(filterDate, periodName).getTime()
- const until = getEndOf(filterDate, periodName).getTime()
+ const start = getStartOf(filterDate, periodName).getTime()
+ const end = getEndOf(filterDate, periodName).getTime()
- return { from, until }
+ return { end, start }
}
function formatDate(value: number, type: 'trnItem' | 'full') {
@@ -34,12 +34,12 @@ export function useDateFormats() {
full: formatByLocale(date, 'dd.MM.yyyy HH:mm', locale.value),
month: formatByLocale(date, 'MMM', locale.value),
week: formatByLocale(date, 'dd.MM', locale.value),
- weekday: `${diff < 2 ? `${formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date, type: 'start' })}, ` : ''} ${formatByLocale(date, 'EEEE', locale.value)}`,
+ weekday: `${diff < 2 ? `${formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date })}, ` : ''} ${formatByLocale(date, 'EEEE', locale.value)}`,
year: formatByLocale(date, 'yyyy', locale.value),
}
case 'trnItem':
- return formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date, type: 'start' })
+ return formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date })
}
}
diff --git a/app/components/date/useStatDate.ts b/app/components/date/useStatDate.ts
index a23d3290..4f3bb147 100644
--- a/app/components/date/useStatDate.ts
+++ b/app/components/date/useStatDate.ts
@@ -43,7 +43,6 @@ export function useStatDate({
intervalsBy: params.value.intervalsBy,
intervalsDuration: params.value.intervalsDuration,
range: range.value,
- rangeOffset: params.value.rangeOffset,
}))
const selectedInterval = computed(() => intervalsInRange.value[params.value.intervalSelected])
@@ -71,10 +70,7 @@ export function useStatDate({
function setRangeByCalendar(r: Range) {
resetCustomAndMaxRangeParams()
- params.value.customDate = {
- end: new Date(r.end).getTime(),
- start: new Date(r.start).getTime(),
- }
+ params.value.customDate = { ...r }
params.value.rangeOffset = 0
params.value.rangeBy = 'day'
diff --git a/app/components/date/utils.ts b/app/components/date/utils.ts
index d1abc7b9..acfeaa4c 100644
--- a/app/components/date/utils.ts
+++ b/app/components/date/utils.ts
@@ -1,12 +1,22 @@
import type { CalendarDate } from '@internationalized/date'
import { getLocalTimeZone, parseDate, today } from '@internationalized/date'
+import type { Duration } from 'date-fns'
import { differenceInDays, endOfDay, endOfMonth, endOfWeek, endOfYear, format, formatISO, startOfDay, startOfMonth, startOfWeek, startOfYear, sub } from 'date-fns'
import { ru } from 'date-fns/locale'
-import type { IntervalsInRangeProps, Range } from '~/components/date/types'
+import type { IntervalsInRangeProps, Period, Range } from '~/components/date/types'
import type { LocaleSlug } from '~/components/locale/types'
+export function toDuration(period: Period, value: number): Duration {
+ switch (period) {
+ case 'day': return { days: value }
+ case 'week': return { weeks: value }
+ case 'month': return { months: value }
+ case 'year': return { years: value }
+ }
+}
+
export function formatByLocale(date: Date, formatter: string, locale?: LocaleSlug) {
const formatOptions = locale === 'ru' ? { locale: ru } : {}
return format(date, formatter, formatOptions)
@@ -14,20 +24,18 @@ export function formatByLocale(date: Date, formatter: string, locale?: LocaleSlu
export function calculateIntervalInRange(params: IntervalsInRangeProps): Range {
const offset = (params.rangeOffset ?? 0) * params.intervalsDuration
- const baseDate = sub(new Date(params.range.end), {
- [`${params.intervalsBy}s`]: offset,
- })
+ const baseDate = sub(new Date(params.range.end), toDuration(params.intervalsBy, offset))
return {
end: getEndOf(baseDate, params.intervalsBy).getTime(),
start: getStartOf(
- sub(baseDate, { [`${params.intervalsBy}s`]: params.intervalsDuration - 1 }),
+ sub(baseDate, toDuration(params.intervalsBy, params.intervalsDuration - 1)),
params.intervalsBy,
).getTime(),
}
}
-export function calculateBestIntervalsBy(range: Range) {
+export function calculateBestIntervalsBy(range: Range): Period {
const rangeDuration = differenceInDays(range.end, range.start)
return rangeDuration > 400
? 'year'
@@ -48,7 +56,7 @@ export function getIntervalsInRange(params: IntervalsInRangeProps) {
})
while (current.end > range.start) {
- list.unshift(current)
+ list.push(current)
current = calculateIntervalInRange({
intervalsBy,
@@ -58,6 +66,8 @@ export function getIntervalsInRange(params: IntervalsInRangeProps) {
})
}
+ list.reverse()
+
if (list.length > 0) {
if (list.at(-1)!.end > range.end) {
list.at(-1)!.end = endOfDay(new Date(range.end)).getTime()
@@ -71,7 +81,7 @@ export function getIntervalsInRange(params: IntervalsInRangeProps) {
return list
}
-export function getStartOf(date: Date, intervalType: string): Date {
+export function getStartOf(date: Date, intervalType: Period): Date {
switch (intervalType) {
case 'year':
return startOfYear(date)
@@ -79,12 +89,12 @@ export function getStartOf(date: Date, intervalType: string): Date {
return startOfMonth(date)
case 'week':
return startOfWeek(date, { weekStartsOn: 1 })
- default:
+ case 'day':
return startOfDay(date)
}
}
-export function getEndOf(date: Date, intervalType: string): Date {
+export function getEndOf(date: Date, intervalType: Period): Date {
switch (intervalType) {
case 'year':
return endOfYear(date)
@@ -92,7 +102,7 @@ export function getEndOf(date: Date, intervalType: string): Date {
return endOfMonth(date)
case 'week':
return endOfWeek(date, { weekStartsOn: 1 })
- default:
+ case 'day':
return endOfDay(date)
}
}
@@ -107,6 +117,6 @@ export function parseUCalendarDate(date: number) {
export function getUCalendarTimedDate(date: CalendarDate) {
const now = new Date()
- const selectedDate = date.toString()
- return new Date(selectedDate).setHours(now.getHours(), now.getMinutes())
+ const localDate = date.toDate(getLocalTimeZone())
+ return localDate.setHours(now.getHours(), now.getMinutes())
}
diff --git a/app/components/stat/Average.vue b/app/components/stat/Average.vue
index 000f8623..6de9c79c 100644
--- a/app/components/stat/Average.vue
+++ b/app/components/stat/Average.vue
@@ -9,7 +9,7 @@ import type { WalletId } from '~/components/wallets/types'
import { useAmount } from '~/components/amount/useAmount'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
-import { getEndOf, getStartOf } from '~/components/date/utils'
+import { getEndOf, getStartOf, toDuration } from '~/components/date/utils'
import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { getTrnTypeByAmount, TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
@@ -31,18 +31,18 @@ const { computeTotalForTrnsIds } = useAmount()
const averageConfig = computed(() => statConfig.config.value.statAverage.count)
-const untilDate = computed(() => getEndOf(sub(new Date(), { [`${statDate.params.value.rangeBy}s`]: statDate.params.value.rangeDuration }), statDate.params.value.rangeBy))
+const untilDate = computed(() => getEndOf(sub(new Date(), toDuration(statDate.params.value.rangeBy, statDate.params.value.rangeDuration)), statDate.params.value.rangeBy))
const dates = computed<Range>(() => ({
end: untilDate.value.getTime(),
- start: getStartOf(sub(untilDate.value, { [`${statDate.params.value.rangeBy}s`]: (statDate.params.value.rangeDuration * averageConfig.value) - 1 }), statDate.params.value.rangeBy).getTime(),
+ start: getStartOf(sub(untilDate.value, toDuration(statDate.params.value.rangeBy, (statDate.params.value.rangeDuration * averageConfig.value) - 1)), statDate.params.value.rangeBy).getTime(),
}))
const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
categoriesIds: props.categoryId ? [...filter.categoriesIds.value, props.categoryId] : filter.categoriesIds.value,
dates: {
- from: dates.value.start,
- until: dates.value.end,
+ end: dates.value.end,
+ start: dates.value.start,
},
walletsIds: props.walletId ? [...(filter.walletsIds.value ?? []), props.walletId] : filter.walletsIds.value,
}))
diff --git a/app/components/stat/CategoriesButtons.vue b/app/components/stat/CategoriesButtons.vue
index 69b592d2..44ebd82d 100644
--- a/app/components/stat/CategoriesButtons.vue
+++ b/app/components/stat/CategoriesButtons.vue
@@ -99,6 +99,7 @@ function onChangeViewOptions(newViewOptions: Pick<DeepPartial<MiniItemConfig>, '
<StatConfigSwitch configKey="vertical" field="isShow" :title="t('stat.config.categories.vertical.title')" />
<StatConfigSwitch configKey="catsRound" field="isShow" :title="t('stat.config.categories.rounds.title')" />
<StatConfigSwitch configKey="catsList" field="isShow" :title="t('stat.config.categories.list.title')" />
+ <StatConfigSwitch configKey="trns" field="isShow" :title="t('trns.title')" />
</div>
</div>
</div>
diff --git a/app/components/stat/Item.vue b/app/components/stat/Item.vue
index 074d2f9d..5aebcd34 100644
--- a/app/components/stat/Item.vue
+++ b/app/components/stat/Item.vue
@@ -33,6 +33,7 @@ const isRoundShow = computed(() => statConfig.config.value.catsRound.isShow)
const isListShow = computed(() => statConfig.config.value.catsList.isShow)
const isVerticalShow = computed(() => statConfig.config.value.vertical.isShow)
const isShowAverage = computed(() => statConfig.config.value.statAverage.isShow)
+const isTrnsShow = computed(() => statConfig.config.value.trns.isShow)
const {
averageTotal,
@@ -166,8 +167,10 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
/>
<StatTrns
+ v-if="isTrnsShow"
:isPeriodOneDay="isPeriodOneDay"
:selectedTrnsIds="selectedAndFilteredTrnsIds"
+ :storageKey="statItemStorageKey"
class="@3xl/page:order-1"
/>
</div>
diff --git a/app/components/stat/Trns.vue b/app/components/stat/Trns.vue
index 5bd9dc80..f37c8470 100644
--- a/app/components/stat/Trns.vue
+++ b/app/components/stat/Trns.vue
@@ -4,23 +4,38 @@ import type { TrnId } from '~/components/trns/types'
defineProps<{
isPeriodOneDay: boolean
selectedTrnsIds: TrnId[]
+ storageKey: string
}>()
+
+const { t } = useI18n()
</script>
<template>
<div class="mb-4 min-w-0 @3xl/main:max-w-md">
- <TrnsList
+ <UiToggle
v-if="selectedTrnsIds.length > 0"
- :isShowDates="!isPeriodOneDay"
- :isShowGroupSum="!isPeriodOneDay"
- :trnsIds="selectedTrnsIds"
- isShowExpense
- isShowFilterByDesc
- isShowIncome
- isShowHeader
- isShowTransfers
- isShowFilterByType
- />
+ :storageKey="`${storageKey}-trns`"
+ :initStatus="true"
+ >
+ <template #header="{ toggle, isShown }">
+ <UiTitleCollapse :isShown @click="toggle">
+ {{ t('trns.title') }} {{ (!isShown && selectedTrnsIds.length > 0) ? selectedTrnsIds.length : '' }}
+ </UiTitleCollapse>
+
+ <TrnsList
+ v-if="isShown"
+ :isShowDates="!isPeriodOneDay"
+ :isShowGroupSum="!isPeriodOneDay"
+ :trnsIds="selectedTrnsIds"
+ isShowExpense
+ isShowFilterByDesc
+ isShowIncome
+ isShowTransfers
+ isShowFilterByType
+ class="pt-2"
+ />
+ </template>
+ </UiToggle>
<TrnsNoTrns v-else />
</div>
diff --git a/app/components/stat/Wrap.vue b/app/components/stat/Wrap.vue
index c3fb8399..1779d173 100644
--- a/app/components/stat/Wrap.vue
+++ b/app/components/stat/Wrap.vue
@@ -32,8 +32,8 @@ const sharedItemProps = computed(() => ({
const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
dates: {
- from: statDate.range.value.start,
- until: statDate.range.value.end,
+ end: statDate.range.value.end,
+ start: statDate.range.value.start,
},
trnsIds: props.trnsIds,
}))
diff --git a/app/components/stat/categories/DetailedSection.vue b/app/components/stat/categories/DetailedSection.vue
index f4f5f18c..e46c3e72 100644
--- a/app/components/stat/categories/DetailedSection.vue
+++ b/app/components/stat/categories/DetailedSection.vue
@@ -107,7 +107,7 @@ const {
<div
v-if="isShown"
- class="grid pt-3"
+ class="grid"
>
<div class="flex overflow-hidden overflow-x-auto pt-2 pl-1">
<StatCategoriesVertical
diff --git a/app/components/stat/categories/GroupingToggle.vue b/app/components/stat/categories/GroupingToggle.vue
index 4d02b3fc..cd8089fe 100644
--- a/app/components/stat/categories/GroupingToggle.vue
+++ b/app/components/stat/categories/GroupingToggle.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
const props = defineProps<{
isGrouped: boolean
- size?: string
+ size?: 'sm' | 'md'
}>()
const emit = defineEmits<{
diff --git a/app/components/stat/categories/Vertical.vue b/app/components/stat/categories/Vertical.vue
index 34d3e7fc..082eedb4 100644
--- a/app/components/stat/categories/Vertical.vue
+++ b/app/components/stat/categories/Vertical.vue
@@ -19,15 +19,13 @@ const emit = defineEmits<{
}>()
const categoriesStore = useCategoriesStore()
-
const category = computed(() => categoriesStore.items[props.item.id])
+const amount = computed(() => formatCompactAmount(props.item.value))
const barStyle = computed(() =>
computeBarStyle(props.item.value, category.value?.color, props.maxCategoryValues, 'height'),
)
-const amount = computed(() => formatCompactAmount(props.item.value))
-
const { longPressRef } = useCategoryLongPress(
() => props.item.id,
() => emit('click', props.item.id),
@@ -38,7 +36,7 @@ const { longPressRef } = useCategoryLongPress(
<div
v-if="category"
ref="longPressRef"
- class="rounded-sm p-1 pb-4 hover:bg-(--item-5)"
+ class="rounded-sm p-1 pt-5 pb-2 hover:bg-(--item-5)"
>
<div class="bg-item-3 flex h-28 items-end rounded-sm">
<div
diff --git a/app/components/stat/categories/collectAndGroup.ts b/app/components/stat/categories/collectAndGroup.ts
index 6975b27c..65fa0f4a 100644
--- a/app/components/stat/categories/collectAndGroup.ts
+++ b/app/components/stat/categories/collectAndGroup.ts
@@ -1,24 +1,21 @@
import type { Categories, CategoryId } from '~/components/categories/types'
import type { CategoriesWithData, CategoryWithData } from '~/components/stat/types'
-import type { TrnId } from '~/components/trns/types'
+import type { TrnId, TrnItem } from '~/components/trns/types'
import { getParentCategoryIdOrUndefined } from '~/components/categories/utils'
-export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData) {
- if (!a || !b)
- return 0
-
+export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData): number {
if (a.value === 0)
return 1
if (b.value === 0)
return -1
- const isP = a.value > 0 && b.value > 0
- const isN = a.value < 0 && b.value < 0
+ const bothPositive = a.value > 0 && b.value > 0
+ const bothNegative = a.value < 0 && b.value < 0
- if (isP)
+ if (bothPositive)
return b.value - a.value
- if (isN)
+ if (bothNegative)
return a.value - b.value
return a.value > 0 ? -1 : 1
}
@@ -27,7 +24,7 @@ export function collectCategoriesByTrns(params: {
categoriesItems: Categories
preCategoriesIds?: CategoryId[]
trnsIds: TrnId[]
- trnsItems: Record<TrnId, { categoryId?: string }>
+ trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>>
}): CategoriesWithData {
const { categoriesItems, preCategoriesIds, trnsIds, trnsItems } = params
@@ -110,8 +107,7 @@ export function groupCategoriesWithValues(
value: 0,
}
- grouped[parentId].categories ??= []
- grouped[parentId].categories.push({
+ grouped[parentId].categories!.push({
...cat,
value: catTotal,
})
diff --git a/app/components/stat/categories/useCategoriesExpanded.ts b/app/components/stat/categories/useCategoriesExpanded.ts
index 802a250e..c109b21f 100644
--- a/app/components/stat/categories/useCategoriesExpanded.ts
+++ b/app/components/stat/categories/useCategoriesExpanded.ts
@@ -9,10 +9,7 @@ type CategoryState = { show: boolean }
type CategoriesState = Record<CategoryId, CategoryState>
function createInitialState(categories: Categories): CategoriesState {
- return Object.keys(categories).reduce((acc, id) => {
- acc[id] = { show: false }
- return acc
- }, {} as CategoriesState)
+ return Object.fromEntries(Object.keys(categories).map(id => [id, { show: false }]))
}
export function useCategoriesExpanded(
@@ -45,9 +42,8 @@ export function useCategoriesExpanded(
function toggleAll() {
const newShow = !isAnyExpanded.value
- Object.keys(currentState.value).forEach((id) => {
+ for (const id of Object.keys(currentState.value))
expandedState.value[id] = { show: newShow }
- })
}
function toggle(id: CategoryId) {
diff --git a/app/components/stat/categories/useCategoryLongPress.ts b/app/components/stat/categories/useCategoryLongPress.ts
index 10eb45f0..477c167e 100644
--- a/app/components/stat/categories/useCategoryLongPress.ts
+++ b/app/components/stat/categories/useCategoryLongPress.ts
@@ -30,7 +30,7 @@ export function useCategoryLongPress(
const isDayDate = statDate.params.value.intervalSelected !== -1 && statDate.params.value.intervalsBy === 'day'
if (isDayDate && statDate.selectedInterval.value?.start) {
- state.values.date = statDate.selectedInterval.value!.start
+ state.values.date = statDate.selectedInterval.value.start
}
else {
state.values.date = Date.now()
diff --git a/app/components/stat/date/Navigation.vue b/app/components/stat/date/Navigation.vue
index 85467ab9..762bf03d 100644
--- a/app/components/stat/date/Navigation.vue
+++ b/app/components/stat/date/Navigation.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { sub } from 'date-fns'
-import { getEndOf, getStartOf } from '~/components/date/utils'
+import { getEndOf, getStartOf, toDuration } from '~/components/date/utils'
import { statDateKey } from '~/components/stat/injectionKeys'
const { t } = useI18n()
@@ -25,7 +25,7 @@ const isStart = computed(() =>
)
const isShowNavHome = computed(() => {
- const start = getStartOf(sub(new Date(), { [`${statDate.params.value.rangeBy}s`]: statDate.params.value.rangeDuration - 1 }), statDate.params.value.rangeBy).getTime()
+ const start = getStartOf(sub(new Date(), toDuration(statDate.params.value.rangeBy, statDate.params.value.rangeDuration - 1)), statDate.params.value.rangeBy).getTime()
const end = getEndOf(new Date(), statDate.params.value.rangeBy).getTime()
return !statDate.params.value.isShowMaxRange && (statDate.params.value.intervalSelected !== -1 || (statDate.range.value.start !== start && statDate.range.value.end !== end))
diff --git a/app/components/stat/date/useGetDateRange.test.ts b/app/components/stat/date/useGetDateRange.test.ts
index 7b584412..738b3531 100644
--- a/app/components/stat/date/useGetDateRange.test.ts
+++ b/app/components/stat/date/useGetDateRange.test.ts
@@ -42,13 +42,6 @@ describe('useGetDateRange', () => {
const { formatDateToStringWithLast, getStringDateRange } = useGetDateRange(t)
const today = fixedDate
- /** Call formatDateToStringWithLast for both 'start' and 'end', return concatenated label */
- function getLabel(params: { by: 'day' | 'month' | 'week' | 'year', duration: number, end: Date, start: Date }, isShowMaxRange?: boolean): string {
- const s = formatDateToStringWithLast({ ...params, type: 'start' }, isShowMaxRange)
- const e = formatDateToStringWithLast({ ...params, type: 'end' }, isShowMaxRange)
- return `${s}${e}`
- }
-
afterAll(() => {
vi.useRealTimers()
})
@@ -109,38 +102,38 @@ describe('useGetDateRange', () => {
})
})
- describe('formatDateToStringWithLast — current/last period labels', () => {
+ describe('formatDateToStringWithLast - current/last period labels', () => {
it('shows "Today" for current day', () => {
- expect(getLabel({ by: 'day', duration: 1, end: today, start: today })).toBe('Today')
+ expect(formatDateToStringWithLast({ by: 'day', duration: 1, end: today, start: today })).toBe('Today')
})
it('shows "Yesterday" for previous day', () => {
const yesterday = sub(today, { days: 1 })
- expect(getLabel({ by: 'day', duration: 1, end: yesterday, start: yesterday })).toBe('Yesterday')
+ expect(formatDateToStringWithLast({ by: 'day', duration: 1, end: yesterday, start: yesterday })).toBe('Yesterday')
})
it('shows "This Month" for current month', () => {
- expect(getLabel({ by: 'month', duration: 1, end: endOfMonth(today), start: startOfMonth(today) })).toBe('This Month')
+ expect(formatDateToStringWithLast({ by: 'month', duration: 1, end: endOfMonth(today), start: startOfMonth(today) })).toBe('This Month')
})
it('shows "Last Month" for previous month', () => {
const lastMonth = sub(today, { months: 1 })
- expect(getLabel({ by: 'month', duration: 1, end: endOfMonth(lastMonth), start: startOfMonth(lastMonth) })).toBe('Last Month')
+ expect(formatDateToStringWithLast({ by: 'month', duration: 1, end: endOfMonth(lastMonth), start: startOfMonth(lastMonth) })).toBe('Last Month')
})
it('shows "Last N periods" when end is in current period', () => {
const start = sub(today, { days: 2 })
- expect(getLabel({ by: 'day', duration: 3, end: today, start })).toBe('Last 3 days')
+ expect(formatDateToStringWithLast({ by: 'day', duration: 3, end: today, start })).toBe('Last 3 days')
})
it('shows "d MMMM" for single day in current year (not today/yesterday)', () => {
const date = new Date('2025-03-15T12:00:00')
- expect(getLabel({ by: 'day', duration: 1, end: date, start: date })).toBe('15 March')
+ expect(formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date })).toBe('15 March')
})
it('shows "d MMM yyyy" for single day in past year', () => {
const date = new Date('2024-06-15T12:00:00')
- expect(getLabel({ by: 'day', duration: 1, end: date, start: date })).toBe('15 Jun 2024')
+ expect(formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date })).toBe('15 Jun 2024')
})
})
})
diff --git a/app/components/stat/date/useGetDateRange.ts b/app/components/stat/date/useGetDateRange.ts
index 78bef59c..7ee9e4ba 100644
--- a/app/components/stat/date/useGetDateRange.ts
+++ b/app/components/stat/date/useGetDateRange.ts
@@ -1,143 +1,87 @@
import { isSameDay, isSameMonth, isSameWeek, isSameYear, sub } from 'date-fns'
-import type { Range, StatDateParams } from '~/components/date/types'
+import type { Period, Range, StatDateParams } from '~/components/date/types'
import type { LocaleSlug } from '~/components/locale/types'
-import { formatByLocale } from '~/components/date/utils'
+import { formatByLocale, toDuration } from '~/components/date/utils'
type DateFormatParams = {
by: StatDateParams['rangeBy']
duration: StatDateParams['rangeDuration']
end: Date
start: Date
- type: 'start' | 'end'
}
-export function useGetDateRange(t: (key: string, choice?: number) => string, locale?: LocaleSlug) {
- const today = new Date()
-
- // Helper functions for period handling
- function handleCurrentPeriod(by: StatDateParams['rangeBy'], type: 'start' | 'end') {
- return type === 'start' ? t(`dates.${by}.current`) : ''
- }
-
- function handleLastPeriod(by: StatDateParams['rangeBy'], type: 'start' | 'end') {
- return type === 'start' ? t(`dates.${by}.last`) : ''
+function isSamePeriod(a: Date, b: Date, by: Period): boolean {
+ switch (by) {
+ case 'year': return isSameYear(a, b)
+ case 'month': return isSameMonth(a, b)
+ case 'week': return isSameWeek(a, b, { weekStartsOn: 1 })
+ case 'day': return isSameDay(a, b)
}
+}
- function handleLastNPeriods(by: StatDateParams['rangeBy'], duration: number, type: 'start' | 'end') {
- return type === 'start' ? '' : `${t(`dates.last.${by}`, duration)} ${duration} ${t(`dates.${by}.plural`, duration)}`
- }
+export function useGetDateRange(t: (key: string, choice?: number) => string, locale?: LocaleSlug) {
+ const today = new Date()
- function formatYearRange({ duration, end, start, type }: DateFormatParams): string {
- if (type === 'start')
- return duration === 1 ? formatByLocale(start, 'yyyy', locale) : `${formatByLocale(start, 'yyyy', locale)} - ${formatByLocale(end, 'yyyy', locale)}`
- return ''
+ function formatYearRange({ duration, end, start }: DateFormatParams): string {
+ return duration === 1
+ ? formatByLocale(start, 'yyyy', locale)
+ : `${formatByLocale(start, 'yyyy', locale)} - ${formatByLocale(end, 'yyyy', locale)}`
}
- function formatMonthRange({ duration, end, start, type }: DateFormatParams): string {
+ function formatMonthRange({ duration, end, start }: DateFormatParams): string {
if (isSameYear(start, today)) {
if (isSameMonth(start, today) || duration === 1)
- return type === 'start' ? formatByLocale(start, 'MMMM', locale) : ''
- return type === 'start' ? formatByLocale(start, 'MMM', locale) : ` - ${formatByLocale(end, 'MMM', locale)}`
+ return formatByLocale(start, 'MMMM', locale)
+ return `${formatByLocale(start, 'MMM', locale)} - ${formatByLocale(end, 'MMM', locale)}`
}
if (isSameYear(start, end)) {
if (isSameMonth(start, end))
- return type === 'start' ? formatByLocale(start, 'MMM yyyy', locale) : ''
- return type === 'start' ? formatByLocale(start, 'MMM', locale) : ` - ${formatByLocale(end, 'MMM yyyy', locale)}`
+ return formatByLocale(start, 'MMM yyyy', locale)
+ return `${formatByLocale(start, 'MMM', locale)} - ${formatByLocale(end, 'MMM yyyy', locale)}`
}
- return type === 'start' ? formatByLocale(start, 'MMM yyyy', locale) : ` - ${formatByLocale(end, 'MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'MMM yyyy', locale)} - ${formatByLocale(end, 'MMM yyyy', locale)}`
}
- function formatWeekRange({ end, start, type }: DateFormatParams): string {
+ function formatWeekRange({ end, start }: DateFormatParams): string {
if (isSameYear(start, today)) {
if (isSameMonth(start, today) || isSameMonth(start, end))
- return type === 'start' ? formatByLocale(start, 'd', locale) : `-${formatByLocale(end, 'd MMM', locale)}`
- return type === 'start' ? formatByLocale(start, 'd MMM', locale) : ` - ${formatByLocale(end, 'd MMM', locale)}`
+ return `${formatByLocale(start, 'd', locale)}-${formatByLocale(end, 'd MMM', locale)}`
+ return `${formatByLocale(start, 'd MMM', locale)} - ${formatByLocale(end, 'd MMM', locale)}`
}
if (isSameYear(start, end)) {
if (isSameMonth(start, end))
- return type === 'start' ? formatByLocale(start, 'd', locale) : `-${formatByLocale(end, 'd MMM yyyy', locale)}`
- return type === 'start' ? formatByLocale(start, 'd MMM', locale) : ` - ${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd', locale)}-${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd MMM', locale)} - ${formatByLocale(end, 'd MMM yyyy', locale)}`
}
- return type === 'start' ? formatByLocale(start, 'd MMM yyyy', locale) : ` - ${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd MMM yyyy', locale)} - ${formatByLocale(end, 'd MMM yyyy', locale)}`
}
- function formatDayRange({ duration, end, start, type }: DateFormatParams): string {
+ function formatDayRange({ duration, end, start }: DateFormatParams): string {
if (isSameYear(start, today)) {
if (isSameMonth(start, end))
- return type === 'start' ? formatByLocale(start, 'd', locale) : `-${formatByLocale(end, 'd MMM', locale)}`
- return type === 'start' ? formatByLocale(start, 'd MMM', locale) : ` - ${formatByLocale(end, 'd MMM', locale)}`
+ return `${formatByLocale(start, 'd', locale)}-${formatByLocale(end, 'd MMM', locale)}`
+ return `${formatByLocale(start, 'd MMM', locale)} - ${formatByLocale(end, 'd MMM', locale)}`
}
if (isSameYear(start, end)) {
if (duration === 1)
- return type === 'start' ? formatByLocale(start, 'd MMM yyyy', locale) : ''
+ return formatByLocale(start, 'd MMM yyyy', locale)
if (isSameMonth(start, end))
- return type === 'start' ? formatByLocale(start, 'd', locale) : `-${formatByLocale(end, 'd MMM yyyy', locale)}`
- return type === 'start' ? formatByLocale(start, 'd MMM', locale) : ` - ${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd', locale)}-${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd MMM', locale)} - ${formatByLocale(end, 'd MMM yyyy', locale)}`
}
- return type === 'start' ? formatByLocale(start, 'd MMM yyyy', locale) : ` - ${formatByLocale(end, 'd MMM yyyy', locale)}`
+ return `${formatByLocale(start, 'd MMM yyyy', locale)} - ${formatByLocale(end, 'd MMM yyyy', locale)}`
}
- function formatDateToStringWithLast(params: DateFormatParams, isShowMaxRange?: boolean): string {
- const { by, duration, end, start, type } = params
-
- // Single duration cases
- if (duration === 1) {
- // Check if date is current period
- const isCurrent = (() => {
- switch (by) {
- case 'year': return isSameYear(start, today)
- case 'month': return isSameYear(start, today) && isSameMonth(start, today)
- case 'week': return isSameWeek(start, today, { weekStartsOn: 1 })
- case 'day': return isSameDay(start, today)
- }
- })()
-
- if (isCurrent)
- return handleCurrentPeriod(by, type)
-
- // Check if date is last period
- const lastPeriod = sub(today, { [`${by}s`]: 1 })
- const isLast = (() => {
- switch (by) {
- case 'year': return isSameYear(start, lastPeriod)
- case 'month': return isSameMonth(start, lastPeriod)
- case 'week': return isSameWeek(start, lastPeriod, { weekStartsOn: 1 })
- case 'day': return isSameDay(start, lastPeriod)
- }
- })()
-
- if (isLast)
- return handleLastPeriod(by, type)
-
- // Special case for single day in current year/month
- if (by === 'day' && isSameYear(start, today)) {
- return type === 'start' ? formatByLocale(start, 'd MMMM', locale) : ''
- }
- }
-
- // Last N periods
- const isCurrentPeriod = (() => {
- switch (by) {
- case 'year': return isSameYear(end, today)
- case 'month': return isSameYear(end, today) && isSameMonth(end, today)
- case 'week': return isSameWeek(end, today, { weekStartsOn: 1 })
- case 'day': return isSameDay(end, today)
- }
- })()
-
- if (!isShowMaxRange && isCurrentPeriod)
- return handleLastNPeriods(by, duration, type)
-
- // Format by date unit
- switch (by) {
+ function formatByPeriod(params: DateFormatParams): string {
+ switch (params.by) {
case 'year': return formatYearRange(params)
case 'month': return formatMonthRange(params)
case 'week': return formatWeekRange(params)
@@ -145,52 +89,42 @@ export function useGetDateRange(t: (key: string, choice?: number) => string, loc
}
}
- /**
- * Calculates and formats a date range string based on the provided parameters.
- *
- * - If the duration is 1 day and the start date is in the current year, returns a localized date string for the start date (if `type` is `'start'`).
- * - Otherwise, formats the date range according to the specified granularity (`by`), which can be `'year'`, `'month'`, `'week'`, or `'day'`.
- *
- * @param params
- * - `by`: The granularity of the date range ('year', 'month', 'week', or 'day').
- * - `duration`: The length of the date range.
- * - `start`: The start date of the range.
- * - `type`: The type of date to format ('start' or other).
- * @returns A formatted date range string based on the input parameters.
- */
- function formatDateToString(params: DateFormatParams): string {
- const { by, duration, start, type } = params
+ function formatDateToStringWithLast(params: DateFormatParams, isShowMaxRange?: boolean): string {
+ const { by, duration, end, start } = params
- if (duration === 1 && by === 'day' && isSameYear(start, today)) {
- return type === 'start' ? formatByLocale(start, 'd MMMM', locale) : ''
- }
+ if (duration === 1) {
+ if (isSamePeriod(start, today, by))
+ return t(`dates.${by}.current`)
- switch (by) {
- case 'year': return formatYearRange(params)
- case 'month': return formatMonthRange(params)
- case 'week': return formatWeekRange(params)
- case 'day': return formatDayRange(params)
+ if (isSamePeriod(start, sub(today, toDuration(by, 1)), by))
+ return t(`dates.${by}.last`)
+
+ if (by === 'day' && isSameYear(start, today))
+ return formatByLocale(start, 'd MMMM', locale)
}
+
+ if (!isShowMaxRange && isSamePeriod(end, today, by))
+ return `${t(`dates.last.${by}`, duration)} ${duration} ${t(`dates.${by}.plural`, duration)}`
+
+ return formatByPeriod(params)
}
- function getStringDateRange(range: Range, by: StatDateParams['rangeBy'], duration: StatDateParams['rangeDuration']) {
- const yearStart = formatDateToString({
- by,
- duration,
- end: new Date(range.end),
- start: new Date(range.start),
- type: 'start',
- })
+ function formatDateToString(params: DateFormatParams): string {
+ const { by, duration, start } = params
+
+ if (duration === 1 && by === 'day' && isSameYear(start, today))
+ return formatByLocale(start, 'd MMMM', locale)
- const yearEnd = formatDateToString({
+ return formatByPeriod(params)
+ }
+
+ function getStringDateRange(range: Range, by: StatDateParams['rangeBy'], duration: StatDateParams['rangeDuration']) {
+ return formatDateToString({
by,
duration,
end: new Date(range.end),
start: new Date(range.start),
- type: 'end',
})
-
- return `${yearStart}${yearEnd}`
}
return {
diff --git a/app/components/stat/filter/useFilter.ts b/app/components/stat/filter/useFilter.ts
index a581082d..94b749ae 100644
--- a/app/components/stat/filter/useFilter.ts
+++ b/app/components/stat/filter/useFilter.ts
@@ -14,7 +14,7 @@ function createQueryFilter<T extends string>(
const value = route.query[queryKey]
if (Array.isArray(value))
return validateFn ? (value as T[]).filter(validateFn) : (value as T[])
- return value ? [...(value as string).split(',')] as T[] : []
+ return value ? (value as string).split(',') as T[] : []
})
function setId(id: T) {
@@ -42,7 +42,7 @@ function createQueryFilter<T extends string>(
router.push({
query: {
...route.query,
- [queryKey]: [...ids.value.filter(i => i !== id)],
+ [queryKey]: ids.value.filter(i => i !== id),
},
})
}
diff --git a/app/components/stat/intervals.ts b/app/components/stat/intervals.ts
index 24cdec37..875874b2 100644
--- a/app/components/stat/intervals.ts
+++ b/app/components/stat/intervals.ts
@@ -56,8 +56,8 @@ export function bucketTrnsByIntervals(
export function computeAverageTotal(
sum: number,
dateRange: Range,
-): Record<string, number> | undefined {
- if (differenceInDays(dateRange.end, dateRange.start) < 2)
+): Partial<Record<'day' | 'week' | 'month', number>> | undefined {
+ if (sum === 0 || differenceInDays(dateRange.end, dateRange.start) < 2)
return undefined
const dif = {
@@ -66,16 +66,16 @@ export function computeAverageTotal(
week: differenceInWeeks(dateRange.end, dateRange.start) + 1,
}
- const items: Record<string, number> = {}
+ const items: Partial<Record<'day' | 'week' | 'month', number>> = {
+ day: sum / dif.day,
+ }
- if (dif.month > 1 && sum !== 0)
- items.month = sum / dif.month
- if (dif.week > 1 && sum !== 0)
+ if (dif.week > 1)
items.week = sum / dif.week
- if (dif.day > 1 && sum !== 0)
- items.day = sum / dif.day
+ if (dif.month > 1)
+ items.month = sum / dif.month
- return Object.keys(items).length > 0 ? items : undefined
+ return items
}
/**
diff --git a/app/components/stat/useStatConfig.ts b/app/components/stat/useStatConfig.ts
index edaa85d5..c4f0bdc2 100644
--- a/app/components/stat/useStatConfig.ts
+++ b/app/components/stat/useStatConfig.ts
@@ -36,6 +36,9 @@ export const ConfigSchema = z.object({
count: z.number(),
isShow: z.boolean(),
}),
+ trns: z.object({
+ isShow: z.boolean(),
+ }),
vertical: z.object({
isGrouped: z.boolean(),
isShow: z.boolean(),
@@ -91,6 +94,10 @@ export function useStatConfig({ props, storageKey }: StatConfigParams) {
isShow: false,
},
+ trns: {
+ isShow: true,
+ },
+
vertical: {
isGrouped: false,
isShow: false,
diff --git a/app/components/stat/useStatItem.ts b/app/components/stat/useStatItem.ts
index 15044f9a..03fa5faa 100644
--- a/app/components/stat/useStatItem.ts
+++ b/app/components/stat/useStatItem.ts
@@ -113,8 +113,8 @@ export function useStatItem({
if (differenceInDays(statDate.range.value.end, statDate.range.value.start) < 2)
return
- const key = filteredType.value === 'netIncome' ? 'sum' : (type.value ?? 'sum')
- const sum = rangeTotal.value[key as keyof TotalReturns] as number ?? 0
+ const key: keyof TotalReturns = (!type.value || type.value === 'netIncome' || filteredType.value === 'netIncome') ? 'sum' : type.value
+ const sum = rangeTotal.value[key] ?? 0
const dateRange = isIntervalSelected.value
? statDate.selectedInterval.value
@@ -147,7 +147,7 @@ export function useStatItem({
})
const chartXAxisLabels = computed(() =>
- intervalsDataWithFilteredCategories.value.map(i => +i.range.start),
+ intervalsDataWithFilteredCategories.value.map(i => i.range.start),
)
function onSetCategoryFilter(categoryId: CategoryId) {
diff --git a/app/components/stat/utils.ts b/app/components/stat/utils.ts
index be6dfb38..66bd3002 100644
--- a/app/components/stat/utils.ts
+++ b/app/components/stat/utils.ts
@@ -2,8 +2,8 @@ import type { SeriesSlug, SeriesSlugSelected, StatTabSlug } from '~/components/s
import { TrnType } from '~/components/trns/types'
-export function getTypesMapping(slug: SeriesSlugSelected | StatTabSlug): TrnType[] | undefined {
- const typeMapping: Record<string, TrnType[]> = {
+export function getTypesMapping(slug: SeriesSlugSelected | StatTabSlug): TrnType[] {
+ const typeMapping: Record<SeriesSlugSelected | StatTabSlug, TrnType[]> = {
expense: [TrnType.Expense, TrnType.Transfer],
income: [TrnType.Income, TrnType.Transfer],
netIncome: [TrnType.Expense, TrnType.Income, TrnType.Transfer],
@@ -11,7 +11,7 @@ export function getTypesMapping(slug: SeriesSlugSelected | StatTabSlug): TrnType
summary: [TrnType.Expense, TrnType.Income, TrnType.Transfer],
}
- return typeMapping[slug] ?? [TrnType.Expense, TrnType.Income, TrnType.Transfer]
+ return typeMapping[slug]
}
/**
diff --git a/app/components/trns/getTrns.ts b/app/components/trns/getTrns.ts
index c3d73788..f1a50a9f 100644
--- a/app/components/trns/getTrns.ts
+++ b/app/components/trns/getTrns.ts
@@ -11,10 +11,10 @@ export function filterTrnsIds(props: TrnsGetterProps) {
const walletsSet = props.walletsIds?.length ? new Set(props.walletsIds) : null
const categoriesSet = props.categoriesIds?.length ? new Set(props.categoriesIds) : null
const typesSet = Array.isArray(props.trnsTypes) ? new Set(props.trnsTypes) : null
- const from = props.dates?.from
- const until = props.dates?.until
+ const start = props.dates?.start
+ const end = props.dates?.end
- const hasFilters = typesSet || from || until || walletsSet || categoriesSet
+ const hasFilters = typesSet || start !== undefined || end !== undefined || walletsSet || categoriesSet
const result = hasFilters
? trnsIds.filter((id) => {
@@ -23,9 +23,9 @@ export function filterTrnsIds(props: TrnsGetterProps) {
return false
if (typesSet && !typesSet.has(trn.type))
return false
- if (from && trn.date < from)
+ if (start !== undefined && trn.date < start)
return false
- if (until && trn.date > until)
+ if (end !== undefined && trn.date > end)
return false
if (walletsSet) {
const matchesWallet = trn.type === TrnType.Transfer
diff --git a/app/components/trns/types.ts b/app/components/trns/types.ts
index 90905c20..58584e86 100644
--- a/app/components/trns/types.ts
+++ b/app/components/trns/types.ts
@@ -71,8 +71,8 @@ export type Trns = Record<TrnId, TrnItem>
export type TrnsGetterProps = {
categoriesIds?: CategoryId[]
dates?: {
- from: number
- until: number
+ start: number
+ end: number
}
sort?: boolean
trnsIds?: TrnId[]
diff --git a/app/components/ui/Toggle.vue b/app/components/ui/Toggle.vue
index dfb0ef65..b29135b8 100644
--- a/app/components/ui/Toggle.vue
+++ b/app/components/ui/Toggle.vue
@@ -10,21 +10,19 @@ const isShown = useStorage(`${props.storageKey}`, props.initStatus)
</script>
<template>
- <div>
- <div>
- <slot
- name="header"
- :isShown
- :toggle="() => isShown = !isShown"
- />
- </div>
+ <div v-if="$slots.header">
+ <slot
+ name="header"
+ :isShown
+ :toggle="() => isShown = !isShown"
+ />
+ </div>
- <div
- v-if="isShown"
- >
- <slot
- :toggle="() => isShown = !isShown"
- />
- </div>
+ <div
+ v-if="isShown && $slots.default"
+ >
+ <slot
+ :toggle="() => isShown = !isShown"
+ />
</div>
</template>
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 739223d0..cdfa89bf 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -87,18 +87,6 @@ export default defineNuxtConfig({
'@nuxt/eslint',
],
- // Pre-render the SPA shell so the service worker can precache it
- // for offline navigation (navigateFallback: '/')
- nitro: {
- prerender: {
- routes: ['/'],
- },
- },
-
- pages: {
- pattern: ['**/*.vue', '!**/_/**'],
- },
-
pwa: {
client: {
installPrompt: true,