Skip to content

Open source personal finance application

init convex

Ilya Komichevfb350ed9bfc6
diff --git a/.env.example b/.env.example
index 3b610b13..2ba9cf18 100644
--- a/.env.example
+++ b/.env.example
@@ -1 +1,3 @@
-OPEN_EXCHANGE_RATES=123456
+CONVEX_DEPLOYMENT=
+VITE_CONVEX_URL=
+VITE_CONVEX_SITE_URL=
diff --git a/.firebaserc b/.firebaserc
deleted file mode 100644
index b9b04985..00000000
--- a/.firebaserc
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "projects": {
- "default": "finapp-17474"
- }
-}
diff --git a/.gitignore b/.gitignore
index b66de1b5..32d0330d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,4 +25,7 @@ logs
!.env.example
+# Migration data
+utils/migrate/data.json
+
ftp.config.js
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..540c0b9c
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,146 @@
+# Finapp
+
+Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Convex backend, Better Auth.
+
+- Node.js >= v24.12.0
+- Package manager: pnpm
+- SSR enabled (`ssr: true`)
+- PWA with service worker (generateSW strategy)
+
+## Commands
+
+- `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` — SSR 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
+
+See [Architecture](docs/architecture.md) for detailed project structure and file descriptions.
+
+## Conventions
+
+- Components: PascalCase, grouped by feature in `components/[feature]/`
+- UI primitives in `components/ui/`
+- Imports use `~/` alias (resolves to `/app/`)
+- ESLint flat config with `@antfu/eslint-config`, Perfectionist for sorting
+- Prettier with Tailwind plugin, single quotes, no semicolons, trailing commas
+- i18n: `no_prefix` strategy, two locales (en-US, ru-RU)
+- Always run `pnpm lint:fix` before committing
+
+## CSS / Theme Rules
+
+- @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
+- 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 → `pushOfflineOp` → fire mutation (no await)
+- `delete(id)` — optimistic UI → `pushOfflineOp` → fire mutation (no await)
+
+Mutation result: `.then()` removes offline op + remaps frontend ID → `.catch()` shows error toast.
+
+### Frontend ID System
+
+New entities get temporary IDs with `local_` prefix (e.g., `local_a1b2c3`). `isLocalId(id)` checks `id.startsWith('local_')` to distinguish from Convex IDs. After successful create mutation, `handleMutationResult()` remaps `items[localId]` → `items[convexId]`.
+
+## Convex Backend
+
+- Schema in `convex/schema.ts`: categories, wallets, trns, userSettings, rates
+- `TrnType` enum in `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
+- `convex/tsconfig.json` is separate from the app tsconfig
+
+### Convex Client Access
+
+| Context | Client | Composable |
+|---------|--------|------------|
+| Server (SSR) | ConvexHttpClient | `useConvexHttpClient()` |
+| Client (browser) | ConvexClient (WebSocket) | `useConvexClientComposable()` |
+| Either (auto-detect) | — | `useConvexClient()` |
+
+- `useConvexQuery()` — SSR-aware reactive query with real-time updates (client: WebSocket subscription, server: `useAsyncData` + HTTP)
+- `useConvexMutation()` — typed mutation caller bound to the current client
+- Stores use imperative `client.query()` instead of `useConvexQuery()` because they manage their own caching and offline merge
+
+## 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
+4. Both servers must run simultaneously (in separate terminals)
+
+### First-time setup
+
+Convex dev deployment env vars must be configured (one-time):
+
+```sh
+npx convex env set BETTER_AUTH_SECRET <value>
+npx convex env set SITE_URL https://<dev-deployment>.eu-west-1.convex.site
+npx convex env set FRONTEND_URL http://localhost:3050
+npx convex env set GOOGLE_CLIENT_ID <value>
+npx convex env set GOOGLE_CLIENT_SECRET <value>
+npx convex env set OPENEXCHANGERATES_APP_ID <value>
+```
+
+CORS: dev deployment origins (`https://<deployment>.convex.site` and `https://<deployment>.convex.cloud`) must be listed in `convex/http.ts` `allowedOrigins`.
+
+## Environment Variables
+
+### 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`
+
+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 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)
+- `SITE_URL` — Convex site URL (Better Auth base URL)
+- `FRONTEND_URL` — frontend URL for cross-domain auth
+- `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` — Google OAuth
+- `OPENEXCHANGERATES_APP_ID` — exchange rates API
+
+## Key Files
+
+| What | Where |
+|------|-------|
+| App entry | `app/app.vue` |
+| Theme logic | `app/plugins/theme.ts`, `app/app.vue` |
+| Auth setup | `app/plugins/convex.ts`, `app/composables/useAuth.ts` |
+| Store sync | `app/composables/useStoreSync.ts` |
+| Offline queue | `app/components/offline/helpers.ts` |
+| Statistics calc | `app/components/amount/getTotal.ts` |
+| Convex schema | `convex/schema.ts` |
+| Frontend IDs | `app/utils/convexId.ts`, `utils/generateId.ts` |
+| Date utils | `app/components/date/utils.ts` |
+| Menu state | `app/components/layout/useMenuData.ts` |
+| Bottom sheet drag | `app/components/bottomSheet/useBottomSheetDrag.ts` |
+
+## Documentation
+
+Built with [Docus](https://docus.dev/) in `../docs/` directory. Content in `../docs/content/en/` and `../docs/content/ru/`.
+
+For detailed architecture, auth flows, offline queue, and sync strategy see `../docs/content/en/3.technical/`.
diff --git a/README.md b/README.md
index 03f4e988..973222c9 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
- **Simple**: No clutter, no distractions — just your transactions and balances.
- **Fast**: Works offline and syncs instantly across devices.
-- **Private**: You own your data — securely stored via Firebase.
+- **Private**: You own your data — securely stored via Convex.
- **Flexible**: Supports multiple currencies with automatic exchange rates.
- **Portable**: Optimized for mobile and desktop, installable as a PWA.
@@ -31,7 +31,7 @@
## 🚀 Features
- Offline-first (PWA) with full CRUD support.
-- Instant real-time sync across devices (Firebase).
+- Instant sync across devices (Convex).
- Mobile-first, but optimized for desktop.
- Dark and Light theme support.
- Multi-currency with automatic exchange rates.
@@ -40,9 +40,11 @@
## 🦄 Tech Stack
- Vue 3
-- Nuxt 3
-- TailwindCSS 4
-- Firebase
+- Nuxt 4
+- Pinia
+- @nuxt/ui v4 (Tailwind CSS v4)
+- Convex (backend)
+- Better Auth (authentication)
- Progressive Web App
<br/>
@@ -57,60 +59,31 @@ cd finapp
pnpm install
```
-### 2. Setup Firebase
-- Create a project in [Firebase Console](https://console.firebase.google.com/).
-- Enable **Realtime Database**.
-- Set Database Rules:
-
-```json
-{
- "rules": {
- "users": {
- "$uid": {
- ".read": "auth != null && auth.uid == $uid",
- ".write": "auth != null && auth.uid == $uid"
- }
- },
- "currencies": {
- ".read": "auth != null",
- ".write": "auth != null"
- },
- "ratesUsd": {
- ".read": "auth != null",
- ".write": "auth != null"
- }
- }
-}
-```
+### 2. Setup Convex
+- Create a project at [convex.dev](https://www.convex.dev/).
+- Copy `.env.example` to `.env` and fill in:
-- Register a **Web App** in Firebase and copy the config.
-- Replace the contents of `services/firebase/config.js` with your config:
-
-```js
-export const firebaseConfig = {
- apiKey: 'YOUR_API_KEY',
- authDomain: 'YOUR_AUTH_DOMAIN',
- databaseURL: 'YOUR_DATABASE_URL',
- messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
- projectId: 'YOUR_PROJECT_ID',
- storageBucket: 'YOUR_STORAGE_BUCKET'
-}
+```bash
+CONVEX_DEPLOYMENT=your_deployment
+VITE_CONVEX_URL=your_convex_url
+VITE_CONVEX_SITE_URL=your_convex_site_url
```
-### 3. Enable Google Authentication
-- In Firebase Console → Authentication → Sign-in method → Enable **Google** provider.
+### 3. Setup Convex Environment Variables
-### 4. Authorize Your Domain (optional)
-- Add your domain under Authentication → Sign-in method → Authorized domains.
-
-### 5. Setup Open Exchange Rates
-- Sign up at [openexchangerates.org](https://openexchangerates.org/signup/free) and get an **App ID**.
-- Rename `.env.example` to `.env` and set your App ID:
+These variables run on the Convex backend. Set them via CLI:
```bash
-OPEN_EXCHANGE_RATES=your_app_id
+npx convex env set SITE_URL your_convex_site_url
+npx convex env set FRONTEND_URL https://your-app-domain.com
+npx convex env set GOOGLE_CLIENT_ID your_client_id
+npx convex env set GOOGLE_CLIENT_SECRET your_client_secret
+npx convex env set OPENEXCHANGERATES_APP_ID your_app_id
```
+- **Google OAuth**: Create credentials in [Google Cloud Console](https://console.cloud.google.com/)
+- **Exchange rates**: Sign up at [openexchangerates.org](https://openexchangerates.org/signup/free)
+
<br/>
## 🛠 Development
@@ -121,21 +94,41 @@ Run local server with hot reload:
pnpm dev
```
+Run Convex dev server (in a separate terminal):
+
+```bash
+pnpm dev:convex
+```
+
<br/>
## 🚀 Production
-Generate static files for deployment:
+Build for SSR (requires Node.js server):
+
+```bash
+pnpm build
+```
+
+Or generate static files for static hosting:
```bash
pnpm generate
```
-Then upload everything in .output/public to any static hosting.
+## 📚 Documentation
-<br/>
+Documentation site built with [Docus](https://docus.dev/). Run locally with `pnpm docs:dev`.
+
+### For users
+- [User Guide](docs/content/en/1.guide/index.md) — features, navigation, wallets, categories, transactions, statistics, settings
-> **Tip**: Use services like Vercel or Netlify for automatic deployments.
+### For developers
+- [Architecture](docs/content/en/2.architecture/index.md) — initialization flow, project structure, store pattern, client access, auth
+- [Transaction Types](docs/content/en/3.transaction-types/index.md) — types, adjustment logic, statistics
+- [Incremental Sync](docs/content/en/4.sync/index.md) — delta sync, deletion detection, performance
+- [Offline Queue](docs/content/en/5.offline-queue/index.md) — queue architecture, collapsing rules, sync scenarios
+- [Technical Decisions](docs/content/en/6.tech/index.md) — rationale behind key design choices
## 🤝 Stay Connected
- Telegram: [@ilkome](https://t.me/ilkome)
diff --git a/app/app.config.ts b/app/app.config.ts
index 464572b5..dc6745c9 100644
--- a/app/app.config.ts
+++ b/app/app.config.ts
@@ -29,9 +29,19 @@ export default defineAppConfig({
viewport: 'scrollerBlock',
},
},
+ modal: {
+ slots: {
+ overlay: '!bg-(--overlay)',
+ },
+ },
toast: {
+ props: {
+ close: false,
+ },
slots: {
- title: 'text-5xl',
+ description: 'text-1',
+ title: 'text-3xl',
+ wrapper: 'flex-row items-center gap-3',
},
},
},
diff --git a/app/app.vue b/app/app.vue
index 3c9583a8..b3b8546b 100644
--- a/app/app.vue
+++ b/app/app.vue
@@ -13,9 +13,20 @@ const toaster: ToasterProps = {
progress: false,
}
-const color = computed(() => colorMode.value === 'dark' ? (colors as any)[appConfig.ui.colors.neutral][900] : 'white')
+onMounted(() => {
+ document.addEventListener('click', (e) => {
+ const target = e.target as HTMLElement
+ const toast = target.closest('li[role="alert"][data-slot="base"]')
+ if (!toast)
+ return
+ const closeBtn = toast.querySelector<HTMLButtonElement>('[data-reka-toast-announce-exclude]')
+ closeBtn?.click()
+ })
+})
+
+const color = computed(() => colorMode.value === 'dark' ? (colors as Record<string, Record<string, string>>)[appConfig.ui.colors.neutral][900] : 'white')
const blackAsPrimary = computed(() => appConfig.theme.blackAsPrimary ? `:root { --ui-primary: black; } .dark { --ui-primary: #ededed; }` : ':root {}')
-const radius = computed(() => `:root { --ui-radius: ${appConfig.theme.radius || '0.375'}rem; }`)
+const radius = computed(() => `:root { --ui-radius: ${appConfig.theme.radius ?? 0.375}rem; }`)
useHead({
htmlAttrs: {
diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 928b4e8c..590d73f7 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -20,7 +20,7 @@
@layer base {
html,
body {
- @apply antialiased text-default bg-[var(--item-1)] select-none;
+ @apply antialiased text-default bg-(--item-1) select-none;
overscroll-behavior-y: none;
}
}
diff --git a/app/assets/css/theme.css b/app/assets/css/theme.css
index 75216b5c..41f78e88 100644
--- a/app/assets/css/theme.css
+++ b/app/assets/css/theme.css
@@ -1,5 +1,4 @@
:root {
- --ui-primary: var(--ui-color-primary-500);
--ui-secondary: var(--ui-color-secondary-500);
--ui-success: var(--ui-color-success-500);
--ui-info: var(--ui-color-info-500);
@@ -9,8 +8,6 @@
--color-neutral-400: var(--ui-color-neutral-400);
--color-neutral-500: var(--ui-color-neutral-500);
- --ui-radius: var(--radius-sm);
-
--expense-1: oklch(0.63 0.24 24.81);
--expense-2: oklch(0.63 0.24 24.81 / 0.5);
--income-1: oklch(0.65 0.2 142.06);
@@ -25,7 +22,6 @@
}
.dark {
- --ui-primary: var(--ui-color-primary-400);
--ui-secondary: var(--ui-color-secondary-400);
--ui-success: var(--ui-color-success-400);
--ui-info: var(--ui-color-info-400);
diff --git a/app/assets/css/utility.css b/app/assets/css/utility.css
index 948f9f2a..5b79e25f 100644
--- a/app/assets/css/utility.css
+++ b/app/assets/css/utility.css
@@ -1,22 +1,13 @@
-@utility flex-center {
- @apply flex items-center justify-center;
-}
-
-@utility flex-center-col {
- @apply flex flex-col items-center justify-center;
+@utility interactive {
+ @apply select-none hover:bg-elevated;
}
-@utility absolute-center {
- @apply absolute top-1/2 left-1/2;
- transform: translate(-50%, -50%);
-}
-
-@utility layoutBase {
- @apply h-dvh;
+@utility flex-center {
+ @apply flex items-center justify-center;
}
@utility pageWrapper {
- @apply @xl/page:max-w-2xl grow px-2 lg:px-4 2xl:px-8;
+ @apply @xl/page:max-w-2xl grow px-3 @md/page:px-4;
}
@utility bottomSheetDrugClassesCustom {
diff --git a/app/assets/js/emo.ts b/app/assets/js/emo.ts
index 6e48dc1c..b581322c 100755
--- a/app/assets/js/emo.ts
+++ b/app/assets/js/emo.ts
@@ -1,5 +1,6 @@
const successEmo = ['🤟', '🤘', '🤙', '👌', '👍', '💪', '👏', '🤗', '🥰', '😍', '🤩']
const errorEmo = ['🤷‍♀️', '🤦‍♀️', '🤔', '😲']
+const warningEmo = ['⚠️', '👀', '🫤', '😬']
function random<T>(items: T[]): T {
return items[Math.floor(Math.random() * items.length)]!
@@ -9,4 +10,5 @@ export {
errorEmo,
random,
successEmo,
+ warningEmo,
}
diff --git a/app/components/about/About.vue b/app/components/about/About.vue
index 66204e87..6e8cde1a 100644
--- a/app/components/about/About.vue
+++ b/app/components/about/About.vue
@@ -4,9 +4,9 @@ const { t } = useI18n()
<template>
<div>
- <UiTitle3 class="pb-4">
+ <UiTitleSection class="pb-4">
{{ t('about.title') }}
- </UiTitle3>
+ </UiTitleSection>
<div class="grid gap-8 pb-3">
<div>
diff --git a/app/components/amount/Amount.vue b/app/components/amount/Amount.vue
index c2190383..51b8136e 100644
--- a/app/components/amount/Amount.vue
+++ b/app/components/amount/Amount.vue
@@ -19,12 +19,19 @@ export type AmountProps = {
variant?: '2xs' | '3xl' | 'base' | 'xs' | 'sm' | 'xl'
}
-const props = withDefaults(defineProps<AmountProps>(), {
- align: 'right',
- isShowBaseRate: true,
- isShowSymbol: true,
- variant: 'base',
-})
+const {
+ align = 'right',
+ amount,
+ colorize,
+ currencyCode,
+ isShowBaseRate = true,
+ isShowMinus,
+ isShowPlus,
+ isShowSymbol = true,
+ precision,
+ type,
+ variant = 'base',
+} = defineProps<AmountProps>()
const emit = defineEmits<{
click: [e: Event]
@@ -36,43 +43,43 @@ const { baseCurrencyCode, getAmountInBaseRate } = useAmount()
<template>
<div
:class="{
- '!text-expense-1': props.colorize === 'expense' && props.type === 0,
- '!text-income-1': props.colorize === 'income' && props.type === 1,
- 'text-2xs': props.variant === '2xs',
- 'text-xs': props.variant === 'xs',
- 'text-sm': props.variant === 'sm',
- 'text-3xl': props.variant === '3xl',
- 'text-xl': props.variant === 'xl',
- 'text-base': props.variant === 'base',
+ '!text-expense-1': colorize === 'expense' && type === 0,
+ '!text-income-1': colorize === 'income' && type === 1,
+ 'text-2xs': variant === '2xs',
+ 'text-xs': variant === 'xs',
+ 'text-sm': variant === 'sm',
+ 'text-3xl': variant === '3xl',
+ 'text-xl': variant === 'xl',
+ 'text-base': variant === 'base',
}"
class="font-secondary grid gap-1 leading-none"
@click="(e: Event) => emit('click', e)"
>
<AmountItem
v-if="amount === 0"
- :align="props.align"
- :isShowSymbol="props.isShowSymbol"
- :symbol="getCurrencySymbol(props.currencyCode)"
+ :align="align"
+ :isShowSymbol="isShowSymbol"
+ :symbol="getCurrencySymbol(currencyCode)"
amount="0"
/>
<template v-if="amount !== 0">
<AmountItem
- :align="props.align"
- :amount="formatAmount(amount, currencyCode, { precision: props.precision })"
- :isShowMinus="props.isShowMinus"
- :isShowPlus="props.isShowPlus"
- :isShowSymbol="props.isShowSymbol"
- :symbol="getCurrencySymbol(props.currencyCode)"
+ :align="align"
+ :amount="formatAmount(amount, currencyCode, { precision })"
+ :isShowMinus="isShowMinus"
+ :isShowPlus="isShowPlus"
+ :isShowSymbol="isShowSymbol"
+ :symbol="getCurrencySymbol(currencyCode)"
/>
<AmountItem
v-if="isShowBaseRate && currencyCode !== baseCurrencyCode"
- :align="props.align"
+ :align="align"
:amount="getAmountInBaseRate({ amount, currencyCode })"
- :isShowMinus="props.isShowMinus"
- :isShowPlus="props.isShowPlus"
- :isShowSymbol="props.isShowSymbol"
+ :isShowMinus="isShowMinus"
+ :isShowPlus="isShowPlus"
+ :isShowSymbol="isShowSymbol"
:symbol="getCurrencySymbol(baseCurrencyCode)"
class="text-xs opacity-70"
/>
diff --git a/app/components/amount/AmountItem.vue b/app/components/amount/AmountItem.vue
index bb09efb6..404032d7 100644
--- a/app/components/amount/AmountItem.vue
+++ b/app/components/amount/AmountItem.vue
@@ -11,12 +11,11 @@ const props = defineProps<{
<template>
<div
- class="flex items-baseline gap-1 leading-none whitespace-nowrap"
- :class="{
- 'justify-center': props.align === 'center',
- 'justify-end': props.align === 'right',
- 'justify-start': props.align === 'left',
- }"
+ :class="cn('flex items-baseline gap-1 leading-none whitespace-nowrap',
+ props.align === 'center' && 'justify-center',
+ props.align === 'right' && 'justify-end',
+ props.align === 'left' && 'justify-start',
+ )"
>
<div v-if="isShowMinus">
-
diff --git a/app/components/amount/getTotal.test.ts b/app/components/amount/getTotal.test.ts
index add1b4b9..2096e563 100644
--- a/app/components/amount/getTotal.test.ts
+++ b/app/components/amount/getTotal.test.ts
@@ -23,6 +23,7 @@ describe('total of Transactions', () => {
})
expect(total).toEqual({
+ adjustment: 0,
expense: 0,
expenseTransfers: 0,
income: 0,
@@ -129,7 +130,7 @@ describe('total of Transactions', () => {
'transactionExpenseWalletCashUSD400',
'transferExpenseWalletCashUSD10IncomeWalletRUB700',
'transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',
- 'transferCategoryNameIncomeWalletCashUSD30',
+ 'transferCategoryIncomeWalletCashUSD30',
'transferCategoryIdExpenseWalletCashUSD30',
]
@@ -154,7 +155,7 @@ describe('total of Transactions', () => {
'transactionIncomeWalletCashUSD1000',
'transactionExpenseWalletCashUSD400',
'transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',
- 'transferCategoryNameIncomeWalletCashUSD30',
+ 'transferCategoryIncomeWalletCashUSD30',
'transferCategoryIdExpenseWalletCashUSD30',
]
@@ -172,36 +173,4 @@ describe('total of Transactions', () => {
expect(total.expenseTransfers).toEqual(70)
expect(total.sumTransfers).toEqual(0)
})
-
- it('total of Transfers with deprecated Transfer type when no Wallets provided', () => {
- const trnsIds = ['transferOLDExpense2500Income3500']
-
- const total = getTotal({
- transferCategoriesIds,
- trnsIds,
- trnsItems,
- walletsItems,
- })
-
- expect(total.incomeTransfers).toEqual(3500)
- expect(total.expenseTransfers).toEqual(2500)
- expect(total.sumTransfers).toEqual(1000)
- })
-
- it('total of Transfers with deprecated Transfer type', () => {
- const walletsIds = ['walletDeprecatedTransferIncome', 'walletDeprecatedTransferExpense']
- const trnsIds = ['transferOLDExpense2500Income3500']
-
- const total = getTotal({
- transferCategoriesIds,
- trnsIds,
- trnsItems,
- walletsIds,
- walletsItems,
- })
-
- expect(total.incomeTransfers).toEqual(3500)
- expect(total.expenseTransfers).toEqual(2500)
- expect(total.sumTransfers).toEqual(1000)
- })
})
diff --git a/app/components/amount/getTotal.ts b/app/components/amount/getTotal.ts
index 33771d72..99ab57f4 100644
--- a/app/components/amount/getTotal.ts
+++ b/app/components/amount/getTotal.ts
@@ -13,7 +13,7 @@ export function getAmountInRate({
}: {
amount: number
baseCurrencyCode?: CurrencyCode
- currencyCode: string
+ currencyCode: CurrencyCode
rates?: Rates
}): number {
if (!baseCurrencyCode || !rates)
@@ -38,6 +38,7 @@ type TotalProps = {
export type DateString = string
export type TotalReturns = {
+ adjustment: number
expense: number
expenseTransfers: number
income: number
@@ -49,7 +50,7 @@ export type TotalReturns = {
export function getTotal(props: TotalProps): TotalReturns {
const { baseCurrencyCode, rates, transferCategoriesIds, trnsIds, trnsItems, walletsIds, walletsItems } = props
- function getAmount(amount: number, currencyCode: string) {
+ function getAmount(amount: number, currencyCode: CurrencyCode) {
return getAmountInRate({
amount,
baseCurrencyCode,
@@ -62,6 +63,7 @@ export function getTotal(props: TotalProps): TotalReturns {
let expense = 0
let incomeTransfers = 0
let expenseTransfers = 0
+ let adjustment = 0
for (const trnId of trnsIds || []) {
const trn = trnsItems[trnId]
@@ -70,6 +72,12 @@ 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]
+ adjustment += getAmount(trn.amount, wallet?.currency || 'USD')
+ continue
+ }
const isTransferCategory = transferCategoriesIds?.includes(trn.categoryId || '')
const wallet = walletsItems[trn.walletId]
const sum = getAmount(trn.amount, wallet?.currency || 'USD')
@@ -116,37 +124,6 @@ export function getTotal(props: TotalProps): TotalReturns {
expenseTransfers += expenseAmount
}
}
-
- // Transfer @deprecated
- else if (trn.type === TrnType.Transfer && 'walletFromId' in trn && 'walletToId' in trn) {
- const incomeWalletId = trn.walletToId as WalletId
- const expenseWalletId = trn.walletFromId as WalletId
- if (!incomeWalletId || !expenseWalletId)
- continue
-
- const incomeWallet = walletsItems[incomeWalletId]
- const expenseWallet = walletsItems[expenseWalletId]
- if (!incomeWallet || !expenseWallet)
- continue
-
- const incomeAmount = getAmount(trn.amountTo as number, incomeWallet.currency)
- const expenseAmount = getAmount(trn.amountFrom as number, expenseWallet.currency)
-
- // Include only selected wallets
- if (walletsIds && walletsIds.length > 0) {
- // Income
- if (walletsIds.includes(incomeWalletId))
- incomeTransfers += incomeAmount
-
- // Expense
- if (walletsIds.includes(expenseWalletId))
- expenseTransfers += expenseAmount
- }
- else {
- incomeTransfers += incomeAmount
- expenseTransfers += expenseAmount
- }
- }
}
// Total
@@ -154,6 +131,7 @@ export function getTotal(props: TotalProps): TotalReturns {
const sumTransfers = incomeTransfers - expenseTransfers
return {
+ adjustment,
expense,
expenseTransfers,
income,
diff --git a/app/components/amount/utils.ts b/app/components/amount/utils.ts
index 4d6a355a..3eb24c0f 100644
--- a/app/components/amount/utils.ts
+++ b/app/components/amount/utils.ts
@@ -1,5 +1,3 @@
-import currency from 'currency.js'
-
import type { CurrencyCode } from '~/components/currencies/types'
import { currencies } from '~/components/currencies/currencies'
@@ -7,17 +5,16 @@ import { currencies } from '~/components/currencies/currencies'
export function formatAmount(amount: number, currencyCode?: CurrencyCode, {
precision = 0,
} = {}) {
- let currencySettings: Partial<currency.Options> | null = null
+ const currencySettings = currencyCode
+ ? currencies.find(c => c.code === currencyCode) ?? null
+ : null
- if (currencyCode && currencies.find(c => c.code === currencyCode))
- currencySettings = currencies.find(c => c.code === currencyCode)
+ const p = precision != null ? precision : currencySettings?.precision ?? 2
- return currency(amount, {
- pattern: currencySettings?.pattern ?? '#',
- precision: precision !== 0 ? precision : currencySettings?.precision ?? 2,
- separator: currencySettings?.separator ?? ' ',
- symbol: '',
- }).format()
+ return new Intl.NumberFormat('en-US', {
+ maximumFractionDigits: p,
+ minimumFractionDigits: p,
+ }).format(amount).replace(/,/g, ' ')
}
export function getCurrencySymbol(currencyCode?: CurrencyCode) {
@@ -30,10 +27,5 @@ export function getCurrencySymbol(currencyCode?: CurrencyCode) {
}
export function formatByCurrency(value: string, separator: string) {
- return currency(value, {
- pattern: '#',
- precision: 0,
- separator,
- })
- .format()
+ return value.replace(/\B(?=(\d{3})+(?!\d))/g, separator)
}
diff --git a/app/components/app/Copyright.vue b/app/components/app/Copyright.vue
index 3929d3ec..38caf22e 100644
--- a/app/components/app/Copyright.vue
+++ b/app/components/app/Copyright.vue
@@ -1,13 +1,10 @@
<script setup lang="ts">
-import { classes } from '~/components/ui/getStyles'
-
const { t } = useI18n()
</script>
<template>
<a
- :class="[classes.item.rounded, classes.item.link, classes.item.center3]"
- class="text-muted px-5 py-2 text-sm"
+ class="interactive flex-center text-muted rounded-sm px-5 py-2 text-sm"
href="https://ilko.me"
>
{{ t('app.madeBy.text') }}
diff --git a/app/components/app/Onboarding.vue b/app/components/app/Onboarding.vue
new file mode 100644
index 00000000..e9672be1
--- /dev/null
+++ b/app/components/app/Onboarding.vue
@@ -0,0 +1,69 @@
+<script setup lang="ts">
+import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+
+const { t } = useI18n()
+const router = useRouter()
+const walletsStore = useWalletsStore()
+const categoriesStore = useCategoriesStore()
+const trnsFormStore = useTrnsFormStore()
+
+const introText = computed(() => {
+ if (!walletsStore.hasItems)
+ return t('onboarding.introWallets')
+
+ if (!categoriesStore.hasItems)
+ return t('onboarding.introCategories')
+
+ return t('onboarding.intro')
+})
+</script>
+
+<template>
+ <div class="onboarding flex min-h-svh items-center justify-center">
+ <div class="flex-center flex-col gap-6 px-4 text-center">
+ <UiLogo class="!text-6xl" />
+
+ <div class="flex flex-col gap-2">
+ <p class="text-muted">
+ {{ introText }}
+ </p>
+ </div>
+
+ <UButton
+ v-if="!walletsStore.hasItems"
+ size="xl"
+ class="min-w-52 justify-center rounded-full px-8 py-3"
+ @click="router.push('/wallets/new?onboarding')"
+ >
+ {{ t('onboarding.actionWallet') }}
+ </UButton>
+
+ <UButton
+ v-else-if="!categoriesStore.hasItems"
+ size="xl"
+ class="min-w-52 justify-center rounded-full px-8 py-3"
+ @click="router.push('/categories/new?onboarding')"
+ >
+ {{ t('onboarding.actionCategory') }}
+ </UButton>
+
+ <UButton
+ v-else
+ size="xl"
+ class="min-w-52 justify-center rounded-full px-8 py-3"
+ @click="trnsFormStore.trnFormCreate()"
+ >
+ {{ t('onboarding.actionTrn') }}
+ </UButton>
+ </div>
+ </div>
+</template>
+
+<style>
+.bg-default:has(.onboarding) {
+ background: transparent !important;
+ border: none !important;
+}
+</style>
diff --git a/app/components/app/Welcome.vue b/app/components/app/Welcome.vue
deleted file mode 100644
index f9cc1bac..00000000
--- a/app/components/app/Welcome.vue
+++ /dev/null
@@ -1,59 +0,0 @@
-<script setup lang="ts">
-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
-import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-
-const { t } = useI18n()
-const router = useRouter()
-const walletsStore = useWalletsStore()
-const categoriesStore = useCategoriesStore()
-const trnsFormStore = useTrnsFormStore()
-
-const introText = computed(() => {
- if (!walletsStore.hasItems) {
- return t('welcome.introWallets')
- }
-
- if (!categoriesStore.hasItems) {
- return t('welcome.introCategories')
- }
-
- return t('welcome.intro')
-})
-</script>
-
-<template>
- <UiPage class="flex h-full items-center justify-center">
- <div
- class="flex-center h-full flex-col pt-10"
- >
- <UiTitle3 class="pb-4">
- {{ introText }}
- </UiTitle3>
-
- <UiButtonAccent
- v-if="!walletsStore.hasItems"
- rounded
- @click="router.push('/wallets/new')"
- >
- {{ t('wallets.new') }}
- </UiButtonAccent>
-
- <UiButtonAccent
- v-else-if="!categoriesStore.hasItems"
- rounded
- @click="router.push('/categories/new')"
- >
- {{ t('categories.new') }}
- </UiButtonAccent>
-
- <UiButtonAccent
- v-else
- rounded
- @click="trnsFormStore.trnFormCreate()"
- >
- {{ t('welcome.createTrn') }}
- </UiButtonAccent>
- </div>
- </UiPage>
-</template>
diff --git a/app/components/app/useAppNav.ts b/app/components/app/useAppNav.ts
deleted file mode 100644
index 58f0dc8d..00000000
--- a/app/components/app/useAppNav.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-export const useAppNav = defineStore('appNav', () => {
- const modals = useModal<'menu' | 'walletsSort'>()
-
- return {
- ...modals,
- }
-})
-
-function useModal<T>() {
- const modals = ref<T[]>([])
-
- function openModal(name: T) {
- if (modals.value.includes(name))
- return
- modals.value.push(name)
- }
-
- function closeModal(name: T) {
- modals.value = modals.value.filter(modal => modal !== name)
- }
-
- function closeAllModals() {
- modals.value = []
- }
-
- function isModalOpen(name: T) {
- return modals.value.includes(name)
- }
-
- return {
- closeAllModals,
- closeModal,
- isModalOpen,
- modals,
- openModal,
- }
-}
diff --git a/app/components/app/useInitApp.ts b/app/components/app/useInitApp.ts
index 9e44829f..0e6020b8 100644
--- a/app/components/app/useInitApp.ts
+++ b/app/components/app/useInitApp.ts
@@ -1,10 +1,19 @@
import localforage from 'localforage'
+import type { LocaleSlug } from '~/components/locale/types'
+
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { setOfflineQueueUserId } from '~/components/offline/helpers'
+import { replayOfflineQueue } from '~/components/offline/replay'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useUserStore } from '~/components/user/useUserStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { blockPersist, unblockPersist } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
+
+const isDbLoading = ref(false)
export function useInitApp() {
const userStore = useUserStore()
@@ -14,16 +23,20 @@ export function useInitApp() {
const trnsStore = useTrnsStore()
async function loadDataFromCache() {
- const [user, currencies, categories, wallets, trns] = await Promise.all([
- localforage.getItem('finapp.user'),
- localforage.getItem('finapp.currencies'),
- localforage.getItem('finapp.categories'),
- localforage.getItem('finapp.wallets'),
- localforage.getItem('finapp.trns'),
+ const [user, userSettings, currencies, categories, wallets, trns] = await Promise.all([
+ localforage.getItem(STORAGE_KEYS.user),
+ localforage.getItem<{ baseCurrency?: string, locale?: LocaleSlug }>(STORAGE_KEYS.userSettings),
+ localforage.getItem(STORAGE_KEYS.currencies),
+ localforage.getItem(STORAGE_KEYS.categories),
+ localforage.getItem(STORAGE_KEYS.wallets),
+ localforage.getItem(STORAGE_KEYS.trns),
])
userStore.setUser(user)
- currenciesStore.setBase(currencies?.base ?? 'USD')
+ if (userSettings?.baseCurrency)
+ userStore.setUserBaseCurrency(userSettings.baseCurrency)
+ if (userSettings?.locale)
+ userStore.setUserLocale(userSettings.locale)
currenciesStore.setRates(currencies?.rates)
walletsStore.setWallets(wallets)
categoriesStore.setCategories(categories)
@@ -31,27 +44,55 @@ export function useInitApp() {
}
function clearLocalData() {
+ // Block all persist operations — prevents in-flight store inits, mutation callbacks,
+ // and debounced persists from re-writing data after cleanup.
+ blockPersist()
+
+ categoriesStore.cancelPersist()
+ trnsStore.cancelPersist()
+ walletsStore.cancelPersist()
+
categoriesStore.setCategories(null)
trnsStore.setTrns(null)
walletsStore.setWallets(null)
userStore.setUser(null)
+
+ // Clear cached data from localforage to prevent data leaks on shared devices.
+ // The offline queue is intentionally preserved — it has its own userId ownership check.
+ for (const key of Object.values(STORAGE_KEYS))
+ localforage.removeItem(key)
}
- function loadDataFromDB() {
+ async function loadDataFromDB() {
+ // Unblock persists — may have been blocked by a prior clearLocalData
+ unblockPersist()
+
+ // Set in-memory userId for queue ownership stamping during pushes
+ setOfflineQueueUserId(userStore.uid)
+
+ isDbLoading.value = true
try {
- currenciesStore.initCurrencies()
- categoriesStore.initCategories()
- walletsStore.initWallets()
- trnsStore.initTrns()
- trnsStore.uploadOfflineTrns()
+ await Promise.all([
+ userStore.initUserSettings(),
+ currenciesStore.initCurrencies(),
+ categoriesStore.initCategories(),
+ walletsStore.initWallets(),
+ trnsStore.initTrns(),
+ ])
+
+ await replayOfflineQueue()
}
catch (e) {
- console.error(e)
+ createLogger('app').error('loadDataFromDB failed', e)
+ }
+ finally {
+ isDbLoading.value = false
}
}
return {
clearLocalData,
+ isDbLoading,
loadDataFromCache,
loadDataFromDB,
}
diff --git a/app/components/bottomSheet/BottomSheet.vue b/app/components/bottomSheet/BottomSheet.vue
index 2078ad95..d1f98f79 100644
--- a/app/components/bottomSheet/BottomSheet.vue
+++ b/app/components/bottomSheet/BottomSheet.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
-import { useElementSize, useEventListener, useWindowSize } from '@vueuse/core'
+import { useElementSize, useScrollLock, useWindowSize } from '@vueuse/core'
-type Event = TouchEvent | MouseEvent
+import { useBottomSheetDrag } from './useBottomSheetDrag'
const props = defineProps<{
drugClassesCustom?: string
@@ -27,389 +27,49 @@ const containerRef = ref<HTMLElement | null>(null)
const handlerRef = ref<HTMLElement | null>(null)
const contentInside = ref<HTMLElement | null>(null)
-// State
-const initialHeight = ref(0)
-
-const initialY = ref(0)
-const clientY = ref(0)
-const isDragging = ref(true)
-const direction = ref<'up' | 'down'>('up')
-const isHandler = ref(false)
-
-const disabled = ref(true)
-const opened = ref(false)
-const isEventsAdded = ref(false)
-
const { height: drugHeight } = useElementSize(drug)
const { height: windowHeight } = useWindowSize()
-/**
- * Next current y
- */
-const nextCurrentY = computed(() => clientY.value - initialY.value)
-
-/*
- * Set direction
- */
-watch(nextCurrentY, (current, prev) => {
- direction.value = current > prev ? 'down' : 'up'
-})
-
-/**
- * Debounce drug
- */
-const debounce = computed(() =>
- disabled.value || isHandler.value ? 0 : settings.pixelOffsetToStartClosing,
-)
-
-/**
- * Diff height
- */
-const diffHeight = computed(() => {
- const containerHeight = drug.value?.clientHeight ?? 0
- const handlerHeight = handlerRef.value?.clientHeight ?? 0
- return Math.round(
- (containerHeight + handlerHeight - nextCurrentY.value)
- / (containerHeight / 100),
- )
-})
-
-/**
- * Diff height with debounce
- */
-const diffHeightWithDebounce = computed(() => {
- const containerHeight = drug.value?.clientHeight ?? 0
- const handlerHeight = handlerRef.value?.clientHeight ?? 0
- return Math.round(
- (containerHeight + handlerHeight - nextCurrentY.value + debounce.value)
- / (containerHeight / 100),
- )
-})
-
-/**
- * Overlay Opacity
- */
-const overlayStyles = computed(() => {
- if (nextCurrentY.value <= debounce.value)
- return
-
- let opacity = 1
- if (diffHeight.value < 0 || diffHeight.value > 100) {
- opacity = nextCurrentY.value <= 100 ? 1 : 0
- }
- else {
- opacity = Number(
- diffHeightWithDebounce.value >= 100
- ? 1
- : diffHeightWithDebounce.value >= 10
- ? `0.${diffHeightWithDebounce.value}`
- : `0.0${diffHeightWithDebounce.value}`,
- )
- }
- return {
- opacity,
- }
-})
-
-/**
- * Drug styles
- */
-const drugStyles = computed(() => {
- if (!opened.value) {
- return {
- ...props.drugStyle,
- opacity: 0,
- transform: 'translateY(30px)',
- }
- }
-
- if (nextCurrentY.value <= debounce.value) {
- return {
- ...props.drugStyle,
- opacity: 1,
- transform: '',
- }
- }
-
- return {
- ...props.drugStyle,
- transform: `translateY(${nextCurrentY.value - debounce.value}px)`,
- }
-})
-
-/**
- * Get client Y
- */
-function getClientY(event: Event): number {
- return 'touches' in event
- ? Math.round(event.touches[0].clientY)
- : event.clientY
-}
-
-/**
- * Content has scroll
- */
-function contentHasScroll(event: Event) {
- // Handle scroll inside slider
- const swiperSlideActive = drug.value?.querySelector('.swiper-slide-active')
- if (swiperSlideActive) {
- const scrollerBlock = swiperSlideActive.querySelector('.scrollerBlock')
- if (scrollerBlock)
- return scrollerBlock.scrollTop > 0 && event.type.includes('touch')
- }
-
- // const scrollerBlock = drug.value?.querySelector('.scrollerBlock')
- // if (!swiperSlideActive && drug.value)
- // return drug.value.scrollTop > 0 && event.type.includes('touch')
-
- const scrollerBlock = drug.value?.querySelector('.scrollerBlock')
- if (!swiperSlideActive && scrollerBlock)
- return scrollerBlock.scrollTop > 0 && event.type.includes('touch')
-}
-
-/**
- * Drag start
- */
-function onDragStart(event: Event): void {
- if (event.target instanceof Element && event?.target?.closest('.sortHandle'))
- return
-
- if (disabled.value)
- return
-
- if (event.target instanceof Element) {
- isHandler.value = event.target.classList.contains('handler')
- const isTarget = event.target.closest('.drug')
- const isHasScroll = contentHasScroll(event)
-
- if ((!isTarget || isHasScroll) && !isHandler.value) {
- isDragging.value = false
- return
- }
-
- clientY.value = getClientY(event)
- initialY.value = clientY.value + initialY.value
- isDragging.value = true
- }
-}
-
-const debug = ref({
- diffHeight: computed(() => diffHeight.value),
- diffHeightWithDebounce: computed(() => diffHeightWithDebounce.value),
- direction: computed(() => direction.value),
- nextCurrentY: computed(() => nextCurrentY.value),
- status: 'standby',
-})
-
-/**
- * Dragging
- */
-function onDragging(event: Event): void {
- if (disabled.value || !isDragging.value)
- return
-
- const isHasScroll = contentHasScroll(event)
-
- const bodyHeight = document.querySelector('body')?.clientHeight ?? 0
- const contentInsideHeight = contentInside.value?.clientHeight ?? 0
- const drugHeight = drug.value?.clientHeight ?? 0
-
- if (
- isDragging.value
- && drug.value
- && drugHeight < contentInsideHeight
- && drugHeight + 10 < bodyHeight
- ) {
- drug.value
- ?.querySelector('.scrollerBlock')
- ?.classList
- .add('pointer-events-none')
- drug.value.style.height = `${initialHeight.value - nextCurrentY.value}px`
- }
- else {
- drug.value
- ?.querySelector('.scrollerBlock')
- ?.classList
- .remove('pointer-events-none')
- }
-
- if (isHasScroll && !isHandler.value) {
- isDragging.value = false
- initialY.value = 0
- clientY.value = 0
- return
- }
-
- // drug on pc only by handler drug on mobile everywhere
- // if (isDragging.value && ((!isHandler.value && event.type.includes('touch') || isHandler.value)))
- // clientY.value = getClientY(event)
-
- if (isDragging.value)
- clientY.value = getClientY(event)
-
- if (settings.debug) {
- debug.value.status = nextCurrentY.value >= settings.pixelsNeedToDrugForClose && direction.value === 'down'
- ? 'will close'
- : 'will open'
- }
-}
-
-/**
- * Drag end
- */
-async function onDragEnd() {
- if (disabled.value || !isDragging.value)
- return
-
- const bodyHeight = document.querySelector('body')?.clientHeight ?? 0
- const contentInsideHeight = contentInside.value?.clientHeight ?? 0
- const drugHeight = drug.value?.clientHeight ?? 0
-
- if (direction.value === 'up' && nextCurrentY.value < 0) {
- await nextTick()
- if (
- isDragging.value
- && drug.value
- && drugHeight < contentInsideHeight
- && drugHeight + 10 < bodyHeight
- ) {
- drug.value.style.height = `${bodyHeight - 10}px`
- }
- }
-
- const isNeedClose
- = nextCurrentY.value >= settings.pixelsNeedToDrugForClose
- && direction.value === 'down'
-
- if (isNeedClose) {
- close()
- }
- else {
- open()
- }
-}
-
-/**
- * Clear
- */
-function clear() {
- clientY.value = 0
- isDragging.value = false
-}
-
-function setInitialY() {
- initialY.value = -(
- (drug.value?.clientHeight ?? 0) + (handlerRef.value?.clientHeight ?? 0)
- )
-}
-
-/**
- * Close modal
- */
-function close() {
- clear()
- setInitialY()
-}
-
-/**
- * Open modal
- */
-function open() {
- clear()
- opened.value = true
- initialY.value = 0
-}
-
-/**
- * On close modal
- */
-function onClose() {
- // Scroll up all scroller blocks
- const scrollerBlocks = drug.value?.querySelectorAll('.scrollerBlock')
- scrollerBlocks?.forEach(el => (el.scrollTop = 0))
- drug.value?.removeEventListener('transitionend', onClose)
- opened.value = false
- emit('closed')
-}
-
-/**
- * Add events listeners
- */
-function addEvents() {
- if (isEventsAdded.value)
- return
-
- isEventsAdded.value = true
-
- // Touch
- if (containerRef.value) {
- containerRef.value.addEventListener('touchstart', onDragStart)
- containerRef.value.addEventListener('touchmove', onDragging)
- containerRef.value.addEventListener('touchend', onDragEnd)
- containerRef.value.addEventListener('mousedown', onDragStart)
- containerRef.value.addEventListener('mouseup', onDragEnd)
-
- document.addEventListener('mousemove', onDragging)
- document.addEventListener('mouseleave', onDragEnd)
- }
-}
-
-/**
- * Watch for diff height
- */
-watch(diffHeight, () => {
- if (isDragging.value)
- return
-
- if (diffHeight.value === 0) {
- disabled.value = true
- useEventListener(drug, 'transitionend', onClose, { passive: true })
- return
- }
-
- disabled.value = false
+const {
+ close,
+ drugStyles,
+ init,
+ isDragging,
+ opened,
+ overflowClasses,
+ overlayStyles,
+ removeEvents,
+ wrapClasses,
+} = useBottomSheetDrag({
+ containerRef,
+ contentInside,
+ drug,
+ drugStyle: toRef(() => props.drugStyle),
+ emit,
+ handlerRef,
+ settings,
})
/**
- * Init modal
+ * Body scroll lock
*/
-async function init() {
- initialHeight.value = drug.value?.clientHeight ?? 0
-
- setTimeout(async () => {
- setInitialY()
- disabled.value = false
- addEvents()
- setTimeout(() => {
- open()
- }, 10)
- }, 10)
-}
-
-function removeEvents() {
- isEventsAdded.value = false
- if (containerRef.value) {
- containerRef.value.removeEventListener('touchstart', onDragStart)
- containerRef.value.removeEventListener('touchmove', onDragging)
- containerRef.value.removeEventListener('touchend', onDragEnd)
- containerRef.value.removeEventListener('mousedown', onDragStart)
- containerRef.value.removeEventListener('mouseup', onDragEnd)
+const isBodyLocked = import.meta.client ? useScrollLock(document.body) : ref(false)
- document.removeEventListener('mousemove', onDragging)
- document.removeEventListener('mouseleave', onDragEnd)
- }
-}
/**
* Run init when mounted or isShow changed
*/
watch(
() => props.isShow,
async (value) => {
- if (value)
+ if (value) {
+ isBodyLocked.value = true
await init()
+ }
- if (!value)
+ if (!value) {
+ isBodyLocked.value = false
removeEvents()
+ }
if (!value && opened.value) {
close()
@@ -418,7 +78,11 @@ watch(
{ immediate: true },
)
-onBeforeUnmount(removeEvents)
+onBeforeUnmount(() => {
+ isBodyLocked.value = false
+ removeEvents()
+})
+
/**
* Height
*/
@@ -431,29 +95,20 @@ const drugClasses = computed(() => [
},
props.drugClassesCustom,
])
-
-const overflowClasses = computed(() => ({
- 'transition-opacity duration-100': !isDragging.value && opened.value,
-}))
-
-const wrapClasses = computed(() => ({
- 'pointer-events-none': props.isHideOverflow,
- 'pointer-events-none invisible opacity-0': !opened.value,
-}))
</script>
<template>
<div
ref="containerRef"
- :class="wrapClasses"
- class="absolute inset-0 z-50 size-full overflow-hidden select-none"
+ :class="[wrapClasses, { 'pointer-events-none': isHideOverflow }]"
+ class="fixed inset-0 z-50 size-full overflow-hidden select-none"
>
<!-- Overlay -->
<div
v-if="!isHideOverflow"
:class="overflowClasses"
:style="overlayStyles"
- class="absolute inset-0 z-10 size-full bg-[var(--overlay)]"
+ class="absolute inset-0 z-10 size-full bg-(--overlay)"
@click="close()"
/>
@@ -468,7 +123,7 @@ const wrapClasses = computed(() => ({
<div ref="handlerRef">
<slot name="handler" :close="close">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</slot>
</div>
diff --git a/app/components/bottomSheet/BottomSheetClose.vue b/app/components/bottomSheet/BottomSheetClose.vue
index 8f492235..61b385fe 100644
--- a/app/components/bottomSheet/BottomSheetClose.vue
+++ b/app/components/bottomSheet/BottomSheetClose.vue
@@ -1,13 +1,13 @@
<script setup lang="ts">
const emit = defineEmits<{
- onClick: [e: Event]
+ click: [e: Event]
}>()
</script>
<template>
<div
- class="bg-item-3 absolute top-1 right-1 z-30 flex size-8 items-center justify-center rounded-full transition ease-in-out hover:bg-[var(--item-5)]"
- @click="(e: Event) => emit('onClick', e)"
+ class="bg-item-3 absolute top-1 right-1 z-30 flex size-8 items-center justify-center rounded-full transition ease-in-out hover:bg-(--item-5)"
+ @click="(e: Event) => emit('click', e)"
>
<Icon
name="lucide:x"
diff --git a/app/components/bottomSheet/BottomSheetHandler.vue b/app/components/bottomSheet/BottomSheetHandler.vue
index f7b22b9c..781a6bb9 100644
--- a/app/components/bottomSheet/BottomSheetHandler.vue
+++ b/app/components/bottomSheet/BottomSheetHandler.vue
@@ -3,7 +3,7 @@
class="
handler flex-center after:bg-item-7 absolute top-0 left-0 z-30
h-[16px] w-full transition
- after:block after:h-[4px] after:w-[32px] after:rounded-sm after:content-[''] hover:bg-[var(--item-5)]
+ after:block after:h-[4px] after:w-[32px] after:rounded-sm after:content-[''] hover:bg-(--item-5)
"
/>
</template>
diff --git a/app/components/bottomSheet/BottomSheetOrDropdown.vue b/app/components/bottomSheet/BottomSheetOrDropdown.vue
index 97dea939..d1e6e69d 100644
--- a/app/components/bottomSheet/BottomSheetOrDropdown.vue
+++ b/app/components/bottomSheet/BottomSheetOrDropdown.vue
@@ -11,8 +11,8 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onCloseModal: []
- onOpenModal: []
+ closeModal: []
+ openModal: []
}>()
const { width } = useWindowSize()
@@ -62,7 +62,7 @@ const open = ref(false)
<div
v-else
class="grow"
- @click="emit('onOpenModal')"
+ @click="emit('openModal')"
>
<slot name="trigger" />
@@ -72,7 +72,7 @@ const open = ref(false)
isShow
:drugClassesCustom="`${props.drugClassesCustom ?? ''} bottomSheetDrugClassesCustom`"
:drugStyle="props.bottomSheetStyle"
- @closed="emit('onCloseModal')"
+ @closed="emit('closeModal')"
>
<template #default="{ close }">
<div class="bottomSheetContent">
diff --git a/app/components/bottomSheet/useBottomSheetDrag.ts b/app/components/bottomSheet/useBottomSheetDrag.ts
new file mode 100644
index 00000000..56346449
--- /dev/null
+++ b/app/components/bottomSheet/useBottomSheetDrag.ts
@@ -0,0 +1,425 @@
+import type { Ref } from 'vue'
+
+import { useEventListener } from '@vueuse/core'
+
+type Event = TouchEvent | MouseEvent
+
+const PERCENT_BASE = 100
+const EDGE_PADDING = 10
+const INIT_DELAY_MS = 10
+
+type UseBottomSheetDragParams = {
+ containerRef: Ref<HTMLElement | null>
+ contentInside: Ref<HTMLElement | null>
+ drug: Ref<HTMLElement | null>
+ drugStyle: Ref<Record<string, string> | undefined>
+ emit: (event: 'closed') => void
+ handlerRef: Ref<HTMLElement | null>
+ settings: {
+ debug: boolean
+ pixelOffsetToStartClosing: number
+ pixelsNeedToDrugForClose: number
+ }
+}
+
+export function useBottomSheetDrag({
+ containerRef,
+ contentInside,
+ drug,
+ drugStyle,
+ emit,
+ handlerRef,
+ settings,
+}: UseBottomSheetDragParams) {
+ // State
+ const initialHeight = ref(0)
+ const initialY = ref(0)
+ const clientY = ref(0)
+ const isDragging = ref(true)
+ const direction = ref<'down' | 'up'>('up')
+ const isHandler = ref(false)
+ const disabled = ref(true)
+ const opened = ref(false)
+ const isEventsAdded = ref(false)
+
+ /**
+ * Next current y
+ */
+ const nextCurrentY = computed(() => clientY.value - initialY.value)
+
+ /**
+ * Set direction
+ */
+ watch(nextCurrentY, (current, prev) => {
+ direction.value = current > prev ? 'down' : 'up'
+ })
+
+ /**
+ * Debounce drug
+ */
+ const debounce = computed(() =>
+ disabled.value || isHandler.value ? 0 : settings.pixelOffsetToStartClosing,
+ )
+
+ /**
+ * Diff height
+ */
+ const diffHeight = computed(() => {
+ const containerHeight = drug.value?.clientHeight ?? 0
+ const handlerHeight = handlerRef.value?.clientHeight ?? 0
+ return Math.round(
+ (containerHeight + handlerHeight - nextCurrentY.value)
+ / (containerHeight / PERCENT_BASE),
+ )
+ })
+
+ /**
+ * Diff height with debounce
+ */
+ const diffHeightWithDebounce = computed(() => {
+ const containerHeight = drug.value?.clientHeight ?? 0
+ const handlerHeight = handlerRef.value?.clientHeight ?? 0
+ return Math.round(
+ (containerHeight + handlerHeight - nextCurrentY.value + debounce.value)
+ / (containerHeight / PERCENT_BASE),
+ )
+ })
+
+ /**
+ * Debug
+ */
+ const debug = ref({
+ diffHeight: computed(() => diffHeight.value),
+ diffHeightWithDebounce: computed(() => diffHeightWithDebounce.value),
+ direction: computed(() => direction.value),
+ nextCurrentY: computed(() => nextCurrentY.value),
+ status: 'standby',
+ })
+
+ /**
+ * Overlay Opacity
+ */
+ const overlayStyles = computed(() => {
+ if (nextCurrentY.value <= debounce.value)
+ return
+
+ let opacity = 1
+ if (diffHeight.value < 0 || diffHeight.value > PERCENT_BASE) {
+ opacity = nextCurrentY.value <= PERCENT_BASE ? 1 : 0
+ }
+ else {
+ opacity = Number(
+ diffHeightWithDebounce.value >= PERCENT_BASE
+ ? 1
+ : diffHeightWithDebounce.value >= EDGE_PADDING
+ ? `0.${diffHeightWithDebounce.value}`
+ : `0.0${diffHeightWithDebounce.value}`,
+ )
+ }
+ return {
+ opacity,
+ }
+ })
+
+ /**
+ * Drug styles
+ */
+ const drugStyles = computed(() => {
+ if (!opened.value) {
+ return {
+ ...drugStyle.value,
+ opacity: 0,
+ transform: 'translateY(30px)',
+ }
+ }
+
+ if (nextCurrentY.value <= debounce.value) {
+ return {
+ ...drugStyle.value,
+ opacity: 1,
+ transform: '',
+ }
+ }
+
+ return {
+ ...drugStyle.value,
+ transform: `translateY(${nextCurrentY.value - debounce.value}px)`,
+ }
+ })
+
+ /**
+ * Get client Y
+ */
+ function getClientY(event: Event): number {
+ return 'touches' in event
+ ? Math.round(event.touches[0].clientY)
+ : event.clientY
+ }
+
+ /**
+ * Content has scroll
+ */
+ function contentHasScroll(event: Event) {
+ // Handle scroll inside slider
+ const swiperSlideActive = drug.value?.querySelector('.swiper-slide-active')
+ if (swiperSlideActive) {
+ const scrollerBlock = swiperSlideActive.querySelector('.scrollerBlock')
+ if (scrollerBlock)
+ return scrollerBlock.scrollTop > 0 && event.type.includes('touch')
+ }
+
+ const scrollerBlock = drug.value?.querySelector('.scrollerBlock')
+ if (!swiperSlideActive && scrollerBlock)
+ return scrollerBlock.scrollTop > 0 && event.type.includes('touch')
+ }
+
+ /**
+ * Drag start
+ */
+ function onDragStart(event: Event): void {
+ if (event.target instanceof Element && event?.target?.closest('.sortHandle'))
+ return
+
+ if (disabled.value)
+ return
+
+ if (event.target instanceof Element) {
+ isHandler.value = event.target.classList.contains('handler')
+ const isTarget = event.target.closest('.drug')
+ const isHasScroll = contentHasScroll(event)
+
+ if ((!isTarget || isHasScroll) && !isHandler.value) {
+ isDragging.value = false
+ return
+ }
+
+ clientY.value = getClientY(event)
+ initialY.value = clientY.value + initialY.value
+ isDragging.value = true
+ }
+ }
+
+ /**
+ * Dragging
+ */
+ function onDragging(event: Event): void {
+ if (disabled.value || !isDragging.value)
+ return
+
+ const isHasScroll = contentHasScroll(event)
+
+ const bodyHeight = document.querySelector('body')?.clientHeight ?? 0
+ const contentInsideHeight = contentInside.value?.clientHeight ?? 0
+ const drugHeight = drug.value?.clientHeight ?? 0
+
+ if (
+ isDragging.value
+ && drug.value
+ && drugHeight < contentInsideHeight
+ && drugHeight + EDGE_PADDING < bodyHeight
+ ) {
+ drug.value
+ ?.querySelector('.scrollerBlock')
+ ?.classList
+ .add('pointer-events-none')
+ drug.value.style.height = `${initialHeight.value - nextCurrentY.value}px`
+ }
+ else {
+ drug.value
+ ?.querySelector('.scrollerBlock')
+ ?.classList
+ .remove('pointer-events-none')
+ }
+
+ if (isHasScroll && !isHandler.value) {
+ isDragging.value = false
+ initialY.value = 0
+ clientY.value = 0
+ return
+ }
+
+ if (isDragging.value)
+ clientY.value = getClientY(event)
+
+ if (settings.debug) {
+ debug.value.status = nextCurrentY.value >= settings.pixelsNeedToDrugForClose && direction.value === 'down'
+ ? 'will close'
+ : 'will open'
+ }
+ }
+
+ /**
+ * Drag end
+ */
+ async function onDragEnd() {
+ if (disabled.value || !isDragging.value)
+ return
+
+ const bodyHeight = document.querySelector('body')?.clientHeight ?? 0
+ const contentInsideHeight = contentInside.value?.clientHeight ?? 0
+ const drugHeight = drug.value?.clientHeight ?? 0
+
+ if (direction.value === 'up' && nextCurrentY.value < 0) {
+ await nextTick()
+ if (
+ isDragging.value
+ && drug.value
+ && drugHeight < contentInsideHeight
+ && drugHeight + EDGE_PADDING < bodyHeight
+ ) {
+ drug.value.style.height = `${bodyHeight - EDGE_PADDING}px`
+ }
+ }
+
+ const isNeedClose
+ = nextCurrentY.value >= settings.pixelsNeedToDrugForClose
+ && direction.value === 'down'
+
+ if (isNeedClose) {
+ close()
+ }
+ else {
+ open()
+ }
+ }
+
+ /**
+ * Clear
+ */
+ function clear() {
+ clientY.value = 0
+ isDragging.value = false
+ }
+
+ function setInitialY() {
+ initialY.value = -(
+ (drug.value?.clientHeight ?? 0) + (handlerRef.value?.clientHeight ?? 0)
+ )
+ }
+
+ /**
+ * Close modal
+ */
+ function close() {
+ clear()
+ setInitialY()
+ }
+
+ /**
+ * Open modal
+ */
+ function open() {
+ clear()
+ opened.value = true
+ initialY.value = 0
+ }
+
+ /**
+ * On close modal
+ */
+ function onClose() {
+ // Scroll up all scroller blocks
+ const scrollerBlocks = drug.value?.querySelectorAll('.scrollerBlock')
+ scrollerBlocks?.forEach(el => (el.scrollTop = 0))
+ drug.value?.removeEventListener('transitionend', onClose)
+ opened.value = false
+ emit('closed')
+ }
+
+ /**
+ * Add events listeners
+ */
+ function addEvents() {
+ if (isEventsAdded.value)
+ return
+
+ isEventsAdded.value = true
+
+ // Touch
+ if (containerRef.value) {
+ containerRef.value.addEventListener('touchstart', onDragStart)
+ containerRef.value.addEventListener('touchmove', onDragging)
+ containerRef.value.addEventListener('touchend', onDragEnd)
+ containerRef.value.addEventListener('mousedown', onDragStart)
+ containerRef.value.addEventListener('mouseup', onDragEnd)
+
+ document.addEventListener('mousemove', onDragging)
+ document.addEventListener('mouseleave', onDragEnd)
+ }
+ }
+
+ /**
+ * Remove events listeners
+ */
+ function removeEvents() {
+ isEventsAdded.value = false
+ if (containerRef.value) {
+ containerRef.value.removeEventListener('touchstart', onDragStart)
+ containerRef.value.removeEventListener('touchmove', onDragging)
+ containerRef.value.removeEventListener('touchend', onDragEnd)
+ containerRef.value.removeEventListener('mousedown', onDragStart)
+ containerRef.value.removeEventListener('mouseup', onDragEnd)
+
+ document.removeEventListener('mousemove', onDragging)
+ document.removeEventListener('mouseleave', onDragEnd)
+ }
+ }
+
+ /**
+ * Watch for diff height
+ */
+ watch(diffHeight, () => {
+ if (isDragging.value)
+ return
+
+ if (diffHeight.value === 0) {
+ disabled.value = true
+ useEventListener(drug, 'transitionend', onClose, { passive: true })
+ return
+ }
+
+ disabled.value = false
+ })
+
+ /**
+ * Init modal
+ */
+ async function init() {
+ initialHeight.value = drug.value?.clientHeight ?? 0
+
+ setTimeout(async () => {
+ setInitialY()
+ disabled.value = false
+ addEvents()
+ setTimeout(() => {
+ open()
+ }, INIT_DELAY_MS)
+ }, INIT_DELAY_MS)
+ }
+
+ return {
+ // State
+ close,
+ debug,
+ direction,
+ disabled,
+ drugStyles,
+ // Functions
+ init,
+ isDragging,
+ open,
+
+ opened,
+ // Computed classes
+ overflowClasses: computed(() => ({
+ 'transition-opacity duration-100': !isDragging.value && opened.value,
+ })),
+ overlayStyles,
+
+ removeEvents,
+
+ wrapClasses: computed<Record<string, boolean>>(() => ({
+ 'pointer-events-none invisible opacity-0': !opened.value,
+ })),
+ }
+}
diff --git a/app/components/categories/CommandPalette.vue b/app/components/categories/CommandPalette.vue
index f6453bcb..34515220 100644
--- a/app/components/categories/CommandPalette.vue
+++ b/app/components/categories/CommandPalette.vue
@@ -9,42 +9,59 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
+ clickParent: [id: CategoryId]
+ close: []
filter: [id: CategoryId]
- onClickParent: [id: CategoryId]
- onClose: []
- onSelected: [id: CategoryId]
+ selected: [id: CategoryId]
}>()
const { t } = useI18n()
const categoriesStore = useCategoriesStore()
-const cats = computed(() => categoriesStore.categoriesRootIds.map((id) => {
- const category = categoriesStore.items[id]!
-
- const items = category?.childIds?.length
- ? categoriesStore.getChildsIds(id).map(childId => ({
- id: childId,
- ...categoriesStore.items[childId],
- suffix: category.name,
- }))
- : [{
- id,
- ...category,
- suffix: category.name,
- }]
-
- return {
- ...category,
+const cats = computed(() => {
+ const adjustmentCategory = categoriesStore.items.adjustment
+ const adjustmentGroup = {
+ ...adjustmentCategory,
childIds: undefined,
- id,
- items,
+ id: 'adjustment',
+ items: [{
+ id: 'adjustment',
+ ...adjustmentCategory,
+ suffix: adjustmentCategory.name,
+ }],
slot: 'category',
}
-}))
+
+ const rootGroups = categoriesStore.categoriesRootIds.map((id) => {
+ const category = categoriesStore.items[id]!
+
+ const items = category?.childIds?.length
+ ? categoriesStore.getChildsIds(id).map(childId => ({
+ id: childId,
+ ...categoriesStore.items[childId],
+ suffix: category.name,
+ }))
+ : [{
+ id,
+ ...category,
+ suffix: category.name,
+ }]
+
+ return {
+ ...category,
+ childIds: undefined,
+ id,
+ items,
+ slot: 'category',
+ }
+ })
+
+ return [adjustmentGroup, ...rootGroups]
+})
function onSelect(item: CategoryItemWithId) {
- emit('onSelected', item.id)
- emit('onClose')
+ emit('selected', item.id)
+ emit('close')
if (props.hide)
props.hide()
}
diff --git a/app/components/categories/Form.vue b/app/components/categories/Form.vue
index 047c5898..2b4103f1 100644
--- a/app/components/categories/Form.vue
+++ b/app/components/categories/Form.vue
@@ -3,25 +3,30 @@ import { generateId } from '~~/utils/generateId'
import type { CategoryForm, CategoryId } from '~/components/categories/types'
-import { errorEmo, random } from '~/assets/js/emo'
import icons from '~/assets/js/icons'
+import { categoryFormSchema } from '~/components/categories/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+import { showErrorToast } from '~/composables/useStoreSync'
const props = defineProps<{
categoryForm: CategoryForm
categoryId?: CategoryId
}>()
-const emit = defineEmits(['updateValue', 'afterSave'])
+const emit = defineEmits<{
+ afterSave: []
+ update: [key: keyof CategoryForm, value: CategoryForm[keyof CategoryForm]]
+}>()
const { t } = useI18n()
const categoriesStore = useCategoriesStore()
-const toast = useToast()
const editCategoryId = props.categoryId ?? generateId()
const isUpdateChildCategoriesColor = ref(true)
+const childIds = computed(() => categoriesStore.getChildsIds(props.categoryId!))
+const hasChildren = computed(() => childIds.value.length > 0)
const isAllowChangeParent = computed(() =>
- categoriesStore.getChildsIds(props.categoryId!).length === 0 && categoriesStore.categoriesForBeParent.length > 0,
+ !hasChildren.value && categoriesStore.categoriesForBeParent.length > 0,
)
const modals = ref({
@@ -40,69 +45,39 @@ const categoryPlaceholder = computed(() => ({
*/
function onParentSelect(parentId: CategoryId | false, close: () => void) {
if (!parentId) {
- emit('updateValue', 'parentId', 0)
+ emit('update', 'parentId', 0)
close()
return
}
- emit('updateValue', 'parentId', parentId)
+ emit('update', 'parentId', parentId)
// Change category color when patent category changed
const parentCategoryColor = categoriesStore.items?.[parentId]?.color
if (parentCategoryColor)
- emit('updateValue', 'color', parentCategoryColor)
+ emit('update', 'color', parentCategoryColor)
close()
}
-/**
- * Validate
- */
-function validate(values: CategoryForm) {
- if (!values.name) {
- toast.add({
- color: 'error',
- description: t('categories.form.name.error'),
- title: random(errorEmo),
- })
+async function onSave() {
+ const parsed = categoryFormSchema.safeParse(props.categoryForm)
+ if (!parsed.success) {
+ showErrorToast('categories.form.name.error')
return
}
- // TODO: refactor
for (const id in categoriesStore.items) {
- if (categoriesStore.items[id].name === values.name && categoriesStore.items[id].parentId === values.parentId) {
- if (editCategoryId) {
- if (editCategoryId !== id) {
- toast.add({
- color: 'error',
- description: t('categories.form.name.exist'),
- title: random(errorEmo),
- })
- return
- }
- }
- else {
- toast.add({
- color: 'error',
- description: t('categories.form.name.exist'),
- title: random(errorEmo),
- })
- return
- }
+ if (categoriesStore.items[id].name === parsed.data.name && categoriesStore.items[id].parentId === parsed.data.parentId && id !== editCategoryId) {
+ showErrorToast('categories.form.name.exist')
+ return
}
}
- return true
-}
-
-async function onSave() {
- if (!validate(props.categoryForm))
- return
-
- await categoriesStore.addCategory({
+ await categoriesStore.saveCategory({
id: editCategoryId,
isUpdateChildCategoriesColor: isUpdateChildCategoriesColor.value,
- values: { ...props.categoryForm },
+ values: parsed.data,
})
emit('afterSave')
}
@@ -122,8 +97,8 @@ async function onSave() {
<FormInput
:placeholder="t('categories.form.name.placeholder')"
- :value="categoryForm.name"
- @updateValue="(value: string) => emit('updateValue', 'name', value)"
+ :modelValue="categoryForm.name"
+ @update:modelValue="(value: string) => emit('update', 'name', value)"
/>
</FormElement>
@@ -173,30 +148,31 @@ async function onSave() {
<!-- Options -->
<div>
- <UiCheckbox
- v-if="categoriesStore.getChildsIds(props.categoryId).length > 0"
+ <UiSwitchItem
+ v-if="hasChildren"
:checkboxValue="isUpdateChildCategoriesColor"
:title="t('categories.form.childColor')"
@click="isUpdateChildCategoriesColor = !isUpdateChildCategoriesColor"
/>
- <UiCheckbox
- v-if="categoriesStore.getChildsIds(props.categoryId).length === 0"
+ <UiSwitchItem
+ v-if="!hasChildren"
:checkboxValue="props.categoryForm.showInQuickSelector"
:title="t('categories.form.favoriteCategory')"
- @click="emit('updateValue', 'showInQuickSelector', !props.categoryForm.showInQuickSelector)"
+ @click="emit('update', 'showInQuickSelector', !props.categoryForm.showInQuickSelector)"
/>
- <UiCheckbox
- v-if="categoriesStore.getChildsIds(props.categoryId).length === 0"
+ <UiSwitchItem
+ v-if="!hasChildren"
:checkboxValue="props.categoryForm.showInLastUsed"
:title="t('categories.form.recentCategory')"
- @click="emit('updateValue', 'showInLastUsed', !props.categoryForm.showInLastUsed)"
+ @click="emit('update', 'showInLastUsed', !props.categoryForm.showInLastUsed)"
/>
</div>
</div>
<div class="flex-center">
<UiButtonAccent
+ class="sm:max-w-xs"
rounded
@click="onSave"
>
@@ -215,7 +191,7 @@ async function onSave() {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -233,7 +209,7 @@ async function onSave() {
:activeColor="props.categoryForm.color"
:icon="props.categoryForm.icon"
isCategory
- @click="color => emit('updateValue', 'color', color)"
+ @click="color => emit('update', 'color', color)"
/>
</div>
@@ -258,7 +234,7 @@ async function onSave() {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -284,8 +260,8 @@ async function onSave() {
<FormInput
:placeholder="t('categories.form.icon.placeholder')"
- :value="categoryForm.icon"
- @updateValue="(value: string) => emit('updateValue', 'icon', value)"
+ :modelValue="categoryForm.icon"
+ @update:modelValue="(value: string) => emit('update', 'icon', value)"
/>
</FormElement>
@@ -297,10 +273,11 @@ async function onSave() {
<div
v-for="icon in iconGroup"
:key="icon"
- :class="[{ '!border-(--ui-primary)': icon === props.categoryForm.icon }]"
+ :class="cn('flex-center text-icon-primary size-10 cursor-pointer rounded-full border-2 border-transparent',
+ icon === props.categoryForm.icon && 'border-(--ui-primary)',
+ )"
:style="{ background: props.categoryForm.color }"
- class="flex-center text-icon-primary size-10 cursor-pointer rounded-full border-2 border-transparent"
- @click="emit('updateValue', 'icon', icon)"
+ @click="emit('update', 'icon', icon)"
>
<Icon :name="icon" size="20" />
</div>
@@ -328,7 +305,7 @@ async function onSave() {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -336,12 +313,12 @@ async function onSave() {
<UiTitleModal>{{ t('categories.form.selectParent') }}</UiTitleModal>
<div class="scrollerBlock bottomSheetContentInside">
- <UiItem2
+ <UiChipButton
:isActive="props.categoryForm.parentId === 0"
@click="onParentSelect(false, close)"
>
{{ t('categories.form.parent.no') }}
- </UiItem2>
+ </UiChipButton>
<CategoriesList
:activeItemId="props.categoryForm.parentId"
diff --git a/app/components/categories/Header.vue b/app/components/categories/Header.vue
index 4a4dab6e..6ca9a635 100644
--- a/app/components/categories/Header.vue
+++ b/app/components/categories/Header.vue
@@ -39,7 +39,7 @@ function onParentClick() {
</div>
<div
- class="flex items-center gap-2 rounded-lg px-3 py-1 hover:bg-[var(--item-5)]"
+ class="flex items-center gap-2 rounded-lg px-3 py-1 hover:bg-(--item-5)"
@click="onParentClick"
>
{{ props.parentCategory.name }}
diff --git a/app/components/categories/Item.vue b/app/components/categories/Item.vue
index 9469713c..4e782e4b 100644
--- a/app/components/categories/Item.vue
+++ b/app/components/categories/Item.vue
@@ -13,7 +13,7 @@ export type CategoryItemProps = {
isShowDots?: boolean
isShowParent?: boolean
lineWidth?: number
- slider?: any
+ slider?: object
}
const props = defineProps<CategoryItemProps>()
diff --git a/app/components/categories/List.vue b/app/components/categories/List.vue
index 16e92914..2d9a727c 100644
--- a/app/components/categories/List.vue
+++ b/app/components/categories/List.vue
@@ -14,7 +14,7 @@ const props = defineProps<{
const emit = defineEmits<{
click: [id: CategoryId]
- onClickIcon: [id: CategoryId]
+ clickIcon: [id: CategoryId]
}>()
const categoriesStore = useCategoriesStore()
@@ -34,7 +34,7 @@ const categoriesStore = useCategoriesStore()
isShowDots
v-bind="categoriesItemProps"
@click="emit('click', categoryId)"
- @onClickIcon="emit('onClickIcon', categoryId)"
+ @clickIcon="emit('clickIcon', categoryId)"
/>
</div>
</template>
diff --git a/app/components/categories/Name.vue b/app/components/categories/Name.vue
index eaecac78..010808f8 100644
--- a/app/components/categories/Name.vue
+++ b/app/components/categories/Name.vue
@@ -1,6 +1,4 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
import type { CategoryItem } from '~/components/categories/types'
const props = defineProps<{
@@ -15,7 +13,7 @@ const props = defineProps<{
</script>
<template>
- <div :class="cn('flex gap-3 items-baseline pt-0', { 'flex-col !gap-0.5': props.alt })">
+ <div :class="cn('flex gap-3 items-baseline pt-0', props.alt && 'flex-col gap-0.5')">
<!-- Parent category name -->
<template v-if="alt && isShowParent && !props.hasChildren && props.category?.parentId">
<div class="text-2xs text-4 leading-none">
diff --git a/app/components/categories/Selector2.vue b/app/components/categories/SelectorGrid.vue
similarity index 79%
rename from app/components/categories/Selector2.vue
rename to app/components/categories/SelectorGrid.vue
index 0c740cb4..934428cd 100644
--- a/app/components/categories/Selector2.vue
+++ b/app/components/categories/SelectorGrid.vue
@@ -2,7 +2,6 @@
import type { CategoryId } from '~/components/categories/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { getStyles } from '~/components/ui/getStyles'
const props = defineProps<{
activeItemId?: CategoryId
@@ -11,23 +10,23 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
+ clickParent: [id: CategoryId]
+ close: []
filter: [id: CategoryId]
- onClickParent: [id: CategoryId]
- onClose: []
- onSelected: [id: CategoryId]
+ selected: [id: CategoryId]
}>()
const categoriesStore = useCategoriesStore()
-const itemClasses = getStyles('item', ['alt', 'rounded'])
+const itemClasses = 'bg-item-3 rounded-sm'
function select(id: CategoryId) {
if (categoriesStore.hasChildren(id)) {
- emit('onClickParent', id)
+ emit('clickParent', id)
return
}
- emit('onSelected', id)
- emit('onClose')
+ emit('selected', id)
+ emit('close')
if (props.hide)
props.hide()
}
diff --git a/app/components/categories/Selector.vue b/app/components/categories/SelectorTree.vue
similarity index 96%
rename from app/components/categories/Selector.vue
rename to app/components/categories/SelectorTree.vue
index 078699f3..5cc278ae 100644
--- a/app/components/categories/Selector.vue
+++ b/app/components/categories/SelectorTree.vue
@@ -9,9 +9,9 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
+ close: []
filter: [id: CategoryId]
- onClose: []
- onSelected: [id: CategoryId]
+ selected: [id: CategoryId]
setCategories: [ids: CategoryId[]]
}>()
@@ -29,8 +29,8 @@ function select(categoryId: CategoryId, isForce: boolean) {
return
}
- emit('onSelected', categoryId)
- emit('onClose')
+ emit('selected', categoryId)
+ emit('close')
if (props.hide)
props.hide()
}
@@ -60,7 +60,7 @@ onMounted(() => {
</script>
<template>
- <div class="">
+ <div>
<div
v-for="categoryId in categoriesStore.categoriesRootIds"
:key="categoryId"
diff --git a/app/components/categories/StatPage.vue b/app/components/categories/StatPage.vue
index 88d238ea..020a9018 100644
--- a/app/components/categories/StatPage.vue
+++ b/app/components/categories/StatPage.vue
@@ -7,6 +7,7 @@ import type { StatTabSlug } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useStatDate } from '~/components/date/useStatDate'
import { useFilter } from '~/components/stat/filter/useFilter'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useStatConfig } from '~/components/stat/useStatConfig'
import { getTypesMapping } from '~/components/stat/utils'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
@@ -20,7 +21,7 @@ const route = useRoute()
const categoriesStore = useCategoriesStore()
const filter = useFilter()
-provide('filter', filter)
+provide(filterKey, filter)
const categoryId = computed(() => route.params.id) as ComputedRef<CategoryId>
const category = ref(categoriesStore.items[categoryId.value])
@@ -52,14 +53,14 @@ const statConfig = useStatConfig({
},
storageKey: storageKey.value,
})
-provide('statConfig', statConfig)
+provide(statConfigKey, statConfig)
const statDate = useStatDate({
key: storageKey.value,
maxRange,
queryParams: route.query,
})
-provide('statDate', statDate)
+provide(statDateKey, statDate)
if (!category.value)
router.replace('/dashboard')
diff --git a/app/components/categories/page/List.vue b/app/components/categories/page/List.vue
index 05796b7f..af90820c 100644
--- a/app/components/categories/page/List.vue
+++ b/app/components/categories/page/List.vue
@@ -21,31 +21,33 @@ const categoriesView = useStorage<'list' | 'grid'>('finapp.categoriesView', 'lis
<UiHeader>
<UiHeaderTitle>{{ t('categories.name') }}</UiHeaderTitle>
<template #actions>
- <UiItem3 @click="categoriesView = categoriesView === 'list' ? 'grid' : 'list'">
+ <UiActionButton @click="categoriesView = categoriesView === 'list' ? 'grid' : 'list'">
<Icon
:name="categoriesView === 'list' ? 'lucide:layout-grid' : 'lucide:list'"
size="20"
/>
- </UiItem3>
+ </UiActionButton>
- <UiItem3 @click="router.push('/categories/new')">
+ <UiActionButton @click="router.push('/categories/new')">
<Icon name="lucide:plus" size="24" />
- </UiItem3>
+ </UiActionButton>
</template>
</UiHeader>
<!-- Empty -->
<div
v-if="categoriesStore.categoriesRootIds.length === 0"
- class="pageWrapper"
+ class="flex-center grow flex-col"
>
- <div class="md:max-w-xs">
- <UiButtonAccent
- @click="router.push('/categories/new')"
- >
- {{ t('categories.new') }}
- </UiButtonAccent>
- </div>
+ <UiTitleSection class="pb-4">
+ {{ t('categories.new') }}
+ </UiTitleSection>
+ <UiButtonAccent
+ rounded
+ @click="router.push('/categories/new')"
+ >
+ {{ t('categories.new') }}
+ </UiButtonAccent>
</div>
<!-- List -->
diff --git a/app/components/categories/page/New.vue b/app/components/categories/page/New.vue
index 791b1bab..77350808 100644
--- a/app/components/categories/page/New.vue
+++ b/app/components/categories/page/New.vue
@@ -1,11 +1,14 @@
<script setup lang="ts">
-import type { CategoryId, CategoryItem } from '~/components/categories/types'
+import type { CategoryItem } from '~/components/categories/types'
-import { getPreparedFormData } from '~/components/categories/utils'
+import { categoryFormSchema } from '~/components/categories/types'
const { t } = useI18n()
+const route = useRoute()
const router = useRouter()
-const categoryForm = ref(getPreparedFormData())
+const categoryForm = ref(categoryFormSchema.parse({}))
+
+const isOnboarding = computed(() => 'onboarding' in route.query)
useHead({
title: `${t('base.add')}: ${categoryForm.value.name ? categoryForm.value.name : t('categories.form.name.label')}`,
@@ -14,14 +17,23 @@ useHead({
<template>
<UiPage class="flex h-full flex-col">
- <UiHeader>
- <UiHeaderTitle>{{ t('categories.createNewTitle') }}</UiHeaderTitle>
+ <h1
+ v-if="isOnboarding"
+ class="pt-2 pb-6 text-center text-2xl font-bold"
+ >
+ {{ t('categories.createNewTitle') }}
+ </h1>
+
+ <UiHeader v-else>
+ <UiHeaderTitle>
+ {{ t('categories.createNewTitle') }}
+ </UiHeaderTitle>
</UiHeader>
<CategoriesForm
:categoryForm="categoryForm"
- @updateValue="(key: CategoryId, value: keyof CategoryItem) => categoryForm[key] = value"
- @afterSave="() => router.replace('/categories')"
+ @update="(key: string, value: CategoryItem[keyof CategoryItem]) => categoryForm[key] = value"
+ @afterSave="() => router.replace('/dashboard')"
/>
</UiPage>
</template>
diff --git a/app/components/categories/page/id/Edit.vue b/app/components/categories/page/id/Edit.vue
index cdc41bcd..d999c62a 100644
--- a/app/components/categories/page/id/Edit.vue
+++ b/app/components/categories/page/id/Edit.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import type { CategoryId, CategoryItem } from '~/components/categories/types'
+import { categoryFormSchema } from '~/components/categories/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { getPreparedFormData } from '~/components/categories/utils'
const { t } = useI18n()
const router = useRouter()
@@ -11,7 +11,7 @@ const categoriesStore = useCategoriesStore()
const categoryId = computed<CategoryId>(() => route.params.id)
const category = computed<CategoryItem>(() => categoriesStore.items[categoryId.value])
-const categoryForm = ref(getPreparedFormData(category.value))
+const categoryForm = ref(categoryFormSchema.parse(category.value))
useHead({
title: `${t('base.edit')}: ${categoryForm.value?.name || t('categories.form.name.label')}`,
@@ -30,7 +30,7 @@ useHead({
<CategoriesForm
:categoryId="categoryId"
:categoryForm="categoryForm"
- @updateValue="(key: CategoryId, value: keyof CategoryItem) => categoryForm[key] = value"
+ @update="(key: string, value: CategoryItem[keyof CategoryItem]) => categoryForm[key] = value"
@afterSave="() => router.replace(`/categories/${categoryId}`)"
/>
</UiPage>
diff --git a/app/components/categories/page/id/Index.vue b/app/components/categories/page/id/Index.vue
index 08d07dd4..1533181e 100644
--- a/app/components/categories/page/id/Index.vue
+++ b/app/components/categories/page/id/Index.vue
@@ -5,15 +5,16 @@ import { differenceInDays } from 'date-fns'
import type { CategoryId } from '~/components/categories/types'
import type { StatTabSlug } from '~/components/stat/types'
-import { errorEmo, random, successEmo } from '~/assets/js/emo'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useStatDate } from '~/components/date/useStatDate'
import { calculateBestIntervalsBy } from '~/components/date/utils'
import { useFilter } from '~/components/stat/filter/useFilter'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useStatConfig } from '~/components/stat/useStatConfig'
import { getTypesMapping } from '~/components/stat/utils'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { showErrorToast, showSuccessToast } from '~/composables/useStoreSync'
const { t } = useI18n()
const categoriesStore = useCategoriesStore()
@@ -22,9 +23,8 @@ const router = useRouter()
const trnsFormStore = useTrnsFormStore()
const trnsStore = useTrnsStore()
const filter = useFilter()
-const toast = useToast()
-provide('filter', filter)
+provide(filterKey, filter)
const categoryId = computed(() => route.params.id) as ComputedRef<CategoryId>
const category = computed(() => categoriesStore.items[categoryId.value])
@@ -57,7 +57,7 @@ const statConfig = useStatConfig({
},
storageKey: storageKey.value,
})
-provide('statConfig', statConfig)
+provide(statConfigKey, statConfig)
const statDate = useStatDate({
initParams: {
@@ -72,7 +72,7 @@ const statDate = useStatDate({
maxRange,
queryParams: route.query,
})
-provide('statDate', statDate)
+provide(statDateKey, statDate)
onActivated(() => {
statConfig.updateConfig('catsList', { isGrouped: false })
@@ -102,11 +102,7 @@ function onClickDelete(close: () => void) {
for (const id in categoriesStore.items) {
if (categoriesStore.items[id]?.parentId === categoryId.value) {
- toast.add({
- color: 'error',
- description: t('categories.form.delete.errorChilds'),
- title: random(errorEmo),
- })
+ showErrorToast('categories.form.delete.errorChilds')
return false
}
@@ -116,24 +112,20 @@ function onClickDelete(close: () => void) {
}
async function onDeleteConfirm() {
- const trnsIdsS = JSON.parse(JSON.stringify(
- trnsStore.getStoreTrnsIds({
- categoriesIds: categoriesStore.getChildsIdsOrParent(categoryId.value),
- }),
- ))
+ const trnsIdsS = [...trnsStore.getStoreTrnsIds({
+ categoriesIds: categoriesStore.getChildsIdsOrParent(categoryId.value),
+ })]
router.push('/categories')
- await categoriesStore.deleteCategory(JSON.parse(JSON.stringify(categoryId.value), trnsIdsS))
+ await categoriesStore.deleteCategory(categoryId.value, trnsIdsS)
// Give some time to complete redirect
- setTimeout(async () => {
- toast.add({
- color: 'success',
- description: trnsIdsS?.length > 0
- ? t('categories.form.delete.okWithTrns', { length: trnsIdsS.length, trns: t('trns.plural', trnsIdsS.length) })
- : t('categories.form.delete.okWithoutTrns'),
- title: random(successEmo),
- })
+ setTimeout(() => {
+ showSuccessToast(trnsIdsS?.length > 0
+ ? 'categories.form.delete.okWithTrns'
+ : 'categories.form.delete.okWithoutTrns', trnsIdsS?.length > 0
+ ? { length: trnsIdsS.length, trns: t('trns.plural', trnsIdsS.length) }
+ : undefined)
}, 300)
}
@@ -189,7 +181,7 @@ const categoriesIds = computed(() => categoriesStore.getChildsIds(categoryId.val
v-if="isShowDeleteConfirm"
:description="deleteDescText"
@closed="isShowDeleteConfirm = false"
- @onConfirm="onDeleteConfirm"
+ @confirm="onDeleteConfirm"
/>
<div
diff --git a/app/components/categories/types.ts b/app/components/categories/types.ts
index 3beac1a9..642c8193 100644
--- a/app/components/categories/types.ts
+++ b/app/components/categories/types.ts
@@ -1,15 +1,25 @@
-export type CategoryId = string | 'transfer'
+import { z } from 'zod/v4'
-export type CategoryItem = {
+import { random } from '~/assets/js/emo'
+import icons from '~/assets/js/icons'
+import { colorsArray } from '~/components/color/colors'
+
+export type CategoryId = string
+
+export const categoryFormSchema = z.object({
+ color: z.string().default(() => random(colorsArray)),
+ icon: z.string().trim().min(1).default(() => random(random(icons))),
+ name: z.string().trim().min(1).default(''),
+ parentId: z.union([z.string(), z.literal(0)]).default(0),
+ showInLastUsed: z.boolean().default(true),
+ showInQuickSelector: z.boolean().default(false),
+})
+
+export type CategoryForm = z.infer<typeof categoryFormSchema>
+
+export type CategoryItem = CategoryForm & {
childIds?: CategoryId[]
- color: string
- editedAt?: number
- icon: string
- name: string
- order?: number
- parentId: CategoryId | 0
- showInLastUsed?: boolean
- showInQuickSelector?: boolean
+ updatedAt?: number
}
export type CategoryItemWithId = CategoryItem & {
@@ -18,20 +28,8 @@ export type CategoryItemWithId = CategoryItem & {
export type Categories = Record<CategoryId, CategoryItem> & Record<'transfer', CategoryItem>
-export type CategoryForm = {
- color: string
- icon: string
- name: string
- order: number
- parentId: string | 0
- showInLastUsed: boolean
- showInQuickSelector: boolean
-}
-
export type AddCategoryParams = {
id: CategoryId
- values: CategoryItem
-} & {
- childIds?: CategoryId[]
isUpdateChildCategoriesColor: boolean
+ values: CategoryItem
}
diff --git a/app/components/categories/useCategoriesStore.test.ts b/app/components/categories/useCategoriesStore.test.ts
new file mode 100644
index 00000000..89615950
--- /dev/null
+++ b/app/components/categories/useCategoriesStore.test.ts
@@ -0,0 +1,426 @@
+import { createPinia, setActivePinia } from 'pinia'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { CategoryItem } from '~/components/categories/types'
+
+// --- Mocks ---
+
+const localforageStore = new Map<string, any>()
+vi.mock('localforage', () => ({
+ default: {
+ getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),
+ removeItem: vi.fn((key: string) => {
+ localforageStore.delete(key)
+ return Promise.resolve()
+ }),
+ setItem: vi.fn((key: string, value: any) => {
+ localforageStore.set(key, value)
+ return Promise.resolve()
+ }),
+ },
+}))
+
+vi.mock('@vueuse/core', () => ({
+ useDebounceFn: (fn: (...args: any[]) => any) => fn,
+}))
+
+vi.mock('vue-deepunref', () => ({
+ deepUnref: (v: any) => v,
+}))
+
+vi.mock('~~/services/convex/api', () => ({
+ convexCategoriesToMap: (v: any) => v,
+}))
+
+vi.mock('~/components/categories/utils', () => ({
+ compareCategoriesByParentAndName: () => 0,
+ getTransactibleCategoriesIds: () => [],
+ getTransferCategoriesIds: () => ['transfer'],
+}))
+
+const mutationMock = vi.fn(() => Promise.resolve())
+const onUpdateMock = vi.fn()
+
+vi.stubGlobal('useConvexClient', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+}))
+vi.stubGlobal('useConvexClientComposable', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+}))
+vi.stubGlobal('asConvexId', (id: string) => id)
+vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))
+vi.stubGlobal('useConvexApi', () => ({
+ api: {
+ categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },
+ },
+}))
+vi.stubGlobal('useConvexClientWithApi', () => ({
+ api: {
+ categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },
+ },
+ client: {
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+ },
+}))
+
+const toastAddMock = vi.fn()
+vi.stubGlobal('useToast', () => ({ add: toastAddMock }))
+vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
+vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+
+vi.mock('~/assets/js/emo', () => ({
+ errorEmo: ['🤷‍♀️'],
+ random: (items: any[]) => items[0],
+}))
+
+vi.stubGlobal('defineStore', (await import('pinia')).defineStore)
+const { computed, shallowRef } = await import('vue')
+vi.stubGlobal('shallowRef', shallowRef)
+vi.stubGlobal('computed', computed)
+
+const removeTrnsFromStoreMock = vi.fn()
+const deleteTrnsByIdsMock = vi.fn()
+vi.mock('~/components/trns/useTrnsStore', () => ({
+ useTrnsStore: () => ({
+ deleteTrnsByIds: deleteTrnsByIdsMock,
+ hasItems: false,
+ items: {},
+ removeTrnsFromStore: removeTrnsFromStoreMock,
+ }),
+}))
+
+vi.mock('~/components/demo/useDemo', () => ({
+ useDemo: () => ({
+ isDemo: { value: false },
+ }),
+}))
+
+vi.mock('~/components/offline/replay', () => ({
+ isReplaying: () => false,
+}))
+
+const offlineHelpers = await import('~/components/offline/helpers')
+vi.mock('~/components/offline/helpers', async (importOriginal) => {
+ const actual = await importOriginal() as any
+ return {
+ clearOfflineQueue: vi.fn(actual.clearOfflineQueue),
+ getAllOfflineOps: vi.fn(actual.getAllOfflineOps),
+ getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),
+ pushOfflineOp: vi.fn(actual.pushOfflineOp),
+ removeOfflineOp: vi.fn(actual.removeOfflineOp),
+ removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),
+ }
+})
+
+const { useCategoriesStore } = await import('~/components/categories/useCategoriesStore')
+
+// --- Helpers ---
+
+function makeCategory(overrides: Partial<CategoryItem> = {}): CategoryItem {
+ return {
+ color: '#f00',
+ icon: 'mdi:food',
+ name: 'Food',
+ parentId: 0,
+ showInLastUsed: true,
+ showInQuickSelector: false,
+ ...overrides,
+ }
+}
+
+// --- Tests ---
+
+describe('useCategoriesStore', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ localforageStore.clear()
+ vi.clearAllMocks()
+ mutationMock.mockReturnValue(Promise.resolve())
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ describe('saveCategory — optimistic UI', () => {
+ it('updates items immediately', () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ expect(store.items).toHaveProperty('c1')
+ expect(store.items.c1.name).toBe('Food')
+ })
+
+ it('saves to localforage', () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ expect(localforageStore.get('finapp.categories')).toHaveProperty('c1')
+ })
+
+ it('pushes to offline queue immediately', () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'categories', id: 'c1', type: 'create' }),
+ )
+ })
+
+ it('fires Convex create mutation for new category', () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.create',
+ expect.objectContaining({ color: '#f00', name: 'Food' }),
+ )
+ })
+
+ it('fires Convex update mutation for existing category', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory({ name: 'Food & Drinks' }),
+ })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.update',
+ expect.objectContaining({ id: 'c1', name: 'Food & Drinks' }),
+ )
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('categories', 'c1')
+ })
+ })
+
+ it('skips transfer category', () => {
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'transfer',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory({ name: 'Transfer' }),
+ })
+
+ expect(mutationMock).not.toHaveBeenCalled()
+ expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()
+ })
+
+ it('updates child colors when isUpdateChildCategoriesColor is true', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),
+ child2: makeCategory({ color: '#f00', name: 'Child 2', parentId: 'parent1' }),
+ parent1: makeCategory({ childIds: ['child1', 'child2'], color: '#f00', name: 'Parent' }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: true,
+ values: makeCategory({ childIds: ['child1', 'child2'], color: '#00f', name: 'Parent' }),
+ })
+
+ expect(store.items.child1.color).toBe('#00f')
+ expect(store.items.child2.color).toBe('#00f')
+ expect(store.items.parent1.color).toBe('#00f')
+ })
+
+ it('fires updateWithChildren mutation when updating children color', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),
+ parent1: makeCategory({ childIds: ['child1'], color: '#f00', name: 'Parent' }),
+ }
+
+ store.saveCategory({
+ id: 'parent1',
+ isUpdateChildCategoriesColor: true,
+ values: makeCategory({ color: '#00f', name: 'Parent' }),
+ })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'categories.updateWithChildren',
+ expect.objectContaining({ childIds: ['child1'], color: '#00f', id: 'parent1' }),
+ )
+ })
+
+ it('syncs childIds when parentId changes', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ c1: makeCategory({ name: 'Child', parentId: 'oldParent' }),
+ newParent: makeCategory({ name: 'New Parent' }),
+ oldParent: makeCategory({ childIds: ['c1'], name: 'Old Parent' }),
+ }
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory({ name: 'Child', parentId: 'newParent' }),
+ })
+
+ expect(store.items.oldParent.childIds).toBeUndefined()
+ expect(store.items.newParent.childIds).toEqual(['c1'])
+ })
+
+ it('shows toast on mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('Server error')))
+ const store = useCategoriesStore()
+
+ store.saveCategory({
+ id: 'c1',
+ isUpdateChildCategoriesColor: false,
+ values: makeCategory(),
+ })
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error' }),
+ )
+ })
+ })
+ })
+
+ describe('deleteCategory — optimistic UI', () => {
+ it('removes item from store immediately', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory(), c2: makeCategory({ name: 'Transport' }) }
+
+ store.deleteCategory('c1')
+
+ expect(store.items).not.toHaveProperty('c1')
+ expect(store.items).toHaveProperty('c2')
+ // transfer should always remain
+ expect(store.items).toHaveProperty('transfer')
+ })
+
+ it('pushes to offline queue', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1')
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'categories', id: 'c1', type: 'delete' }),
+ )
+ })
+
+ it('only pushes category delete op (backend cascades trns)', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1', ['trn1', 'trn2'])
+
+ // Only category delete op — no explicit trns delete ops
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledTimes(1)
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'categories', id: 'c1', type: 'delete' }),
+ )
+ })
+
+ it('removes trns from store immediately (optimistic)', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1', ['trn1', 'trn2'])
+
+ expect(removeTrnsFromStoreMock).toHaveBeenCalledWith(['trn1', 'trn2'])
+ })
+
+ it('fires Convex remove mutation', () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1')
+
+ expect(mutationMock).toHaveBeenCalledWith('categories.remove', { id: 'c1' })
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1')
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('categories', 'c1')
+ })
+ })
+
+ it('skips transfer category', () => {
+ const store = useCategoriesStore()
+
+ store.deleteCategory('transfer')
+
+ expect(mutationMock).not.toHaveBeenCalled()
+ expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()
+ })
+
+ it('shows toast on delete mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('Server error')))
+ const store = useCategoriesStore()
+ store.items = { ...store.items, c1: makeCategory() }
+
+ store.deleteCategory('c1')
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error' }),
+ )
+ })
+ })
+
+ it('syncs parent childIds on delete', () => {
+ const store = useCategoriesStore()
+ store.items = {
+ ...store.items,
+ c1: makeCategory({ name: 'Child', parentId: 'parent1' }),
+ parent1: makeCategory({ childIds: ['c1', 'c2'], name: 'Parent' }),
+ }
+
+ store.deleteCategory('c1')
+
+ expect(store.items.parent1.childIds).toEqual(['c2'])
+ })
+ })
+})
diff --git a/app/components/categories/useCategoriesStore.ts b/app/components/categories/useCategoriesStore.ts
index 246bcc5e..31ea95bc 100644
--- a/app/components/categories/useCategoriesStore.ts
+++ b/app/components/categories/useCategoriesStore.ts
@@ -1,36 +1,44 @@
-import type { ComputedRef, ShallowRef } from 'vue'
+import { convexCategoriesToMap } from '~~/services/convex/api'
-import localforage from 'localforage'
-import { computed, shallowRef } from 'vue'
-import { deepUnref } from 'vue-deepunref'
-import { getDataAndWatch, removeData, saveData, unsubscribeData, updateData } from '~~/services/firebase/api'
-
-import type { AddCategoryParams, Categories, CategoryId, CategoryItem, CategoryItemWithId } from '~/components/categories/types'
+import type { AddCategoryParams, Categories, CategoryId, CategoryItem } from '~/components/categories/types'
import type { TrnId } from '~/components/trns/types'
+import type { RemapInfo } from '~/composables/useStoreSync'
-import { compareCategoriesByParentAndName, getPreparedFormData, getTransactibleCategoriesIds, getTransferCategoriesIds } from '~/components/categories/utils'
+import { compareCategoriesByParentAndName, getTransactibleCategoriesIds, getTransferCategoriesIds } from '~/components/categories/utils'
import { useDemo } from '~/components/demo/useDemo'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
+import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
-import { useUserStore } from '~/components/user/useUserStore'
+import { createDebouncedPersist, handleMutationResult, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
+
+const adjustment: CategoryItem = {
+ childIds: [],
+ color: 'var(--text-4)',
+ icon: 'mdi:plus-minus',
+ name: 'Adjustment',
+ parentId: 0,
+ showInLastUsed: false,
+ showInQuickSelector: false,
+}
const transfer: CategoryItem = {
childIds: [],
- color: 'var(--ui-primary)',
+ color: 'var(--text-4)',
icon: 'mdi:repeat',
name: 'Transfer',
- order: 9999,
parentId: 0,
showInLastUsed: false,
showInQuickSelector: false,
}
type CategoriesStore = {
- addCategory: (params: AddCategoryParams) => Promise<void>
+ cancelPersist: () => void
categoriesForBeParent: ComputedRef<CategoryId[]>
categoriesIds: ComputedRef<CategoryId[]>
categoriesIdsForTrnValues: ComputedRef<CategoryId[]>
categoriesRootIds: ComputedRef<CategoryId[]>
- deleteCategory: (id: CategoryId, trnsIds?: TrnId[]) => Promise<void>
+ deleteCategory: (id: CategoryId, trnsIds?: TrnId[]) => Promise<RemapInfo | void> | void
favoriteCategoriesIds: ComputedRef<CategoryId[]>
getChildsIds: (categoryId: CategoryId) => CategoryId[]
getChildsIdsOrParent: (categoryId: CategoryId) => CategoryId[]
@@ -41,25 +49,22 @@ type CategoriesStore = {
isItTransactible: (categoryId: CategoryId) => boolean
items: ShallowRef<Categories>
recentCategoriesIds: ComputedRef<CategoryId[]>
- saveCategoriesOrder: (ids: CategoryId[]) => void
+ saveCategory: (params: AddCategoryParams) => Promise<RemapInfo | void> | void
setCategories: (values: Categories | null) => void
transactibleIds: ComputedRef<CategoryId[]>
transferCategoriesIds: ComputedRef<CategoryId[]>
- unsubscribeCategories: () => void
}
+const logger = createLogger('categories')
+
export const useCategoriesStore = defineStore('categories', (): CategoriesStore => {
- const userStore = useUserStore()
const trnsStore = useTrnsStore()
- const { addDemoCategory, deleteDemoCategory, isDemo } = useDemo()
+ const { isDemo } = useDemo()
- const items = shallowRef<Categories>({ transfer })
- const hasItems = computed(() => {
- if (Object.keys(items.value).filter(id => id !== 'transfer').length > 0)
- return true
-
- return false
- })
+ const items = shallowRef<Categories>({ adjustment, transfer })
+ const hasItems = computed(() =>
+ Object.keys(items.value).some(id => id !== 'transfer' && id !== 'adjustment'),
+ )
const transferCategoriesIds = computed(() => getTransferCategoriesIds(items.value))
@@ -74,8 +79,9 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value || !items.value)
return []
+ const transferIds = new Set(transferCategoriesIds.value)
return Object.keys(items.value)
- .filter(id => items.value?.[id]?.parentId === 0)
+ .filter(id => items.value?.[id]?.parentId === 0 && !transferIds.has(id) && id !== 'adjustment')
.sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
})
@@ -83,39 +89,36 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value || !items.value)
return []
- return categoriesRootIds.value.filter((id: CategoryId) => {
- const hasTrnsInCategory = Object.values(trnsStore.items ?? {})?.some(trn => trn.categoryId === id)
-
- if (hasTrnsInCategory || transferCategoriesIds.value.includes(id))
- return false
+ const usedCategoryIds = new Set(
+ Object.values(trnsStore.items ?? {}).map(trn => trn.categoryId),
+ )
+ const transferIds = new Set(transferCategoriesIds.value)
- return id
- })
+ return categoriesRootIds.value.filter((id: CategoryId) =>
+ !usedCategoryIds.has(id) && !transferIds.has(id),
+ )
})
const transactibleIds = computed(() => getTransactibleCategoriesIds(items.value))
+ const transactibleIdsSet = computed(() => new Set(transactibleIds.value))
const favoriteCategoriesIds = computed(() => {
if (!hasItems.value)
return []
- const filteredCategories = Object.keys(items.value)
+ return Object.keys(items.value)
.filter(id => items.value[id]?.showInQuickSelector)
- .map(id => ({ id, ...items.value[id] }))
-
- return filteredCategories
.sort((a, b) => {
- const parentNameA = items.value[a.parentId]?.name || ''
- const parentNameB = items.value[b.parentId]?.name || ''
+ const catA = items.value[a]!
+ const catB = items.value[b]!
+ const parentNameA = items.value[catA.parentId]?.name || ''
+ const parentNameB = items.value[catB.parentId]?.name || ''
- // First compare by parent name
if (parentNameA !== parentNameB)
return parentNameA.localeCompare(parentNameB)
- // If parent names are equal, compare by category name
- return a.name.localeCompare(b.name)
+ return catA.name.localeCompare(catB.name)
})
- .map(c => c.id)
})
const recentCategoriesIds = computed(() => {
@@ -124,65 +127,72 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
const trnsItems = trnsStore.items
const maxCategories = Math.min(categoriesIds.value.length, 16)
+ const transferIds = new Set(transferCategoriesIds.value)
+ const favoriteIds = new Set(favoriteCategoriesIds.value)
+
+ // Track most recent date per category (single pass)
+ const latestDateByCategory = new Map<CategoryId, number>()
+ for (const trnId in trnsItems) {
+ const trn = trnsItems[trnId]
+ if (!trn || trn.type === TrnType.Transfer || trn.categoryId === 'adjustment')
+ continue
- // Get sorted transaction IDs, excluding type 2 (transfers)
- const recentTrnsIds = Object.keys(trnsItems)
- .filter(id => trnsItems[id]?.type !== 2)
- .sort((a, b) => trnsItems[b]?.date - trnsItems[a]?.date)
-
- // Collect unique valid categories
- const categories = recentTrnsIds.reduce<CategoryItemWithId[]>((acc, trnId) => {
- if (acc.length >= maxCategories)
- return acc
+ const categoryId = trn.categoryId
+ const existing = latestDateByCategory.get(categoryId)
+ if (!existing || trn.date > existing)
+ latestDateByCategory.set(categoryId, trn.date)
+ }
- const categoryId = trnsItems[trnId]?.categoryId
- const category = categoryId ? items.value[categoryId] : undefined
+ // Filter valid categories and pick top N by most recent usage
+ const recentIds = [...latestDateByCategory.entries()]
+ .sort(([, dateA], [, dateB]) => dateB - dateA)
+ .reduce<CategoryId[]>((acc, [categoryId]) => {
+ if (acc.length >= maxCategories)
+ return acc
- const shouldSkip = !category
- || ('showInLastUsed' in category && !category.showInLastUsed)
- || acc.some(c => c.id === categoryId)
- || transferCategoriesIds.value.includes(categoryId)
- || favoriteCategoriesIds.value.includes(categoryId)
+ const category = items.value[categoryId]
+ if (!category || !category.showInLastUsed || transferIds.has(categoryId) || favoriteIds.has(categoryId))
+ return acc
- if (shouldSkip)
+ acc.push(categoryId)
return acc
+ }, [])
- acc.push({ id: categoryId, ...category })
- return acc
- }, [])
-
- return categories
- .sort((a, b) => compareCategoriesByParentAndName(a, b, items.value))
- .map(c => c.id)
+ return recentIds
+ .sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
})
const categoriesIdsForTrnValues = computed<CategoryId[]>(() => {
+ const transferIds = new Set(transferCategoriesIds.value)
return categoriesIds.value.filter((id) => {
- const isTransferCategory = transferCategoriesIds.value.includes(id)
- const category = items.value[id]
- const hasNoChildren = !category?.childIds?.length
-
- return !isTransferCategory && hasNoChildren
+ if (transferIds.has(id))
+ return false
+ return !items.value[id]?.childIds?.length
})
})
- function initCategories() {
- getDataAndWatch(
- `users/${userStore.uid}/categories`,
- (categories: Categories) => setCategories(categories),
- )
+ const debouncedPersist = createDebouncedPersist<Categories>(STORAGE_KEYS.categories)
+
+ async function initCategories() {
+ try {
+ const { api, client } = useConvexClientWithApi()
+ const categories = await client.query(api.categories.list, {})
+ let data: Categories | null = categories?.length ? convexCategoriesToMap(categories) : null
+
+ if (data)
+ data = await mergeOfflineOps(data, 'categories')
+
+ setCategories(data)
+ }
+ catch (e) {
+ logger.error('init failed', e)
+ }
}
function setCategories(values: Categories | null) {
- const categories = values ? formatCategories({ ...values, transfer }) : { transfer }
+ const categories = values ? { ...values, adjustment, transfer } : { adjustment, transfer }
items.value = categories
- localforage.setItem('finapp.categories', deepUnref(categories))
- }
-
- function unsubscribeCategories() {
- const userStore = useUserStore()
- unsubscribeData(`users/${userStore.uid}/categories`)
- setCategories(null)
+ debouncedPersist(categories)
}
function hasChildren(categoryId: CategoryId) {
@@ -200,110 +210,158 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value)
return []
- return hasChildren(categoryId)
- ? Object.keys(items.value)
- .filter(id => items.value[id]?.parentId === categoryId)
- .sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
- : []
+ const category = items.value[categoryId]
+ if (!category?.childIds?.length)
+ return []
+
+ return [...category.childIds]
+ .sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
}
function getChildsIdsOrParent(categoryId: CategoryId) {
if (!hasItems.value)
return []
- return hasChildren(categoryId)
- ? Object.keys(items.value).filter(id => items.value[id]?.parentId === categoryId)
+ const category = items.value[categoryId]
+ return category?.childIds?.length
+ ? [...category.childIds]
: [categoryId]
}
- function saveCategoriesOrder(ids: CategoryId[]) {
- const userStore = useUserStore()
- updateData(`users/${userStore.uid}/categories`, { order: ids })
- }
-
function getTransactibleIds(ids?: CategoryId[]) {
return getTransactibleCategoriesIds(items.value ?? {}, ids)
}
function isItTransactible(categoryId: CategoryId) {
- return transactibleIds.value.includes(categoryId)
+ return transactibleIdsSet.value.has(categoryId)
}
- async function addCategory({ id, isUpdateChildCategoriesColor, values }: AddCategoryParams) {
- const uid = userStore.uid
- const categoryChildIds = getChildsIds(id)
- const categoryValues = getPreparedFormData(values)
-
- if (isDemo.value) {
- return addDemoCategory({
- childIds: categoryChildIds,
- id,
- isUpdateChildCategoriesColor,
- values,
- })
- }
+ function syncOptimisticParentChildIds(categories: Categories, id: CategoryId, oldParentId: CategoryId | 0, newParentId: CategoryId | 0) {
+ if (oldParentId === newParentId)
+ return
- // Update category
- await saveData(`users/${uid}/categories/${id}`, categoryValues)
+ if (oldParentId && oldParentId !== 0) {
+ const pId = String(oldParentId)
+ if (categories[pId]) {
+ const filtered = (categories[pId].childIds ?? []).filter(cid => cid !== id)
+ categories[pId] = { ...categories[pId], childIds: filtered.length ? filtered : undefined }
+ }
+ }
- // Update child categories colors
- if (isUpdateChildCategoriesColor && categoryChildIds) {
- for (const childId of categoryChildIds)
- await saveData(`users/${uid}/categories/${childId}/color`, categoryValues.color)
+ if (newParentId && newParentId !== 0) {
+ const pId = String(newParentId)
+ if (categories[pId])
+ categories[pId] = { ...categories[pId], childIds: [...(categories[pId].childIds ?? []), id] }
}
}
- async function deleteCategory(id: CategoryId, trnsIds?: TrnId[]) {
- if (isDemo.value) {
- deleteDemoCategory(id, trnsIds)
+ function applyOptimisticUpdate(id: CategoryId, categoryValues: CategoryItem, isUpdateChildCategoriesColor: boolean, categoryChildIds: CategoryId[]) {
+ const existingChildIds = items.value?.[id]?.childIds
+ const updatedItems: Categories = {
+ ...items.value,
+ [id]: existingChildIds ? { ...categoryValues, childIds: existingChildIds } : categoryValues,
}
- else {
- await removeData(`users/${userStore.uid}/categories/${id}`)
- if (trnsIds)
- await trnsStore.deleteTrnsByIds(trnsIds)
+
+ if (isUpdateChildCategoriesColor && categoryChildIds.length > 0) {
+ for (const childId of categoryChildIds) {
+ if (updatedItems[childId])
+ updatedItems[childId] = { ...updatedItems[childId], color: categoryValues.color }
+ }
}
+
+ syncOptimisticParentChildIds(updatedItems, id, items.value?.[id]?.parentId ?? 0, categoryValues.parentId)
+
+ setCategories(updatedItems)
}
- function formatCategories(items: Categories): Categories {
- const formattedItems = { ...items }
+ function saveCategory({ id, isUpdateChildCategoriesColor, values }: AddCategoryParams) {
+ if (id === 'transfer' || id === 'adjustment')
+ return
- // Step 1: Build parent-child relationships
- for (const categoryId in formattedItems) {
- const category = formattedItems[categoryId]
- const parentId = category?.parentId
+ const categoryChildIds = getChildsIds(id)
- if (!parentId || !formattedItems[parentId])
- continue
+ // Frontend IDs are always treated as new creates (server generates real ID)
+ const isExisting = !isLocalId(id) && items.value && id in items.value
- const parent = formattedItems[parentId]
- parent.childIds = parent.childIds || []
+ // Optimistic UI
+ applyOptimisticUpdate(id, values, isUpdateChildCategoriesColor, categoryChildIds)
- if (!parent.childIds.includes(categoryId))
- parent.childIds.push(categoryId)
+ if (!pushSaveOp({ entity: 'categories', id, isDemo: isDemo.value, isExisting: !!isExisting, values: values as unknown as Record<string, unknown> }))
+ return
+
+ const { api, client } = useConvexClientWithApi()
+ const action = isExisting ? 'update' : 'create'
+
+ const categoryData = {
+ color: values.color,
+ icon: values.icon,
+ name: values.name,
+ parentId: values.parentId && values.parentId !== 0 ? asConvexId<'categories'>(String(values.parentId)) : 0 as const,
+ showInLastUsed: values.showInLastUsed,
+ showInQuickSelector: values.showInQuickSelector,
}
- // Step 2: Set default values and clean up invalid child references
- for (const categoryId in formattedItems) {
- const category = formattedItems[categoryId]!
+ const mutation = isExisting && isUpdateChildCategoriesColor && categoryChildIds.length > 0
+ ? client.mutation(api.categories.updateWithChildren, {
+ childIds: categoryChildIds.map(cid => asConvexId<'categories'>(cid)),
+ id: asConvexId<'categories'>(id),
+ ...categoryData,
+ })
+ : isExisting
+ ? client.mutation(api.categories.update, { id: asConvexId<'categories'>(id), ...categoryData })
+ : client.mutation(api.categories.create, categoryData)
+
+ return handleMutationResult({
+ action,
+ entity: 'categories',
+ errorMessage: 'categories.errors.saveFailed',
+ id,
+ items,
+ mutation,
- // Set default values for optional properties
- formattedItems[categoryId] = {
- ...category,
- icon: category.icon.replace('mdi mdi-', 'mdi:'),
- showInLastUsed: category.showInLastUsed ?? false,
- showInQuickSelector: category.showInQuickSelector ?? false,
- }
+ })
+ }
- // Remove references to non-existent child categories
- if (category.childIds?.length)
- formattedItems[categoryId].childIds = category.childIds.filter(childId => formattedItems[childId])
+ function deleteCategory(id: CategoryId, trnsIds?: TrnId[]) {
+ if (id === 'transfer' || id === 'adjustment')
+ return
+
+ // Optimistic UI
+ const categories = { ...items.value }
+ const category = categories[id]
+ if (category?.parentId && category.parentId !== 0) {
+ const pId = String(category.parentId)
+ const parent = categories[pId]
+ if (parent) {
+ const filtered = (parent.childIds ?? []).filter(cid => cid !== id)
+ categories[pId] = { ...parent, childIds: filtered.length ? filtered : undefined }
+ }
}
+ delete categories[id]
+ setCategories(categories)
+
+ // Optimistic: remove trns from store immediately (backend cascade handles actual deletion)
+ if (trnsIds?.length)
+ trnsStore.removeTrnsFromStore(trnsIds)
+
+ if (!pushDeleteOp({ entity: 'categories', id, isDemo: isDemo.value }))
+ return
+
+ // Fire-and-forget mutation, cleanup on success
+ const { api, client } = useConvexClientWithApi()
+ return handleMutationResult({
+ action: 'delete',
+ entity: 'categories',
+ errorMessage: 'categories.errors.deleteFailed',
+ id,
+ items,
+ mutation: client.mutation(api.categories.remove, { id: asConvexId<'categories'>(id) }),
- return formattedItems
+ })
}
return {
- addCategory,
+ cancelPersist: () => debouncedPersist.cancel?.(),
categoriesForBeParent,
categoriesIds,
categoriesIdsForTrnValues,
@@ -319,10 +377,9 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
isItTransactible,
items,
recentCategoriesIds,
- saveCategoriesOrder,
+ saveCategory,
setCategories,
transactibleIds,
transferCategoriesIds,
- unsubscribeCategories,
}
})
diff --git a/app/components/categories/utils.test.ts b/app/components/categories/utils.test.ts
index 87dc3d18..79f9065b 100644
--- a/app/components/categories/utils.test.ts
+++ b/app/components/categories/utils.test.ts
@@ -55,7 +55,6 @@ const mockCategories2: Categories = {
color: '#701a75',
icon: 'mdi:paper-roll-outline',
name: 'Gas',
- order: 1,
parentId: '241120_k27ehb',
showInLastUsed: true,
showInQuickSelector: false,
@@ -64,7 +63,6 @@ const mockCategories2: Categories = {
color: '#52525b',
icon: 'mdi:mushroom',
name: 'Просто категория',
- order: 1,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
@@ -76,7 +74,6 @@ const mockCategories2: Categories = {
color: '#701a75',
icon: 'mdi:truck-delivery',
name: 'Auto',
- order: 1,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
@@ -86,7 +83,6 @@ const mockCategories2: Categories = {
color: 'var(--ui-primary)',
icon: 'mdi:repeat',
name: 'Transfer',
- order: 9999,
parentId: 0,
showInLastUsed: false,
showInQuickSelector: false,
@@ -123,9 +119,34 @@ describe('getTransactibleCategoriesIds', () => {
})
describe('getTransferCategoriesIds', () => {
- it('returns transfer categories ids', () => {
+ it('returns only the reserved transfer ID', () => {
const result = getTransferCategoriesIds(mockCategories)
- expect(result).toEqual(['transfer', 'transfer2', 'transfer3'])
+ expect(result).toEqual(['transfer'])
+ })
+
+ it('does not match user categories named "transfer" or "перевод"', () => {
+ const items: Categories = {
+ myTransfer: {
+ color: '#000',
+ icon: 'mdi:repeat',
+ name: 'transfer',
+ parentId: 0,
+ },
+ transfer: {
+ color: 'var(--ui-primary)',
+ icon: 'mdi:repeat',
+ name: 'Transfer',
+ parentId: 0,
+ },
+ перевод: {
+ color: '#000',
+ icon: 'mdi:repeat',
+ name: 'перевод',
+ parentId: 0,
+ },
+ }
+ const result = getTransferCategoriesIds(items)
+ expect(result).toEqual(['transfer'])
})
it('empty categories object', () => {
diff --git a/app/components/categories/utils.ts b/app/components/categories/utils.ts
index 359ff263..a820b97b 100644
--- a/app/components/categories/utils.ts
+++ b/app/components/categories/utils.ts
@@ -1,35 +1,33 @@
import type { Categories, CategoryId, CategoryItem } from '~/components/categories/types'
-import { random } from '~/assets/js/emo'
-import icons from '~/assets/js/icons'
-import { colorsArray } from '~/components/color/colors'
-
export function getTransactibleCategoriesIds(items: Categories, ids?: CategoryId[]) {
- return (ids ?? Object.keys(items ?? [])).reduce((acc, id) => {
+ const seen = new Set<CategoryId>()
+ const result: CategoryId[] = []
+
+ for (const id of ids ?? Object.keys(items ?? [])) {
const category = items?.[id]
if (category?.parentId === 0 && category?.childIds?.length) {
- acc.push(...category.childIds.filter(childId => !acc.includes(childId)))
+ for (const childId of category.childIds) {
+ if (!seen.has(childId)) {
+ seen.add(childId)
+ result.push(childId)
+ }
+ }
}
- else if (!acc.includes(id)) {
- acc.push(id)
+ else if (!seen.has(id)) {
+ seen.add(id)
+ result.push(id)
}
- return acc
- }, [] as CategoryId[])
-}
+ }
-export function getTransferCategoriesIds(items: Categories): CategoryId[] {
- const names = ['перевод', 'transfer']
- return [
- ...Object.keys(items ?? {})
- .filter(id => names.includes(`${items[id]?.name}`.toLowerCase())),
- ]
+ return result
}
-export function getParentCategory(items: Categories, parentId: CategoryId | 0): CategoryItem | false {
- if (parentId === 0)
- return false
+export function getTransferCategoriesIds(items: Categories): CategoryId[] {
+ if (!items?.transfer)
+ return []
- return items[parentId] ?? false
+ return ['transfer']
}
export function getParentCategoryIdOrReturnSame(items: Categories, categoryId: CategoryId): CategoryId {
@@ -39,7 +37,7 @@ export function getParentCategoryIdOrReturnSame(items: Categories, categoryId: C
return category.parentId ?? categoryId
}
-export function getParentCategoryId2(items: Categories, categoryId: CategoryId): CategoryId | undefined {
+export function getParentCategoryIdOrUndefined(items: Categories, categoryId: CategoryId): CategoryId | undefined {
const category = items[categoryId]
return category?.parentId === 0 ? undefined : category?.parentId
}
@@ -49,15 +47,3 @@ export function compareCategoriesByParentAndName(a: CategoryItem, b: CategoryIte
const parentNameB = items[b.parentId]?.name || ''
return parentNameA.localeCompare(parentNameB) || a.name.localeCompare(b.name)
}
-
-export function getPreparedFormData(values?: any): CategoryItem {
- return {
- color: values?.color ?? random(colorsArray),
- icon: values?.icon ?? random(random(icons)),
- name: values?.name ?? '',
- order: values?.order ?? 1,
- parentId: values?.parentId ?? 0,
- showInLastUsed: values?.showInLastUsed ?? true,
- showInQuickSelector: values?.showInQuickSelector ?? false,
- }
-}
diff --git a/app/components/color/Palette.vue b/app/components/color/Palette.vue
index 649c6742..46aad2cf 100644
--- a/app/components/color/Palette.vue
+++ b/app/components/color/Palette.vue
@@ -39,8 +39,10 @@ function findWalletWithColor(color: string) {
<div
v-for="(color, idx) in colorsGroup"
:key="idx"
- class="w-full overflow-hidden rounded-sm border-2 border-transparent"
- :class="[{ '!border-(--ui-primary) !shadow': color === props.activeColor, 'pointer-events-none': !color }]"
+ :class="cn('w-full overflow-hidden rounded-sm border-2 border-transparent',
+ color === props.activeColor && 'border-(--ui-primary) shadow',
+ !color && 'pointer-events-none',
+ )"
@click="emit('click', color)"
>
<div class="flex-center h-10" :style="{ background: color }">
@@ -66,9 +68,9 @@ function findWalletWithColor(color: string) {
{{ t('color.custom') }}
</template>
<FormInput
- :value="activeColor"
+ :modelValue="activeColor"
type="color"
- @updateValue="(event: HTMLInputEvent) => emit('click', event.target.value)"
+ @update:modelValue="(value: string) => emit('click', value)"
/>
</FormElement>
</div>
diff --git a/app/components/currencies/List.vue b/app/components/currencies/List.vue
index 03074939..4761216f 100644
--- a/app/components/currencies/List.vue
+++ b/app/components/currencies/List.vue
@@ -1,4 +1,6 @@
<script setup lang="ts">
+import type { CurrencyCode } from '~/components/currencies/types'
+
import { currencies } from '~/components/currencies/currencies'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
@@ -7,7 +9,9 @@ const props = defineProps<{
isHideUnused?: boolean
isShowAllButton?: boolean
}>()
-const emit = defineEmits(['onSelect'])
+const emit = defineEmits<{
+ select: [code: CurrencyCode]
+}>()
const { t } = useI18n()
const walletsStore = useWalletsStore()
@@ -33,9 +37,8 @@ const list = computed(() => {
<div class="grid h-full grid-rows-[auto_1fr] overflow-hidden px-2">
<div>
<FormInput
- :value="searchInput"
+ v-model="searchInput"
:placeholder="`${t('currencies.list.search')}...`"
- @updateValue="(value: string) => searchInput = value"
/>
</div>
@@ -52,7 +55,7 @@ const list = computed(() => {
:lineWidth="6"
class="group"
insideClasses="!min-h-[44px]"
- @click="emit('onSelect', 'all')"
+ @click="emit('select', 'all')"
>
<div class="flex items-center">
<div class="w-14 pl-1">
@@ -74,7 +77,7 @@ const list = computed(() => {
:lineWidth="6"
class="group"
insideClasses="!min-h-[44px]"
- @click="emit('onSelect', currencyCode)"
+ @click="emit('select', currencyCode)"
>
<div class="flex items-center">
<div class="w-14 pl-1">
@@ -98,7 +101,7 @@ const list = computed(() => {
:isActive="currency.code === active"
:lineWidth="6"
class="group"
- @click="emit('onSelect', currency.code)"
+ @click="emit('select', currency.code)"
>
<div class="flex items-center">
<div class="w-14 pl-1">
diff --git a/app/components/currencies/Modal.vue b/app/components/currencies/Modal.vue
index c774eaef..49def5cf 100644
--- a/app/components/currencies/Modal.vue
+++ b/app/components/currencies/Modal.vue
@@ -8,14 +8,14 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onClose: []
- onSelect: [code: CurrencyCode]
+ close: []
+ select: [code: CurrencyCode]
}>()
const { t } = useI18n()
-function onSelect(code: CurrencyCode, close: () => void) {
- emit('onSelect', code)
+function select(code: CurrencyCode, close: () => void) {
+ emit('select', code)
close()
}
</script>
@@ -25,11 +25,11 @@ function onSelect(code: CurrencyCode, close: () => void) {
<BottomSheet
isShow
drugClassesCustom="bottomSheetDrugClassesCustom"
- @closed="emit('onClose')"
+ @closed="emit('close')"
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -40,7 +40,7 @@ function onSelect(code: CurrencyCode, close: () => void) {
:active="props.activeCode"
:isShowAllButton="props.isShowAllButton"
:isHideUnused="props.isHideUnused"
- @onSelect="(c: CurrencyCode) => onSelect(c, close)"
+ @select="(c: CurrencyCode) => select(c, close)"
/>
</div>
</template>
diff --git a/app/components/currencies/useCurrenciesStore.ts b/app/components/currencies/useCurrenciesStore.ts
index 95c9e1b0..3fa7bc3c 100644
--- a/app/components/currencies/useCurrenciesStore.ts
+++ b/app/components/currencies/useCurrenciesStore.ts
@@ -1,92 +1,62 @@
-import { startOfDay } from 'date-fns'
import localforage from 'localforage'
-import { deepUnref } from 'vue-deepunref'
-import { getDataOnce, saveData } from '~~/services/firebase/api'
+import { defineStore } from 'pinia'
-import type { CurrencyCode, Rates } from '~/components/currencies/types'
+import type { Rates } from '~/components/currencies/types'
import { currencies as allCurrencies } from '~/components/currencies/currencies'
-import { useDemo } from '~/components/demo/useDemo'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { useUserStore } from '~/components/user/useUserStore'
+import { isPersistBlocked } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('currencies')
-const serviceUrlBase = `https://openexchangerates.org/api/latest.json?app_id=`
export const currencies = allCurrencies
export const useCurrenciesStore = defineStore('currencies', () => {
- const { $config } = useNuxtApp()
const userStore = useUserStore()
- const { isDemo } = useDemo()
- const base = ref<CurrencyCode>('USD')
+ const base = computed(() => userStore.baseCurrency)
const rates = ref<Rates>({})
- async function getRatesOfUSD(apiKey: string) {
+ async function initCurrencies() {
try {
- const { data } = await useAsyncData<{ rates: Rates }>(
- 'rates',
- () => $fetch(`${serviceUrlBase}${apiKey}`),
- )
- return data.value?.rates
+ const { api, client } = useConvexClientWithApi()
+
+ // Get latest rates from Convex
+ const latestRates = await client.query(api.rates.getLatest, {})
+
+ if (latestRates?.rates) {
+ setRates(latestRates.rates as Rates)
+ }
+ else {
+ // If no rates exist, try to refresh them via action
+ await client.action(api.rates.refreshRates, {})
+ const freshRates = await client.query(api.rates.getLatest, {})
+ if (freshRates?.rates)
+ setRates(freshRates.rates as Rates)
+ }
}
catch (e) {
- console.error('Currencies api are unavailable', e)
- return undefined
+ logger.error('init failed', e)
}
}
- async function initCurrencies() {
- // User base currency in DB
- const userBaseCurrency: CurrencyCode = await getDataOnce(`users/${userStore.uid}/settings/baseCurrency`) || 'USD'
-
- // Rates for today
- const today = startOfDay(new Date()).getTime()
-
- let ratesBasedOnUsd: Rates | undefined = await getDataOnce(`ratesUsd/history/${today}`)
-
- if (!ratesBasedOnUsd) {
- ratesBasedOnUsd = await getRatesOfUSD($config.public.ratesApiKey)
- if (!ratesBasedOnUsd)
- return
-
- await saveData('ratesUsd/latest', ratesBasedOnUsd)
- await saveData(`ratesUsd/history/${today}`, ratesBasedOnUsd)
- }
-
- setBase(userBaseCurrency)
- setRates(ratesBasedOnUsd)
- }
-
function setRates(values: Rates) {
rates.value = values
- localforage.setItem('finapp.currencies', {
- base: base.value,
- rates: values,
- })
- }
-
- function setBase(value: CurrencyCode) {
- base.value = value
+ if (isPersistBlocked())
+ return
- localforage.setItem('finapp.currencies', {
- base: value,
- rates: deepUnref(rates.value),
+ localforage.setItem(STORAGE_KEYS.currencies, {
+ rates: values,
})
}
- function updateBase(value: CurrencyCode) {
- setBase(value)
-
- if (!isDemo.value)
- saveData(`users/${userStore.uid}/settings/baseCurrency`, value)
- }
-
return {
base,
initCurrencies,
rates,
- setBase,
setRates,
- updateBase,
}
})
diff --git a/app/components/date/LinkItem.vue b/app/components/date/LinkItem.vue
index f0446d7a..04027fb5 100644
--- a/app/components/date/LinkItem.vue
+++ b/app/components/date/LinkItem.vue
@@ -1,8 +1,4 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { classes } from '~/components/ui/getStyles'
-
export type DateLinkItemProps = {
isActive?: boolean
variant?: 'small'
@@ -18,8 +14,8 @@ const emit = defineEmits<{
<div
:class="cn(
'flex items-center text-nowrap rounded-sm text-xs leading-none px-3',
- [classes.item.link, classes.item.minh3, classes.item.center2],
- props.variant === 'small' ? 'px-2 text-2xs text-muted' : 'bg-[var(--item-4)]',
+ 'interactive flex items-center justify-center min-h-[32px]',
+ props.variant === 'small' ? 'px-2 text-2xs text-muted' : 'bg-(--item-4)',
props.isActive ? 'text-primary' : '',
)"
@click="(e: Event) => emit('click', e)"
diff --git a/app/components/date/LinkItemNoBg.vue b/app/components/date/LinkItemNoBg.vue
index 376243a6..0b5ec00b 100644
--- a/app/components/date/LinkItemNoBg.vue
+++ b/app/components/date/LinkItemNoBg.vue
@@ -1,6 +1,4 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
isActive?: boolean
}>()
@@ -11,12 +9,9 @@ const emit = defineEmits<{
<template>
<div
- :class="[
- getStyles('item', ['center2', 'padding4', 'minh3']), {
- 'text-primary bg-[var(--item-5)]': props.isActive,
- },
- ]"
- class="rounded-full text-xs leading-none text-nowrap text-(--ui-text)"
+ :class="cn('flex min-h-[32px] items-center justify-center rounded-full px-1 text-xs leading-none text-nowrap text-(--ui-text)',
+ props.isActive && 'text-primary bg-(--item-5)',
+ )"
@click="(e: Event) => emit('click', e)"
>
<slot />
diff --git a/app/components/date/Nav.vue b/app/components/date/Nav.vue
index ac3dc8bc..49bfc905 100644
--- a/app/components/date/Nav.vue
+++ b/app/components/date/Nav.vue
@@ -1,14 +1,10 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-const props = withDefaults(defineProps<{
+const { isEnd, isShowNavHome, isStart, position = 'left' } = defineProps<{
isEnd: boolean
isShowNavHome: boolean
isStart: boolean
position?: 'left' | 'right'
-}>(), {
- position: 'left',
-})
+}>()
const emit = defineEmits<{
changeDate: [action: 'prev' | 'next' | 'today']
@@ -17,32 +13,32 @@ const emit = defineEmits<{
<template>
<div class="flex items-center gap-1">
- <UiItem3
- v-if="props.position === 'left' && props.isShowNavHome"
+ <UiActionButton
+ v-if="position === 'left' && isShowNavHome"
@click="emit('changeDate', 'today')"
>
<Icon name="lucide:undo-2" size="20" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- :class="[getStyles('item', ['bg2']), { '!hover:transparent opacity-30': isStart }]"
+ <UiActionButton
+ :class="cn('bg-item-3', isStart && 'hover:transparent opacity-30')"
@click="emit('changeDate', 'prev')"
>
<Icon name="lucide:chevron-left" size="24" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- :class="[getStyles('item', ['bg2']), { '!hover:transparent opacity-30': isEnd }]"
+ <UiActionButton
+ :class="cn('bg-item-3', isEnd && 'hover:transparent opacity-30')"
@click="emit('changeDate', 'next')"
>
<Icon name="lucide:chevron-left" size="24" class="rotate-180" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- v-if="props.position === 'right' && props.isShowNavHome"
+ <UiActionButton
+ v-if="position === 'right' && isShowNavHome"
@click="emit('changeDate', 'today')"
>
<Icon name="lucide:undo-2" size="20" />
- </UiItem3>
+ </UiActionButton>
</div>
</template>
diff --git a/app/components/date/Ranges.vue b/app/components/date/Ranges.vue
index 4554d321..058354bb 100644
--- a/app/components/date/Ranges.vue
+++ b/app/components/date/Ranges.vue
@@ -11,7 +11,7 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onClose: []
+ close: []
}>()
const { t } = useI18n()
@@ -95,12 +95,12 @@ function isRangeSelected(rd: IntervalGroupedLabel) {
function selectRange(igl: IntervalGroupedLabel) {
props.statDate.setRangeByPeriod(igl)
- emit('onClose')
+ emit('close')
}
function selectMaxRange(isSkipEmpty = false) {
props.statDate.setMaxRange(isSkipEmpty)
- emit('onClose')
+ emit('close')
}
</script>
diff --git a/app/components/date/types.ts b/app/components/date/types.ts
index a158602a..be10070f 100644
--- a/app/components/date/types.ts
+++ b/app/components/date/types.ts
@@ -34,15 +34,11 @@ export type StatDateParamsQuery = {
rangeOffset: string
}
-export type GroupBy = 'period' | 'all' | 'daySelector'
-
export type IntervalsInRangeProps = Pick<StatDateParams, 'intervalsBy' | 'intervalsDuration'> & {
range: Range
} & Pick<StatDateParams, 'rangeOffset'>
-export type CalculateRangeParams = Pick<StatDateParams, 'rangeDuration' | 'rangeBy' | 'rangeOffset'>
-
-export type Interval = Pick<StatDateParams, 'rangeDuration' | 'rangeBy'>
+type Interval = Pick<StatDateParams, 'rangeDuration' | 'rangeBy'>
export type Grouped = Pick<StatDateParams, 'intervalsBy' | 'intervalsDuration'>
export type IntervalGroupedLabel = Grouped & Interval & {
diff --git a/app/components/date/useStatDate.ts b/app/components/date/useStatDate.ts
index 252605f8..9a443de8 100644
--- a/app/components/date/useStatDate.ts
+++ b/app/components/date/useStatDate.ts
@@ -213,5 +213,3 @@ export function useStatDate({
setRangeByPeriod,
}
}
-
-export type statDate = ReturnType<typeof useStatDate>
diff --git a/app/components/date/utils.ts b/app/components/date/utils.ts
index 7cc493b2..d1abc7b9 100644
--- a/app/components/date/utils.ts
+++ b/app/components/date/utils.ts
@@ -1,3 +1,5 @@
+import type { CalendarDate } from '@internationalized/date'
+
import { getLocalTimeZone, parseDate, today } from '@internationalized/date'
import { differenceInDays, endOfDay, endOfMonth, endOfWeek, endOfYear, format, formatISO, startOfDay, startOfMonth, startOfWeek, startOfYear, sub } from 'date-fns'
import { ru } from 'date-fns/locale'
@@ -103,7 +105,7 @@ export function parseUCalendarDate(date: number) {
return parseDate(formatISO(date, { representation: 'date' }))
}
-export function getUCalendarTimedDate(date: any) {
+export function getUCalendarTimedDate(date: CalendarDate) {
const now = new Date()
const selectedDate = date.toString()
return new Date(selectedDate).setHours(now.getHours(), now.getMinutes())
diff --git a/app/components/demo/data.ts b/app/components/demo/data.ts
index 4615552c..5d870555 100644
--- a/app/components/demo/data.ts
+++ b/app/components/demo/data.ts
@@ -16,176 +16,178 @@ export const data: {
categories: {
'4b6473ee7324': {
color: '#d84315',
- editedAt: 1585408887791,
icon: 'mdi:pill',
name: { en: 'Health', ru: 'Здоровье' },
order: 8,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408887791,
},
'06ca25500ef2': {
color: '#4fc3f7',
- editedAt: 1585408861256,
icon: 'mdi:airplane',
name: { en: 'Travel', ru: 'Путешествия' },
order: 11,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861256,
},
'd564ed02cf7f': {
color: '#8bc34a',
- editedAt: 1585408861256,
icon: 'mdi:human-male',
name: { en: 'Freelance', ru: 'Фриланс' },
order: 9,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861256,
},
'KsNnR1EDBl9tAZTaWUP': {
color: '#90a4ae',
- editedAt: 1585408861252,
icon: 'mdi:car-sports',
name: { en: 'Auto', ru: 'Авто' },
order: 0,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861252,
},
'KsNnRB3MqKvAqwo5IEf': {
color: '#d4e157',
- editedAt: 1585073319837,
icon: 'mdi:food',
name: { en: 'Cafe', ru: 'Кафе' },
order: 1,
parentId: 'KxKMi55aCVkJXsiDE',
showInLastUsed: true,
showInQuickSelector: true,
+ updatedAt: 1585073319837,
},
'KsNnREUqdH4nTGEjEhl': {
color: '#ba68c8',
- editedAt: 1585408861253,
icon: 'mdi:account-heart',
name: { en: 'Family', ru: 'Семья' },
order: 1,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861253,
},
'KsNnRHjakWM4imFmCpI': {
color: '#d4e157',
- editedAt: 1584359067144,
icon: 'mdi:food-apple',
name: { en: 'Groceries', ru: 'Продукты' },
order: 2,
parentId: 'KxKMi55aCVkJXsiDE',
showInLastUsed: true,
+ showInQuickSelector: false,
+ updatedAt: 1584359067144,
},
'KsNnS6QgcjgSVeA3KaM': {
color: '#90a4ae',
- editedAt: 1584359067348,
icon: 'mdi:gas-station',
name: { en: 'Gas', ru: 'Бензин' },
parentId: 'KsNnR1EDBl9tAZTaWUP',
showInLastUsed: true,
showInQuickSelector: true,
+ updatedAt: 1584359067348,
},
'KsNnSMR4DtZXFr75V2Y': {
color: '#8d6e63',
- editedAt: 1585078567615,
icon: 'mdi:fire',
name: { en: 'Gas', ru: 'Газ' },
parentId: 'KsNnTR_IP7TZ5UQ39MV',
showInLastUsed: false,
showInQuickSelector: false,
+ updatedAt: 1585078567615,
},
'KsNnSzI9bi2L6YtJpFl': {
color: '#90a4ae',
- editedAt: 1585078593530,
icon: 'mdi:cogs',
name: { en: 'Spare parts', ru: 'Запчасти' },
parentId: 'KsNnR1EDBl9tAZTaWUP',
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585078593530,
},
'KsNnT85ujLHZFMRjqau': {
color: '#8d6e63',
- editedAt: 1585078530426,
icon: 'mdi:microsoft-internet-explorer',
name: { en: 'Internet', ru: 'Интернет' },
parentId: 'KsNnTR_IP7TZ5UQ39MV',
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585078530426,
},
'KsNnTR_IP7TZ5UQ39MV': {
color: '#8d6e63',
- editedAt: 1585408861254,
icon: 'mdi:home-currency-usd',
name: { en: 'Home pay', ru: 'Домашние платежи' },
order: 2,
parentId: 0,
showInLastUsed: false,
showInQuickSelector: false,
+ updatedAt: 1585408861254,
},
'KsNnUCHgx-3TJVpEOo5': {
color: '#8d6e63',
- editedAt: 1585078546884,
icon: 'mdi:toilet',
name: { en: 'Water', ru: 'Вода' },
parentId: 'KsNnTR_IP7TZ5UQ39MV',
showInLastUsed: false,
showInQuickSelector: false,
+ updatedAt: 1585078546884,
},
'KsNnUVvhaCBzUOIce-c': {
color: '#ff8a65',
- editedAt: 1585408861256,
icon: 'mdi:account-tie',
name: { en: 'Office', ru: 'Офис' },
order: 10,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861256,
},
'KsNnVKle-reg5skNcxE': {
color: '#26a69a',
- editedAt: 1585408861254,
icon: 'mdi:cellphone-android',
name: { en: 'Phone', ru: 'Телефон' },
order: 5,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408861254,
},
'KsNnVRQvYywN2OZFrEq': {
color: '#1b5e20',
- editedAt: 1585408861255,
icon: 'mdi:vuejs',
name: { en: 'Vuejs', ru: 'Vuejs' },
order: 6,
parentId: 0,
showInLastUsed: true,
+ showInQuickSelector: false,
+ updatedAt: 1585408861255,
},
'KsNnVUo-gQZCYr_Tqjx': {
color: '#f48fb1',
- editedAt: 1585408875803,
icon: 'mdi:badminton',
name: { en: 'Sport', ru: 'Спорт' },
order: 7,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408875803,
},
'KxKMi55aCVkJXsiDE': {
color: '#d4e157',
- editedAt: 1585408895295,
icon: 'mdi:cupcake',
name: { en: 'Food', ru: 'Еда' },
order: 4,
parentId: 0,
showInLastUsed: true,
showInQuickSelector: false,
+ updatedAt: 1585408895295,
},
},
@@ -194,62 +196,62 @@ export const data: {
color: '#1565c0',
currency: 'RUB',
desc: { en: '', ru: '' },
- editedAt: 1585408895295,
isWithdrawal: true,
name: { en: 'Rubles Cash', ru: 'Наличные рубли' },
order: 4,
type: 'cash',
+ updatedAt: 1585408895295,
},
'200921_WrAFwe': {
color: '#ef5350',
currency: 'USD',
desc: { en: '', ru: '' },
- editedAt: 1585408895295,
isWithdrawal: true,
name: { en: 'USD', ru: 'Доллары' },
order: 10,
type: 'cash',
+ updatedAt: 1585408895295,
},
'210614_uvi9w8': {
color: '#ad1457',
currency: 'USD',
desc: { en: 'Money for study', ru: 'Деньги на учебу' },
- editedAt: 1585408895295,
isWithdrawal: true,
name: { en: 'Study', ru: 'Учеба' },
order: 9,
type: 'cash',
+ updatedAt: 1585408895295,
},
'220315_p78836': {
color: '#388e3c',
currency: 'USD',
desc: { en: 'Money for party', ru: 'Деньги на вечеринку' },
- editedAt: 1585408895295,
isArchived: true,
isWithdrawal: true,
name: { en: 'Party', ru: 'Вечеринка' },
order: 25,
type: 'cashless',
+ updatedAt: 1585408895295,
},
'231223_x83sls': {
color: '#1565c0',
currency: 'RUB',
desc: { en: 'Money for auto', ru: 'Деньги на авто' },
- editedAt: 1585408895295,
isWithdrawal: true,
name: { en: 'Auto', ru: 'Авто' },
order: 3,
type: 'cash',
+ updatedAt: 1585408895295,
},
'240324_3zjma5': {
color: '#d32f2f',
creditLimit: 160000,
currency: 'RUB',
desc: { en: 'Money for office', ru: 'Деньги на офис' },
- editedAt: 1585408895295,
name: { en: 'Credit Card', ru: 'Кредитная карта' },
order: 1,
type: 'credit',
+ updatedAt: 1585408895295,
},
},
}
diff --git a/app/components/demo/useDemo.ts b/app/components/demo/useDemo.ts
index e12a6e8b..b060411c 100644
--- a/app/components/demo/useDemo.ts
+++ b/app/components/demo/useDemo.ts
@@ -1,16 +1,17 @@
import { startOfYear, subYears } from 'date-fns'
import localforage from 'localforage'
-import type { AddCategoryParams, Categories, CategoryId } from '~/components/categories/types'
+import type { Categories } from '~/components/categories/types'
import type { LocaleSlug } from '~/components/locale/types'
-import type { TrnId, Trns } from '~/components/trns/types'
-import type { WalletId, WalletItem, Wallets } from '~/components/wallets/types'
+import type { Trns } from '~/components/trns/types'
+import type { Wallets } from '~/components/wallets/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
import currencies from '~/components/demo/currencies.json'
import { data } from '~/components/demo/data'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { useUserStore } from '~/components/user/useUserStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const config = {
@@ -27,7 +28,7 @@ export function useDemo() {
const trnsStore = useTrnsStore()
async function generateDemoData(locale: LocaleSlug) {
- localforage.clear()
+ await localforage.clear()
const translatedData: {
categories: Categories
@@ -43,7 +44,7 @@ export function useDemo() {
}, {} as Wallets),
}
- currenciesStore.setBase('USD')
+ useUserStore().setUserBaseCurrency('USD')
currenciesStore.setRates(currencies)
categoriesStore.setCategories(translatedData.categories)
walletsStore.setWallets(translatedData.wallets)
@@ -51,7 +52,7 @@ export function useDemo() {
const startDate = subYears(startOfYear(new Date()), config.subtractYears).getTime()
const endDate = new Date().getTime()
- const trns: Trns = [...Array.from({ length: config.trnsCount })].reduce((acc, _, i) => {
+ const trns: Trns = Array.from({ length: config.trnsCount }).reduce((acc, _, i) => {
return {
...acc,
[i]: {
@@ -68,69 +69,8 @@ export function useDemo() {
trnsStore.setTrns(trns)
}
- function addDemoCategory({ childIds, id, isUpdateChildCategoriesColor, values }: AddCategoryParams) {
- const items = {
- ...categoriesStore.items,
- [id]: values,
- }
-
- if (isUpdateChildCategoriesColor && childIds) {
- for (const childId of childIds) {
- if (items[childId]) {
- items[childId].color = values.color
- }
- }
- }
- categoriesStore.setCategories(items)
- }
-
- async function deleteDemoCategory(id: CategoryId, trnsIds?: TrnId[]) {
- if (trnsIds)
- await deleteDemoTrns(trnsIds)
-
- const items = { ...categoriesStore.items }
- delete items[id]
-
- categoriesStore.setCategories(items)
- }
-
- async function deleteDemoTrns(ids: TrnId[]) {
- const trns = { ...trnsStore.items }
- for (const id of ids)
- delete trns[id]
-
- await trnsStore.setTrns(trns)
- }
-
- async function sortDemoWallets(ids: WalletId[], wallets: Wallets) {
- const sortedWallets = ids.reduce((acc, walletId, index) => {
- const wallet = wallets[walletId]
- acc[walletId] = wallet
- acc[walletId].order = index
- return acc
- }, {} as Record<WalletId, WalletItem>)
-
- walletsStore.setWallets(sortedWallets)
- return 'ok'
- }
-
- async function deleteDemoWallet(id: WalletId, trnsIds?: TrnId[]) {
- if (trnsIds)
- await deleteDemoTrns(trnsIds)
-
- const items = { ...walletsStore.items }
- delete items[id]
-
- walletsStore.setWallets(items)
- }
-
return {
- addDemoCategory,
- deleteDemoCategory,
- deleteDemoTrns,
- deleteDemoWallet,
generateDemoData,
isDemo,
- sortDemoWallets,
}
}
diff --git a/app/components/form/Element.vue b/app/components/form/Element.vue
index 6021816a..b34a2410 100644
--- a/app/components/form/Element.vue
+++ b/app/components/form/Element.vue
@@ -4,9 +4,9 @@
<template>
<div>
- <UiTitle3 class="pb-2">
+ <UiTitleSection class="pb-2">
<slot name="label" />
- </UiTitle3>
+ </UiTitleSection>
<slot />
</div>
diff --git a/app/components/form/Input.vue b/app/components/form/Input.vue
index 4486584f..750a3bca 100644
--- a/app/components/form/Input.vue
+++ b/app/components/form/Input.vue
@@ -1,24 +1,21 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
+ modelValue: string | number
placeholder?: string
type?: 'text' | 'number' | 'color'
- value: string | number
}>()
const emit = defineEmits<{
- updateValue: [value: string]
+ 'update:modelValue': [value: string]
}>()
</script>
<template>
<input
:placeholder="props.placeholder"
- :value="props.value"
- :class="getStyles('item', ['link', 'rounded'])"
+ :value="props.modelValue"
:type="props.type ?? 'text'"
- class="border-item-6 bg-item-3 placeholder:text-muted hover:text-1 m-0 w-full border border-solid px-3 py-2 text-base font-normal hover:border-(--ui-primary) hover:bg-[var(--item-5)] hover:outline-none"
- @input="(event: HTMLInputEvent) => emit('updateValue', event.target.value)"
+ class="border-item-6 bg-item-3 placeholder:text-muted m-0 w-full rounded-sm border border-solid px-3 py-2 text-base font-normal outline-none hover:bg-(--item-5) focus:border-(--ui-primary)"
+ @input="(event: HTMLInputEvent) => emit('update:modelValue', event.target.value)"
>
</template>
diff --git a/app/components/form/Select.vue b/app/components/form/Select.vue
index c7ad18c3..afbdaefb 100644
--- a/app/components/form/Select.vue
+++ b/app/components/form/Select.vue
@@ -1,4 +1,4 @@
-<script lang="ts" setup>
+<script setup lang="ts">
const props = defineProps<{
options: {
label: string
@@ -36,6 +36,6 @@ select {
background-position: right 0.7rem center;
background-repeat: no-repeat;
background-size: 1.25em 1.25em;
- @apply hover:bg-[var(--item-5)] bg-item-3 hover:outline-none border border-transparent hover:border-(--ui-primary) -my-px block min-h-[42px] w-full max-w-lg grow items-center gap-0 gap-x-2 overflow-hidden rounded-md px-4 pr-10 py-2 ring-0;
+ @apply bg-item-3 border border-transparent outline-none -my-px block min-h-[42px] w-full grow items-center gap-0 gap-x-2 overflow-hidden rounded-md px-4 pr-10 py-2 ring-0 hover:bg-(--item-5) focus:border-(--ui-primary);
}
</style>
diff --git a/app/components/form/Switch.vue b/app/components/form/Switch.vue
index 4d1dde96..722d2aa7 100644
--- a/app/components/form/Switch.vue
+++ b/app/components/form/Switch.vue
@@ -5,7 +5,7 @@ defineProps<{
}>()
const emit = defineEmits<{
- (e: 'click', value: boolean): void
+ click: [value: boolean]
}>()
</script>
@@ -16,12 +16,14 @@ const emit = defineEmits<{
</div>
<div
- :class="{ 'bg-(--ui-primary)': value, 'bg-(--ui-bg-accented)': !value }"
- class="relative h-5 w-10 rounded-xl p-px px-[2px] transition-colors ease-in-out"
+ :class="cn('relative h-5 w-10 rounded-xl py-px px-[2px] transition-colors ease-in-out',
+ value ? 'bg-(--ui-primary)' : 'bg-(--ui-bg-accented)',
+ )"
>
<div
- :class="{ 'translate-x-4.5': value }"
- class="bg-default size-4.5 rounded-xl shadow-md transition-transform ease-in-out"
+ :class="cn('bg-default size-4.5 rounded-xl shadow-md transition-transform ease-in-out',
+ value && 'translate-x-4.5',
+ )"
/>
</div>
</div>
diff --git a/app/components/form/Textarea.vue b/app/components/form/Textarea.vue
index a75a8ae8..9aa88ac9 100644
--- a/app/components/form/Textarea.vue
+++ b/app/components/form/Textarea.vue
@@ -1,23 +1,20 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
+ modelValue: string | number
placeholder: string
type?: 'text' | 'number'
- value: string | number
}>()
const emit = defineEmits<{
- updateValue: [value: string]
+ 'update:modelValue': [value: string]
}>()
</script>
<template>
<textarea
:placeholder="props.placeholder"
- :value="props.value"
- :class="getStyles('item', ['link', 'rounded'])"
- class="border-item-6 bg-item-3 placeholder:text-muted hover:text-1 m-0 w-full border border-solid px-3 py-2 text-base font-normal hover:border-(--ui-primary) hover:bg-[var(--item-5)] hover:outline-none"
- @input="(event: HTMLInputEvent) => emit('updateValue', event.target.value)"
+ :value="props.modelValue"
+ class="border-item-6 bg-item-3 placeholder:text-muted m-0 w-full rounded-sm border border-solid px-3 py-2 text-base font-normal outline-none hover:bg-(--item-5) focus:border-(--ui-primary)"
+ @input="(event: HTMLInputEvent) => emit('update:modelValue', event.target.value)"
/>
</template>
diff --git a/app/components/layout/ConfirmModal.vue b/app/components/layout/ConfirmModal.vue
index 4a6871ae..04151801 100644
--- a/app/components/layout/ConfirmModal.vue
+++ b/app/components/layout/ConfirmModal.vue
@@ -1,82 +1,65 @@
<script setup lang="ts">
-defineProps<{
+const props = defineProps<{
description?: string
+ title?: string
}>()
const emit = defineEmits<{
- (e: 'closed'): void
- (e: 'onConfirm'): void
+ closed: []
+ confirm: []
}>()
const { t } = useI18n()
-const items = computed(() => ({
- no: {
- click: (close: () => void) => {
- close()
- },
- icon: 'mdi:close',
- localeKey: 'base.no',
- },
+const isOpen = ref(true)
- yes: {
- click: (close: () => void) => {
- emit('onConfirm')
- close()
- },
- icon: 'mdi:check',
- localeKey: 'base.yes',
- },
-}))
+function onConfirm(close: () => void) {
+ emit('confirm')
+ close()
+}
+
+function onClosed() {
+ isOpen.value = false
+ emit('closed')
+}
</script>
<template>
- <Teleport to="body">
- <BottomSheet
- drugClassesCustom="bottomSheetDrugClassesCustom"
- isShow
- @closed="emit('closed')"
- >
- <template #handler="{ close }">
- <BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
- </template>
-
- <template #default="{ close }">
- <div class="bottomSheetContent">
- <UiTitleModal>
- {{ t('base.sure') }}
- </UiTitleModal>
-
- <div class="scrollerBlock bottomSheetContentInside !px-3">
- <div
- v-if="description"
- class="text-alert-1"
- >
- {{ description }}
- </div>
+ <UModal
+ v-model:open="isOpen"
+ :title="props.title || t('base.sure')"
+ :ui="{ content: 'max-w-sm', footer: 'justify-between' }"
+ @update:open="(val: boolean) => { if (!val) onClosed() }"
+ >
+ <template #body>
+ <div
+ v-if="description"
+ class="text-muted"
+ >
+ {{ description }}
+ </div>
+ </template>
- <div class="flex gap-3 py-4">
- <UiElement
- v-for="(item, slug) in items"
- :key="slug"
- class="grow"
- insideClasses="!min-h-[44px] bg-item-3"
- @click="item.click(close)"
- >
- <template #leftIcon>
- <Icon
- :name="item.icon"
- size="22"
- />
- </template>
+ <template #footer="{ close }">
+ <UButton
+ variant="outline"
+ color="neutral"
+ size="xl"
+ class="px-6 text-sm"
+ @click="close"
+ >
+ {{ t('base.cancel') }}
+ </UButton>
- {{ t(item.localeKey) }}
- </UiElement>
- </div>
- </div>
- </div>
- </template>
- </BottomSheet>
- </Teleport>
+ <UButton
+ variant="soft"
+ color="error"
+ size="xl"
+ class="px-6"
+ @click="onConfirm(close)"
+ >
+ {{ t('base.delete') }}
+ </UButton>
+ </template>
+ </UModal>
</template>
diff --git a/app/components/layout/MenuBottom.vue b/app/components/layout/MenuBottom.vue
index 95c688b2..2dcc0319 100644
--- a/app/components/layout/MenuBottom.vue
+++ b/app/components/layout/MenuBottom.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import useMenuData from '~/components/layout/useMenuData'
+import { useMenuData } from '~/components/layout/useMenuData'
const { itemsBottom } = useMenuData()
</script>
diff --git a/app/components/layout/MenuBottomModal.vue b/app/components/layout/MenuBottomModal.vue
index 551545d1..32b888e3 100644
--- a/app/components/layout/MenuBottomModal.vue
+++ b/app/components/layout/MenuBottomModal.vue
@@ -1,9 +1,8 @@
<script setup lang="ts">
-import { useAppNav } from '~/components/app/useAppNav'
import { useDemo } from '~/components/demo/useDemo'
import { useUserStore } from '~/components/user/useUserStore'
-const { closeAllModals, isModalOpen } = useAppNav()
+const emit = defineEmits<{ close: [] }>()
const { t } = useI18n()
const userStore = useUserStore()
const { isDemo } = useDemo()
@@ -12,13 +11,12 @@ const { isDemo } = useDemo()
<template>
<Teleport to="body">
<LazyBottomSheet
- v-if="isModalOpen('menu')"
isShow
- @closed="closeAllModals"
+ @closed="emit('close')"
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<div class="bottomSheetContent">
diff --git a/app/components/layout/Sidebar.vue b/app/components/layout/Sidebar.vue
index c8203354..113d4ec7 100644
--- a/app/components/layout/Sidebar.vue
+++ b/app/components/layout/Sidebar.vue
@@ -1,11 +1,9 @@
<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'
-import type { WalletId } from '~/components/wallets/types'
-
import { useDemo } from '~/components/demo/useDemo'
-import { getStyles } from '~/components/ui/getStyles'
import { useUserStore } from '~/components/user/useUserStore'
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const props = defineProps<{
isShowSidebar?: boolean
@@ -20,6 +18,7 @@ const userStore = useUserStore()
const { isDemo } = useDemo()
const { t } = useI18n()
const { width } = useWindowSize()
+const walletsStore = useWalletsStore()
const isShowLogoMenu = ref(false)
</script>
@@ -48,13 +47,12 @@ const isShowLogoMenu = ref(false)
<BottomSheetOrDropdown
:isOpen="isShowLogoMenu"
isShowCloseBtn
- @onOpenModal="isShowLogoMenu = true"
- @onCloseModal="isShowLogoMenu = false"
+ @openModal="isShowLogoMenu = true"
+ @closeModal="isShowLogoMenu = false"
>
<template #trigger>
<div
- :class="getStyles('item', ['link', 'rounded'])"
- class="group-data-[state='open']:!bg-item-4 block cursor-default px-3 py-2"
+ class="interactive group-data-[state='open']:!bg-item-4 block cursor-default rounded-sm px-3 py-2"
>
<UiLogo />
</div>
@@ -74,26 +72,16 @@ const isShowLogoMenu = ref(false)
</BottomSheetOrDropdown>
</div>
- <div
- v-if="isDemo"
- class="px-4"
- >
- <UiButtonAccent @click="userStore.signOut">
- {{ t('demo.exit') }}
- </UiButtonAccent>
- </div>
-
<LayoutSidebarMenu class="px-2 pb-2" />
- <div class="px-2 pb-6">
- <UiTitle3 class="!text-4 pb-2 pl-3">
+ <div v-if="walletsStore.sortedIds.length > 0" class="px-2 pb-6">
+ <UiTitleSection class="!text-4 pb-2 pl-3">
{{ t('wallets.title') }}
- </UiTitle3>
+ </UiTitleSection>
<WalletsList
:limit="10"
isShowToggle
- @onClick="(id: WalletId) => router.push(`/wallets/${id}`)"
>
<template #default="{ walletsIdsSorted, walletsItemsLimited }">
<WalletsItem
@@ -112,9 +100,12 @@ const isShowLogoMenu = ref(false)
<div
v-if="walletsIdsSorted.length === 0"
- class="px-2"
+ class="flex-center flex-col py-4"
>
- <UiButtonAccent @click="router.push('/wallets/new')">
+ <UiButtonAccent
+ rounded
+ @click="router.push('/wallets/new')"
+ >
{{ t('wallets.new') }}
</UiButtonAccent>
</div>
@@ -123,17 +114,26 @@ const isShowLogoMenu = ref(false)
</div>
</div>
- <div class="absolute bottom-1 left-0 hidden w-full items-center md:flex">
+ <div class="absolute bottom-0 left-0 hidden w-full flex-col gap-2 md:flex">
+ <div
+ v-if="isDemo && props.isShowSidebar"
+ class="px-4"
+ >
+ <UiButtonAccent @click="userStore.signOut">
+ {{ t('demo.exit') }}
+ </UiButtonAccent>
+ </div>
+
<UTooltip
:text="t('app.toggleSidebar')"
:kbds="['Meta', '\\']"
>
- <UiItem1
+ <UiActionButton
class="text-4 z-10"
@click="emit('toggleSidebar')"
>
<Icon :name="props.isShowSidebar ? 'lucide:panel-left-close' : 'lucide:panel-left'" size="18" />
- </UiItem1>
+ </UiActionButton>
</UTooltip>
</div>
</div>
diff --git a/app/components/layout/SidebarMenu.vue b/app/components/layout/SidebarMenu.vue
index 66c9cd92..1caf68c2 100644
--- a/app/components/layout/SidebarMenu.vue
+++ b/app/components/layout/SidebarMenu.vue
@@ -1,11 +1,9 @@
<script setup lang="ts">
-import useMenuData from '~/components/layout/useMenuData'
+import { useMenuData } from '~/components/layout/useMenuData'
-withDefaults(defineProps<{
+const { isShowText = true } = defineProps<{
isShowText?: boolean
-}>(), {
- isShowText: true,
-})
+}>()
const { items } = useMenuData()
</script>
diff --git a/app/components/layout/SidebarMenuItem.vue b/app/components/layout/SidebarMenuItem.vue
index 3f1bfa61..1e15bd5d 100644
--- a/app/components/layout/SidebarMenuItem.vue
+++ b/app/components/layout/SidebarMenuItem.vue
@@ -1,43 +1,36 @@
<script setup lang="ts">
import type { MenuItem } from '~/components/layout/useMenuData'
-import useMenuData from '~/components/layout/useMenuData'
-import { getStyles } from '~/components/ui/getStyles'
+import { useMenuData } from '~/components/layout/useMenuData'
-const props = withDefaults(defineProps<{
+const { isShowText = true, item, menuId, position } = defineProps<{
isShowText?: boolean
item: MenuItem
menuId: string
position?: 'bottom'
-}>(), {
- isShowText: true,
-})
+}>()
const { checkIsActive, onClick } = useMenuData()
</script>
<template>
<div
- :class="[
- getStyles('item', ['center', 'link', 'minh2', 'rounded', 'padding1']),
- {
- '!text-primary': checkIsActive(props.menuId),
- 'gap-3': props.isShowText,
- },
- ]"
- class="group text-muted min-h-[44px] md:min-h-[38px]"
- @click="onClick(props.menuId)"
+ :class="cn('group interactive flex min-h-[44px] items-center rounded-sm px-2 py-1.5 md:min-h-[38px]',
+ checkIsActive(menuId) ? 'text-primary' : 'text-muted',
+ isShowText && 'gap-3',
+ )"
+ @click="onClick(menuId)"
>
<div class="flex min-w-8 items-center justify-center">
<Icon
- :name="props.item.icon"
+ :name="item.icon"
:size="position === 'bottom' ? '26' : '22'"
class="text-lg leading-none"
/>
</div>
<div
- v-if="props.isShowText"
+ v-if="isShowText"
class="text-sm font-medium"
>
{{ item.name }}
diff --git a/app/components/layout/useMenuData.ts b/app/components/layout/useMenuData.ts
index dc90ffd2..d40c6761 100644
--- a/app/components/layout/useMenuData.ts
+++ b/app/components/layout/useMenuData.ts
@@ -1,5 +1,4 @@
/* eslint-disable perfectionist/sort-objects */
-import { useAppNav } from '~/components/app/useAppNav'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
@@ -13,13 +12,14 @@ export type MenuItem = {
}
}
-export default function useMenuData() {
+const isMenuOpen = ref(false)
+
+export function useMenuData() {
const { t } = useI18n()
const { trnFormCreate } = useTrnsFormStore()
const walletsStore = useWalletsStore()
const categoriesStore = useCategoriesStore()
const route = useRoute()
- const { closeAllModals, openModal } = useAppNav()
const items = computed<Record<string, MenuItem>>(() => {
const list = {
@@ -53,7 +53,7 @@ export default function useMenuData() {
},
}
- if (process.env.NODE_ENV === 'development') {
+ if (import.meta.dev) {
list.dev = {
icon: 'hugeicons:laptop-programming',
name: t('dev.menu.title'),
@@ -72,7 +72,7 @@ export default function useMenuData() {
}))
function onClick(menuId: string) {
- closeAllModals()
+ isMenuOpen.value = false
if (menuId === 'trnForm') {
if (walletsStore.hasItems && categoriesStore.hasItems)
@@ -81,7 +81,7 @@ export default function useMenuData() {
}
if (menuId === 'menu') {
- openModal('menu')
+ isMenuOpen.value = true
return
}
@@ -97,5 +97,6 @@ export default function useMenuData() {
itemsBottom,
onClick,
checkIsActive,
+ isMenuOpen,
}
}
diff --git a/app/components/locale/Switcher.vue b/app/components/locale/Switcher.vue
index 5ecaa260..19a21e32 100644
--- a/app/components/locale/Switcher.vue
+++ b/app/components/locale/Switcher.vue
@@ -1,6 +1,4 @@
<script setup lang="ts">
-import { saveData } from '~~/services/firebase/api'
-
import type { LocaleSlug } from '~/components/locale/types'
import { useUserStore } from '~/components/user/useUserStore'
@@ -9,7 +7,7 @@ const props = defineProps<{
isShowTitle?: boolean
}>()
-const { locale, setLocale, t } = useI18n()
+const { locale, t } = useI18n()
const userStore = useUserStore()
const options = [{
@@ -19,30 +17,21 @@ const options = [{
label: t('locale.en'),
value: 'en',
}]
-
-function changeLocale(locale: LocaleSlug) {
- setLocale(locale)
-
- if (!userStore.uid)
- return
-
- saveData(`users/${userStore.uid}/settings/lang`, locale)
-}
</script>
<template>
<div>
<template v-if="props.isShowTitle">
- <UiTitle3
+ <UiTitleSection
class="pb-2"
>
{{ t('locale.title') }}
- </UiTitle3>
+ </UiTitleSection>
<FormSelect
:options
:value="locale"
- @change="(locale: LocaleSlug) => changeLocale(locale)"
+ @change="(locale: LocaleSlug) => userStore.saveUserLocale(locale)"
/>
</template>
@@ -56,7 +45,7 @@ function changeLocale(locale: LocaleSlug) {
size="lg"
square
variant="ghost"
- @click="changeLocale(locale === 'ru' ? 'en' : 'ru')"
+ @click="userStore.saveUserLocale(locale === 'ru' ? 'en' : 'ru')"
/>
</UTooltip>
</template>
diff --git a/app/components/offline/helpers.test.ts b/app/components/offline/helpers.test.ts
new file mode 100644
index 00000000..8e051495
--- /dev/null
+++ b/app/components/offline/helpers.test.ts
@@ -0,0 +1,192 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ clearOfflineQueue,
+ getAllOfflineOps,
+ getOfflineOpsByEntity,
+ pushOfflineOp,
+ removeOfflineOp,
+ removeOfflineOpByType,
+} from '~/components/offline/helpers'
+
+// Mock localforage
+const store = new Map<string, any>()
+
+vi.mock('localforage', () => ({
+ default: {
+ getItem: vi.fn((key: string) => Promise.resolve(store.get(key) ?? null)),
+ removeItem: vi.fn((key: string) => {
+ store.delete(key)
+ return Promise.resolve()
+ }),
+ setItem: vi.fn((key: string, value: any) => {
+ store.set(key, value)
+ return Promise.resolve()
+ }),
+ },
+}))
+
+beforeEach(() => {
+ store.clear()
+})
+
+afterEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('pushOfflineOp', () => {
+ it('adds operation to empty queue', async () => {
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0]).toMatchObject({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ expect(queue[0].timestamp).toBeGreaterThan(0)
+ })
+
+ it('appends operations for different entities', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(2)
+ })
+
+ describe('collapsing rules', () => {
+ it('create + update → create with merged data', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { name: 'Cash Updated' }, entity: 'wallets', id: 'w1', type: 'update' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].type).toBe('create')
+ expect(queue[0].data).toEqual({ name: 'Cash Updated' })
+ })
+
+ it('create + delete → both removed', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(0)
+ })
+
+ it('update + update → update with merged data', async () => {
+ await pushOfflineOp({ data: { name: 'Old' }, entity: 'wallets', id: 'w1', type: 'update' })
+ await pushOfflineOp({ data: { name: 'New' }, entity: 'wallets', id: 'w1', type: 'update' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].type).toBe('update')
+ expect(queue[0].data).toEqual({ name: 'New' })
+ })
+
+ it('update + delete → replace with delete', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'update' })
+ await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].type).toBe('delete')
+ })
+
+ it('delete + any → ignores new operation', async () => {
+ await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].type).toBe('delete')
+ })
+ })
+})
+
+describe('removeOfflineOp', () => {
+ it('removes all operations for entity+id', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+
+ await removeOfflineOp('wallets', 'w1')
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ expect(queue[0].entity).toBe('trns')
+ })
+
+ it('does nothing when not found', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+
+ await removeOfflineOp('wallets', 'w999')
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(1)
+ })
+})
+
+describe('removeOfflineOpByType', () => {
+ it('removes specific operation by type', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+
+ await removeOfflineOpByType('wallets', 'w1', 'create')
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(0)
+ })
+})
+
+describe('getOfflineOpsByEntity', () => {
+ it('filters by entity', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ await pushOfflineOp({ data: { name: 'Food' }, entity: 'categories', id: 'c1', type: 'create' })
+
+ const walletOps = await getOfflineOpsByEntity('wallets')
+ expect(walletOps).toHaveLength(1)
+ expect(walletOps[0].entity).toBe('wallets')
+ })
+
+ it('returns empty array when no matching ops', async () => {
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+
+ const walletOps = await getOfflineOpsByEntity('wallets')
+ expect(walletOps).toHaveLength(0)
+ })
+})
+
+describe('clearOfflineQueue', () => {
+ it('removes all operations', async () => {
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+
+ await clearOfflineQueue()
+
+ const queue = await getAllOfflineOps()
+ expect(queue).toHaveLength(0)
+ })
+})
+
+describe('cross-entity isolation', () => {
+ it('different entities have separate operations', async () => {
+ await pushOfflineOp({ data: { a: 1 }, entity: 'trns', id: 'id1', type: 'create' })
+ await pushOfflineOp({ data: { b: 2 }, entity: 'wallets', id: 'id1', type: 'create' })
+
+ const trnsOps = await getOfflineOpsByEntity('trns')
+ const walletsOps = await getOfflineOpsByEntity('wallets')
+
+ expect(trnsOps).toHaveLength(1)
+ expect(trnsOps[0].data).toEqual({ a: 1 })
+ expect(walletsOps).toHaveLength(1)
+ expect(walletsOps[0].data).toEqual({ b: 2 })
+ })
+
+ it('collapsing only applies within same entity+id', async () => {
+ await pushOfflineOp({ data: { a: 1 }, entity: 'trns', id: 'id1', type: 'create' })
+ await pushOfflineOp({ data: { b: 2 }, entity: 'wallets', id: 'id1', type: 'create' })
+ await pushOfflineOp({ entity: 'trns', id: 'id1', type: 'delete' })
+
+ const queue = await getAllOfflineOps()
+ // trns create+delete collapsed to nothing, wallets create remains
+ expect(queue).toHaveLength(1)
+ expect(queue[0].entity).toBe('wallets')
+ })
+})
diff --git a/app/components/offline/helpers.ts b/app/components/offline/helpers.ts
new file mode 100644
index 00000000..9ce59e2d
--- /dev/null
+++ b/app/components/offline/helpers.ts
@@ -0,0 +1,230 @@
+import localforage from 'localforage'
+
+import type { EntityType, OfflineOp } from '~/components/offline/types'
+
+import { createLogger } from '~/utils/logger'
+
+const QUEUE_KEY = 'finapp.offline.queue'
+const QUEUE_USER_KEY = 'finapp.offline.queueUserId'
+
+const logger = createLogger('offline')
+
+/**
+ * Module-level userId for stamping queue ownership at push time.
+ * Set via setOfflineQueueUserId() during app init / replay.
+ */
+let _currentUserId: string | null = null
+
+export function setOfflineQueueUserId(userId: string | null): void {
+ _currentUserId = userId
+}
+
+const OLD_KEYS = [
+ 'finapp.wallets.offline.update',
+ 'finapp.wallets.offline.delete',
+ 'finapp.categories.offline.update',
+ 'finapp.categories.offline.delete',
+ 'finapp.trns.offline.update',
+ 'finapp.trns.offline.delete',
+]
+
+let oldKeysCleaned = false
+
+async function cleanOldKeys() {
+ if (oldKeysCleaned)
+ return
+ oldKeysCleaned = true
+ for (const key of OLD_KEYS)
+ await localforage.removeItem(key)
+}
+
+async function readQueue(): Promise<OfflineOp[]> {
+ await cleanOldKeys()
+ const raw = await localforage.getItem<OfflineOp[]>(QUEUE_KEY)
+ return Array.isArray(raw) ? raw : []
+}
+
+async function writeQueue(queue: OfflineOp[]): Promise<void> {
+ await localforage.setItem(QUEUE_KEY, queue)
+}
+
+/**
+ * Add operation to the unified offline queue with collapsing.
+ *
+ * Collapsing rules (matching by entity + id):
+ * | Existing | New | Result |
+ * |----------|--------|-------------------------------------|
+ * | create | update | create with merged data |
+ * | create | delete | remove both (never reached server) |
+ * | update | update | update with merged data |
+ * | update | delete | replace update with delete |
+ * | delete | * | ignore new (delete is terminal) |
+ * | — | * | append as-is |
+ */
+let writeChain = Promise.resolve()
+
+export function pushOfflineOp(op: Omit<OfflineOp, 'timestamp'>): Promise<void> {
+ writeChain = writeChain.then(() => pushOfflineOpImpl(op), () => pushOfflineOpImpl(op))
+ return writeChain
+}
+
+async function pushOfflineOpImpl(op: Omit<OfflineOp, 'timestamp'>): Promise<void> {
+ // Ensure queue ownership is stamped on first push
+ if (_currentUserId) {
+ const storedUserId = await localforage.getItem<string>(QUEUE_USER_KEY)
+ if (!storedUserId)
+ await localforage.setItem(QUEUE_USER_KEY, _currentUserId)
+ }
+
+ const queue = await readQueue()
+
+ const existingIdx = findLastIndex(queue, o => o.entity === op.entity && o.id === op.id)
+
+ if (existingIdx === -1) {
+ queue.push({ ...op, timestamp: Date.now() })
+ await writeQueue(queue)
+ logger.log(`queued ${op.type}: ${op.entity}/${op.id}`)
+ return
+ }
+
+ const existing = queue[existingIdx]
+
+ // delete is terminal — ignore any new operation
+ if (existing.type === 'delete') {
+ logger.log(`skip ${op.type} (already deleted): ${op.entity}/${op.id}`)
+ return
+ }
+
+ if (op.type === 'delete') {
+ if (existing.type === 'create') {
+ // Never reached server — remove both
+ queue.splice(existingIdx, 1)
+ logger.log(`collapsed create+delete (removed): ${op.entity}/${op.id}`)
+ }
+ else {
+ // update → delete: replace
+ queue[existingIdx] = { ...op, timestamp: Date.now() }
+ logger.log(`collapsed update→delete: ${op.entity}/${op.id}`)
+ }
+ await writeQueue(queue)
+ return
+ }
+
+ // create + update → create with merged data
+ // update + update → update with merged data
+ queue[existingIdx] = {
+ ...existing,
+ data: { ...existing.data, ...op.data },
+ timestamp: Date.now(),
+ }
+ await writeQueue(queue)
+ logger.log(`collapsed ${existing.type}+${op.type}: ${op.entity}/${op.id}`)
+}
+
+/**
+ * Remove all operations for entity+id (after successful mutation).
+ * Serialized through writeChain to prevent race conditions with pushOfflineOp.
+ */
+export function removeOfflineOp(entity: EntityType, id: string): Promise<void> {
+ writeChain = writeChain.then(() => removeOfflineOpImpl(entity, id), () => removeOfflineOpImpl(entity, id))
+ return writeChain
+}
+
+async function removeOfflineOpImpl(entity: EntityType, id: string): Promise<void> {
+ const queue = await readQueue()
+ const filtered = queue.filter(o => !(o.entity === entity && o.id === id))
+ if (filtered.length !== queue.length) {
+ await writeQueue(filtered)
+ logger.log(`synced: ${entity}/${id}`)
+ }
+}
+
+/**
+ * Remove all operations for entity + multiple ids in a single read/write.
+ * Serialized through writeChain to prevent race conditions.
+ */
+export function removeOfflineOps(entity: EntityType, ids: string[]): Promise<void> {
+ writeChain = writeChain.then(() => removeOfflineOpsImpl(entity, ids), () => removeOfflineOpsImpl(entity, ids))
+ return writeChain
+}
+
+async function removeOfflineOpsImpl(entity: EntityType, ids: string[]): Promise<void> {
+ const idSet = new Set(ids)
+ const queue = await readQueue()
+ const filtered = queue.filter(o => !(o.entity === entity && idSet.has(o.id)))
+ if (filtered.length !== queue.length) {
+ await writeQueue(filtered)
+ logger.log(`synced ${ids.length} ops: ${entity}`)
+ }
+}
+
+/**
+ * Remove a specific operation matching entity+id+type.
+ * Serialized through writeChain to prevent race conditions.
+ */
+export function removeOfflineOpByType(entity: EntityType, id: string, type: OfflineOp['type']): Promise<void> {
+ writeChain = writeChain.then(() => removeOfflineOpByTypeImpl(entity, id, type), () => removeOfflineOpByTypeImpl(entity, id, type))
+ return writeChain
+}
+
+async function removeOfflineOpByTypeImpl(entity: EntityType, id: string, type: OfflineOp['type']): Promise<void> {
+ const queue = await readQueue()
+ const filtered = queue.filter(o => !(o.entity === entity && o.id === id && o.type === type))
+ if (filtered.length !== queue.length) {
+ await writeQueue(filtered)
+ logger.log(`synced ${type}: ${entity}/${id}`)
+ }
+}
+
+/**
+ * Get all operations in order (for replay).
+ */
+export async function getAllOfflineOps(): Promise<OfflineOp[]> {
+ return readQueue()
+}
+
+/**
+ * Get operations for a specific entity (for init merge).
+ */
+export async function getOfflineOpsByEntity(entity: EntityType): Promise<OfflineOp[]> {
+ const queue = await readQueue()
+ return queue.filter(o => o.entity === entity)
+}
+
+/**
+ * Get the userId associated with the current offline queue.
+ */
+export async function getQueueUserId(): Promise<string | null> {
+ return localforage.getItem<string>(QUEUE_USER_KEY)
+}
+
+/**
+ * Set the userId associated with the current offline queue.
+ */
+export async function setQueueUserId(userId: string): Promise<void> {
+ await localforage.setItem(QUEUE_USER_KEY, userId)
+}
+
+/**
+ * Clear the entire offline queue (logout or user mismatch).
+ * Serialized through writeChain to prevent race conditions with pushOfflineOp.
+ */
+export function clearOfflineQueue(): Promise<void> {
+ writeChain = writeChain.then(() => clearOfflineQueueImpl(), () => clearOfflineQueueImpl())
+ return writeChain
+}
+
+async function clearOfflineQueueImpl(): Promise<void> {
+ await localforage.removeItem(QUEUE_KEY)
+ await localforage.removeItem(QUEUE_USER_KEY)
+ _currentUserId = null
+ logger.log('queue cleared')
+}
+
+function findLastIndex<T>(arr: T[], predicate: (item: T) => boolean): number {
+ for (let i = arr.length - 1; i >= 0; i--) {
+ if (predicate(arr[i]))
+ return i
+ }
+ return -1
+}
diff --git a/app/components/offline/replay.ts b/app/components/offline/replay.ts
new file mode 100644
index 00000000..6f2720ef
--- /dev/null
+++ b/app/components/offline/replay.ts
@@ -0,0 +1,243 @@
+import type { CategoryItem } from '~/components/categories/types'
+import type { CurrencyCode } from '~/components/currencies/types'
+import type { LocaleSlug } from '~/components/locale/types'
+import type { OfflineOp } from '~/components/offline/types'
+import type { TrnItem } from '~/components/trns/types'
+import type { WalletItem } from '~/components/wallets/types'
+
+import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+import { clearOfflineQueue, getAllOfflineOps, getQueueUserId, removeOfflineOp, setOfflineQueueUserId, setQueueUserId } from '~/components/offline/helpers'
+import { TrnType } from '~/components/trns/types'
+import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { useUserStore } from '~/components/user/useUserStore'
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('offline/replay')
+
+let _isReplaying = false
+
+export function isReplaying(): boolean {
+ return _isReplaying
+}
+
+/**
+ * Remap local IDs in trn data using the collected remap map.
+ */
+function remapTrnIds(data: TrnItem, remapIds: Map<string, string>): TrnItem {
+ if (data.type === TrnType.Transfer) {
+ return {
+ ...data,
+ expenseWalletId: remapIds.get(data.expenseWalletId) ?? data.expenseWalletId,
+ incomeWalletId: remapIds.get(data.incomeWalletId) ?? data.incomeWalletId,
+ }
+ }
+ return {
+ ...data,
+ categoryId: remapIds.get(data.categoryId) ?? data.categoryId,
+ walletId: remapIds.get(data.walletId) ?? data.walletId,
+ }
+}
+
+/**
+ * Check if a trn references wallets/categories that don't exist in the store.
+ */
+function isTrnOrphaned(data: TrnItem, walletsStore: ReturnType<typeof useWalletsStore>, categoriesStore: ReturnType<typeof useCategoriesStore>): boolean {
+ if (data.type === TrnType.Transfer)
+ return !walletsStore.items?.[data.expenseWalletId] || !walletsStore.items?.[data.incomeWalletId]
+ return !walletsStore.items?.[data.walletId] || !categoriesStore.items[data.categoryId]
+}
+
+/**
+ * Collect remap info from resolved promises into the remap map.
+ */
+async function collectRemaps(promises: (Promise<unknown> | undefined)[], remapIds: Map<string, string>) {
+ const results = await Promise.all(promises.map(p => p ?? Promise.resolve()))
+ for (const r of results) {
+ if (r && typeof r === 'object' && 'localId' in r && 'convexId' in r)
+ remapIds.set(r.localId as string, r.convexId as string)
+ }
+}
+
+export async function replayOfflineQueue(): Promise<void> {
+ if (!import.meta.client)
+ return
+
+ if (_isReplaying)
+ return
+
+ const userStore = useUserStore()
+ const currentUserId = userStore.uid
+
+ // Verify queue ownership — don't replay another user's queue
+ try {
+ const queueUserId = await getQueueUserId()
+ if (queueUserId && queueUserId !== currentUserId) {
+ logger.log(`queue belongs to ${queueUserId}, current user is ${currentUserId} — clearing`)
+ await clearOfflineQueue()
+ return
+ }
+
+ // Set ownership for future ops (both in-memory and persisted)
+ if (currentUserId) {
+ setOfflineQueueUserId(currentUserId)
+ await setQueueUserId(currentUserId)
+ }
+ }
+ catch (e) {
+ logger.error('queue ownership check failed, clearing queue for safety', e)
+ await clearOfflineQueue().catch(() => {})
+ return
+ }
+
+ const queue = await getAllOfflineOps()
+ if (!queue.length)
+ return
+
+ logger.log(`replaying ${queue.length} operations`)
+
+ const walletsStore = useWalletsStore()
+ const categoriesStore = useCategoriesStore()
+ const trnsStore = useTrnsStore()
+
+ // Group operations by entity
+ const walletOps: OfflineOp[] = []
+ const categoryOps: OfflineOp[] = []
+ const trnOps: OfflineOp[] = []
+ const settingsOps: OfflineOp[] = []
+
+ for (const op of queue) {
+ // Frontend IDs: skip deletes (nothing to delete on server)
+ if (isLocalId(op.id) && op.type === 'delete') {
+ logger.log(`skip delete (frontend ID): ${op.entity}/${op.id}`)
+ await removeOfflineOp(op.entity, op.id)
+ continue
+ }
+
+ switch (op.entity) {
+ case 'wallets':
+ walletOps.push(op)
+ break
+ case 'categories':
+ categoryOps.push(op)
+ break
+ case 'trns':
+ trnOps.push(op)
+ break
+ case 'userSettings':
+ settingsOps.push(op)
+ break
+ }
+ }
+
+ _isReplaying = true
+ const remapIds = new Map<string, string>()
+ let orphanCount = 0
+
+ try {
+ // Phase 1: Replay wallets — creates & updates in parallel, await all, collect remaps
+ if (walletOps.length > 0) {
+ logger.log(`phase 1: ${walletOps.length} wallet ops`)
+ const promises = walletOps.map((op) => {
+ if (op.type === 'delete')
+ return walletsStore.deleteWallet(op.id)
+ return walletsStore.saveWallet({ id: op.id, values: op.data as unknown as WalletItem })
+ })
+ await collectRemaps(promises, remapIds)
+ }
+
+ // Phase 2: Replay categories — parents first, then children (children may reference local parent IDs)
+ if (categoryOps.length > 0) {
+ const parentOps = categoryOps.filter((op) => {
+ if (op.type === 'delete')
+ return true
+ const data = op.data as unknown as CategoryItem
+ return !data.parentId || data.parentId === 0
+ })
+ const childOps = categoryOps.filter((op) => {
+ if (op.type === 'delete')
+ return false
+ const data = op.data as unknown as CategoryItem
+ return data.parentId && data.parentId !== 0
+ })
+
+ // Phase 2a: Parent categories
+ if (parentOps.length > 0) {
+ logger.log(`phase 2a: ${parentOps.length} parent category ops`)
+ const promises = parentOps.map((op) => {
+ if (op.type === 'delete')
+ return categoriesStore.deleteCategory(op.id)
+ return categoriesStore.saveCategory({
+ id: op.id,
+ isUpdateChildCategoriesColor: false,
+ values: op.data as unknown as CategoryItem,
+ })
+ })
+ await collectRemaps(promises, remapIds)
+ }
+
+ // Phase 2b: Child categories (remap parentId if needed)
+ if (childOps.length > 0) {
+ logger.log(`phase 2b: ${childOps.length} child category ops`)
+ const promises = childOps.map((op) => {
+ const data = op.data as unknown as CategoryItem
+ const remappedParentId = remapIds.get(String(data.parentId)) ?? data.parentId
+ const values = remappedParentId !== data.parentId
+ ? { ...data, parentId: remappedParentId }
+ : data
+ return categoriesStore.saveCategory({
+ id: op.id,
+ isUpdateChildCategoriesColor: false,
+ values: values as CategoryItem,
+ })
+ })
+ await collectRemaps(promises, remapIds)
+ }
+ }
+
+ // Phase 3: Replay trns — remap wallet/category IDs, fire-and-forget
+ if (trnOps.length > 0) {
+ logger.log(`phase 3: ${trnOps.length} trn ops`)
+ for (const op of trnOps) {
+ if (op.type === 'delete') {
+ trnsStore.deleteTrn(op.id)
+ continue
+ }
+
+ const data = op.data as unknown as TrnItem
+ const remapped = remapTrnIds(data, remapIds)
+
+ // Orphan detection with remapped IDs
+ if (isTrnOrphaned(remapped, walletsStore, categoriesStore)) {
+ orphanCount++
+ logger.log(`skip (orphaned): ${op.entity}/${op.id}`)
+ await removeOfflineOp(op.entity, op.id)
+ continue
+ }
+
+ trnsStore.saveTrn({ id: op.id, values: remapped })
+ }
+ }
+
+ // Phase 4: Settings — fire-and-forget
+ for (const op of settingsOps) {
+ if (op.data?.baseCurrency)
+ userStore.saveUserBaseCurrency(op.data.baseCurrency as CurrencyCode)
+ if (op.data?.locale)
+ userStore.saveUserLocale(op.data.locale as LocaleSlug)
+ }
+ }
+ finally {
+ _isReplaying = false
+ }
+
+ if (orphanCount > 0) {
+ const { showWarningToast } = await import('~/composables/useStoreSync')
+ showWarningToast('trns.errors.orphanedSkipped', { count: orphanCount })
+ }
+
+ if (remapIds.size > 0)
+ logger.log(`replay complete: ${remapIds.size} IDs remapped`)
+ else
+ logger.log('replay complete')
+}
diff --git a/app/components/offline/storageKeys.ts b/app/components/offline/storageKeys.ts
new file mode 100644
index 00000000..0c09abc1
--- /dev/null
+++ b/app/components/offline/storageKeys.ts
@@ -0,0 +1,9 @@
+export const STORAGE_KEYS = {
+ categories: 'finapp.categories',
+ currencies: 'finapp.currencies',
+ trns: 'finapp.trns',
+ trnsSyncMeta: 'finapp.trns.syncMeta',
+ user: 'finapp.user',
+ userSettings: 'finapp.userSettings',
+ wallets: 'finapp.wallets',
+} as const
diff --git a/app/components/offline/types.ts b/app/components/offline/types.ts
new file mode 100644
index 00000000..f4982e0d
--- /dev/null
+++ b/app/components/offline/types.ts
@@ -0,0 +1,9 @@
+export type EntityType = 'categories' | 'trns' | 'userSettings' | 'wallets'
+
+export type OfflineOp = {
+ data?: Record<string, unknown>
+ entity: EntityType
+ id: string
+ timestamp: number
+ type: 'create' | 'delete' | 'update'
+}
diff --git a/app/components/stat/Average.vue b/app/components/stat/Average.vue
index ca353880..91533489 100644
--- a/app/components/stat/Average.vue
+++ b/app/components/stat/Average.vue
@@ -1,5 +1,4 @@
<script setup lang="ts">
-// import { useStorage } from '@vueuse/core'
import { sub } from 'date-fns'
import type { CategoryId } from '~/components/categories/types'
@@ -53,10 +52,10 @@ const total = computed(() => getTotalOfTrnsIds(datedTrnsIds.value))
<template>
<div class="grid gap-4">
<div class="grid w-full grow gap-1">
- <UiTitle6 class="!leading-3 text-nowrap">
+ <UiTextSubtitle class="!leading-3 text-nowrap">
{{ t('money.average') }}
<br>{{ t('stat.average.forLast') }}
- </UiTitle6>
+ </UiTextSubtitle>
<div class="flex gap-4">
<Amount
diff --git a/app/components/stat/CategoriesButtons.vue b/app/components/stat/CategoriesButtons.vue
index e66076ed..1c7ee36f 100644
--- a/app/components/stat/CategoriesButtons.vue
+++ b/app/components/stat/CategoriesButtons.vue
@@ -1,10 +1,14 @@
<script setup lang="ts">
+import type { DeepPartial } from '~~/utils/types'
+
import defu from 'defu'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
+import type { MiniItemConfig } from '~/components/stat/useStatConfig'
+
+import { statConfigKey } from '~/components/stat/injectionKeys'
const { t } = useI18n()
-const statConfig = inject('statConfig') as StatConfigProvider
+const statConfig = inject(statConfigKey)!
const favorites = computed(() => ({
isShow: computed(() => {
@@ -89,27 +93,29 @@ const viewPresets = computed(() => ({
const isShowMorePresets = ref(false)
-function onChangeViewOptions(newViewOptions: any) {
+function onChangeViewOptions(newViewOptions: Pick<DeepPartial<MiniItemConfig>, 'catsList'>) {
const c = defu(newViewOptions.catsList, statConfig.config.value.catsList)
statConfig.updateConfig('catsList', c)
}
</script>
<template>
- <div class="">
+ <div>
<!-- List -->
<div class="border-item-4 grid gap-3 border-b pb-2 last:border-0">
- <UiTitleOption>{{ t('stat.catButtons.listItemsOptions') }}</UiTitleOption>
+ <UiTitleSection size="sm">
+ {{ t('stat.catButtons.listItemsOptions') }}
+ </UiTitleSection>
<div class="flex gap-1">
- <UiItem2
+ <UiChipButton
v-for="view in viewPresets"
:key="view.title"
@click="onChangeViewOptions(view.props)"
>
{{ view.title }}
- </UiItem2>
+ </UiChipButton>
- <UiItem2
+ <UiChipButton
class="!grow-0"
@click="isShowMorePresets = !isShowMorePresets"
>
@@ -117,25 +123,25 @@ function onChangeViewOptions(newViewOptions: any) {
:name="isShowMorePresets ? 'lucide:chevron-up' : 'lucide:chevron-down'"
size="18"
/>
- </UiItem2>
+ </UiChipButton>
</div>
<div v-if="isShowMorePresets">
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.catsList.isItemsBg"
:title="t('stat.catButtons.isItemsBg')"
@click="statConfig.updateConfig('catsList', { isItemsBg: !statConfig.config.value.catsList.isItemsBg })"
/>
<!-- Lines -->
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.catsList.isLines"
:title="t('stat.catButtons.isLines')"
@click="statConfig.updateConfig('catsList', { isLines: !statConfig.config.value.catsList.isLines })"
/>
<!-- Round icons -->
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.catsList.isRoundIcon"
:title="t('stat.catButtons.isRoundIcon')"
@click="statConfig.updateConfig('catsList', { isRoundIcon: !statConfig.config.value.catsList.isRoundIcon })"
@@ -186,19 +192,21 @@ function onChangeViewOptions(newViewOptions: any) {
<div
class="border-item-4 grid gap-3 border-b pt-3 pb-2 last:border-0"
>
- <UiTitleOption>{{ t('stat.catButtons.elements') }}</UiTitleOption>
- <div class="">
- <UiCheckbox
+ <UiTitleSection size="sm">
+ {{ t('stat.catButtons.elements') }}
+ </UiTitleSection>
+ <div>
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.vertical.isShow"
:title="t('stat.config.categories.vertical.title')"
@click="statConfig.updateConfig('vertical', { isShow: !statConfig.config.value.vertical.isShow })"
/>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.catsRound.isShow"
:title="t('stat.config.categories.rounds.title')"
@click="statConfig.updateConfig('catsRound', { isShow: !statConfig.config.value.catsRound.isShow })"
/>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.catsList.isShow"
:title="t('stat.config.categories.list.title')"
@click="statConfig.updateConfig('catsList', { isShow: !statConfig.config.value.catsList.isShow })"
diff --git a/app/components/stat/ConfigModal.vue b/app/components/stat/ConfigModal.vue
index c9785cf8..c4ac849c 100644
--- a/app/components/stat/ConfigModal.vue
+++ b/app/components/stat/ConfigModal.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import type { StatConfigModal } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import { useStatChart } from '~/components/stat/chart/useStatChart'
+import { statConfigKey } from '~/components/stat/injectionKeys'
import { chartViewOptions } from '~/components/stat/useStatConfig'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
@@ -11,7 +11,7 @@ const props = defineProps<{
statConfigModal: StatConfigModal
}>()
-const statConfig = inject('statConfig') as StatConfigProvider
+const statConfig = inject(statConfigKey)!
const { t } = useI18n()
const walletsStore = useWalletsStore()
const { chartTypes } = useStatChart()
@@ -34,8 +34,8 @@ function updateStatAverage(value: number) {
:title="t('stat.config.menu.label')"
:isOpen="props.statConfigModal.isShow"
isShowCloseBtn
- @onOpenModal="props.statConfigModal.show"
- @onCloseModal="props.statConfigModal.close"
+ @openModal="props.statConfigModal.show"
+ @closeModal="props.statConfigModal.close"
>
<template #trigger>
<UTooltip :text="t('stat.config.menu.label')">
@@ -57,17 +57,17 @@ function updateStatAverage(value: number) {
<!-- Chart -->
<div class="border-item-3 border-b pb-3">
- <UiTitleOption class="pb-2">
+ <UiTitleSection size="sm" class="pb-2">
{{ t('stat.config.chartShow.title') }}
- </UiTitleOption>
+ </UiTitleSection>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.chartShow"
:title="t('stat.config.chartShow.label')"
@click="statConfig.updateConfig('chartShow', !statConfig.config.value.chartShow)"
/>
- <UiCheckbox
+ <UiSwitchItem
v-if="statConfig.config.value.chartShow"
:checkboxValue="statConfig.config.value.date.isShowQuick"
:title="t('stat.config.date.quick.label')"
@@ -79,7 +79,7 @@ function updateStatAverage(value: number) {
v-if="statConfig.config.value.chartShow"
class="grid gap-4"
>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.chart.isShowAverage ?? false"
:title="t('stat.config.chart.average.label')"
@click="statConfig.updateConfig('chart', { isShowAverage: !statConfig.config.value.chart.isShowAverage })"
@@ -87,33 +87,35 @@ function updateStatAverage(value: number) {
<!-- Chart: view -->
<div class="hidden gap-3 md:grid">
- <UiTitleOption>
+ <UiTitleSection size="sm">
{{ t('stat.config.chartView.label') }}
- </UiTitleOption>
+ </UiTitleSection>
- <UiTabs1>
- <UiTabsItem4
+ <UiTabsBar>
+ <UiTabsItemPill
v-for="view in chartViewOptions"
:key="view"
+ variant="outline"
:isActive="statConfig.config.value.chartView === view"
class="grow"
@click="statConfig.updateConfig('chartView', view)"
>
{{ t(`stat.config.chartView.${view}`) }}
- </UiTabsItem4>
- </UiTabs1>
+ </UiTabsItemPill>
+ </UiTabsBar>
</div>
<!-- Chart: type -->
<div class="grid gap-3">
- <UiTitleOption>
+ <UiTitleSection size="sm">
{{ t('stat.config.chart.type.label') }}
- </UiTitleOption>
+ </UiTitleSection>
- <UiTabs1>
- <UiTabsItem4
+ <UiTabsBar>
+ <UiTabsItemPill
v-for="item in chartTypes"
:key="item.value"
+ variant="outline"
:isActive="statConfig.config.value.chartType === item.value"
class="flex grow gap-1"
@click="statConfig.updateConfig('chartType', item.value)"
@@ -123,8 +125,8 @@ function updateStatAverage(value: number) {
:size="16"
/>
{{ item.label }}
- </UiTabsItem4>
- </UiTabs1>
+ </UiTabsItemPill>
+ </UiTabsBar>
</div>
</div>
</div>
@@ -134,11 +136,11 @@ function updateStatAverage(value: number) {
v-if="props.isShowWallets"
class="border-item-3 border-b pb-3"
>
- <UiTitleOption class="pb-2">
+ <UiTitleSection size="sm" class="pb-2">
{{ t('stat.config.wallets.title') }}
- </UiTitleOption>
+ </UiTitleSection>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.wallets.isShow"
:title="t('stat.config.wallets.label')"
@click="statConfig.updateConfig('wallets', { isShow: !statConfig.config.value.wallets.isShow })"
@@ -150,29 +152,29 @@ function updateStatAverage(value: number) {
class="flex gap-4 pt-2"
>
<div class="flex gap-1">
- <UiItem2
+ <UiChipButton
:class="[{
'!hover:transparent opacity-30': statConfig.config.value.wallets.count === 1,
}]"
@click="updateWalletsLimit(statConfig.config.value.wallets.count - 1)"
>
<Icon name="lucide:minus" />
- </UiItem2>
+ </UiChipButton>
<FormInput
:placeholder="t('stat.config.showedWallets.placeholder')"
- :value="statConfig.config.value.wallets.count"
+ :modelValue="statConfig.config.value.wallets.count"
min="1"
class="!w-16 max-w-24 !px-2 text-center"
type="number"
- @updateValue="value => statConfig.updateConfig('wallets', { count: +value })"
+ @update:modelValue="value => statConfig.updateConfig('wallets', { count: +value })"
/>
- <UiItem2
+ <UiChipButton
:class="{ '!hover:transparent opacity-30': statConfig.config.value.wallets.count >= walletsStore.sortedIds.length }"
@click="updateWalletsLimit(statConfig.config.value.wallets.count + 1)"
>
<Icon name="lucide:plus" />
- </UiItem2>
+ </UiChipButton>
</div>
</div>
</div>
@@ -181,11 +183,11 @@ function updateStatAverage(value: number) {
<div
class="border-item-3 border-b pb-3"
>
- <UiTitleOption class="pb-2">
+ <UiTitleSection size="sm" class="pb-2">
{{ t('statistics.title') }}
- </UiTitleOption>
+ </UiTitleSection>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="statConfig.config.value.statAverage.isShow"
:title="t('stat.config.statAverage.count.label')"
@click="statConfig.updateConfig('statAverage', { isShow: !statConfig.config.value.statAverage.isShow })"
@@ -197,28 +199,28 @@ function updateStatAverage(value: number) {
class="flex gap-4 pt-2"
>
<div class="flex gap-1">
- <UiItem2
+ <UiChipButton
:class="[{
'!hover:transparent opacity-30': statConfig.config.value.statAverage.count === 1,
}]"
@click="updateStatAverage(statConfig.config.value.statAverage.count - 1)"
>
<Icon name="lucide:minus" />
- </UiItem2>
+ </UiChipButton>
<FormInput
:placeholder="t('stat.config.showedWallets.placeholder')"
- :value="statConfig.config.value.statAverage.count"
+ :modelValue="statConfig.config.value.statAverage.count"
min="1"
class="!w-16 max-w-24 !px-2 text-center"
type="number"
- @updateValue="value => statConfig.updateConfig('statAverage', { count: +value })"
+ @update:modelValue="value => statConfig.updateConfig('statAverage', { count: +value })"
/>
- <UiItem2
+ <UiChipButton
@click="updateStatAverage(statConfig.config.value.statAverage.count + 1)"
>
<Icon name="lucide:plus" />
- </UiItem2>
+ </UiChipButton>
</div>
</div>
</div>
diff --git a/app/components/stat/Header.vue b/app/components/stat/Header.vue
index 21e2a44f..2b7424d0 100644
--- a/app/components/stat/Header.vue
+++ b/app/components/stat/Header.vue
@@ -1,9 +1,8 @@
<script setup lang="ts">
-import type { FilterProvider } from '~/components/stat/filter/types'
import type { StatConfigModal, StatTabSlug } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import type { WalletId } from '~/components/wallets/types'
+import { filterKey, statConfigKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
@@ -24,8 +23,8 @@ const props = defineProps<{
}
}>()
-const filter = inject('filter') as FilterProvider
-const statConfig = inject('statConfig') as StatConfigProvider
+const filter = inject(filterKey)!
+const statConfig = inject(statConfigKey)!
const walletsStore = useWalletsStore()
const trnsFormStore = useTrnsFormStore()
diff --git a/app/components/stat/Item.vue b/app/components/stat/Item.vue
index 755b5194..211d6860 100644
--- a/app/components/stat/Item.vue
+++ b/app/components/stat/Item.vue
@@ -1,26 +1,17 @@
<script setup lang="ts">
-import { useStorage } from '@vueuse/core'
-import { differenceInDays, differenceInMonths, differenceInWeeks } from 'date-fns'
-
import type { CategoryId } from '~/components/categories/types'
-import type { Range, StatDateProvider } from '~/components/date/types'
-import type { FilterProvider } from '~/components/stat/filter/types'
-import type { ChartSeries, IntervalData, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
+import type { SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
-import { useAmount } from '~/components/amount/useAmount'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import StatCategoriesSection from '~/components/stat/categories/Section.vue'
-import { useStatChart } from '~/components/stat/chart/useStatChart'
-import { getTypesMapping } from '~/components/stat/utils'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
+import { useStatItem } from '~/components/stat/useStatItem'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
const props = defineProps<{
hasChildren?: boolean
isOneCategory?: boolean
- isQuickModal?: boolean
preCategoriesIds?: CategoryId[]
statTab: StatTabSlug
storageKey: string
@@ -30,171 +21,46 @@ const props = defineProps<{
}>()
const route = useRoute()
-const filter = inject('filter') as FilterProvider
-const statDate = inject('statDate') as StatDateProvider
-const statConfig = inject('statConfig') as StatConfigProvider
-const categoryId = computed(() => props.isOneCategory ? route.params.id as CategoryId : undefined)
-
+const { t } = useI18n()
+const filter = inject(filterKey)!
+const statDate = inject(statDateKey)!
+const statConfig = inject(statConfigKey)!
const categoriesStore = useCategoriesStore()
const trnsStore = useTrnsStore()
-const { getTotalOfTrnsIds } = useAmount()
-const { addMarkArea, createSeriesItem } = useStatChart()
-
-const newBaseStorageKey = computed(() => `finapp-${statDate.params.value.intervalsBy}-${props.storageKey}-${JSON.stringify(filter?.categoriesIds?.value)}`)
-const filteredType = useStorage<SeriesSlugSelected>(`finapp-filtered-type-${props.type}-${newBaseStorageKey.value}`, 'netIncome')
-const filteredCategoriesIds = ref<CategoryId[]>([])
-
-const selectedType2 = computed(() => {
- if (props.statTab === 'summary')
- return filteredType.value
-
- if (props.statTab === 'split')
- return props.type
-
- return props.statTab
-})
-
-const selectedType3 = computed(() => {
- if (props.statTab === 'summary')
- return 'summary'
-
- if (props.statTab === 'split')
- return props.type
-
- return props.statTab
-})
-
-const selectedTypesMapping = computed(() => getTypesMapping(selectedType2.value))
-
-const statTypeShow = computed(() => ({
- expense: true,
- income: true,
-}))
-
-const isPeriodOneDay = computed(() => (statDate.params.value.rangeBy === 'day' && statDate.params.value.rangeDuration === 1) || (statDate.params.value.intervalsBy === 'day' && statDate.params.value.intervalSelected !== -1))
-
-const rangeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
- trnsIds: props.trnsIds,
-}, {
- includesChildCategories: false,
-}))
-
-const rangeTrnsIdsWithFilteredCategories = computed(() => trnsStore.getStoreTrnsIds({
- categoriesIds: filteredCategoriesIds.value,
- trnsIds: props.trnsIds,
-}, {
- includesChildCategories: true,
-}))
-
-const intervalsData = computed(() => getIntervalsData(rangeTrnsIds.value, statDate.intervalsInRange.value))
-const intervalsDataWithFilteredCategories = computed(() => getIntervalsData(rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value))
-
-const selectedTrnsIds = computed(() => {
- return trnsStore.getStoreTrnsIds({
- trnsIds: statDate.params.value.intervalSelected !== -1
- ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
- : rangeTrnsIds.value,
- trnsTypes: selectedTypesMapping.value,
- }, { includesChildCategories: false })
-})
-
-const selectedAndFilteredTrnsIds = computed(() => {
- return trnsStore.getStoreTrnsIds({
- categoriesIds: filteredCategoriesIds.value,
- trnsIds: statDate.params.value.intervalSelected !== -1
- ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
- : rangeTrnsIds.value,
- trnsTypes: selectedTypesMapping.value,
- }, { includesChildCategories: true })
-})
-
-function onSetCategoryFilter(categoryId: CategoryId) {
- if (filteredCategoriesIds.value.includes(categoryId))
- return filteredCategoriesIds.value = []
-
- filteredCategoriesIds.value = [categoryId]
-}
-
-const rangeTotal = computed(() => {
- const trnsIds = statDate.params.value.intervalSelected !== -1
- ? intervalsDataWithFilteredCategories.value[statDate.params.value.intervalSelected]?.trnsIds
- : rangeTrnsIdsWithFilteredCategories.value
-
- return getTotalOfTrnsIds(trnsIds)
-})
-const averageTotal = computed(() => {
- if (differenceInDays(statDate.range.value.end, statDate.range.value.start) < 2)
- return
-
- const sum = filteredType.value === 'netIncome' ? rangeTotal.value.sum : rangeTotal.value[props.type]
-
- const date = statDate.params.value.intervalSelected !== -1
- ? statDate.selectedInterval.value
- : statDate.range.value
-
- const dif = {
- day: differenceInDays(date?.end, date?.start) + 1,
- month: differenceInMonths(date?.end, date?.start) + 1,
- week: differenceInWeeks(date?.end, date?.start) + 1,
- }
-
- const items = {
- month: 0,
- week: 0,
- // eslint-disable-next-line perfectionist/sort-objects
- day: 0,
- }
-
- if (dif.month > 1)
- items.month = sum / dif.month
-
- if (dif.day > 1)
- items.day = sum / dif.day
-
- if (dif.week > 1)
- items.week = sum / dif.week
-
- return Object.fromEntries(Object.entries(items).filter(([_, value]) => value !== 0))
-})
-
-const typesToShow = computed(() => {
- if (props.statTab === 'summary') {
- if (filteredType.value === 'netIncome')
- return ['income', 'expense']
-
- if (filteredType.value === 'income')
- return ['income']
-
- if (filteredType.value === 'expense')
- return ['expense']
- }
-
- if (props.statTab === 'expense' || props.statTab === 'income')
- return [props.statTab]
-
- return [props.type]
+const categoryId = computed(() => props.isOneCategory ? route.params.id as CategoryId : undefined)
+const isNotTransferCategory = computed(() => !props.isOneCategory || !categoriesStore.transferCategoriesIds.includes(categoryId.value))
+
+const {
+ averageTotal,
+ chartSeries,
+ chartXAxisLabels,
+ filteredCategoriesIds,
+ filteredType,
+ isPeriodOneDay,
+ newBaseStorageKey,
+ onClickSumItem,
+ onSetCategoryFilter,
+ rangeTotal,
+ selectedAndFilteredTrnsIds,
+ selectedTrnsIds,
+ selectedTypeForSum,
+} = useStatItem({
+ filter,
+ statConfig,
+ statDate,
+ statTab: computed(() => props.statTab),
+ storageKey: computed(() => props.storageKey),
+ trnsIds: computed(() => props.trnsIds),
+ type: computed(() => props.type),
})
-const chart = {
- series: computed<ChartSeries[]>(() => {
- const intervalTotals = intervalsDataWithFilteredCategories.value.map(g => g.total)
- const baseSeries = typesToShow.value.map(type => createSeriesItem(type, intervalTotals, statConfig.config.value.chart.isShowAverage ? intervalsDataWithFilteredCategories.value.reduce((acc, i) => acc + i.total[type], 0) / (intervalsData.value.length) : false))
-
- const selectedInterval = intervalsDataWithFilteredCategories.value?.[statDate.params.value.intervalSelected]
- if (!selectedInterval?.range.start || statDate.params.value.intervalSelected < 0)
- return baseSeries
-
- return addMarkArea(baseSeries, selectedInterval.range.start, statConfig.config.value?.chartType)
- }),
- xAxisLabels: computed(() => intervalsDataWithFilteredCategories.value.map(i => +i.range.start) ?? []),
-}
-
const quickViewTrns = ref<TrnId[]>([])
+const isShowTrns = ref(false)
-function onClickCategory(categoryId: CategoryId) {
+function onClickCategory(clickedCategoryId: CategoryId) {
if (route.name === 'categories-id') {
- filter.setCategoryId(categoryId)
+ filter.setCategoryId(clickedCategoryId)
const baseParams = {
filterCategories: filter?.categoriesIds?.value.join(','),
@@ -203,56 +69,37 @@ function onClickCategory(categoryId: CategoryId) {
}
const queryParams = new URLSearchParams({ ...baseParams }).toString()
- return useRouter().push(`/categories/${categoryId}?${queryParams}`)
+ return useRouter().push(`/categories/${clickedCategoryId}?${queryParams}`)
}
// Show quick view
quickViewTrns.value = trnsStore.getStoreTrnsIds({
- categoriesIds: [categoryId],
+ categoriesIds: [clickedCategoryId],
trnsIds: selectedAndFilteredTrnsIds.value,
}, { includesChildCategories: true })
}
-const isShowTrns = ref(false)
-function onClickSumItem(type: SeriesSlugSelected) {
- if (type === 'netIncome') {
+function handleClickSumItem(type: SeriesSlugSelected) {
+ if (type === 'netIncome')
isShowTrns.value = true
- }
-
- filteredType.value = type === filteredType.value ? 'netIncome' : type
-}
-
-function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
- return intervalsInRange.reduce((acc, range) => {
- const trnsIdsInRange = trnsIds.filter((id) => {
- const trnDate = trnsStore.items?.[id]?.date
- return trnDate! >= range.start && trnDate! <= range.end
- })
-
- acc.push({
- range,
- total: getTotalOfTrnsIds(trnsIdsInRange),
- trnsIds: trnsIdsInRange,
- })
- return acc
- }, [] as IntervalData[])
+ onClickSumItem(type)
}
</script>
<template>
<div class="@container/stat">
<StatChartWrap
- v-if="!props.isOneCategory || (props.isOneCategory && !categoriesStore.transferCategoriesIds.includes(categoryId))"
+ v-if="isNotTransferCategory"
:chartView="statConfig.config.value.chartView"
- :series="chart.series.value"
- :xAxisLabels="chart.xAxisLabels.value"
+ :series="chartSeries"
+ :xAxisLabels="chartXAxisLabels"
class="pb-3"
>
<StatDateQuick v-if="statConfig.config.value.date.isShowQuick" />
</StatChartWrap>
- <div class="grid content-start gap-3">
+ <div class="grid min-w-0 content-start gap-3">
<StatDateNavigation>
<StatFilterSelected
v-if="filter.isShow?.value && filter.categoriesIds.value.length > 0 || filter.walletsIds.value.length > 0"
@@ -262,25 +109,25 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
</StatDateNavigation>
<StatSumWrap
- v-if="!props.isOneCategory || (props.isOneCategory && !categoriesStore.transferCategoriesIds.includes(categoryId))"
+ v-if="isNotTransferCategory"
:averageConfig="statConfig.config.value.statAverage.count"
:averageTotal
:categoryId
:filter
:filteredType="filteredType"
:isShowAverage="statConfig.config.value.statAverage.isShow"
- :isShowExpense="statTypeShow.expense"
- :isShowIncome="statTypeShow.income"
+ :isShowExpense="true"
+ :isShowIncome="true"
:statDate
:total="rangeTotal"
:trnsIds
- :type="selectedType3"
+ :type="selectedTypeForSum"
:walletId
- @click="onClickSumItem"
+ @click="handleClickSumItem"
@clickAverage="statConfig.updateConfig('statAverage', { isShow: !statConfig.config.value.statAverage.isShow })"
/>
- <div class="_min-h-dvh grid content-start items-start gap-4">
+ <div class="_min-h-dvh grid min-w-0 content-start items-start gap-4">
<StatCategoriesSection
v-if="statConfig.config.value.catsRound.isShow && (props.hasChildren || (props.preCategoriesIds ?? []).length > 0)"
:filteredCategoriesIds
@@ -288,7 +135,7 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
:preCategoriesIds="props.preCategoriesIds || categoriesStore.favoriteCategoriesIds"
:selectedTrnsIds
@clickCategory="onClickCategory"
- @onSetCategoryFilter="onSetCategoryFilter"
+ @setCategoryFilter="onSetCategoryFilter"
/>
<div
@@ -304,7 +151,7 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
:storageKey="newBaseStorageKey"
:type="props.type ?? 'netIncome'"
@clickCategory="onClickCategory"
- @onSetCategoryFilter="onSetCategoryFilter"
+ @setCategoryFilter="onSetCategoryFilter"
/>
<StatTrns
@@ -321,7 +168,7 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
<!-- Quick View Trns -->
<Teleport
v-if="quickViewTrns?.length > 0"
- to="#pageScroll"
+ to="body"
>
<BottomSheet
v-if="quickViewTrns?.length > 0"
@@ -331,7 +178,7 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<div class="bottomSheetContent">
@@ -366,7 +213,7 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<div class="bottomSheetContent">
diff --git a/app/components/stat/Menu.vue b/app/components/stat/Menu.vue
index 6ac5f8f3..fd15d754 100644
--- a/app/components/stat/Menu.vue
+++ b/app/components/stat/Menu.vue
@@ -57,7 +57,7 @@ watch(() => props.active, () => {
:key="item.id"
:class="[{
'rounded-none border-b border-b-1 !border-(--ui-primary)': item.id === props.active,
- 'text-muted hover:mb-1 hover:bg-[var(--item-5)] hover:pb-1': item.id !== props.active,
+ 'text-muted hover:mb-1 hover:bg-(--item-5) hover:pb-1': item.id !== props.active,
}]"
class="rounded-lg px-3 py-1.5 pb-2 text-xs tracking-wide text-nowrap lg:text-sm"
@click="onClickStatMenu(item.id)"
diff --git a/app/components/stat/Page.vue b/app/components/stat/Page.vue
index 7a669f33..70ef5d2b 100644
--- a/app/components/stat/Page.vue
+++ b/app/components/stat/Page.vue
@@ -7,6 +7,7 @@ import type { WalletId } from '~/components/wallets/types'
import { useStatDate } from '~/components/date/useStatDate'
import { useFilter } from '~/components/stat/filter/useFilter'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useStatConfig } from '~/components/stat/useStatConfig'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
@@ -15,7 +16,7 @@ const route = useRoute()
const trnsStore = useTrnsStore()
const filter = useFilter()
-provide('filter', filter)
+provide(filterKey, filter)
const activeTab = useStorage<StatTabSlug>('dashboard-tab', 'summary')
const storageKey = computed(() => `dashboard-${activeTab.value}`)
@@ -30,10 +31,10 @@ const maxRange = computed(() => trnsStore.getRange(trnsIds.value))
const statConfig = useStatConfig({
storageKey: storageKey.value,
})
-provide('statConfig', statConfig)
+provide(statConfigKey, statConfig)
const statDate = useStatDate({ key: storageKey.value, maxRange, queryParams: route.query })
-provide('statDate', statDate)
+provide(statDateKey, statDate)
watch(filter.categoriesIds, () => {
statConfig.config.value.isShowEmptyCategories = filter.categoriesIds.value.length > 0
diff --git a/app/components/stat/Trns.vue b/app/components/stat/Trns.vue
index aa97afc3..0b1332a7 100644
--- a/app/components/stat/Trns.vue
+++ b/app/components/stat/Trns.vue
@@ -11,7 +11,7 @@ defineProps<{
</script>
<template>
- <div class="mb-4 @3xl/main:max-w-md">
+ <div class="mb-4 min-w-0 @3xl/main:max-w-md">
<TrnsList
v-if="selectedTrnsIds.length > 0"
:isShowDates="!isPeriodOneDay"
diff --git a/app/components/stat/categories/Line.vue b/app/components/stat/categories/Line.vue
index 2873a4f3..e92cb5f2 100644
--- a/app/components/stat/categories/Line.vue
+++ b/app/components/stat/categories/Line.vue
@@ -2,12 +2,11 @@
import { onLongPress } from '@vueuse/core'
import type { CategoryId } from '~/components/categories/types'
-import type { StatDateProvider } from '~/components/date/types'
import type { CategoryWithData } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const props = defineProps<{
@@ -26,11 +25,11 @@ const props = defineProps<{
const emit = defineEmits<{
click: [categoryId: CategoryId]
- onClickIcon: [id: CategoryId]
+ clickIcon: [id: CategoryId]
}>()
-const statDate = inject('statDate') as StatDateProvider
-const statConfig = inject('statConfig') as StatConfigProvider
+const statDate = inject(statDateKey)!
+const statConfig = inject(statConfigKey)!
const trnsFormStore = useTrnsFormStore()
const categoriesStore = useCategoriesStore()
const currenciesStore = useCurrenciesStore()
@@ -124,14 +123,14 @@ onLongPress(
:color="category?.color"
:name="category?.icon"
invert
- @click="emit('onClickIcon', props.item.id)"
+ @click="emit('clickIcon', props.item.id)"
/>
<UiIconBase
v-else
:color="category?.color"
:name="category?.icon"
class="ml-1 !w-6"
- @click="emit('onClickIcon', props.item.id)"
+ @click="emit('clickIcon', props.item.id)"
/>
</template>
diff --git a/app/components/stat/categories/Round.vue b/app/components/stat/categories/Round.vue
index 02e615b9..7f2b2d79 100644
--- a/app/components/stat/categories/Round.vue
+++ b/app/components/stat/categories/Round.vue
@@ -2,11 +2,11 @@
import { onLongPress } from '@vueuse/core'
import type { CategoryId } from '~/components/categories/types'
-import type { StatDateProvider } from '~/components/date/types'
import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const props = defineProps<{
@@ -18,7 +18,7 @@ const emit = defineEmits<{
click: [categoryId: CategoryId]
}>()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const categoriesStore = useCategoriesStore()
const currenciesStore = useCurrenciesStore()
const trnsFormStore = useTrnsFormStore()
@@ -64,8 +64,9 @@ onLongPress(
<div
v-if="category"
ref="longPressRef"
- :class="{ 'opacity-60': props.item.value === 0 }"
- class="dark:bg-item-3 relative flex items-center gap-2 overflow-hidden rounded-full p-1 pr-2 hover:bg-[var(--item-5)]"
+ :class="cn('dark:bg-item-3 relative flex items-center gap-2 overflow-hidden rounded-full p-1 pr-2 hover:bg-(--item-5)',
+ props.item.value === 0 && 'opacity-60',
+ )"
>
<div
:style="{ backgroundColor: category?.color }"
diff --git a/app/components/stat/categories/Round2lines.vue b/app/components/stat/categories/Round2lines.vue
index 1b3ca7ce..651a954f 100644
--- a/app/components/stat/categories/Round2lines.vue
+++ b/app/components/stat/categories/Round2lines.vue
@@ -2,11 +2,11 @@
import { onLongPress } from '@vueuse/core'
import type { CategoryId } from '~/components/categories/types'
-import type { StatDateProvider } from '~/components/date/types'
import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const props = defineProps<{
@@ -18,7 +18,7 @@ const emit = defineEmits<{
click: [categoryId: CategoryId]
}>()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const categoriesStore = useCategoriesStore()
const currenciesStore = useCurrenciesStore()
const trnsFormStore = useTrnsFormStore()
@@ -64,7 +64,7 @@ onLongPress(
<div
v-if="category"
ref="longPressRef"
- class="dark:bg-item-3 relative flex items-center gap-2 overflow-hidden rounded-2xl border border-transparent p-1 pr-3 hover:bg-[var(--item-5)]"
+ class="dark:bg-item-3 relative flex items-center gap-2 overflow-hidden rounded-2xl border border-transparent p-1 pr-3 hover:bg-(--item-5)"
>
<div
:style="{ backgroundColor: category?.color }"
diff --git a/app/components/stat/categories/Section.vue b/app/components/stat/categories/Section.vue
index fcdce0cd..621b6a9e 100644
--- a/app/components/stat/categories/Section.vue
+++ b/app/components/stat/categories/Section.vue
@@ -1,9 +1,9 @@
<script setup lang="ts">
import type { CategoryId } from '~/components/categories/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import type { TrnId } from '~/components/trns/types'
import { useStatCategories } from '~/components/stat/categories/useStatCategories'
+import { statConfigKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
filteredCategoriesIds: CategoryId[]
@@ -14,13 +14,13 @@ const props = defineProps<{
const emit = defineEmits<{
clickCategory: [categoryId: CategoryId]
- onSetCategoryFilter: [categoryId: CategoryId]
+ setCategoryFilter: [categoryId: CategoryId]
}>()
const visibleCategoriesLimit = 12
const { getCategoriesWithData } = useStatCategories()
-const statConfig = inject('statConfig') as StatConfigProvider
+const statConfig = inject(statConfigKey)!
const isExpanded = ref(false)
const roundCategories = computed(() => getCategoriesWithData(props.selectedTrnsIds ?? [], statConfig.config.value.catsRound.isGrouped, props.preCategoriesIds))
@@ -40,33 +40,35 @@ const visibleCategories = computed(() => isExpanded.value ? roundCategories.valu
}"
class="transition-opacity"
isShowAmount
- @click="emit('onSetCategoryFilter', item.id)"
+ @click="emit('setCategoryFilter', item.id)"
/>
<div
v-if="!props.isOneCategory"
class="flex items-center"
>
- <UiTabs1>
- <UiItem4
+ <UiTabsBar>
+ <UiActionButton
v-if="roundCategories.length > visibleCategoriesLimit"
+ size="sm"
@click="isExpanded = !isExpanded"
>
<Icon
:name="isExpanded ? 'lucide:chevron-up' : 'lucide:chevron-down'"
:size="20"
/>
- </UiItem4>
+ </UiActionButton>
- <UiItem4
+ <UiActionButton
+ size="sm"
@click="statConfig.config.value.catsRound.isGrouped = !statConfig.config.value.catsRound.isGrouped"
>
<Icon
:name="statConfig.config.value.catsRound.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
:size="20"
/>
- </UiItem4>
- </UiTabs1>
+ </UiActionButton>
+ </UiTabsBar>
</div>
</div>
</template>
diff --git a/app/components/stat/categories/Section2.vue b/app/components/stat/categories/Section2.vue
index a20ac25b..abf26593 100644
--- a/app/components/stat/categories/Section2.vue
+++ b/app/components/stat/categories/Section2.vue
@@ -3,11 +3,11 @@ import { useStorage } from '@vueuse/core'
import type { Categories, CategoryId } from '~/components/categories/types'
import type { CategoryWithData, StatTabSlug } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import type { TrnId } from '~/components/trns/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useStatCategories } from '~/components/stat/categories/useStatCategories'
+import { statConfigKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
isOneCategory?: boolean
@@ -20,13 +20,13 @@ const props = defineProps<{
const emit = defineEmits<{
clickCategory: [categoryId: CategoryId]
- onSetCategoryFilter: [categoryId: CategoryId]
+ setCategoryFilter: [categoryId: CategoryId]
}>()
const { t } = useI18n()
const { getCategoriesWithData } = useStatCategories()
const categoriesStore = useCategoriesStore()
-const statConfig = inject('statConfig') as StatConfigProvider
+const statConfig = inject(statConfigKey)!
const categoriesWithData = computed<CategoryWithData[]>(() => {
const isGrouped = statConfig.config.value[statConfig.config.value.catsView === 'list' ? 'catsList' : 'catsRound'].isGrouped
@@ -123,15 +123,15 @@ function toggleRoot(id: CategoryId) {
>
<template #header="{ toggle, isShown }">
<div class="flex items-center justify-between">
- <UiTitle8 :isShown @click="toggle">
+ <UiTitleCollapse :isShown @click="toggle">
{{ t('stat.config.categories.vertical.title') }} {{ (!isShown && verticalCategories.filter(c => c.value !== 0).length > 0) ? verticalCategories.filter(c => c.value !== 0).length : '' }}
- </UiTitle8>
+ </UiTitleCollapse>
<div
v-if="isShown && !props.isOneCategory"
class="flex items-center"
>
- <UiItem1
+ <UiActionButton
:isActive="statConfig.config.value.vertical.isGrouped"
@click="statConfig.config.value.vertical.isGrouped = !statConfig.config.value.vertical.isGrouped"
>
@@ -139,7 +139,7 @@ function toggleRoot(id: CategoryId) {
:name="statConfig.config.value.vertical.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
:size="20"
/>
- </UiItem1>
+ </UiActionButton>
</div>
</div>
@@ -169,15 +169,15 @@ function toggleRoot(id: CategoryId) {
>
<template #header="{ toggle, isShown }">
<div class="flex items-center justify-between">
- <UiTitle8 :isShown @click="toggle">
+ <UiTitleCollapse :isShown @click="toggle">
{{ t('stat.config.categories.list.title') }} {{ (!isShown && categoriesWithData.length > 0) ? categoriesWithData.length : '' }}
- </UiTitle8>
+ </UiTitleCollapse>
<div
v-if="isShown"
class="flex items-center gap-1"
>
- <UiItem1
+ <UiActionButton
v-if="statConfig.config.value.catsView === 'list' && !props.isOneCategory && statConfig.config.value.catsList.isGrouped"
@click="toggleOpened"
>
@@ -196,9 +196,9 @@ function toggleRoot(id: CategoryId) {
name="lucide:folder"
size="20"
/>
- </UiItem1>
+ </UiActionButton>
- <UiItem1
+ <UiActionButton
v-if="!props.isOneCategory"
:isActive="statConfig.config.value.catsList.isGrouped"
@click="statConfig.config.value.catsList.isGrouped = !statConfig.config.value.catsList.isGrouped"
@@ -207,7 +207,7 @@ function toggleRoot(id: CategoryId) {
:name="statConfig.config.value.catsList.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
:size="20"
/>
- </UiItem1>
+ </UiActionButton>
</div>
</div>
@@ -219,7 +219,7 @@ function toggleRoot(id: CategoryId) {
}"
class="pt-2"
>
- <UiToggle3
+ <UiToggleControlled
v-for="item in linesCategories"
:key="item.id"
:class="{
@@ -266,7 +266,7 @@ function toggleRoot(id: CategoryId) {
/>
</div>
</div>
- </UiToggle3>
+ </UiToggleControlled>
</div>
</template>
</UiToggle>
diff --git a/app/components/stat/categories/SectionWithCollapse.vue b/app/components/stat/categories/SectionWithCollapse.vue
deleted file mode 100644
index 341af18a..00000000
--- a/app/components/stat/categories/SectionWithCollapse.vue
+++ /dev/null
@@ -1,426 +0,0 @@
-<script setup lang="ts">
-import { useStorage } from '@vueuse/core'
-import defu from 'defu'
-
-import type { Categories, CategoryId } from '~/components/categories/types'
-import type { CategoryWithData, StatTabSlug } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
-import type { TrnId } from '~/components/trns/types'
-
-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { useStatCategories } from '~/components/stat/categories/useStatCategories'
-
-const props = defineProps<{
- isOneCategory?: boolean
- preCategoriesIds?: CategoryId[]
- selectedAndFilteredTrnsIds?: TrnId[]
- selectedTrnsIds?: TrnId[]
- storageKey: string
- type: StatTabSlug
-}>()
-
-const emit = defineEmits<{
- clickCategory: [categoryId: CategoryId]
- onSetCategoryFilter: [categoryId: CategoryId]
-}>()
-
-const { t } = useI18n()
-const { getCategoriesWithData } = useStatCategories()
-const categoriesStore = useCategoriesStore()
-const statConfig = inject('statConfig') as StatConfigProvider
-
-const categoriesWithData = computed<CategoryWithData[]>(() => {
- const isGrouped = statConfig.config.value[statConfig.config.value.catsView === 'list' ? 'catsList' : 'catsRound'].isGrouped
-
- const cats: CategoryId[] = []
- if (statConfig.config.value?.isShowEmptyCategories && props.preCategoriesIds) {
- cats.push(...props.preCategoriesIds)
- }
-
- return getCategoriesWithData(props.selectedTrnsIds ?? [], isGrouped, cats)
-})
-
-const categoriesStat = computed<{ grouped: CategoryWithData[], ungrouped: CategoryWithData[] }>(() => ({
- grouped: getCategoriesWithData(props.selectedTrnsIds ?? [], true),
- ungrouped: getCategoriesWithData(props.selectedTrnsIds ?? [], false),
-}))
-
-const verticalCategories = computed<CategoryWithData[]>(() => categoriesStat.value[statConfig.config.value.vertical.isGrouped ? 'grouped' : 'ungrouped'])
-const verticalBiggestCatNumber = computed(() => getBiggestCatNumber(verticalCategories.value))
-
-const linesCategories = computed<CategoryWithData[]>(() => categoriesStat.value[statConfig.config.value.catsList.isGrouped ? 'grouped' : 'ungrouped'])
-const linesBiggestCatNumber = computed(() => getBiggestCatNumber(linesCategories.value))
-
-// const roundCategories = computed<CategoryWithData[]>(() => categoriesStat.value[statConfig.config.value.catsRound.isGrouped ? 'grouped' : 'ungrouped'])
-const biggestCatNumber = computed(() => getBiggestCatNumber(categoriesWithData.value))
-
-function getBiggestCatNumber(categories: CategoryWithData[]) {
- const income = categories.filter(c => c.value > 0).at(0)?.value ?? 0
- const expense = categories.filter(c => c.value < 0).at(0)?.value ?? 0
-
- return {
- expense: Math.abs(expense),
- income,
- }
-}
-
-type CategoryStateInside = Record<CategoryId, { show: boolean }>
-type CategoryState = { categories?: CategoryStateInside, show: boolean }
-type CategoriesState = Record<CategoryId, CategoryState>
-
-function createInitialChildState(childIds?: CategoryId[]): CategoryStateInside {
- return (childIds ?? []).reduce((acc, childId) => {
- acc[childId] = { show: false }
- return acc
- }, {} as CategoryStateInside)
-}
-
-function createInitialState(storeCategories: Categories): CategoriesState {
- return Object.entries(storeCategories).reduce((acc, [id, cat]) => {
- acc[id] = {
- categories: createInitialChildState(cat.childIds),
- show: false,
- }
- return acc
- }, {} as CategoriesState)
-}
-
-const categoriesOpened = useStorage<CategoriesState>(
- `statCategoriesOpened1${props.storageKey}`,
- createInitialState(categoriesStore.items ?? {}),
-)
-
-function getChildState(cat: CategoryWithData): CategoryStateInside {
- return Object.values(cat.categories ?? {}).reduce((acc, child) => {
- acc[child.id] = { show: categoriesOpened.value[cat.id]?.categories?.[child.id]?.show ?? false }
- return acc
- }, {} as CategoryStateInside)
-}
-
-function getCurrentState(categories: CategoryWithData[]): CategoriesState {
- return categories.reduce((acc, cat) => {
- acc[cat.id] = {
- categories: getChildState(cat),
- show: categoriesOpened.value[cat.id]?.show ?? false,
- }
- return acc
- }, {} as CategoriesState)
-}
-
-const currentState = computed(() => getCurrentState(categoriesWithData.value))
-
-const openedStatus = computed(() => {
- const cats = Object.values(currentState.value)
- return {
- isAllChildOpen: cats.every(cat => Object.values(cat.categories ?? {}).every(c => c.show)),
- isAllRootOpen: cats.every(cat => cat.show),
- isAnyChildOpen: cats.some(cat => Object.values(cat.categories ?? {}).some(c => c.show)),
- isAnyRootOpen: cats.some(cat => cat.show),
- }
-})
-
-function toggleOpened() {
- if (openedStatus.value.isAllRootOpen && !openedStatus.value.isAllChildOpen) {
- updateState(currentState.value, { childShow: true })
- return
- }
- if (openedStatus.value.isAnyRootOpen) {
- updateState(currentState.value, { childShow: false, parentShow: false })
- return
- }
- updateState(currentState.value, { parentShow: true })
-}
-
-function toggleRoot(id: CategoryId) {
- const root = currentState.value[id]
- const allOpen = Object.values(root?.categories ?? {}).some(c => c.show)
- if (root?.show && allOpen) {
- categoriesOpened.value[id].categories = Object.keys(currentState.value[id]?.categories ?? {}).reduce((childAcc, childId) => {
- childAcc[childId] = { show: false }
- return childAcc
- }, {} as CategoryStateInside)
- return
- }
- categoriesOpened.value[id].show = !categoriesOpened.value[id]?.show
-}
-
-function toggleChild(id: CategoryId, childId: CategoryId) {
- categoriesOpened.value[id].categories[childId].show = !categoriesOpened.value[id]?.categories?.[childId]?.show
-}
-
-function updateState(state: CategoriesState, options: { childShow?: boolean, parentShow?: boolean }) {
- const { childShow, parentShow } = options
- const newState = Object.entries(state).reduce((acc, [id, cat]) => {
- acc[id] = { ...cat }
- if (parentShow !== undefined) {
- acc[id].show = parentShow
- }
- if (childShow !== undefined) {
- acc[id].categories = Object.fromEntries(
- Object.keys(cat.categories ?? {}).map(childId => [childId, { show: childShow }]),
- )
- }
- return acc
- }, {} as CategoriesState)
- categoriesOpened.value = defu(newState, categoriesOpened.value)
-}
-</script>
-
-<template>
- <div
- v-if="categoriesWithData.length > 0"
- class="@3xl/main:max-w-lg"
- >
- <!-- Vertical -->
- <UiToggle
- v-if="statConfig.config.value.vertical.isShow"
- :storageKey="`${storageKey}-${type}-vertical`"
- :initStatus="true"
- >
- <template #header="{ toggle, isShown }">
- <div class="flex items-center justify-between">
- <UiTitle8 :isShown @click="toggle">
- {{ t('stat.config.categories.vertical.title') }} {{ (!isShown && verticalCategories.filter(c => c.value !== 0).length > 0) ? verticalCategories.filter(c => c.value !== 0).length : '' }}
- </UiTitle8>
-
- <div
- v-if="isShown && !props.isOneCategory"
- class="flex items-center"
- >
- <UiTabs1>
- <UiItem1
- :isActive="statConfig.config.value.vertical.isGrouped"
- @click="statConfig.config.value.vertical.isGrouped = true"
- >
- <Icon
- name="lucide:network"
- :size="16"
- />
- </UiItem1>
-
- <UiItem1
- :isActive="!statConfig.config.value.vertical.isGrouped"
- @click="statConfig.config.value.vertical.isGrouped = false"
- >
- <Icon
- name="lucide:folder-tree"
- :size="16"
- />
- </UiItem1>
- </UiTabs1>
- </div>
- </div>
-
- <div
- v-if="isShown"
- class="grid pt-3"
- >
- <div class="flex overflow-hidden overflow-x-auto pt-2 pl-1">
- <StatCategoriesVertical
- v-for="item in verticalCategories.filter(c => c.value !== 0)"
- :key="item.id"
- :item="item"
- :biggestCatNumber="verticalBiggestCatNumber"
- @click="emit('clickCategory', item.id)"
- />
- </div>
- </div>
- </template>
- </UiToggle>
-
- <!-- List -->
- <UiToggle
- v-if="statConfig.config.value.catsList.isShow"
- :storageKey="`${storageKey}-${type}-list`"
- :initStatus="true"
- class="@3xl/main:max-w-md"
- >
- <template #header="{ toggle, isShown }">
- <div class="flex items-center justify-between">
- <UiTitle8 :isShown @click="toggle">
- {{ t('stat.config.categories.list.title') }} {{ (!isShown && categoriesWithData.length > 0) ? categoriesWithData.length : '' }}
- </UiTitle8>
-
- <div
- v-if="isShown"
- class="flex items-center gap-1"
- >
- <UiItem1
- v-if="statConfig.config.value.catsView === 'list'"
- @click="toggleOpened"
- >
- <Icon
- v-if="openedStatus.isAnyRootOpen && !openedStatus.isAllChildOpen"
- name="lucide:folder-open"
- />
- <Icon
- v-if="openedStatus.isAnyRootOpen && openedStatus.isAllChildOpen"
- name="lucide:folder-kanban"
- />
- <Icon
- v-if="!openedStatus.isAnyRootOpen && !openedStatus.isAllRootOpen"
- name="lucide:folder"
- />
- </UiItem1>
-
- <UiTabs1 v-if="!props.isOneCategory">
- <UiItem1
- :isActive="statConfig.config.value.catsList.isGrouped"
- @click="statConfig.config.value.catsList.isGrouped = true"
- >
- <Icon
- name="lucide:network"
- :size="16"
- />
- </UiItem1>
-
- <UiItem1
- :isActive="!statConfig.config.value.catsList.isGrouped"
- @click="statConfig.config.value.catsList.isGrouped = false"
- >
- <Icon
- name="lucide:folder-tree"
- :size="16"
- />
- </UiItem1>
- </UiTabs1>
- </div>
- </div>
-
- <div
- v-if="isShown"
- :class="{
- '@3xl/main:max-w-md': !statConfig.config.value.catsList.isGrouped,
- 'grid gap-1': statConfig.config.value.catsList.isItemsBg,
- }"
- class="pt-2"
- >
- <UiToggle3
- v-for="item in linesCategories"
- :key="item.id"
- :class="{
- group: !statConfig.config.value.catsList.isItemsBg,
- }"
- :isShown="categoriesOpened[item.id]?.show ?? false"
- :openPadding="statConfig.config.value.catsList.isGrouped ? '!pb-3' : ''"
- @click="toggleRoot(item.id)"
- >
- <template #header="{ toggle: toggle2, isShown: isShownRoot }">
- <div class="-mt-px flex items-stretch justify-between">
- <UiToggleAction
- v-if="item.trnsIds.length > 0"
- :isShown="isShownRoot"
- :class="{
- '-mr-2.5': !statConfig.config.value.catsList.isItemsBg,
- }"
- @click="toggle2"
- />
- <div
- v-else
- :class="{
- 'mr-2 pr-[3px]': statConfig.config.value.catsList.isItemsBg,
- }"
- class="w-8"
- />
-
- <StatCategoriesLine
- :isShowParent="props.isOneCategory ? false : !statConfig.config.value.catsList.isGrouped"
- :item="item"
- :biggestCatNumber="linesBiggestCatNumber"
- :lineWidth="statConfig.config.value.catsList.isLines ? 0 : 1"
- class="grow"
- @click="emit('clickCategory', item.id)"
- />
- </div>
- </template>
-
- <!-- Inside -->
- <div class="mt-[-2px] ml-5 -translate-x-px pl-3">
- <div
- v-if="!item.categories || item.categories.length === 0"
- class="mb-3 ml-11"
- >
- <TrnsList
- :trnsIds="item.trnsIds"
- :size="10"
- alt
- isShowExpense
- isShowIncome
- isShowTransfers
- />
- </div>
-
- <div
- v-if="item.categories && statConfig.config.value.catsList.isGrouped"
- class="flex flex-wrap gap-1 pt-2 pl-12"
- >
- <StatCategoriesRound
- v-for="itemInside in item.categories"
- :key="itemInside.id"
- :item="itemInside"
- isShowAmount
- @click="emit('clickCategory', itemInside.id)"
- />
- </div>
-
- <div
- :class="{
- 'mt-1': statConfig.config.value.catsList.isItemsBg,
- }"
- class="_gap-1 grid"
- >
- <UiToggle3
- v-for="itemInside in item.categories"
- :key="itemInside.id"
- :class="{
- group: !statConfig.config.value.catsList.isItemsBg,
- }"
- :isShown="categoriesOpened[item.id]?.categories[itemInside.id]?.show ?? false"
- :openPadding="statConfig.config.value.catsList.isGrouped ? '!pb-3' : ''"
- @click="toggleChild(item.id, itemInside.id)"
- >
- <template #header="{ toggle: toggleInside, isShown: isShownInside }">
- <div class="flex items-stretch justify-between">
- <UiToggleAction
- v-if="statConfig.config.value.catsList.isGrouped"
- :isShown="isShownInside"
- :class="{
- '-mr-2.5': !statConfig.config.value.catsList.isItemsBg,
- }"
- @click="toggleInside"
- />
-
- <StatCategoriesLine
- :isShowParent="!statConfig.config.value.catsList.isGrouped"
- :item="itemInside"
- :biggestCatNumber="biggestCatNumber"
- :lineWidth="statConfig.config.value.catsList.isLines ? 0 : 1"
- class="grow"
- :class="{
- 'my-px': statConfig.config.value.catsList.isItemsBg,
- }"
- @click="emit('clickCategory', itemInside.id)"
- />
- </div>
- </template>
-
- <!-- Inside -->
- <div class="mt-[-2px] ml-5 -translate-x-px pl-14">
- <TrnsList
- :trnsIds="itemInside.trnsIds"
- :size="5"
- alt
- isShowExpense
- isShowIncome
- isShowTransfers
- />
- </div>
- </UiToggle3>
- </div>
- </div>
- </UiToggle3>
- </div>
- </template>
- </UiToggle>
- </div>
-</template>
diff --git a/app/components/stat/categories/Vertical.vue b/app/components/stat/categories/Vertical.vue
index 60efbdf4..8ac3be5e 100644
--- a/app/components/stat/categories/Vertical.vue
+++ b/app/components/stat/categories/Vertical.vue
@@ -2,10 +2,10 @@
import { onLongPress } from '@vueuse/core'
import type { CategoryId } from '~/components/categories/types'
-import type { StatDateProvider } from '~/components/date/types'
import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+import { statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const props = defineProps<{
@@ -18,10 +18,10 @@ const props = defineProps<{
const emit = defineEmits<{
click: [categoryId: CategoryId]
- onClickIcon: [id: CategoryId]
+ clickIcon: [id: CategoryId]
}>()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const trnsFormStore = useTrnsFormStore()
const categoriesStore = useCategoriesStore()
@@ -93,7 +93,7 @@ onLongPress(
<div
v-if="category"
ref="longPressRef"
- class="rounded-sm p-1 pb-4 hover:bg-[var(--item-5)]"
+ class="rounded-sm p-1 pb-4 hover:bg-(--item-5)"
>
<div class="bg-item-3 flex h-28 items-end rounded-sm">
<div
@@ -101,10 +101,9 @@ onLongPress(
:style="getBarStyle()"
>
<div
- :class="{
- 'text-income-1': props.item.value > 0,
- }"
- class="font-secondary absolute top-[-14px] w-full text-center text-xs leading-none"
+ :class="cn('font-secondary absolute top-[-14px] w-full text-center text-xs leading-none',
+ props.item.value > 0 && 'text-income-1',
+ )"
>
{{ amount }}
</div>
diff --git a/app/components/stat/categories/useStatCategories.ts b/app/components/stat/categories/useStatCategories.ts
index 203fcedd..0d1439a5 100644
--- a/app/components/stat/categories/useStatCategories.ts
+++ b/app/components/stat/categories/useStatCategories.ts
@@ -4,7 +4,7 @@ import type { TrnId } from '~/components/trns/types'
import { useAmount } from '~/components/amount/useAmount'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { getParentCategoryId2 } from '~/components/categories/utils'
+import { getParentCategoryIdOrUndefined } from '~/components/categories/utils'
import { sortCategoriesByAmount } from '~/components/stat/utils'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
@@ -14,11 +14,12 @@ export function useStatCategories() {
const { getTotalOfTrnsIds } = useAmount()
function collectCategoriesByTrns(trnsIds: TrnId[], preCategoriesIds?: CategoryId[]): CategoriesWithData {
+ const transferIds = new Set(categoriesStore.transferCategoriesIds)
const categoriesByTrns = trnsIds.reduce((acc, trnId) => {
const categoryId = trnsStore.items?.[trnId]?.categoryId
const category = categoryId && categoriesStore.items[categoryId]
- if (!categoryId || !category || categoriesStore.transferCategoriesIds.includes(categoryId))
+ if (!categoryId || !category || transferIds.has(categoryId))
return acc
acc[categoryId] ??= {
@@ -61,8 +62,9 @@ export function useStatCategories() {
function groupCategories(categoriesByTrns: CategoriesWithData): CategoryWithData[] {
const groupedCategories = Object.values(categoriesByTrns).reduce((acc, cat) => {
- const parentId = getParentCategoryId2(categoriesStore.items, cat.id)
+ const parentId = getParentCategoryIdOrUndefined(categoriesStore.items, cat.id)
const parentCategory = parentId && categoriesStore.items[parentId]
+ const catTotal = getTotalOfTrnsIds(cat.trnsIds).sum
if (!parentId || !parentCategory) {
acc[cat.id] ??= {
@@ -70,7 +72,7 @@ export function useStatCategories() {
id: cat.id,
name: cat.name,
trnsIds: cat.trnsIds,
- value: getTotalOfTrnsIds(cat.trnsIds).sum,
+ value: catTotal,
}
return acc
}
@@ -86,15 +88,20 @@ export function useStatCategories() {
acc[parentId].categories ??= []
acc[parentId].categories.push({
...cat,
- value: getTotalOfTrnsIds(cat.trnsIds).sum,
+ value: catTotal,
})
acc[parentId].trnsIds.push(...cat.trnsIds)
- acc[parentId].value += getTotalOfTrnsIds(cat.trnsIds).sum
- acc[parentId].categories.sort(sortCategoriesByAmount)
+ acc[parentId].value += catTotal
return acc
}, {} as CategoriesWithData)
+ // Sort child categories after grouping (not inside the loop)
+ for (const group of Object.values(groupedCategories)) {
+ if (group.categories?.length > 1)
+ group.categories.sort(sortCategoriesByAmount)
+ }
+
return Object.values(groupedCategories).sort(sortCategoriesByAmount)
}
diff --git a/app/components/stat/chart/Intervals.vue b/app/components/stat/chart/Intervals.vue
index f28300b3..00ee4a1e 100644
--- a/app/components/stat/chart/Intervals.vue
+++ b/app/components/stat/chart/Intervals.vue
@@ -9,7 +9,7 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onChangePeriod: [value: Period]
+ changePeriod: [value: Period]
}>()
const { t } = useI18n()
@@ -47,10 +47,10 @@ const value = ref(props.period)
v-model="value"
:items="items"
:ui="{
- base: 'ring-0 text-muted text-2xs hover:bg-[var(--item-5)]',
+ base: 'ring-0 text-muted text-2xs hover:bg-(--item-5)',
trailingIcon: 'size-4',
content: 'w-24',
}"
- @change="emit('onChangePeriod', value)"
+ @change="emit('changePeriod', value)"
/>
</template>
diff --git a/app/components/stat/chart/View.vue b/app/components/stat/chart/View.vue
index 1efcbe78..3877089c 100644
--- a/app/components/stat/chart/View.vue
+++ b/app/components/stat/chart/View.vue
@@ -9,29 +9,28 @@ import VChart from 'vue-echarts'
import type { Period } from '~/components/date/types'
import type { ChartType } from '~/components/stat/chart/types'
import type { PeriodNameWithAll } from '~/components/stat/filter/types'
+import type { ChartSeries } from '~/components/stat/types'
import { formatByLocale } from '~/components/date/utils'
import { config, lineConfig } from '~/components/stat/chart/config'
import { getLocalAmount } from '~/components/stat/chart/utils'
-const props = withDefaults(
- defineProps<{
- chartType?: ChartType
- isShowDataLabels?: boolean
- isShowExpense?: boolean
- isShowIncome?: boolean
- isShowSummary?: boolean
- period: Period
- series: unknown[]
- xAxisLabels: number[]
- }>(),
- {
- chartType: 'line',
- config: () => ({}),
- isShowExpense: true,
- isShowIncome: true,
- },
-)
+const {
+ chartType = 'line',
+ isShowDataLabels,
+ period,
+ series,
+ xAxisLabels,
+} = defineProps<{
+ chartType?: ChartType
+ isShowDataLabels?: boolean
+ isShowExpense?: boolean
+ isShowIncome?: boolean
+ isShowSummary?: boolean
+ period: Period
+ series: ChartSeries[]
+ xAxisLabels: number[]
+}>()
const emit = defineEmits<{
click: [idx: number]
@@ -70,19 +69,19 @@ function getFormatForChart(periodName: PeriodNameWithAll) {
const option = computed(() => {
const data = defu(config, {
- series: setChartSeries(props.series),
+ series: setChartSeries(series),
xAxis: {
- data: props.xAxisLabels,
+ data: xAxisLabels,
type: 'category',
},
})
data.xAxis.axisLabel.formatter = (date: string) => {
- return formatByLocale(new Date(+date), getFormatForChart(props.period, new Date(+date)), locale.value)
+ return formatByLocale(new Date(+date), getFormatForChart(period, new Date(+date)), locale.value)
}
data.xAxis.axisPointer.label.formatter = ({ value }: { value: string }) => {
- return formatByLocale(new Date(+value), getFormatForChart(props.period, new Date(+value)), locale.value)
+ return formatByLocale(new Date(+value), getFormatForChart(period, new Date(+value)), locale.value)
}
return data
@@ -97,16 +96,16 @@ async function onClickChart(params: { offsetX: number, offsetY: number }) {
emit('click', index)
}
-function setChartSeries(series: unknown[]) {
+function setChartSeries(series: ChartSeries[]) {
return series
- .map((item: any) => ({
+ .map((item: ChartSeries) => ({
...defu(lineConfig, item),
label: {
...lineConfig.label,
- show: props.isShowDataLabels,
+ show: isShowDataLabels,
},
- stack: (props.chartType || item.type) === 'bar' ? 'b' : false,
- type: item.markedArea ? 'bar' : (props.chartType || item.type),
+ stack: (chartType || item.type) === 'bar' ? 'b' : false,
+ type: item.markedArea ? 'bar' : (chartType || item.type),
}))
}
</script>
@@ -122,9 +121,9 @@ function setChartSeries(series: unknown[]) {
autoresize
>
<template #tooltip="params">
- <div class="rounded-md bg-[var(--item-5)] px-2 pt-2">
+ <div class="rounded-md bg-(--item-5) px-2 pt-2">
<div class="text-muted pb-2 text-xs">
- {{ formatByLocale(new Date(+params[0].name), getFormatForChart(props.period), locale) }}
+ {{ formatByLocale(new Date(+params[0].name), getFormatForChart(period), locale) }}
</div>
<div class="grid gap-0">
diff --git a/app/components/stat/chart/Wrap.vue b/app/components/stat/chart/Wrap.vue
index 32e3d820..e45171ad 100644
--- a/app/components/stat/chart/Wrap.vue
+++ b/app/components/stat/chart/Wrap.vue
@@ -1,8 +1,9 @@
<script setup lang="ts">
-import type { Period, StatDateProvider } from '~/components/date/types'
+import type { Period } from '~/components/date/types'
import type { ChartSeries } from '~/components/stat/types'
-import type { MiniItemConfig, StatConfigProvider } from '~/components/stat/useStatConfig'
+import type { MiniItemConfig } from '~/components/stat/useStatConfig'
+import { statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const props = defineProps<{
@@ -11,8 +12,8 @@ const props = defineProps<{
xAxisLabels: number[]
}>()
-const statDate = inject('statDate') as StatDateProvider
-const statConfig = inject('statConfig') as StatConfigProvider
+const statDate = inject(statDateKey)!
+const statConfig = inject(statConfigKey)!
const trnsFormStore = useTrnsFormStore()
function onClickChart(idx: number) {
@@ -60,7 +61,7 @@ function onChangePeriod(period: Period) {
:class="{ 'border-item-4 border-l': statConfig.config.value?.date.isShowQuick }"
:period="statDate.params.value.intervalsBy"
:range="statDate.range.value"
- @onChangePeriod="onChangePeriod"
+ @changePeriod="onChangePeriod"
/>
</div>
</div>
diff --git a/app/components/stat/chart/utils.ts b/app/components/stat/chart/utils.ts
index 75316f13..82a9f1d7 100644
--- a/app/components/stat/chart/utils.ts
+++ b/app/components/stat/chart/utils.ts
@@ -6,14 +6,12 @@ export function markArea(value: number) {
}
export function getCompactAmount(amount: number) {
- return Intl.NumberFormat('en', { notation: 'compact' }).format(amount)
+ return new Intl.NumberFormat('en', { notation: 'compact' }).format(amount)
}
export function getLocalAmount(amount: number) {
- return amount.toLocaleString('ru', {
- currency: 'RUB',
+ return new Intl.NumberFormat('ru', {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
- style: 'decimal',
- })
+ }).format(amount)
}
diff --git a/app/components/stat/date/Nav.vue b/app/components/stat/date/Nav.vue
index ac3dc8bc..49bfc905 100644
--- a/app/components/stat/date/Nav.vue
+++ b/app/components/stat/date/Nav.vue
@@ -1,14 +1,10 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-const props = withDefaults(defineProps<{
+const { isEnd, isShowNavHome, isStart, position = 'left' } = defineProps<{
isEnd: boolean
isShowNavHome: boolean
isStart: boolean
position?: 'left' | 'right'
-}>(), {
- position: 'left',
-})
+}>()
const emit = defineEmits<{
changeDate: [action: 'prev' | 'next' | 'today']
@@ -17,32 +13,32 @@ const emit = defineEmits<{
<template>
<div class="flex items-center gap-1">
- <UiItem3
- v-if="props.position === 'left' && props.isShowNavHome"
+ <UiActionButton
+ v-if="position === 'left' && isShowNavHome"
@click="emit('changeDate', 'today')"
>
<Icon name="lucide:undo-2" size="20" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- :class="[getStyles('item', ['bg2']), { '!hover:transparent opacity-30': isStart }]"
+ <UiActionButton
+ :class="cn('bg-item-3', isStart && 'hover:transparent opacity-30')"
@click="emit('changeDate', 'prev')"
>
<Icon name="lucide:chevron-left" size="24" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- :class="[getStyles('item', ['bg2']), { '!hover:transparent opacity-30': isEnd }]"
+ <UiActionButton
+ :class="cn('bg-item-3', isEnd && 'hover:transparent opacity-30')"
@click="emit('changeDate', 'next')"
>
<Icon name="lucide:chevron-left" size="24" class="rotate-180" />
- </UiItem3>
+ </UiActionButton>
- <UiItem3
- v-if="props.position === 'right' && props.isShowNavHome"
+ <UiActionButton
+ v-if="position === 'right' && isShowNavHome"
@click="emit('changeDate', 'today')"
>
<Icon name="lucide:undo-2" size="20" />
- </UiItem3>
+ </UiActionButton>
</div>
</template>
diff --git a/app/components/stat/date/Navigation.vue b/app/components/stat/date/Navigation.vue
index 088acae9..b1c4d49d 100644
--- a/app/components/stat/date/Navigation.vue
+++ b/app/components/stat/date/Navigation.vue
@@ -1,12 +1,11 @@
<script setup lang="ts">
import { sub } from 'date-fns'
-import type { StatDateProvider } from '~/components/date/types'
-
import { getEndOf, getStartOf } from '~/components/date/utils'
+import { statDateKey } from '~/components/stat/injectionKeys'
const { t } = useI18n()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const isShowNav = computed(() =>
!statDate.params.value.isShowMaxRange
@@ -77,22 +76,22 @@ function changeDate(way: 'next' | 'prev' | 'today') {
:isOpen="statDate.modals.value.dateSelector"
class="flex grow-0 gap-1"
isShowCloseBtn
- @onOpenModal="statDate.modals.value.dateSelector = true"
- @onCloseModal="statDate.modals.value.dateSelector = false"
+ @openModal="statDate.modals.value.dateSelector = true"
+ @closeModal="statDate.modals.value.dateSelector = false"
>
<template #trigger>
- <UiTitle8
+ <UiTitleCollapse
class="_bg-item-4 text-md !grow-0"
isShown
>
<StatDateRange />
- </UiTitle8>
+ </UiTitleCollapse>
</template>
<template #content="{ close }">
<StatDateSelector
class="min-w-[362px] pb-2 md:px-3"
- @onClose="close"
+ @close="close"
/>
</template>
</BottomSheetOrDropdown>
diff --git a/app/components/stat/date/Quick.vue b/app/components/stat/date/Quick.vue
index 6b53bfe2..dbd674f6 100644
--- a/app/components/stat/date/Quick.vue
+++ b/app/components/stat/date/Quick.vue
@@ -2,13 +2,13 @@
import Swiper from 'swiper'
import 'swiper/css'
-import type { StatDateProvider } from '~/components/date/types'
+import { statDateKey } from '~/components/stat/injectionKeys'
const emit = defineEmits<{
- onClose: []
+ close: []
}>()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const sliderRef = ref<any>(null)
const sliderObj = ref<any>(null)
@@ -39,7 +39,7 @@ onMounted(() => {
:itemProps="{ variant: 'small' }"
:statDate
view="periods"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
</div>
@@ -48,7 +48,7 @@ onMounted(() => {
:itemProps="{ variant: 'small' }"
:statDate
view="presets"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
</div>
@@ -57,7 +57,7 @@ onMounted(() => {
:itemProps="{ variant: 'small' }"
:statDate
view="maximum"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
</div>
</div>
diff --git a/app/components/stat/date/Range.vue b/app/components/stat/date/Range.vue
index 649dbc3e..fa516df4 100644
--- a/app/components/stat/date/Range.vue
+++ b/app/components/stat/date/Range.vue
@@ -1,9 +1,10 @@
<script setup lang="ts">
-import type { Range, StatDateProvider } from '~/components/date/types'
+import type { Range } from '~/components/date/types'
import { useGetDateRange } from '~/components/stat/date/useGetDateRange'
+import { statDateKey } from '~/components/stat/injectionKeys'
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const { locale, t } = useI18n()
const { getStringDateRange } = useGetDateRange(t, locale.value)
diff --git a/app/components/stat/date/Selector.vue b/app/components/stat/date/Selector.vue
index a4004e8c..03f30d03 100644
--- a/app/components/stat/date/Selector.vue
+++ b/app/components/stat/date/Selector.vue
@@ -1,14 +1,15 @@
<script setup lang="ts">
-import type { Grouped, Range, StatDateProvider } from '~/components/date/types'
+import type { Grouped, Range } from '~/components/date/types'
import { getUCalendarToday, parseUCalendarDate } from '~/components/date/utils'
+import { statDateKey } from '~/components/stat/injectionKeys'
const emit = defineEmits<{
- onClose: []
+ close: []
}>()
const { t } = useI18n()
-const statDate = inject('statDate') as StatDateProvider
+const statDate = inject(statDateKey)!
const tabs = {
items: ref(['presets', 'calendar']),
@@ -45,14 +46,14 @@ function onSelectRange(value: unknown) {
} as Range
statDate.setRangeByCalendar(range)
- emit('onClose')
+ emit('close')
}
</script>
<template>
<div>
- <UiTabs1 class="mb-2">
- <UiTabsItem1
+ <UiTabsBar class="mb-2">
+ <UiTabsItemFill
v-for="tab in tabs.items.value"
:key="tab"
:title="t(tab)"
@@ -60,8 +61,8 @@ function onSelectRange(value: unknown) {
@click="tabs.selected.value = tab"
>
{{ t(`dates.calendar.${tab}`) }}
- </UiTabsItem1>
- </UiTabs1>
+ </UiTabsItemFill>
+ </UiTabsBar>
<div
v-if="tabs.selected.value === 'presets'"
@@ -73,14 +74,14 @@ function onSelectRange(value: unknown) {
:statDate
isShowRangeAdjust
view="periods"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
<div class="flex flex-wrap gap-1">
<DateRanges
:statDate
view="presets"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
</div>
@@ -88,16 +89,16 @@ function onSelectRange(value: unknown) {
<DateRanges
:statDate
view="maximum"
- @onClose="emit('onClose')"
+ @close="emit('close')"
/>
</div>
</div>
<!-- Grouped by -->
<div class="grid gap-3">
- <UiTitleOption class="px-1">
+ <UiTitleSection size="sm" class="px-1">
{{ t('dates.calendar.intervalsGrouped') }}
- </UiTitleOption>
+ </UiTitleSection>
<div class="grid gap-2">
<div class="flex flex-wrap gap-1">
diff --git a/app/components/stat/date/useGetDateRange.test.ts b/app/components/stat/date/useGetDateRange.test.ts
index f2c32132..f36b865f 100644
--- a/app/components/stat/date/useGetDateRange.test.ts
+++ b/app/components/stat/date/useGetDateRange.test.ts
@@ -1,5 +1,5 @@
import { addMonths, endOfDay, endOfMonth, endOfWeek, endOfYear, startOfDay, startOfMonth, startOfWeek, startOfYear } from 'date-fns'
-import { describe, expect, it } from 'vitest'
+import { afterAll, describe, expect, it, vi } from 'vitest'
import { useGetDateRange } from '~/components/stat/date/useGetDateRange'
@@ -23,9 +23,20 @@ function t(key: string) {
return translations[key] || key
}
+// Fix "today" to June 15 2025 so tests don't depend on the current date
+const fixedDate = new Date('2025-06-15T12:00:00')
+
+// Must set fake timers before useGetDateRange captures `new Date()` internally
+vi.useFakeTimers()
+vi.setSystemTime(fixedDate)
+
describe('useGetDateRange', () => {
const { getStringDateRange } = useGetDateRange(t)
- const today = new Date()
+ const today = fixedDate
+
+ afterAll(() => {
+ vi.useRealTimers()
+ })
describe('year ranges', () => {
it('should format current year', () => {
@@ -33,7 +44,7 @@ describe('useGetDateRange', () => {
end: endOfYear(today).getTime(),
start: startOfYear(today).getTime(),
}
- expect(getStringDateRange(range, 'year', 1)).toBe(today.getFullYear().toString())
+ expect(getStringDateRange(range, 'year', 1)).toBe('2025')
})
it('should format year range', () => {
diff --git a/app/components/stat/date/useGetDateRange.ts b/app/components/stat/date/useGetDateRange.ts
index 6797d34c..78bef59c 100644
--- a/app/components/stat/date/useGetDateRange.ts
+++ b/app/components/stat/date/useGetDateRange.ts
@@ -119,7 +119,7 @@ export function useGetDateRange(t: (key: string, choice?: number) => string, loc
// Special case for single day in current year/month
if (by === 'day' && isSameYear(start, today)) {
- return type === 'start' ? formatByLocale(start, 'd MMMM') : ''
+ return type === 'start' ? formatByLocale(start, 'd MMMM', locale) : ''
}
}
@@ -162,7 +162,7 @@ export function useGetDateRange(t: (key: string, choice?: number) => string, loc
const { by, duration, start, type } = params
if (duration === 1 && by === 'day' && isSameYear(start, today)) {
- return type === 'start' ? formatByLocale(start, 'd MMMM') : ''
+ return type === 'start' ? formatByLocale(start, 'd MMMM', locale) : ''
}
switch (by) {
diff --git a/app/components/stat/filter/Selected.vue b/app/components/stat/filter/Selected.vue
index f5154659..60b217e9 100644
--- a/app/components/stat/filter/Selected.vue
+++ b/app/components/stat/filter/Selected.vue
@@ -1,8 +1,6 @@
<script setup lang="ts">
-import type { FilterProvider } from '~/components/stat/filter/types'
-
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { getStyles } from '~/components/ui/getStyles'
+import { filterKey } from '~/components/stat/injectionKeys'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const props = defineProps<{
@@ -10,10 +8,10 @@ const props = defineProps<{
isShowWallets?: boolean
}>()
-const filter = inject('filter') as FilterProvider
+const filter = inject(filterKey)!
const walletsStore = useWalletsStore()
const categoriesStore = useCategoriesStore()
-const itemClasses = getStyles('item', ['alt', 'rounded'])
+const itemClasses = 'bg-item-3 rounded-sm'
</script>
<template>
diff --git a/app/components/stat/filter/Selector.vue b/app/components/stat/filter/Selector.vue
index ba8122b0..80d87484 100644
--- a/app/components/stat/filter/Selector.vue
+++ b/app/components/stat/filter/Selector.vue
@@ -1,12 +1,12 @@
<script setup lang="ts">
-import type { FilterProvider } from '~/components/stat/filter/types'
+import { filterKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
isShowCategories?: boolean
isShowWallets?: boolean
}>()
-const filter = inject('filter') as FilterProvider
+const filter = inject(filterKey)!
const { t } = useI18n()
const modals = ref({
@@ -22,8 +22,8 @@ const modals = ref({
:title="t('wallets.filter')"
:isOpen="modals.wallets"
isShowCloseBtn
- @onOpenModal="modals.wallets = true"
- @onCloseModal="modals.wallets = false"
+ @openModal="modals.wallets = true"
+ @closeModal="modals.wallets = false"
>
<template #trigger>
<UTooltip :text="t('wallets.filter')">
@@ -51,7 +51,7 @@ const modals = ref({
<WalletsSelector
:selectedIds="filter?.walletsIds.value"
class="min-w-80 px-3"
- @onSelected="filter.toggleWalletId"
+ @selected="filter.toggleWalletId"
/>
<div class="px-3 py-2">
@@ -68,8 +68,8 @@ const modals = ref({
:title="t('categories.filter')"
:isOpen="modals.categories"
isShowCloseBtn
- @onOpenModal="modals.categories = true"
- @onCloseModal="modals.categories = false"
+ @openModal="modals.categories = true"
+ @closeModal="modals.categories = false"
>
<template #trigger>
<UTooltip :text="t('categories.filter')">
@@ -95,11 +95,11 @@ const modals = ref({
<template #custom="{ close }">
<div class="grid h-full max-h-[60dvh] grid-rows-[1fr_auto] overflow-hidden">
<div class="scrollerBlock overflow-y-auto">
- <CategoriesSelector
+ <CategoriesSelectorTree
:selectedIds="filter?.categoriesIds.value"
class="min-w-80 px-3"
@filter="filter.toggleCategoryId"
- @onSelected="filter.toggleCategoryId"
+ @selected="filter.toggleCategoryId"
@setCategories="filter.setCategories"
/>
</div>
diff --git a/app/components/stat/filter/types.ts b/app/components/stat/filter/types.ts
index a6bbbb11..9f841e2e 100644
--- a/app/components/stat/filter/types.ts
+++ b/app/components/stat/filter/types.ts
@@ -1,12 +1,12 @@
import type { useFilter } from '~/components/stat/filter/useFilter'
-export type PeriodSchema = {
+type PeriodSchema = {
date: number
showedPeriods: number
type: 'line' | 'bar'
}
-export type Periods = {
+type Periods = {
day: PeriodSchema
month: PeriodSchema
week: PeriodSchema
diff --git a/app/components/stat/filter/useFilter.ts b/app/components/stat/filter/useFilter.ts
index 778a7965..44655e93 100644
--- a/app/components/stat/filter/useFilter.ts
+++ b/app/components/stat/filter/useFilter.ts
@@ -45,7 +45,7 @@ export function useFilter() {
router.push({
query: {
...route.query,
- filterWallets: [...new Set([...walletsIds.value, ...newWalletsIds])],
+ filterWallets: [...new Set(walletsIds.value.concat(newWalletsIds))],
},
})
}
@@ -85,7 +85,7 @@ export function useFilter() {
router.push({
query: {
...route.query,
- filterCategories: [...new Set([...categoriesIds.value, ...newCategoriesIds])],
+ filterCategories: [...new Set(categoriesIds.value.concat(newCategoriesIds))],
},
})
}
@@ -94,7 +94,7 @@ export function useFilter() {
router.push({
query: {
...route.query,
- filterCategories: [...new Set([...newCategoriesIds])],
+ filterCategories: newCategoriesIds,
},
})
}
diff --git a/app/components/stat/injectionKeys.ts b/app/components/stat/injectionKeys.ts
new file mode 100644
index 00000000..7d8cf480
--- /dev/null
+++ b/app/components/stat/injectionKeys.ts
@@ -0,0 +1,9 @@
+import type { InjectionKey } from 'vue'
+
+import type { StatDateProvider } from '~/components/date/types'
+import type { FilterProvider } from '~/components/stat/filter/types'
+import type { StatConfigProvider } from '~/components/stat/useStatConfig'
+
+export const filterKey: InjectionKey<FilterProvider> = Symbol('filter')
+export const statDateKey: InjectionKey<StatDateProvider> = Symbol('statDate')
+export const statConfigKey: InjectionKey<StatConfigProvider> = Symbol('statConfig')
diff --git a/app/components/stat/sum/Item.vue b/app/components/stat/sum/Item.vue
index f65dae85..d915de46 100644
--- a/app/components/stat/sum/Item.vue
+++ b/app/components/stat/sum/Item.vue
@@ -25,22 +25,21 @@ const currenciesStore = useCurrenciesStore()
<template>
<div
- class="flex-1 grow flex-wrap rounded-sm border border-transparent bg-[var(--item-3)] px-2 py-2 @2xl/page:max-w-max @2xl/page:px-4 @2xl/page:py-2"
- :class="{
- '!bg-item-2 !border-(--ui-primary)/40': props.isActive,
- }"
+ :class="cn('flex-1 flex-wrap rounded-sm border border-transparent bg-(--item-3) px-2 py-2 @2xl/page:max-w-max @2xl/page:px-4 @2xl/page:py-2',
+ props.isActive && 'bg-item-2 border-(--ui-primary)/40',
+ )"
@click="(e: Event) => emit('click', e)"
>
<div class="flex items-end gap-5">
<div class="grid gap-1">
- <UiTitle6 v-if="props.title">
+ <UiTextSubtitle v-if="props.title">
{{ props.title }}
- </UiTitle6>
+ </UiTextSubtitle>
- <UiTitle6 v-if="!props.title">
+ <UiTextSubtitle v-if="!props.title">
{{ props.isTotal ? t('money.all') : '' }}
{{ t(`money.${props.type}`) }}
- </UiTitle6>
+ </UiTextSubtitle>
<Amount
:amount="props.amount"
@@ -66,7 +65,7 @@ const currenciesStore = useCurrenciesStore()
:key="averageItem"
class="grid gap-1 pb-[2px]"
>
- <UiTitle6>{{ t('money.average') }} <br> {{ t(`dates.${slug}.simple`) }}</UiTitle6>
+ <UiTextSubtitle>{{ t('money.average') }} <br> {{ t(`dates.${slug}.simple`) }}</UiTextSubtitle>
<Amount
:amount="type === 'expense' ? -averageItem : averageItem"
diff --git a/app/components/stat/sum/ItemWallet.vue b/app/components/stat/sum/ItemWallet.vue
index 64e04ff8..64132c3f 100644
--- a/app/components/stat/sum/ItemWallet.vue
+++ b/app/components/stat/sum/ItemWallet.vue
@@ -1,6 +1,5 @@
<script setup lang="ts">
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
-import { getStyles } from '~/components/ui/getStyles'
const props = defineProps<{
amount: number
@@ -18,11 +17,10 @@ const currenciesStore = useCurrenciesStore()
<template>
<div
- :class="[getStyles('item', ['center', 'minh1', 'minw1'])]"
- class="grid grow-0 gap-1 py-1 lg:gap-1"
+ class="flex grid min-h-[42px] min-w-[42px] grow-0 items-center gap-1 py-1 lg:gap-1"
@click="(e: Event) => emit('click', e)"
>
- <UiTitle6>{{ props.title }}</UiTitle6>
+ <UiTextSubtitle>{{ props.title }}</UiTextSubtitle>
<Amount
:amount="props.amount"
diff --git a/app/components/stat/sum/Wrap.vue b/app/components/stat/sum/Wrap.vue
index b8d0b489..815c92b0 100644
--- a/app/components/stat/sum/Wrap.vue
+++ b/app/components/stat/sum/Wrap.vue
@@ -1,16 +1,11 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
import type { TotalReturns } from '~/components/amount/getTotal'
import type { CategoryId } from '~/components/categories/types'
-import type { StatDateProvider } from '~/components/date/types'
-import type { FilterProvider } from '~/components/stat/filter/types'
import type { SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
-import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
-import { classes } from '~/components/ui/getStyles'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
averageTotal?: Record<string, number>
@@ -31,17 +26,16 @@ const emit = defineEmits<{
clickAverage: []
}>()
-const statConfig = inject('statConfig') as StatConfigProvider
-const filter = inject('filter') as FilterProvider
-const statDate = inject('statDate') as StatDateProvider
+const statConfig = inject(statConfigKey)!
+const filter = inject(filterKey)!
+const statDate = inject(statDateKey)!
-const className = computed(() => cn([
- 'min-w-min',
- [classes.item.rounded, classes.item.minh1, classes.item.center, classes.item.padding3],
+const className = computed(() => cn(
+ 'min-w-min rounded-sm min-h-[42px] flex items-center px-3',
{
- [classes.item.link]: props.isShowIncome && props.isShowExpense && props.type === 'summary',
+ interactive: props.isShowIncome && props.isShowExpense && props.type === 'summary',
},
-]))
+))
function onClick(type: SeriesSlugSelected) {
if (props.isShowIncome && props.isShowExpense) {
diff --git a/app/components/stat/types.ts b/app/components/stat/types.ts
index b077e698..5c4c39c8 100644
--- a/app/components/stat/types.ts
+++ b/app/components/stat/types.ts
@@ -8,14 +8,9 @@ export type MoneyTypeSlug = 'expense' | 'income'
export type StatTabSlug = 'income' | 'expense' | 'summary' | 'split'
export type SeriesSlug = 'income' | 'expense'
export type SeriesSlugSelected = 'income' | 'expense' | 'netIncome'
-export type MoneyTypeNumber = 0 | 1 | 3
+export type MoneyTypeNumber = 0 | 1 | 2
-export type TotalCategories = {
- expense: CategoryWithData[]
- income: CategoryWithData[]
-}
-
-export type CategoryWithDataBase = {
+type CategoryWithDataBase = {
id: CategoryId
name: CategoryItem['name']
trnsIds: TrnId[]
@@ -28,12 +23,13 @@ export type CategoryWithData = CategoryWithDataBase & {
export type CategoriesWithData = Record<CategoryId, CategoryWithData>
-export type CategoriesWithTrns = Record<CategoryId, TrnId[]>
-
export type ChartSeries = {
color?: string
data: number[]
- markArea?: any
+ markArea?: {
+ data: [{ xAxis: string }, { xAxis: string }][]
+ itemStyle: { color: string, opacity: number }
+ }
markedArea?: 'markedArea'
markLine?: Record<string, unknown>
name: string
diff --git a/app/components/stat/useStatItem.ts b/app/components/stat/useStatItem.ts
new file mode 100644
index 00000000..dea02c34
--- /dev/null
+++ b/app/components/stat/useStatItem.ts
@@ -0,0 +1,223 @@
+import type { ComputedRef } from 'vue'
+
+import { useStorage } from '@vueuse/core'
+import { differenceInDays, differenceInMonths, differenceInWeeks } from 'date-fns'
+
+import type { CategoryId } from '~/components/categories/types'
+import type { Range, StatDateProvider } from '~/components/date/types'
+import type { FilterProvider } from '~/components/stat/filter/types'
+import type { ChartSeries, IntervalData, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
+import type { StatConfigProvider } from '~/components/stat/useStatConfig'
+import type { TrnId } from '~/components/trns/types'
+
+import { useAmount } from '~/components/amount/useAmount'
+import { useStatChart } from '~/components/stat/chart/useStatChart'
+import { getTypesMapping } from '~/components/stat/utils'
+import { useTrnsStore } from '~/components/trns/useTrnsStore'
+
+type UseStatItemParams = {
+ filter: FilterProvider
+ statConfig: StatConfigProvider
+ statDate: StatDateProvider
+ statTab: ComputedRef<StatTabSlug>
+ storageKey: ComputedRef<string>
+ trnsIds: ComputedRef<TrnId[]>
+ type: ComputedRef<SeriesSlugSelected | undefined>
+}
+
+export function useStatItem({
+ filter,
+ statConfig,
+ statDate,
+ statTab,
+ storageKey,
+ trnsIds,
+ type,
+}: UseStatItemParams) {
+ const trnsStore = useTrnsStore()
+ const { getTotalOfTrnsIds } = useAmount()
+ const { addMarkArea, createSeriesItem } = useStatChart()
+
+ const newBaseStorageKey = computed(() =>
+ `finapp-${statDate.params.value.intervalsBy}-${storageKey.value}-${JSON.stringify(filter?.categoriesIds?.value)}`,
+ )
+
+ const filteredType = useStorage<SeriesSlugSelected>(
+ `finapp-filtered-type-${type.value}-${newBaseStorageKey.value}`,
+ 'netIncome',
+ )
+
+ const filteredCategoriesIds = ref<CategoryId[]>([])
+
+ const selectedType = computed(() => {
+ if (statTab.value === 'summary')
+ return filteredType.value
+ if (statTab.value === 'split')
+ return type.value
+ return statTab.value
+ })
+
+ const selectedTypeForSum = computed(() => {
+ if (statTab.value === 'summary')
+ return 'summary'
+ if (statTab.value === 'split')
+ return type.value
+ return statTab.value
+ })
+
+ const selectedTypesMapping = computed(() => getTypesMapping(selectedType.value))
+
+ const isPeriodOneDay = computed(() =>
+ (statDate.params.value.rangeBy === 'day' && statDate.params.value.rangeDuration === 1)
+ || (statDate.params.value.intervalsBy === 'day' && statDate.params.value.intervalSelected !== -1),
+ )
+
+ const rangeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
+ trnsIds: trnsIds.value,
+ }, { includesChildCategories: false }))
+
+ const rangeTrnsIdsWithFilteredCategories = computed(() => trnsStore.getStoreTrnsIds({
+ categoriesIds: filteredCategoriesIds.value,
+ trnsIds: trnsIds.value,
+ }, { includesChildCategories: true }))
+
+ function getIntervalsData(ids: TrnId[], intervalsInRange: Range[]) {
+ return intervalsInRange.reduce((acc, range) => {
+ const trnsIdsInRange = ids.filter((id) => {
+ const trnDate = trnsStore.items?.[id]?.date
+ return trnDate != null && trnDate >= range.start && trnDate <= range.end
+ })
+
+ acc.push({
+ range,
+ total: getTotalOfTrnsIds(trnsIdsInRange),
+ trnsIds: trnsIdsInRange,
+ })
+
+ return acc
+ }, [] as IntervalData[])
+ }
+
+ const intervalsData = computed(() => getIntervalsData(rangeTrnsIds.value, statDate.intervalsInRange.value))
+ const intervalsDataWithFilteredCategories = computed(() => getIntervalsData(rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value))
+
+ const selectedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
+ trnsIds: statDate.params.value.intervalSelected !== -1
+ ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
+ : rangeTrnsIds.value,
+ trnsTypes: selectedTypesMapping.value,
+ }, { includesChildCategories: false }))
+
+ const selectedAndFilteredTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
+ categoriesIds: filteredCategoriesIds.value,
+ trnsIds: statDate.params.value.intervalSelected !== -1
+ ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
+ : rangeTrnsIds.value,
+ trnsTypes: selectedTypesMapping.value,
+ }, { includesChildCategories: true }))
+
+ const rangeTotal = computed(() => {
+ const ids = statDate.params.value.intervalSelected !== -1
+ ? intervalsDataWithFilteredCategories.value[statDate.params.value.intervalSelected]?.trnsIds
+ : rangeTrnsIdsWithFilteredCategories.value
+ return getTotalOfTrnsIds(ids)
+ })
+
+ const averageTotal = computed(() => {
+ if (differenceInDays(statDate.range.value.end, statDate.range.value.start) < 2)
+ return
+
+ const sum = filteredType.value === 'netIncome' ? rangeTotal.value.sum : rangeTotal.value[type.value]
+
+ const date = statDate.params.value.intervalSelected !== -1
+ ? statDate.selectedInterval.value
+ : statDate.range.value
+
+ const dif = {
+ day: differenceInDays(date?.end, date?.start) + 1,
+ month: differenceInMonths(date?.end, date?.start) + 1,
+ week: differenceInWeeks(date?.end, date?.start) + 1,
+ }
+
+ const items = {
+ month: 0,
+ week: 0,
+ // eslint-disable-next-line perfectionist/sort-objects
+ day: 0,
+ }
+
+ if (dif.month > 1)
+ items.month = sum / dif.month
+ if (dif.day > 1)
+ items.day = sum / dif.day
+ if (dif.week > 1)
+ items.week = sum / dif.week
+
+ return Object.fromEntries(Object.entries(items).filter(([_, value]) => value !== 0))
+ })
+
+ const typesToShow = computed(() => {
+ if (statTab.value === 'summary') {
+ if (filteredType.value === 'netIncome')
+ return ['income', 'expense']
+ if (filteredType.value === 'income')
+ return ['income']
+ if (filteredType.value === 'expense')
+ return ['expense']
+ }
+
+ if (statTab.value === 'expense' || statTab.value === 'income')
+ return [statTab.value]
+
+ return [type.value]
+ })
+
+ const chartSeries = computed<ChartSeries[]>(() => {
+ const intervalTotals = intervalsDataWithFilteredCategories.value.map(g => g.total)
+ const baseSeries = typesToShow.value.map(t =>
+ createSeriesItem(
+ t,
+ intervalTotals,
+ statConfig.config.value.chart.isShowAverage
+ ? intervalsDataWithFilteredCategories.value.reduce((acc, i) => acc + i.total[t], 0) / intervalsData.value.length
+ : false,
+ ),
+ )
+
+ const selectedInterval = intervalsDataWithFilteredCategories.value?.[statDate.params.value.intervalSelected]
+ if (!selectedInterval?.range.start || statDate.params.value.intervalSelected < 0)
+ return baseSeries
+
+ return addMarkArea(baseSeries, selectedInterval.range.start, statConfig.config.value?.chartType)
+ })
+
+ const chartXAxisLabels = computed(() =>
+ intervalsDataWithFilteredCategories.value.map(i => +i.range.start),
+ )
+
+ function onSetCategoryFilter(categoryId: CategoryId) {
+ if (filteredCategoriesIds.value.includes(categoryId))
+ return filteredCategoriesIds.value = []
+ filteredCategoriesIds.value = [categoryId]
+ }
+
+ function onClickSumItem(clickedType: SeriesSlugSelected) {
+ filteredType.value = clickedType === filteredType.value ? 'netIncome' : clickedType
+ }
+
+ return {
+ averageTotal,
+ chartSeries,
+ chartXAxisLabels,
+ filteredCategoriesIds,
+ filteredType,
+ isPeriodOneDay,
+ newBaseStorageKey,
+ onClickSumItem,
+ onSetCategoryFilter,
+ rangeTotal,
+ selectedAndFilteredTrnsIds,
+ selectedTrnsIds,
+ selectedTypeForSum,
+ }
+}
diff --git a/app/components/stat/utils.ts b/app/components/stat/utils.ts
index 8ba8f651..8a987c29 100644
--- a/app/components/stat/utils.ts
+++ b/app/components/stat/utils.ts
@@ -1,5 +1,6 @@
import type { CategoryWithData, StatTabSlug } from '~/components/stat/types'
-import type { TrnType } from '~/components/trns/types'
+
+import { TrnType } from '~/components/trns/types'
export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData) {
if (!a || !b)
@@ -22,12 +23,11 @@ export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData)
export function getTypesMapping(slug: StatTabSlug): TrnType[] | undefined {
const typeMapping: Record<StatTabSlug, TrnType[]> = {
- expense: [0, 2],
- income: [1, 2],
- split: [0, 1, 2],
- summary: [0, 1, 2],
+ expense: [TrnType.Expense, TrnType.Transfer],
+ income: [TrnType.Income, TrnType.Transfer],
+ split: [TrnType.Expense, TrnType.Income, TrnType.Transfer],
+ summary: [TrnType.Expense, TrnType.Income, TrnType.Transfer],
}
- const trnsTypes = typeMapping[slug]
- return trnsTypes ?? [0, 1, 2]
+ return typeMapping[slug] ?? [TrnType.Expense, TrnType.Income, TrnType.Transfer]
}
diff --git a/app/components/theme/Picker.vue b/app/components/theme/Picker.vue
index 00ba3f4c..efabb813 100644
--- a/app/components/theme/Picker.vue
+++ b/app/components/theme/Picker.vue
@@ -2,6 +2,10 @@
import { omit } from '#ui/utils'
import colors from 'tailwindcss/colors'
+const props = defineProps<{
+ inline?: boolean
+}>()
+
const appConfig = useAppConfig()
const colorMode = useColorMode()
const { t } = useI18n()
@@ -17,7 +21,7 @@ const neutral = computed({
})
const colorsToOmit = ['inherit', 'current', 'transparent', 'black', 'white', ...neutralColors]
-const primaryColors = Object.keys(omit(colors, colorsToOmit as any))
+const primaryColors = Object.keys(omit(colors, colorsToOmit as (keyof typeof colors)[]))
const primary = computed({
get() {
return appConfig.ui.colors.primary
@@ -58,10 +62,149 @@ function setBlackAsPrimary(value: boolean) {
appConfig.theme.blackAsPrimary = value
window.localStorage.setItem('nuxt-ui-black-as-primary', String(value))
}
+
+const currentPrimaryLabel = computed(() => {
+ if (appConfig.theme.blackAsPrimary)
+ return 'Black'
+ return primary.value
+})
+
+const openMode = ref(false)
+const openPrimary = ref(false)
+const openNeutral = ref(false)
+const openRadius = ref(false)
</script>
<template>
+ <!-- Inline mode: collapsible items -->
+ <div
+ v-if="props.inline"
+ class="border-item-6 overflow-hidden rounded-lg border"
+ >
+ <div class="px-4 pt-4 pb-2 text-lg font-semibold">
+ {{ t('theme.title') }}
+ </div>
+ <!-- Theme mode -->
+ <UCollapsible v-model:open="openMode" class="border-item-6 border-b">
+ <button class="flex w-full cursor-pointer items-center gap-2 px-4 py-3 text-left text-sm font-semibold">
+ {{ t('theme.picker.theme') }}
+ <span class="text-muted text-xs font-normal capitalize">{{ colorMode.preference }}</span>
+ <UIcon name="i-lucide-chevron-down" :class="cn('text-muted ml-auto size-4 transition-transform', openMode && 'rotate-180')" />
+ </button>
+
+ <template #content>
+ <div class="grid grid-cols-3 gap-1 px-4 pb-4">
+ <ThemePickerButton
+ v-for="m in modes"
+ :key="m.label"
+ v-bind="m"
+ :selected="colorMode.preference === m.label"
+ @click="mode = m.label"
+ />
+ </div>
+ </template>
+ </UCollapsible>
+
+ <!-- Primary color -->
+ <UCollapsible v-model:open="openPrimary" class="border-item-6 border-b">
+ <button class="flex w-full cursor-pointer items-center gap-2 px-4 py-3 text-left text-sm font-semibold">
+ <span
+ v-if="appConfig.theme.blackAsPrimary"
+ class="inline-block size-2 rounded-full bg-black dark:bg-white"
+ />
+ <span
+ v-else
+ class="inline-block size-2 rounded-full bg-(--color-light) dark:bg-(--color-dark)"
+ :style="{
+ '--color-light': `var(--color-${primary}-500)`,
+ '--color-dark': `var(--color-${primary}-400)`,
+ }"
+ />
+ {{ t('theme.picker.primary') }}
+ <span class="text-muted text-xs font-normal capitalize">{{ currentPrimaryLabel }}</span>
+ <UIcon name="i-lucide-chevron-down" :class="cn('text-muted ml-auto size-4 transition-transform', openPrimary && 'rotate-180')" />
+ </button>
+
+ <template #content>
+ <div class="grid grid-cols-3 gap-1 px-4 pb-4">
+ <ThemePickerButton
+ chip="primary"
+ label="Black"
+ :selected="appConfig.theme.blackAsPrimary"
+ @click="setBlackAsPrimary(true)"
+ >
+ <template #leading>
+ <span class="inline-block h-2 w-2 rounded-full bg-black dark:bg-white" />
+ </template>
+ </ThemePickerButton>
+
+ <ThemePickerButton
+ v-for="color in primaryColors"
+ :key="color"
+ :label="color"
+ :chip="color"
+ :selected="!appConfig.theme.blackAsPrimary && primary === color"
+ @click="primary = color"
+ />
+ </div>
+ </template>
+ </UCollapsible>
+
+ <!-- Neutral color -->
+ <UCollapsible v-model:open="openNeutral" class="border-item-6 border-b">
+ <button class="flex w-full cursor-pointer items-center gap-2 px-4 py-3 text-left text-sm font-semibold">
+ <span
+ class="inline-block size-2 rounded-full bg-(--color-light) dark:bg-(--color-dark)"
+ :style="{
+ '--color-light': `var(--color-${neutral}-500)`,
+ '--color-dark': `var(--color-${neutral}-400)`,
+ }"
+ />
+ {{ t('theme.picker.neutral') }}
+ <span class="text-muted text-xs font-normal capitalize">{{ neutral }}</span>
+ <UIcon name="i-lucide-chevron-down" :class="cn('text-muted ml-auto size-4 transition-transform', openNeutral && 'rotate-180')" />
+ </button>
+
+ <template #content>
+ <div class="grid grid-cols-3 gap-1 px-4 pb-4">
+ <ThemePickerButton
+ v-for="color in neutralColors"
+ :key="color"
+ :label="color"
+ :chip="color"
+ :selected="neutral === color"
+ @click="neutral = color"
+ />
+ </div>
+ </template>
+ </UCollapsible>
+
+ <!-- Radius -->
+ <UCollapsible v-model:open="openRadius">
+ <button class="flex w-full cursor-pointer items-center gap-2 px-4 py-3 text-left text-sm font-semibold">
+ {{ t('theme.picker.radius') }}
+ <span class="text-muted text-xs font-normal">{{ radius }}</span>
+ <UIcon name="i-lucide-chevron-down" :class="cn('text-muted ml-auto size-4 transition-transform', openRadius && 'rotate-180')" />
+ </button>
+
+ <template #content>
+ <div class="grid grid-cols-5 gap-1 px-4 pb-4">
+ <ThemePickerButton
+ v-for="r in radiuses"
+ :key="r"
+ :label="String(r)"
+ class="justify-center px-0"
+ :selected="radius === r"
+ @click="radius = r"
+ />
+ </div>
+ </template>
+ </UCollapsible>
+ </div>
+
+ <!-- Popover mode: button with popover -->
<UPopover
+ v-else
:ui="{ content: 'w-72 px-6 py-4 flex flex-col gap-4' }"
>
<template #default="{ open }">
diff --git a/app/components/theme/Switcher.vue b/app/components/theme/Switcher.vue
index 21c6b7ec..4121bb00 100644
--- a/app/components/theme/Switcher.vue
+++ b/app/components/theme/Switcher.vue
@@ -15,11 +15,11 @@ const { options, preference, setTheme } = useTheme()
<template>
<div>
<template v-if="props.isShowTitle">
- <UiTitle3
+ <UiTitleSection
class="pb-2"
>
{{ t('theme.title') }}
- </UiTitle3>
+ </UiTitleSection>
<FormSelect
:options
diff --git a/app/components/theme/SwitcherTabs.vue b/app/components/theme/SwitcherTabs.vue
index 428a2276..bb124a0f 100644
--- a/app/components/theme/SwitcherTabs.vue
+++ b/app/components/theme/SwitcherTabs.vue
@@ -5,14 +5,15 @@ const { options, preference, setTheme } = useTheme()
</script>
<template>
- <UiTabs2>
- <UiTabsItem4
+ <UiTabsScroll>
+ <UiTabsItemPill
v-for="theme in options"
:key="theme.value"
+ variant="outline"
:isActive="preference === theme.value"
@click="setTheme(theme.value)"
>
{{ theme.label }}
- </UiTabsItem4>
- </UiTabs2>
+ </UiTabsItemPill>
+ </UiTabsScroll>
</template>
diff --git a/app/components/trnForm/Bottom.vue b/app/components/trnForm/Bottom.vue
index db5ae80b..bd8aabcc 100644
--- a/app/components/trnForm/Bottom.vue
+++ b/app/components/trnForm/Bottom.vue
@@ -75,7 +75,7 @@ onMounted(init)
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<div class="trnForm bg-default @container/trnForm">
@@ -113,7 +113,7 @@ onMounted(init)
<div class="grid gap-4 pb-4">
<TrnFormSelectionWalletsFast />
<TrnFormSelectionCategoriesFast
- @onSelectCategory="id => trnsFormStore.values.categoryId = id"
+ @selectCategory="id => trnsFormStore.values.categoryId = id"
/>
</div>
</div>
diff --git a/app/components/trnForm/Calendar.vue b/app/components/trnForm/Calendar.vue
index ebfe4e5d..c265c6a2 100644
--- a/app/components/trnForm/Calendar.vue
+++ b/app/components/trnForm/Calendar.vue
@@ -2,6 +2,8 @@
/*
* UCalendar has bad type definitions
*/
+import type { CalendarDate } from '@internationalized/date'
+
import { getUCalendarTimedDate, getUCalendarToday, parseUCalendarDate } from '~/components/date/utils'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
@@ -13,7 +15,7 @@ const trnsFormStore = useTrnsFormStore()
const date = ref(parseUCalendarDate(trnsFormStore.values.date))
const maxDate = getUCalendarToday()
-function onUpdate(date: unknown) {
+function onUpdate(date: CalendarDate) {
props.onClose()
if (!date)
diff --git a/app/components/trnForm/Categories.vue b/app/components/trnForm/Categories.vue
index 32f15c96..1c957949 100644
--- a/app/components/trnForm/Categories.vue
+++ b/app/components/trnForm/Categories.vue
@@ -8,7 +8,7 @@ import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const emit = defineEmits<{
- (e: 'click', id: CategoryId): void
+ click: [id: CategoryId]
}>()
const { t } = useI18n()
@@ -47,7 +47,7 @@ onMounted(() => {
<!-- Recent -->
<div class="swiper-slide h-full">
<div
- class="scrollerBlock font-primary rounded-t-2xl bg-[var(--item-1)] px-3 py-4 text-center text-xl font-semibold"
+ class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold"
>
{{ t('categories.recentCategories') }}
</div>
@@ -64,7 +64,7 @@ onMounted(() => {
<!-- Main -->
<div class="swiper-slide h-full">
<div
- class="scrollerBlock font-primary rounded-t-2xl bg-[var(--item-1)] px-3 py-4 text-center text-xl font-semibold"
+ class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold"
>
{{ t('categories.title') }}
</div>
@@ -80,7 +80,7 @@ onMounted(() => {
<!-- Favorite -->
<div class="swiper-slide h-full">
- <div class="scrollerBlock font-primary rounded-t-2xl bg-[var(--item-1)] px-3 py-4 text-center text-xl font-semibold">
+ <div class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold">
{{ t('categories.favoriteCategories') }}
</div>
<div class="px-3 pb-1">
@@ -97,28 +97,28 @@ onMounted(() => {
</div>
<div v-if="sliderObj" class="px-3 py-2">
- <UiTabs1>
- <UiTabsItem1
+ <UiTabsBar>
+ <UiTabsItemFill
:isActive="sliderObj.activeIndex === 0"
@click="sliderObj.slideTo(0)"
>
{{ t('categories.recentCategories') }}
- </UiTabsItem1>
+ </UiTabsItemFill>
- <UiTabsItem1
+ <UiTabsItemFill
:isActive="sliderObj.activeIndex === 1"
@click="sliderObj.slideTo(1)"
>
{{ t('categories.allTitle') }}
- </UiTabsItem1>
+ </UiTabsItemFill>
- <UiTabsItem1
+ <UiTabsItemFill
:isActive="sliderObj.activeIndex === 2"
@click="sliderObj.slideTo(2)"
>
{{ t('categories.favoriteCategories') }}
- </UiTabsItem1>
- </UiTabs1>
+ </UiTabsItemFill>
+ </UiTabsBar>
</div>
</div>
</template>
diff --git a/app/components/trnForm/Date.vue b/app/components/trnForm/Date.vue
index 8f16d216..0ad2a9c5 100644
--- a/app/components/trnForm/Date.vue
+++ b/app/components/trnForm/Date.vue
@@ -32,18 +32,18 @@ function changeDate(way: 'prev' | 'next' | 'today') {
:isOpen="isShow"
class="grow"
isShowCloseBtn
- @onOpenModal="isShow = true"
- @onCloseModal="isShow = false"
+ @openModal="isShow = true"
+ @closeModal="isShow = false"
>
<template #trigger>
- <UiItem1 class="text-2 grid grow !justify-start p-2">
+ <UiActionButton class="text-2 grid grow !justify-start p-2">
<div class="text-1 text-sm">
{{ formattedDate.day }} {{ formattedDate.month }}
</div>
<div class="font-regular text-2xs leading-none">
{{ formattedDate.weekday }}
</div>
- </UiItem1>
+ </UiActionButton>
</template>
<template #content="{ close }">
diff --git a/app/components/trnForm/EditedTrn.vue b/app/components/trnForm/EditedTrn.vue
index 680657a2..57b48cf7 100644
--- a/app/components/trnForm/EditedTrn.vue
+++ b/app/components/trnForm/EditedTrn.vue
@@ -1,4 +1,4 @@
-<script lang="ts" setup>
+<script setup lang="ts">
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
@@ -9,7 +9,7 @@ const { t } = useI18n()
const showModalConfirm = ref(false)
function handleDeleteConfirm() {
- trnsStore.deleteTrn(JSON.parse(JSON.stringify(trnsFormStore.values.trnId)))
+ trnsStore.deleteTrn(trnsFormStore.values.trnId)
showModalConfirm.value = false
}
@@ -60,6 +60,7 @@ const actions = computed(() => ({
class="relative mb-2 px-3"
>
<TrnsItem
+ v-if="trnsStore.computeTrnItem(trnsFormStore.values.trnId)"
:trnItem="trnsStore.computeTrnItem(trnsFormStore.values.trnId)"
class="group bg-item-3 rounded-lg"
@click="trnsFormStore.values.trnId = null"
@@ -69,14 +70,14 @@ const actions = computed(() => ({
v-if="showModalConfirm"
class="absolute -bottom-4 left-0 z-20 w-full px-4"
>
- <div class="text-1 z-10 grid h-full content-center gap-4 rounded-lg border border-(--ui-primary) bg-[var(--item-1)] p-3">
+ <div class="text-1 z-10 grid h-full content-center gap-4 rounded-lg border border-(--ui-primary) bg-(--item-1) p-3">
{{ t('trnForm.delete.alert') }}
<div class="flex gap-2">
<UiElement
v-for="(item, slug) in actions"
:key="slug"
- :insideClasses="slug === 'yes' ? '!min-h-[44px] bg-item-4' : '!min-h-[44px] bg-item-3'"
+ :insideClasses="`min-h-[44px] ${slug === 'yes' ? 'bg-item-4' : 'bg-item-3'}`"
class="grow"
@click="item.click"
>
@@ -97,7 +98,7 @@ const actions = computed(() => ({
<!-- Trn actions -->
<div class="flex pt-2">
- <UiItem1
+ <UiActionButton
v-for="(item, slug) in items"
:key="slug"
variant="text"
@@ -113,7 +114,7 @@ const actions = computed(() => ({
<div class="text-muted leading-none">
{{ t(item.label) }}
</div>
- </UiItem1>
+ </UiActionButton>
</div>
</div>
</template>
diff --git a/app/components/trnForm/FloatOpener.vue b/app/components/trnForm/FloatOpener.vue
index 32b45ebd..3042f8ef 100644
--- a/app/components/trnForm/FloatOpener.vue
+++ b/app/components/trnForm/FloatOpener.vue
@@ -9,7 +9,7 @@ const { onClose, trnFormCreate, ui } = useTrnsFormStore()
v-if="!ui.isShow"
class="
group fixed top-0 right-0 h-full w-[300px] items-end
- justify-end from-transparent to-[var(--item-5)]
+ justify-end from-transparent to-(--item-5)
transition hover:bg-gradient-to-r xl:flex
"
@click="ui.isShow ? onClose() : trnFormCreate()"
diff --git a/app/components/trnForm/Main.vue b/app/components/trnForm/Main.vue
index b2d97f4b..672e7f23 100644
--- a/app/components/trnForm/Main.vue
+++ b/app/components/trnForm/Main.vue
@@ -8,11 +8,9 @@ import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-const props = withDefaults(defineProps<{
+const { maxHeight = '60vh' } = defineProps<{
maxHeight?: string
-}>(), {
- maxHeight: '60vh',
-})
+}>()
const { t } = useI18n()
const categoriesStore = useCategoriesStore()
@@ -42,7 +40,7 @@ function show(slide: number) {
<TrnFormSelection
v-if="isShow"
v-model:isShow="isShow"
- :maxHeight="props.maxHeight"
+ :maxHeight="maxHeight"
:initialSlide
/>
@@ -64,7 +62,7 @@ function show(slide: number) {
:highlight="trnsFormStore.values.trnType === 0 ? 'expense' : 'income'"
:isShowSum="trnsFormStore.getIsShowSum()"
class="px-3 pb-2"
- @onChange="trnsFormStore.onChangeAmount"
+ @change="trnsFormStore.onChangeAmount"
/>
<div class="grid gap-3 px-3 pb-6">
@@ -75,31 +73,31 @@ function show(slide: number) {
>
<TrnFormSelectorWallet
v-if="walletId"
- :bottomSheetStyle="{ maxHeight: props.maxHeight }"
+ :bottomSheetStyle="{ maxHeight }"
:isLaptop
:title="t('trnForm.wallet.select')"
:walletId="walletId"
- @onOpen="show(0)"
- @onSelected="(id: WalletId) => trnsFormStore.values.walletId = id"
+ @open="show(0)"
+ @selected="(id: WalletId) => trnsFormStore.values.walletId = id"
/>
<TrnFormSelectorCategory
- v-if="trnsFormStore.values.categoryId"
- :bottomSheetStyle="{ maxHeight: props.maxHeight }"
+ v-if="trnsFormStore.values.categoryId || categoriesStore.categoriesIdsForTrnValues[0]"
+ :bottomSheetStyle="{ maxHeight }"
:category="categoriesStore.items[trnsFormStore.values.categoryId ?? categoriesStore.categoriesIdsForTrnValues[0]]"
:categoryId="trnsFormStore.values.categoryId ?? categoriesStore.categoriesIdsForTrnValues[0]"
:isLaptop
:title="t('trnForm.category.select')"
- @onOpen="show(2)"
- @onSelected="(id: CategoryId) => trnsFormStore.values.categoryId = id"
+ @open="show(2)"
+ @selected="(id: CategoryId) => trnsFormStore.values.categoryId = id"
/>
</div>
<TrnFormMainAmountTransfer
v-if="trnsFormStore.values.trnType === 2"
- :bottomSheetStyle="{ maxHeight: props.maxHeight }"
+ :bottomSheetStyle="{ maxHeight }"
isLaptop
- @onOpen="show(0)"
+ @open="show(0)"
/>
<TrnFormMainCalculator />
@@ -114,7 +112,7 @@ function show(slide: number) {
padding-bottom: calc(env(safe-area-inset-bottom) - 16px);
.trnForm__pagination {
- @apply absolute left-1/2 z-[2] flex items-center justify-center w-auto p-1.5 rounded-md bg-[var(--item-1)];
+ @apply absolute left-1/2 z-[2] flex items-center justify-center w-auto p-1.5 rounded-md bg-(--item-1);
transform: translateX(-50%);
bottom: 1px;
}
diff --git a/app/components/trnForm/Selection.vue b/app/components/trnForm/Selection.vue
index 107bf1dc..1cce7b11 100644
--- a/app/components/trnForm/Selection.vue
+++ b/app/components/trnForm/Selection.vue
@@ -11,16 +11,10 @@ import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import 'swiper/css'
-const props = withDefaults(
- defineProps<{
- initialSlide?: number
- maxHeight?: string
- }>(),
- {
- initialSlide: 0,
- maxHeight: '60vh',
- },
-)
+const { initialSlide = 0, maxHeight = '60vh' } = defineProps<{
+ initialSlide?: number
+ maxHeight?: string
+}>()
const isShow = defineModel('isShow', {
default: false,
@@ -36,7 +30,7 @@ onMounted(() => {
if (!sliderObj.value) {
sliderObj.value = new Swiper(sliderRef.value, {
init: false,
- initialSlide: props.initialSlide,
+ initialSlide,
longSwipesMs: 60,
longSwipesRatio: 0.1,
modules: [Pagination],
@@ -74,12 +68,12 @@ async function onSelectParentCategory(id: CategoryId) {
<Teleport to="body">
<BottomSheet
:isShow="isShow"
- drugClassesCustom="bg-[var(--item-1)] max-w-md"
+ drugClassesCustom="bg-(--item-1) max-w-md"
@closed="isShow = false"
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -87,44 +81,44 @@ async function onSelectParentCategory(id: CategoryId) {
<div class="swiper-wrapper">
<!-- Wallets -->
<div
- :style="{ height: props.maxHeight }"
+ :style="{ height: maxHeight }"
class="swiper-slide"
>
<div class="scrollerBlock h-full overflow-y-auto pb-3">
<TrnFormSelectionWalletsAll
:maxHeight="maxHeight"
- @onSelectWallet="id => onSelectWallet(id, close)"
+ @selectWallet="id => onSelectWallet(id, close)"
/>
</div>
</div>
<!-- Categories fast -->
<div
- :style="{ height: props.maxHeight }"
+ :style="{ height: maxHeight }"
class="swiper-slide"
>
<div class="scrollerBlock grid h-full gap-4 overflow-y-auto pb-3">
<TrnFormSelectionCategoriesFast
- @onSelectCategory="id => onSelectCategory(id, close)"
- @onSelectParentCategory="id => onSelectParentCategory(id)"
+ @selectCategory="id => onSelectCategory(id, close)"
+ @selectParentCategory="id => onSelectParentCategory(id)"
/>
</div>
</div>
<!-- Categories -->
<div
- :style="{ height: props.maxHeight }"
+ :style="{ height: maxHeight }"
class="swiper-slide"
>
<div class="scrollerBlock h-full overflow-y-auto pb-3">
- <UiTitle3
- class="sticky top-0 z-10 bg-[var(--item-1)] px-3 pt-4 pb-3"
+ <UiTitleSection
+ class="sticky top-0 z-10 bg-(--item-1) px-3 pt-4 pb-3"
@click="trnsFormStore.ui.catsRootModal = true"
>
{{ t('categories.title') }}
- </UiTitle3>
- <CategoriesSelector
- @onSelected="id => onSelectCategory(id, close)"
+ </UiTitleSection>
+ <CategoriesSelectorTree
+ @selected="id => onSelectCategory(id, close)"
/>
</div>
</div>
diff --git a/app/components/trnForm/SelectionCategoriesFast.vue b/app/components/trnForm/SelectionCategoriesFast.vue
index 18a4aa35..402cb343 100644
--- a/app/components/trnForm/SelectionCategoriesFast.vue
+++ b/app/components/trnForm/SelectionCategoriesFast.vue
@@ -6,8 +6,8 @@ import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
const emit = defineEmits<{
close: []
- onSelectCategory: [id: CategoryId]
- onSelectParentCategory: [id: CategoryId]
+ selectCategory: [id: CategoryId]
+ selectParentCategory: [id: CategoryId]
}>()
const { t } = useI18n()
@@ -21,16 +21,16 @@ const trnsFormStore = useTrnsFormStore()
v-if="categoriesStore.favoriteCategoriesIds.length > 0"
class="pt-2"
>
- <UiTitle7 class="mx-2">
+ <UiTitleCollapse arrow="right" class="mx-2">
{{ t('categories.favoriteCategories') }}
- </UiTitle7>
+ </UiTitleCollapse>
- <CategoriesSelector2
+ <CategoriesSelectorGrid
:activeItemId="trnsFormStore.values.categoryId"
:hide="emit('close')"
:ids="categoriesStore.favoriteCategoriesIds"
- @onClickParent="id => emit('onSelectParentCategory', id)"
- @onSelected="id => emit('onSelectCategory', id)"
+ @clickParent="id => emit('selectParentCategory', id)"
+ @selected="id => emit('selectCategory', id)"
/>
</div>
@@ -40,12 +40,23 @@ const trnsFormStore = useTrnsFormStore()
{{ t('categories.recentCategories') }}
</UiTitleModal>
- <CategoriesSelector2
+ <CategoriesSelectorGrid
:activeItemId="trnsFormStore.values.categoryId"
:hide="emit('close')"
:ids="categoriesStore.recentCategoriesIds"
- @onClickParent="id => emit('onSelectParentCategory', id)"
- @onSelected="id => emit('onSelectCategory', id)"
+ @clickParent="id => emit('selectParentCategory', id)"
+ @selected="id => emit('selectCategory', id)"
+ />
+ </div>
+
+ <!-- All categories fallback when no favorites and no recent -->
+ <div v-if="categoriesStore.favoriteCategoriesIds.length === 0 && categoriesStore.recentCategoriesIds.length === 0 && categoriesStore.categoriesIdsForTrnValues.length > 0">
+ <CategoriesSelectorGrid
+ :activeItemId="trnsFormStore.values.categoryId"
+ :hide="emit('close')"
+ :ids="categoriesStore.categoriesIdsForTrnValues"
+ @clickParent="id => emit('selectParentCategory', id)"
+ @selected="id => emit('selectCategory', id)"
/>
</div>
</template>
diff --git a/app/components/trnForm/SelectionWalletsAll.vue b/app/components/trnForm/SelectionWalletsAll.vue
index 21e5c0ef..61ad7d25 100644
--- a/app/components/trnForm/SelectionWalletsAll.vue
+++ b/app/components/trnForm/SelectionWalletsAll.vue
@@ -8,7 +8,7 @@ defineProps<{
}>()
const emit = defineEmits<{
- onSelectWallet: [id: WalletId]
+ selectWallet: [id: WalletId]
}>()
const { t } = useI18n()
@@ -24,7 +24,7 @@ const trnsFormStore = useTrnsFormStore()
<WalletsSelector
:activeItemId="trnsFormStore.values.walletId ?? undefined"
class="min-w-80 px-2 py-px"
- @onSelected="id => emit('onSelectWallet', id)"
+ @selected="id => emit('selectWallet', id)"
/>
</div>
</template>
diff --git a/app/components/trnForm/SelectorCategory.vue b/app/components/trnForm/SelectorCategory.vue
index 513fe905..c1e44c94 100644
--- a/app/components/trnForm/SelectorCategory.vue
+++ b/app/components/trnForm/SelectorCategory.vue
@@ -10,8 +10,8 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onOpen: [slide: number]
- onSelected: [id: CategoryId]
+ open: [slide: number]
+ selected: [id: CategoryId]
}>()
const isShow = ref(false)
@@ -24,8 +24,8 @@ const isShow = ref(false)
:bottomSheetStyle="props.bottomSheetStyle"
drugClassesCustom="h-full max-w-md"
isShowCloseBtn
- @onOpenModal="isShow = true"
- @onCloseModal="isShow = false"
+ @openModal="isShow = true"
+ @closeModal="isShow = false"
>
<template #trigger>
<CategoriesItem
@@ -41,7 +41,7 @@ const isShow = ref(false)
:hide="close"
:activeItemId="props.categoryId"
class="bottomSheetContentInside -mt-2 min-w-72"
- @onSelected="(id: CategoryId) => { emit('onSelected', id); close() }"
+ @selected="(id: CategoryId) => { emit('selected', id); close() }"
/>
</template>
</BottomSheetOrDropdown>
diff --git a/app/components/trnForm/SelectorWallet.vue b/app/components/trnForm/SelectorWallet.vue
index 103a93b7..8cc9d416 100644
--- a/app/components/trnForm/SelectorWallet.vue
+++ b/app/components/trnForm/SelectorWallet.vue
@@ -11,8 +11,8 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onOpen: [slide: number]
- onSelected: [id: WalletId]
+ open: [slide: number]
+ selected: [id: WalletId]
}>()
const walletsStore = useWalletsStore()
@@ -27,8 +27,8 @@ const isShow = ref(false)
:title="props.title"
drugClassesCustom="h-full max-w-md"
isShowCloseBtn
- @onCloseModal="isShow = false"
- @onOpenModal="isShow = true"
+ @closeModal="isShow = false"
+ @openModal="isShow = true"
>
<template #trigger>
<WalletsItem
@@ -46,7 +46,7 @@ const isShow = ref(false)
:hide="close"
:activeItemId="props.walletId"
class="min-w-80 px-2"
- @onSelected="(id: WalletId) => emit('onSelected', id)"
+ @selected="(id: WalletId) => emit('selected', id)"
/>
</template>
</BottomSheetOrDropdown>
diff --git a/app/components/trnForm/Sidebar.vue b/app/components/trnForm/Sidebar.vue
index da7d44b2..a0668ff9 100644
--- a/app/components/trnForm/Sidebar.vue
+++ b/app/components/trnForm/Sidebar.vue
@@ -53,7 +53,7 @@ watch(isShow, (v) => {
>
<div class="border-left border-item-6 border-item-4 bg-item-2 relative h-full overflow-hidden rounded-l-xl border border-r-0 shadow-2xl">
<div class="absolute top-2 right-2">
- <BottomSheetClose @onClick="trnsFormStore.onClose()" />
+ <BottomSheetClose @click="trnsFormStore.onClose()" />
</div>
<div ref="sliderRef" class="swiper-container h-full">
@@ -71,7 +71,7 @@ watch(isShow, (v) => {
class="-mt-8 grid gap-2 pb-6"
>
<TrnFormSelectionCategoriesFast
- @onSelectCategory="id => trnsFormStore.values.categoryId = id"
+ @selectCategory="id => trnsFormStore.values.categoryId = id"
/>
</div>
</div>
@@ -79,13 +79,13 @@ watch(isShow, (v) => {
<!-- Quick selector -->
<div
- class="swiper-slide bg-[var(--bg-)]"
+ class="swiper-slide bg-(--bg-)"
:style="{ height: '100%' }"
>
<div class="scrollerBlock h-full overflow-y-auto overscroll-contain">
- <UiTitle3 class="bg-default sticky top-0 z-10 px-4 pt-5 pb-3 md:text-xl">
+ <UiTitleSection class="bg-default sticky top-0 z-10 px-4 pt-5 pb-3 md:text-xl">
{{ t('trns.history') }}
- </UiTitle3>
+ </UiTitleSection>
<TrnFormTrnsSlide
:slider="sliderObj"
diff --git a/app/components/trnForm/TrnsSlide.vue b/app/components/trnForm/TrnsSlide.vue
index 0a3a0d86..82af96d8 100644
--- a/app/components/trnForm/TrnsSlide.vue
+++ b/app/components/trnForm/TrnsSlide.vue
@@ -89,8 +89,8 @@ const tabs = computed<{ id: FilterBy, name: string }[]>(() => [
<TrnFormDate />
</div>
- <UiTabs1 class="mb-4">
- <UiTabsItem1
+ <UiTabsBar class="mb-4">
+ <UiTabsItemFill
v-for="tab in tabs"
:key="tab.id"
class="text-xs whitespace-nowrap"
@@ -98,8 +98,8 @@ const tabs = computed<{ id: FilterBy, name: string }[]>(() => [
@click="changeFilter(tab.id)"
>
{{ tab.name }}
- </UiTabsItem1>
- </UiTabs1>
+ </UiTabsItemFill>
+ </UiTabsBar>
</template>
</TrnsList>
</div>
diff --git a/app/components/trnForm/main/ActionSide.vue b/app/components/trnForm/main/ActionSide.vue
index ea59d2a6..64c734d4 100644
--- a/app/components/trnForm/main/ActionSide.vue
+++ b/app/components/trnForm/main/ActionSide.vue
@@ -19,7 +19,7 @@ async function onClickSubmit() {
if (!trnFormData)
return
- await trnsStore.addTrn({
+ await trnsStore.saveTrn({
id: trnFormData.id,
values: trnFormData.values,
})
@@ -29,11 +29,13 @@ async function onClickSubmit() {
<template>
<div
- :class="{
- '!hover:bg-(--ui-primary) text-icon-primary !bg-(--ui-primary)/60': !isMath && isSubmittable,
- 'text-muted': !isSubmittable || isMath,
- }"
- class="bg-item-4 text-1 flex size-full items-center justify-center rounded-[var(--ui-radius)] p-1 py-4 text-center transition hover:scale-[1.02] hover:bg-[var(--item-5)]"
+ :class="cn(
+ 'flex size-full items-center justify-center rounded-(--ui-radius) p-1 py-4 text-center transition hover:scale-[1.02]',
+ !isMath && isSubmittable
+ ? 'bg-(--ui-primary)/60 hover:bg-(--ui-primary) text-icon-primary'
+ : 'bg-item-4 text-1 hover:bg-(--item-5)',
+ (!isSubmittable || isMath) && 'text-muted',
+ )"
@click="onClickSubmit"
>
<Icon :name="isMath ? 'lucide:equal' : 'lucide:check'" size="40" />
diff --git a/app/components/trnForm/main/AmountTransfer.vue b/app/components/trnForm/main/AmountTransfer.vue
index d3c9f4fd..983616d7 100644
--- a/app/components/trnForm/main/AmountTransfer.vue
+++ b/app/components/trnForm/main/AmountTransfer.vue
@@ -1,11 +1,10 @@
<script setup lang="ts">
import type { MoneyTypeSlug } from '~/components/stat/types'
-import type { TransferType } from '~/components/trns/types'
+import type { TransferSide } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { TrnType } from '~/components/trns/types'
-import { getStyles } from '~/components/ui/getStyles'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const props = defineProps<{
@@ -14,21 +13,21 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onOpen: [slide: number]
+ open: [slide: number]
}>()
const trnsFormStore = useTrnsFormStore()
const walletsStore = useWalletsStore()
const { t } = useI18n()
-const items = ref<Record<MoneyTypeSlug, { amountsIdx: 1 | 2, transferType: TransferType }>>({
+const items = ref<Record<MoneyTypeSlug, { amountsIdx: 1 | 2, transferType: TransferSide }>>({
expense: {
amountsIdx: 1,
- transferType: 0,
+ transferType: 'expense',
},
income: {
amountsIdx: 2,
- transferType: 1,
+ transferType: 'income',
},
})
@@ -85,24 +84,23 @@ function copyAmount() {
</script>
<template>
- <div class="">
+ <div>
<template
v-for="(item, slug) in items"
:key="slug"
>
<div
- :class="[{
- '!border-(--ui-primary)/50': trnsFormStore.values.transferType === item.transferType,
- }, getStyles('item', ['rounded'])]"
- class="-m-1 grid gap-2 overflow-hidden border border-transparent p-2"
+ :class="cn('-m-1 grid gap-2 overflow-hidden rounded-sm border border-transparent p-2',
+ trnsFormStore.values.transferType === item.transferType && 'border-(--ui-primary)/50',
+ )"
@click="trnsFormStore.onChangeTransferType(item.transferType)"
>
<div class="flex items-center gap-2 whitespace-nowrap">
<div
- :class="[getStyles('item', ['bg2', 'link', 'rounded']), {
- 'bg-[var(--item-5)]': trnsFormStore.values.transferType === item.transferType,
+ :class="[{
+ 'bg-(--item-5)': trnsFormStore.values.transferType === item.transferType,
}]"
- class="text-1/70 flex min-h-[44px] w-1/2 grow items-center px-3 py-2 text-sm lg:min-h-[42px]"
+ class="text-1/70 bg-item-3 interactive flex min-h-[44px] w-1/2 grow items-center rounded-sm px-3 py-2 text-sm lg:min-h-[42px]"
>
{{ t(`trnForm.transfer.${slug}`) }}
</div>
@@ -113,8 +111,8 @@ function copyAmount() {
:isLaptop
:title="t(`trnForm.transfer.${slug}`)"
:walletId="incomeWalletId"
- @onOpen="n => emit('onOpen', n)"
- @onSelected="id => trnsFormStore.values.incomeWalletId = id"
+ @open="n => emit('open', n)"
+ @selected="id => trnsFormStore.values.incomeWalletId = id"
/>
<TrnFormSelectorWallet
@@ -123,8 +121,8 @@ function copyAmount() {
:isLaptop
:title="t(`trnForm.transfer.${slug}`)"
:walletId="expenseWalletId"
- @onOpen="n => emit('onOpen', n)"
- @onSelected="id => trnsFormStore.values.expenseWalletId = id"
+ @open="n => emit('open', n)"
+ @selected="id => trnsFormStore.values.expenseWalletId = id"
/>
</div>
@@ -133,25 +131,25 @@ function copyAmount() {
:key="item.amountsIdx"
:amount="trnsFormStore.values.amount[item.amountsIdx]"
:amountRaw="trnsFormStore.values.amountRaw[item.amountsIdx]"
- :highlight="item.transferType === 0 ? 'expense' : 'income'"
+ :highlight="item.transferType"
:isShowSum="trnsFormStore.getIsShowSum()"
isTransfer
- @onChange="trnsFormStore.onChangeAmount"
+ @change="trnsFormStore.onChangeAmount"
/>
</div>
<!-- Actions -->
<div
- v-if="item.transferType === 0"
+ v-if="item.transferType === 'expense'"
class="flex justify-center gap-1 pt-3 pb-1"
>
- <UiItem1 @click="switchWallets">
+ <UiActionButton @click="switchWallets">
<Icon name="lucide:arrow-up-down" size="24" />
- </UiItem1>
+ </UiActionButton>
- <UiItem1 @click="copyAmount">
+ <UiActionButton @click="copyAmount">
<Icon name="lucide:clipboard-paste" size="24" />
- </UiItem1>
+ </UiActionButton>
</div>
</template>
</div>
diff --git a/app/components/trnForm/main/CalculatorButton.vue b/app/components/trnForm/main/CalculatorButton.vue
index f18b317b..9c4419ce 100644
--- a/app/components/trnForm/main/CalculatorButton.vue
+++ b/app/components/trnForm/main/CalculatorButton.vue
@@ -16,7 +16,7 @@ const emit = defineEmits<{
text-2xl
font-normal
transition hover:scale-[1.02]
- hover:bg-[var(--item-5)]
+ hover:bg-(--item-5)
@xs/trnForm:w-14
@sm/trnForm:w-16
"
diff --git a/app/components/trnForm/main/Description.vue b/app/components/trnForm/main/Description.vue
index 22e9176b..659502ce 100644
--- a/app/components/trnForm/main/Description.vue
+++ b/app/components/trnForm/main/Description.vue
@@ -26,8 +26,8 @@ function onSave(close: () => void) {
class="grow"
drugClassesCustom="max-w-md"
isShowCloseBtn
- @onCloseModal="trnsFormStore.closeTrnFormModal('description')"
- @onOpenModal="trnsFormStore.openTrnFormModal('description')"
+ @closeModal="trnsFormStore.closeTrnFormModal('description')"
+ @openModal="trnsFormStore.openTrnFormModal('description')"
>
<template #trigger>
<TrnFormMainCalculatorButton class="relative">
@@ -43,9 +43,8 @@ function onSave(close: () => void) {
<div class="grid min-w-80 gap-4">
<div class="px-2">
<FormTextarea
- :value="desc"
+ v-model="desc"
:placeholder="t('trnForm.description.placeholder')"
- @updateValue="(value: string) => desc = value"
/>
</div>
diff --git a/app/components/trnForm/main/Input.vue b/app/components/trnForm/main/Input.vue
index a23d71e6..42f81746 100644
--- a/app/components/trnForm/main/Input.vue
+++ b/app/components/trnForm/main/Input.vue
@@ -8,7 +8,7 @@ defineProps<{
}>()
const emit = defineEmits<{
- (e: 'onChange', value: string): void
+ change: [value: string]
}>()
const { t } = useI18n()
@@ -36,10 +36,10 @@ const { t } = useI18n()
'text-center': !isTransfer,
}"
:placeholder="t('trnForm.enterAmount')"
- :value="amountRaw"
+ :modelValue="amountRaw"
class="swiper-no-swiping bg-item-2 font-secondary border-transparent pt-6 pb-2 text-center !text-3xl placeholder:text-3xl"
inputmode="tel"
- @updateValue="(value: string) => emit('onChange', value || '')"
+ @update:modelValue="(value: string) => emit('change', value || '')"
/>
</div>
</template>
diff --git a/app/components/trnForm/main/Types.vue b/app/components/trnForm/main/Types.vue
index 306b6060..de0976f5 100644
--- a/app/components/trnForm/main/Types.vue
+++ b/app/components/trnForm/main/Types.vue
@@ -18,27 +18,27 @@ function isItActive(amountType: TrnType) {
</script>
<template>
- <UiTabs1 class="!gap-0">
- <UiTabsItem3
+ <UiTabsBar class="!gap-0">
+ <UiTabsItemPill
:isActive="isItActive(0)"
@click="setAmountType(0)"
>
{{ t('money.expense') }}
- </UiTabsItem3>
+ </UiTabsItemPill>
- <UiTabsItem3
+ <UiTabsItemPill
:isActive="isItActive(1)"
@click="setAmountType(1)"
>
{{ t('money.income') }}
- </UiTabsItem3>
+ </UiTabsItemPill>
- <UiTabsItem3
+ <UiTabsItemPill
v-if="walletsStore.sortedIds.length > 1"
:isActive="isItActive(2)"
@click="setAmountType(2)"
>
{{ t('trnForm.transferTitle') }}
- </UiTabsItem3>
- </UiTabs1>
+ </UiTabsItemPill>
+ </UiTabsBar>
</template>
diff --git a/app/components/trnForm/useTrnsFormStore.ts b/app/components/trnForm/useTrnsFormStore.ts
index 3d4570ed..1d32129a 100644
--- a/app/components/trnForm/useTrnsFormStore.ts
+++ b/app/components/trnForm/useTrnsFormStore.ts
@@ -1,13 +1,11 @@
-import { defineStore } from 'pinia'
import { generateId } from '~~/utils/generateId'
import type { CategoryId } from '~/components/categories/types'
import type { TrnFormUi } from '~/components/trnForm/types'
import type { CalculatorKey } from '~/components/trnForm/utils/calculate'
-import type { TransferType, TrnFormValues, TrnId, TrnItem } from '~/components/trns/types'
+import type { TransferSide, TrnFormValues, TrnId, TrnItem } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
-import { errorEmo, random } from '~/assets/js/emo'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { createExpressionString, evaluateExpression, formatInput } from '~/components/trnForm/utils/calculate'
import { formatTransaction, formatTransfer } from '~/components/trnForm/utils/formatData'
@@ -15,6 +13,7 @@ import { validate } from '~/components/trnForm/utils/validate'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { showErrorToast } from '~/composables/useStoreSync'
type Values = {
categoriesIds: CategoryId[]
@@ -29,12 +28,9 @@ type Values = {
})
export const useTrnsFormStore = defineStore('trnForm', () => {
- const { t } = useI18n()
const categoriesStore = useCategoriesStore()
- const trnsFormStore = useTrnsFormStore()
const trnsStore = useTrnsStore()
const walletsStore = useWalletsStore()
- const toast = useToast()
const values = reactive<TrnFormValues>({
amount: [0, 0, 0],
@@ -44,7 +40,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
desc: undefined,
expenseWalletId: null,
incomeWalletId: null,
- transferType: 0,
+ transferType: 'expense',
trnId: null,
trnType: 0,
walletId: null,
@@ -71,7 +67,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
const activeAmountIdx = computed(() =>
values.trnType !== TrnType.Transfer
? 0
- : 1 + values.transferType,
+ : values.transferType === 'expense' ? 1 : 2,
)
function onChangeAmount(amountRaw: string) {
@@ -85,7 +81,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
}
function getIsShowSum() {
- if (values.trnType === 2) {
+ if (values.trnType === TrnType.Transfer) {
const expense = values.amount[1] !== 0
&& formatInput(values.amount[1]) !== values.amountRaw[1]
const income = values.amount[2] !== 0
@@ -101,7 +97,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
values.trnType = trnType
}
- function onChangeTransferType(transferType: TransferType) {
+ function onChangeTransferType(transferType: TransferSide) {
values.transferType = transferType
}
@@ -112,6 +108,29 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
values.trnId = null
}
+ function $reset() {
+ values.amount = [0, 0, 0]
+ values.amountRaw = ['', '', '']
+ values.categoryId = null
+ values.date = new Date().getTime()
+ values.desc = undefined
+ values.expenseWalletId = null
+ values.incomeWalletId = null
+ values.transferType = 'expense'
+ values.trnId = null
+ values.trnType = 0
+ values.walletId = null
+
+ ui.value = {
+ catsRootModal: false,
+ isShow: false,
+ walletsModal: false,
+ }
+ modal.value = {
+ description: false,
+ }
+ }
+
function onClose() {
if (values.trnId)
onClear()
@@ -124,9 +143,9 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
if (props.action === 'create') {
values.trnType = 0
- if (!values.walletId)
+ if (!values.walletId || !props.walletsIds.includes(values.walletId))
values.walletId = props.walletId ?? props.trn?.walletId ?? props.walletsIds[0]
- if (!values.categoryId)
+ if (!values.categoryId || !props.categoriesIds.includes(values.categoryId as CategoryId))
values.categoryId = props.trn?.categoryId ?? props.categoriesIds[0]
values.incomeWalletId = props.walletsIds[0]
@@ -158,36 +177,42 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
}
async function onSubmit() {
- const data = values.trnType !== 2
+ // Validate wallet/category exist before formatting
+ if (values.trnType !== TrnType.Transfer) {
+ if (!values.walletId || !walletsStore.items?.[values.walletId]) {
+ showErrorToast('trnForm.errors.selectWallet')
+ return
+ }
+ if (!values.categoryId || !categoriesStore.items?.[values.categoryId]) {
+ showErrorToast('trnForm.errors.selectCategory')
+ return
+ }
+ }
+
+ const data = values.trnType !== TrnType.Transfer
? formatTransaction(values)
: formatTransfer(values)
- try {
- const validateStatus = validate(data)
-
- if (validateStatus.error || !data) {
- toast.add({
- color: 'error',
- description: t(validateStatus.error!) ?? 'No data',
- title: random(errorEmo),
- })
- return
- }
+ if (!data) {
+ showErrorToast('base.noData')
+ return
+ }
- return {
- id: values.trnId ?? generateId(),
- values: data,
- }
+ const error = validate(data)
+ if (error) {
+ showErrorToast(error)
+ return
}
- catch (e) {
- console.error(e)
- return false
+
+ return {
+ id: values.trnId ?? generateId(),
+ values: data,
}
}
function onChangeCountSum() {
// Transfer
- if (values.trnType === 2) {
+ if (values.trnType === TrnType.Transfer) {
values.amountRaw[1] = formatInput(values.amount[1])
values.amountRaw[2] = formatInput(values.amount[2])
return
@@ -213,7 +238,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
trnId,
walletsIds: walletsStore.sortedIds,
})
- trnsFormStore.ui.isShow = true
+ ui.value.isShow = true
}
function trnFormCreate(props?: { categoryId?: CategoryId, walletId?: WalletId }) {
@@ -224,11 +249,11 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
walletId: props?.walletId ?? walletsStore.sortedIds[0],
walletsIds: walletsStore.sortedIds,
})
- trnsFormStore.ui.isShow = true
+ ui.value.isShow = true
if (props) {
if (props.categoryId)
- trnsFormStore.values.categoryId = props.categoryId
+ values.categoryId = props.categoryId
}
}
@@ -238,21 +263,19 @@ export const useTrnsFormStore = defineStore('trnForm', () => {
if (!trn)
return
- if (trn.type !== TrnType.Transfer) {
- setValues({
- action: 'duplicate',
- amount: trn.amount,
- categoriesIds: categoriesStore.categoriesIdsForTrnValues,
- trn,
- trnId,
- walletsIds: walletsStore.sortedIds,
- })
- }
+ setValues({
+ action: 'duplicate',
+ categoriesIds: categoriesStore.categoriesIdsForTrnValues,
+ trn,
+ trnId,
+ walletsIds: walletsStore.sortedIds,
+ })
- trnsFormStore.ui.isShow = true
+ ui.value.isShow = true
}
return {
+ $reset,
activeAmountIdx,
closeTrnFormModal,
getIsShowSum,
diff --git a/app/components/trnForm/utils/formatData.test.ts b/app/components/trnForm/utils/formatData.test.ts
index 55465261..738d10e6 100644
--- a/app/components/trnForm/utils/formatData.test.ts
+++ b/app/components/trnForm/utils/formatData.test.ts
@@ -11,7 +11,7 @@ const valuesBase: TrnFormValues = {
date: 99999,
expenseWalletId: 'expenseWalletId',
incomeWalletId: 'incomeWalletId',
- transferType: 1,
+ transferType: 'income',
trnId: 'id',
trnType: 2,
walletId: 'WalletId',
@@ -25,13 +25,13 @@ const transaction: {
amount: 10,
categoryId: 'CategoryId',
date: 99999,
- edited: 1690711427451,
type: 0,
+ updatedAt: 1690711427451,
walletId: 'WalletId',
},
raw: {
...valuesBase,
- transferType: 1,
+ transferType: 'income',
trnType: 0,
},
}
@@ -43,16 +43,16 @@ const transfer: {
generated: {
categoryId: 'transfer',
date: 99999,
- edited: 1690711427451,
expenseAmount: 20,
expenseWalletId: 'expenseWalletId',
incomeAmount: 30,
incomeWalletId: 'incomeWalletId',
type: 2,
+ updatedAt: 1690711427451,
},
raw: {
...valuesBase,
- transferType: 1,
+ transferType: 'income',
trnType: 2,
},
}
@@ -161,12 +161,10 @@ tests.forEach((test) => {
const data = test.id === 'transactions'
? formatTransaction(variant.data.expect)
: formatTransfer(variant.data.expect)
- delete data.editedAt
- delete data.edited
+ delete data.updatedAt
const res = variant.data.become
- delete res.editedAt
- delete res.edited
+ delete res.updatedAt
expect(data).toEqual(res)
})
diff --git a/app/components/trnForm/utils/formatData.ts b/app/components/trnForm/utils/formatData.ts
index bb4dc542..2c472318 100644
--- a/app/components/trnForm/utils/formatData.ts
+++ b/app/components/trnForm/utils/formatData.ts
@@ -1,7 +1,9 @@
import type { Transaction, Transfer, TrnFormValues } from '~/components/trns/types'
+import { TrnType } from '~/components/trns/types'
+
function formatTransaction(props: TrnFormValues): Transaction | false {
- if (props.trnType === 2 || !props.categoryId || !props.walletId) {
+ if (props.trnType === TrnType.Transfer || !props.categoryId || !props.walletId) {
return false
}
@@ -10,9 +12,9 @@ function formatTransaction(props: TrnFormValues): Transaction | false {
categoryId: props.categoryId,
date: props.date || new Date().getTime(),
- edited: new Date().getTime(),
-
type: props.trnType,
+
+ updatedAt: new Date().getTime(),
walletId: props.walletId,
}
@@ -23,7 +25,7 @@ function formatTransaction(props: TrnFormValues): Transaction | false {
}
function formatTransfer(props: TrnFormValues): Transfer | false {
- if (props.trnType !== 2 || !props.expenseWalletId || !props.incomeWalletId) {
+ if (props.trnType !== TrnType.Transfer || !props.expenseWalletId || !props.incomeWalletId) {
return false
}
@@ -31,15 +33,15 @@ function formatTransfer(props: TrnFormValues): Transfer | false {
categoryId: 'transfer' as const,
date: props.date,
- edited: new Date().getTime(),
-
expenseAmount: props.amount[1],
- expenseWalletId: props.expenseWalletId,
+ expenseWalletId: props.expenseWalletId,
incomeAmount: props.amount[2],
- incomeWalletId: props.incomeWalletId,
+ incomeWalletId: props.incomeWalletId,
type: props.trnType,
+
+ updatedAt: new Date().getTime(),
}
if (props.desc)
diff --git a/app/components/trnForm/utils/validate.ts b/app/components/trnForm/utils/validate.ts
index 18876816..e6e7ade2 100644
--- a/app/components/trnForm/utils/validate.ts
+++ b/app/components/trnForm/utils/validate.ts
@@ -1,50 +1,28 @@
-export function validate(values: any) {
- if (!values.amount && values.type !== 2) {
- return {
- error: 'trnForm.errors.amountEmpty',
- }
- }
+import type { Transaction, Transfer } from '~/components/trns/types'
- if (values.amount <= 0 && values.type !== 2) {
- return {
- error: 'trnForm.errors.amountNegative',
- }
- }
+import { trnItemSchema, TrnType } from '~/components/trns/types'
- if (values.amount === 0 && values.type !== 2) {
- return {
- error: 'trnForm.errors.amountZero',
- }
- }
+export function validate(values: Transaction | Transfer): string | null {
+ const result = trnItemSchema.safeParse(values)
- if (!values.walletId && values.type !== 2) {
- return {
- error: 'trnForm.errors.selectWallet',
- }
- }
+ if (!result.success) {
+ const issue = result.error.issues[0]
- if (!values.categoryId && values.type !== 2) {
- return {
- error: 'trnForm.errors.selectCategory',
- }
- }
+ if (values.type === TrnType.Transfer)
+ return 'trnForm.errors.transferAmountEmpty'
- // Transfer
- if (values.type === 2) {
- if (Number(values.incomeAmount) === 0 || Number(values.expenseAmount) === 0) {
- return {
- error: 'trnForm.errors.transferAmountEmpty',
- }
- }
-
- if (values.incomeWalletId === values.expenseWalletId) {
- return {
- error: 'trnForm.errors.transferSameWallet',
- }
- }
- }
+ if (issue?.path?.includes('amount'))
+ return 'trnForm.errors.amountEmpty'
+ if (issue?.path?.includes('walletId'))
+ return 'trnForm.errors.selectWallet'
+ if (issue?.path?.includes('categoryId'))
+ return 'trnForm.errors.selectCategory'
- return {
- valid: true,
+ return 'trnForm.errors.amountEmpty'
}
+
+ if (values.type === TrnType.Transfer && values.incomeWalletId === values.expenseWalletId)
+ return 'trnForm.errors.transferSameWallet'
+
+ return null
}
diff --git a/app/components/trns/Item.vue b/app/components/trns/Item.vue
index 55f827c8..bf70a817 100644
--- a/app/components/trns/Item.vue
+++ b/app/components/trns/Item.vue
@@ -18,7 +18,7 @@ const emit = defineEmits<{
<UiElement
v-if="props.trnItem"
:lineWidth="props.alt ? 3 : 0"
- :insideClasses="`${props.alt ? 'py-2 min-h-[32px]' : 'py-3 !min-h-[38px]'}`"
+ :insideClasses="props.alt ? 'py-2 min-h-[32px]' : 'py-3 min-h-[38px]'"
@click="emit('click')"
>
<template v-if="!alt" #leftIcon>
@@ -41,7 +41,7 @@ const emit = defineEmits<{
</div>
<div
- v-if="trnItem.type === 2"
+ v-if="trnItem.type === TrnType.Transfer"
class="flex items-center gap-2"
>
<Icon
@@ -82,11 +82,11 @@ const emit = defineEmits<{
</div>
<Amount
- v-if="trnItem.type !== 2"
+ v-if="trnItem.type !== TrnType.Transfer"
:amount="trnItem.amount"
:currencyCode="trnItem.wallet?.currency"
- :isShowMinus="trnItem.type === 0"
- :isShowPlus="trnItem.type === 1"
+ :isShowMinus="trnItem.type === TrnType.Expense"
+ :isShowPlus="trnItem.type === TrnType.Income"
:type="trnItem.type"
align="right"
class="grow"
@@ -96,7 +96,7 @@ const emit = defineEmits<{
<!-- Transfer -->
<div
- v-if="trnItem.type === 2"
+ v-if="trnItem.type === TrnType.Transfer"
class="grid gap-1"
>
<div class="text-3 flex items-center gap-1 text-sm leading-none">
@@ -116,8 +116,6 @@ const emit = defineEmits<{
/>
<template v-if="trnItem.incomeAmount !== trnItem.expenseAmount">
- <Icon name="lucide:" size="16" />
-
<Amount
:amount="trnItem.incomeAmount || trnItem.amount"
:class="{
diff --git a/app/components/trns/List.vue b/app/components/trns/List.vue
index aaca75e2..3878b1ab 100644
--- a/app/components/trns/List.vue
+++ b/app/components/trns/List.vue
@@ -10,28 +10,34 @@ import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
-const props = withDefaults(
- defineProps<{
- alt?: boolean
- initTrnType?: TrnsViewType
- isHideDates?: boolean
- isShowDates?: boolean
- isShowExpense?: boolean
- isShowFilterByDesc?: boolean
- isShowFilterByType?: boolean
- isShowGroupSum?: boolean
- isShowHeader?: boolean
- isShowIncome?: boolean
- isShowTransfers?: boolean
- size?: number
- trnsIds?: TrnId[]
- }>(),
- {
- initTrnType: 'all',
- size: 30,
- trnsIds: () => [],
- },
-)
+const {
+ alt,
+ initTrnType = 'all',
+ isShowDates,
+ isShowExpense,
+ isShowFilterByDesc,
+ isShowFilterByType,
+ isShowGroupSum,
+ isShowHeader,
+ isShowIncome,
+ isShowTransfers,
+ size = 30,
+ trnsIds = [],
+} = defineProps<{
+ alt?: boolean
+ initTrnType?: TrnsViewType
+ isHideDates?: boolean
+ isShowDates?: boolean
+ isShowExpense?: boolean
+ isShowFilterByDesc?: boolean
+ isShowFilterByType?: boolean
+ isShowGroupSum?: boolean
+ isShowHeader?: boolean
+ isShowIncome?: boolean
+ isShowTransfers?: boolean
+ size?: number
+ trnsIds?: TrnId[]
+}>()
const emit = defineEmits<{
click: []
@@ -46,7 +52,7 @@ const { getTotalOfTrnsIds } = useAmount()
const { t } = useI18n()
const { formatDate } = useDateFormats()
const isShowWithDesc = ref(false)
-const filterBy = ref<TrnsViewType>(props.initTrnType)
+const filterBy = ref<TrnsViewType>(initTrnType)
const pageNumber = ref(1)
type TypeFilter = {
@@ -58,39 +64,30 @@ type TypeFilter = {
}
const typeFilters = computed<TypeFilter[]>(() => {
- const all = {
- count: props.trnsIds.length,
- isShow: true,
- name: t('common.all'),
- slug: 'all',
- type: undefined,
- }
-
- const transfers = {
- count: props.trnsIds.filter(id => trnsStore.items[id]?.type === TrnType.Transfer).length,
- isShow: props.isShowTransfers,
- name: t('transfer.titleMoney'),
- slug: 'transfer',
- type: TrnType.Transfer,
- }
-
- const expense = {
- count: props.trnsIds.filter(id => trnsStore.items[id].type === TrnType.Expense).length,
- isShow: props.isShowExpense,
- name: t('money.expense'),
- slug: 'expense',
- type: TrnType.Expense,
- }
-
- const income = {
- count: props.trnsIds.filter(id => trnsStore.items[id].type === TrnType.Income).length,
- isShow: props.isShowIncome,
- name: t('money.income'),
- slug: 'income',
- type: TrnType.Income,
+ const counts = { adjustment: 0, expense: 0, income: 0, transfer: 0 }
+ for (const id of trnsIds) {
+ const trn = trnsStore.items[id]
+ if (!trn)
+ continue
+ if (trn.categoryId === 'adjustment') {
+ counts.adjustment++
+ continue
+ }
+ if (trn.type === TrnType.Expense)
+ counts.expense++
+ else if (trn.type === TrnType.Income)
+ counts.income++
+ else if (trn.type === TrnType.Transfer)
+ counts.transfer++
}
- return [all, expense, income, transfers].filter(item => item.isShow)
+ return [
+ { count: trnsIds.length, isShow: true, name: t('common.all'), slug: 'all', type: undefined },
+ { count: counts.expense, isShow: isShowExpense, name: t('money.expense'), slug: 'expense', type: TrnType.Expense },
+ { count: counts.income, isShow: isShowIncome, name: t('money.income'), slug: 'income', type: TrnType.Income },
+ { count: counts.transfer, isShow: isShowTransfers, name: t('transfer.titleMoney'), slug: 'transfer', type: TrnType.Transfer },
+ { count: counts.adjustment, isShow: counts.adjustment > 0, name: t('trnForm.adjustmentTitle'), slug: 'adjustment', type: undefined },
+ ].filter(item => item.isShow)
})
const selectedTypeFilter = computed(() => {
@@ -98,20 +95,27 @@ const selectedTypeFilter = computed(() => {
})
const isTrnsWithDesc = computed(() => {
- let ids = props.trnsIds ?? []
+ let ids = trnsIds ?? []
if (filterBy.value !== 'all') {
- ids = props.trnsIds.filter(id => trnsStore.items[id].type === selectedTypeFilter.value?.type)
+ ids = trnsIds.filter((id) => {
+ if (filterBy.value === 'adjustment')
+ return trnsStore.items[id]?.categoryId === 'adjustment'
+ return trnsStore.items[id].type === selectedTypeFilter.value?.type
+ })
}
return (ids).some(id => trnsStore.items[id]?.desc)
})
const selectedIds = computed(() => {
- let ids = props.trnsIds ?? []
+ let ids = trnsIds ?? []
if (filterBy.value !== 'all') {
- ids = props.trnsIds.filter((id) => {
+ ids = trnsIds.filter((id) => {
+ if (filterBy.value === 'adjustment')
+ return trnsStore.items[id]?.categoryId === 'adjustment'
+
if (filterBy.value === 'transfer') {
return trnsStore.items[id]?.type === selectedTypeFilter.value?.type || categoriesStore.transferCategoriesIds.includes(trnsStore.items[id]?.categoryId)
}
@@ -127,7 +131,7 @@ const selectedIds = computed(() => {
return ids
})
-const paginatedTrnsIds = computed(() => selectedIds.value.slice(0, pageNumber.value * props.size))
+const paginatedTrnsIds = computed(() => selectedIds.value.slice(0, pageNumber.value * size))
const isShowedAllTrns = computed(() => paginatedTrnsIds.value.length === selectedIds.value.length)
@@ -137,6 +141,9 @@ function setFilterBy(type: TrnsViewType | 'all') {
return
}
+ if (type !== 'all' && typeFilters.value.find(f => f.slug === type)?.count === 0)
+ return
+
filterBy.value = type ?? 'all'
}
@@ -164,7 +171,7 @@ function onOpenTrnForm(date: number) {
</script>
<template>
- <div>
+ <div class="min-w-0">
<!-- Header -->
<slot
v-if="isShowHeader"
@@ -172,37 +179,38 @@ function onOpenTrnForm(date: number) {
:paginatedTrnsIds
:selectedIds
>
- <UiTitle8 isHideArrow>
+ <UiTitleCollapse isHideArrow>
{{ t('trns.title') }} {{ selectedIds.length > 0 ? selectedIds.length : '' }}
- </UiTitle8>
+ </UiTitleCollapse>
</slot>
<slot name="contentBefore" />
<!-- Filter by type -->
- <UiTabs2
+ <UiTabsScroll
v-if="isShowFilterByType && typeFilters.length > 2"
class="mb-2"
>
- <UiTabsItem4
+ <UiTabsItemPill
v-for="filterItem in typeFilters"
:key="filterItem.slug"
+ variant="outline"
:isActive="filterBy === filterItem.slug"
:class="{
- 'opacity-50': filterItem.count === 0,
+ 'pointer-events-none opacity-50': filterItem.count === 0,
}"
@click="setFilterBy(filterItem.slug)"
>
{{ filterItem.name }}
- </UiTabsItem4>
- </UiTabs2>
+ </UiTabsItemPill>
+ </UiTabsScroll>
<!-- With Description -->
<div
v-if="isShowFilterByDesc && isTrnsWithDesc && selectedIds.length > 0"
class="relative"
>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="isShowWithDesc"
:title="t('trns.filter.showTrnsWithDesc')"
showCheckbox
@@ -211,7 +219,7 @@ function onOpenTrnForm(date: number) {
</div>
<!-- No Trns -->
- <TrnsNoTrns v-if="props.isShowDates && selectedIds.length === 0" />
+ <TrnsNoTrns v-if="isShowDates && selectedIds.length === 0" />
<!-- Hide dates -->
<div v-if="!isShowDates">
@@ -241,16 +249,17 @@ function onOpenTrnForm(date: number) {
/>
</div>
- <TrnsItemWrap
- v-for="trnId in paginatedTrnsIds"
- :key="trnId"
- :alt="props.alt"
- :date="formatDate(trnsStore.computeTrnItem(trnId)?.date, 'trnItem')"
- :trnId="trnId"
- :trnItem="trnsStore.computeTrnItem(trnId)"
- class="group/trn group"
- @click="emit('click')"
- />
+ <template v-for="trnId in paginatedTrnsIds" :key="trnId">
+ <TrnsItemWrap
+ v-if="trnsStore.computeTrnItem(trnId)"
+ :alt="alt"
+ :date="formatDate(trnsStore.computeTrnItem(trnId)?.date, 'trnItem')"
+ :trnId="trnId"
+ :trnItem="trnsStore.computeTrnItem(trnId)"
+ class="group/trn group"
+ @click="emit('click')"
+ />
+ </template>
</div>
<!-- With dates -->
@@ -301,16 +310,17 @@ function onOpenTrnForm(date: number) {
</div>
<div>
- <TrnsItemWrap
- v-for="trnId in groupTrnsIds"
- :key="trnId"
- :alt="props.alt"
- :trnId="trnId"
- :trnItem="trnsStore.computeTrnItem(trnId)"
- :date="formatDate(trnsStore.computeTrnItem(trnId)?.date, 'trnItem')"
- class="group"
- @click="emit('click')"
- />
+ <template v-for="trnId in groupTrnsIds" :key="trnId">
+ <TrnsItemWrap
+ v-if="trnsStore.computeTrnItem(trnId)"
+ :alt="alt"
+ :trnId="trnId"
+ :trnItem="trnsStore.computeTrnItem(trnId)"
+ :date="formatDate(trnsStore.computeTrnItem(trnId)?.date, 'trnItem')"
+ class="group"
+ @click="emit('click')"
+ />
+ </template>
</div>
</div>
</div>
@@ -321,7 +331,7 @@ function onOpenTrnForm(date: number) {
class="px-2 pt-1"
>
<div
- class="flex-center text-muted hover:bg-item-6 rounded-[var(--ui-radius)] bg-[var(--item-5)] px-5 py-2 text-sm"
+ class="flex-center text-muted hover:bg-item-6 rounded-(--ui-radius) bg-(--item-5) px-5 py-2 text-sm"
@click="pageNumber = ++pageNumber"
>
{{ t('trns.more') }} {{ paginatedTrnsIds.length }} /
diff --git a/app/components/trns/getTrns.test.ts b/app/components/trns/getTrns.test.ts
index 248ca96e..8e7dcc62 100644
--- a/app/components/trns/getTrns.test.ts
+++ b/app/components/trns/getTrns.test.ts
@@ -13,7 +13,7 @@ describe('get Transactions IDs', () => {
'transactionExpenseWalletCashUSD400',
'transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',
'transferExpenseWalletCashUSD10IncomeWalletRUB700',
- 'transferCategoryNameIncomeWalletCashUSD30',
+ 'transferCategoryIncomeWalletCashUSD30',
'transferCategoryIdExpenseWalletCashUSD30',
]))
})
@@ -28,15 +28,6 @@ describe('get Transactions IDs', () => {
]))
})
- it('get Transactions IDs in Wallets with deprecated Transfers', () => {
- const walletsIds = ['walletDeprecatedTransferIncome', 'walletDeprecatedTransferExpense']
- const trnsIds = getTrnsIds({ trnsItems, walletsIds })
-
- expect(trnsIds).toEqual(expect.arrayContaining([
- 'transferOLDExpense2500Income3500',
- ]))
- })
-
it('get All Transactions', () => {
const trnsIds = getTrnsIds({ trnsItems })
@@ -48,9 +39,8 @@ describe('get Transactions IDs', () => {
'transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',
'transferExpenseWalletRUB300IncomeWalletCreditUSD10',
'transferExpenseWalletCashUSD10IncomeWalletRUB700',
- 'transferCategoryNameIncomeWalletCashUSD30',
+ 'transferCategoryIncomeWalletCashUSD30',
'transferCategoryIdExpenseWalletCashUSD30',
- 'transferOLDExpense2500Income3500',
]))
})
})
diff --git a/app/components/trns/getTrns.ts b/app/components/trns/getTrns.ts
index 7f5fc635..7d552695 100644
--- a/app/components/trns/getTrns.ts
+++ b/app/components/trns/getTrns.ts
@@ -6,6 +6,10 @@ export function getTrnsIds(props: TrnsGetterProps) {
const trnsIds: TrnId[] = props.trnsIds || Object.keys(props.trnsItems ?? {})
+ 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 filters: Array<(ids: TrnId[]) => TrnId[]> = [
// Type filter
ids => props.trnType != null
@@ -13,8 +17,8 @@ export function getTrnsIds(props: TrnsGetterProps) {
: ids,
// Types filter
- ids => Array.isArray(props.trnsTypes)
- ? ids.filter(id => props.trnsTypes?.includes(props.trnsItems?.[id]?.type))
+ ids => typesSet
+ ? ids.filter(id => typesSet.has(props.trnsItems?.[id]?.type))
: ids,
// Date filters
@@ -26,23 +30,18 @@ export function getTrnsIds(props: TrnsGetterProps) {
: ids,
// Wallet filter
- ids => props.walletsIds?.length
+ ids => walletsSet
? ids.filter((id) => {
const trn = props.trnsItems?.[id]
- const walletIds = [
- trn?.walletId,
- trn?.expenseWalletId,
- trn?.incomeWalletId,
- trn?.walletToId,
- trn?.walletFromId,
- ]
- return walletIds.some(walletId => props.walletsIds?.includes(walletId))
+ return walletsSet.has(trn?.walletId)
+ || walletsSet.has(trn?.expenseWalletId)
+ || walletsSet.has(trn?.incomeWalletId)
})
: ids,
// Category filter
- ids => props.categoriesIds?.length
- ? ids.filter(id => props.categoriesIds?.includes(props.trnsItems?.[id]?.categoryId))
+ ids => categoriesSet
+ ? ids.filter(id => categoriesSet.has(props.trnsItems?.[id]?.categoryId))
: ids,
]
diff --git a/app/components/trns/helpers.ts b/app/components/trns/helpers.ts
deleted file mode 100644
index 3a708b97..00000000
--- a/app/components/trns/helpers.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import localforage from 'localforage'
-
-import type { TrnId, Trns } from '~/components/trns/types'
-
-// save added trn to local
-export async function saveTrnToAddLaterLocal({ id, values }: Trns) {
- const trns: Trns = await localforage.getItem('finapp.trns.offline.update') || {}
- await localforage.setItem('finapp.trns.offline.update', {
- ...trns,
- [id]: values,
- })
-}
-
-// remove added trn from local
-export async function removeTrnToAddLaterLocal(id: TrnId) {
- const trns: Trns = await localforage.getItem('finapp.trns.offline.update') || {}
- if (trns[id]) {
- delete trns[id]
- await localforage.setItem('finapp.trns.offline.update', trns || {})
- }
-}
-
-// save deleted trn to local
-export async function saveTrnIdForDeleteWhenClientOnline(id: TrnId) {
- const ids: TrnId[] = await localforage.getItem('finapp.trns.offline.delete') ?? []
-
- if (ids?.includes(id))
- return
-
- ids?.push(id)
- await localforage.setItem('finapp.trns.offline.delete', ids)
-}
-
-// remove deleted trn from local
-export async function removeTrnToDeleteLaterLocal(id: TrnId) {
- const ids: TrnId[] = await localforage.getItem('finapp.trns.offline.delete') ?? []
-
- const trnId = ids.find(trnId => trnId === id)
- if (!trnId)
- return
-
- const newIds = ids.filter(trnId => trnId !== id)
- await localforage.setItem('finapp.trns.offline.delete', newIds)
-}
diff --git a/app/components/trns/pages/History.vue b/app/components/trns/pages/History.vue
index e51fd176..81fb980e 100644
--- a/app/components/trns/pages/History.vue
+++ b/app/components/trns/pages/History.vue
@@ -5,12 +5,13 @@ import type { CategoryId } from '~/components/categories/types'
import type { WalletId } from '~/components/wallets/types'
import { useFilter } from '~/components/stat/filter/useFilter'
+import { filterKey } from '~/components/stat/injectionKeys'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
const { t } = useI18n()
const filter = useFilter()
const trnsStore = useTrnsStore()
-provide('filter', filter)
+provide(filterKey, filter)
useHead({
title: t('trns.history'),
@@ -66,7 +67,7 @@ watch([filter.categoriesIds, filter.walletsIds], () => {
</UiHeader>
<div class="pageWrapper bg-default mb-4 rounded-xl pt-1 pb-4">
- <div class="grid gap-3 @3xl/main:max-w-md">
+ <div class="grid min-w-0 gap-3 @3xl/main:max-w-md">
<TrnsList
:trnsIds
isShowDates
diff --git a/app/components/trns/types.ts b/app/components/trns/types.ts
index d24d97ae..a5d901a4 100644
--- a/app/components/trns/types.ts
+++ b/app/components/trns/types.ts
@@ -1,76 +1,66 @@
+import { z } from 'zod/v4'
+
import type { CategoryId, CategoryItem } from '~/components/categories/types'
import type { WalletId, WalletItem } from '~/components/wallets/types'
-export type TrnId = string
-
export enum TrnType {
- Expense,
- Income,
- Transfer,
+ Expense = 0,
+ Income = 1,
+ Transfer = 2,
}
-export type TrnsViewType = 'all' | 'expense' | 'income' | 'transfer'
-
-export enum TransferType {
- Expense,
- Income,
-}
+export type TrnId = string
-export enum TrnTypeSlug {
- Expense = 'expense',
- Income = 'income',
- Transfer = 'transfer',
+export type TrnsViewType = 'adjustment' | 'all' | 'expense' | 'income' | 'transfer'
+
+export type TransferSide = 'expense' | 'income'
+
+const baseTrnSchema = z.object({
+ date: z.number(),
+ desc: z.string().optional(),
+ updatedAt: z.number(),
+})
+
+const transactionSchema = baseTrnSchema.extend({
+ amount: z.number().positive(),
+ categoryId: z.string().min(1),
+ type: z.union([z.literal(TrnType.Expense), z.literal(TrnType.Income)]),
+ walletId: z.string().min(1),
+})
+
+const transferSchema = baseTrnSchema.extend({
+ categoryId: z.literal('transfer'),
+ expenseAmount: z.number().positive(),
+ expenseWalletId: z.string().min(1),
+ incomeAmount: z.number().positive(),
+ incomeWalletId: z.string().min(1),
+ type: z.literal(TrnType.Transfer),
+})
+
+export const trnItemSchema = z.discriminatedUnion('type', [
+ transactionSchema,
+ transferSchema,
+])
+
+export type Transaction = z.infer<typeof transactionSchema>
+export type Transfer = z.infer<typeof transferSchema>
+export type TrnItem = z.infer<typeof trnItemSchema>
+type TrnItemFullBase = {
+ category: CategoryItem
+ categoryParent?: CategoryItem
+ id: TrnId
}
-type BaseTrn = {
- date: number
- desc?: string
- /** @deprecated: use desc */
- description?: string
- edited: number
+type TransactionFull = Transaction & TrnItemFullBase & {
+ wallet: WalletItem
}
-export type Transaction = {
- amount: number
- categoryId: CategoryId
- type: TrnType.Income | TrnType.Expense
- walletId: WalletId
-} & BaseTrn
-
-export type Transfer = {
- categoryId: 'transfer'
- expenseAmount: number
-
- expenseWalletId: WalletId
- incomeAmount: number
-
- incomeWalletId: WalletId
- type: TrnType.Transfer
-} & BaseTrn
-
-/** @deprecated: use Transfer */
-export type TransferDeprecated = {
- amountFrom: number
- amountTo: number
- categoryId: 'transfer'
- date: number
-
- edited: number
- type: TrnType.Transfer
-
- walletFromId: WalletId
- walletToId: WalletId
+type TransferFull = Transfer & TrnItemFullBase & {
+ expenseWallet: WalletItem
+ incomeWallet: WalletItem
}
-export type TrnItem = Transaction | Transfer
-export type TrnItemWithId = (Transaction | Transfer) & TrnId
-export type TrnItemFull = (Transaction | Transfer)
- & { id: TrnId }
- & { category: CategoryItem }
- & { categoryParent?: CategoryItem }
- & { wallet: WalletItem }
-
-export type TrnItemDirty = Transaction | Transfer | TransferDeprecated
+export type TrnItemFull = TransactionFull | TransferFull
export type Trns = Record<TrnId, TrnItem>
@@ -101,7 +91,7 @@ export type TrnFormValues = {
desc?: string
expenseWalletId: WalletId | null
incomeWalletId: WalletId | null
- transferType: TransferType
+ transferType: TransferSide
trnId: null | TrnId
trnType: TrnType
diff --git a/app/components/trns/useTrnsStore.test.ts b/app/components/trns/useTrnsStore.test.ts
new file mode 100644
index 00000000..82d2bdff
--- /dev/null
+++ b/app/components/trns/useTrnsStore.test.ts
@@ -0,0 +1,586 @@
+import { createPinia, setActivePinia } from 'pinia'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { TrnItem } from '~/components/trns/types'
+
+// --- Mocks ---
+
+const localforageStore = new Map<string, any>()
+vi.mock('localforage', () => ({
+ default: {
+ getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),
+ removeItem: vi.fn((key: string) => {
+ localforageStore.delete(key)
+ return Promise.resolve()
+ }),
+ setItem: vi.fn((key: string, value: any) => {
+ localforageStore.set(key, value)
+ return Promise.resolve()
+ }),
+ },
+}))
+
+vi.mock('@vueuse/core', () => ({
+ useDebounceFn: (fn: (...args: any[]) => any) => fn,
+}))
+
+vi.mock('vue-deepunref', () => ({
+ deepUnref: (v: any) => v,
+}))
+
+vi.mock('~~/services/convex/api', () => ({
+ convexTrnsToMap: (arr: any[]) => {
+ const map: Record<string, any> = {}
+ for (const item of arr) {
+ const { _id, ...rest } = item
+ map[_id] = rest
+ }
+ return map
+ },
+}))
+
+const mutationMock = vi.fn(() => Promise.resolve())
+const queryMock = vi.fn(() => Promise.resolve(null))
+const onUpdateMock = vi.fn()
+
+// Mock Convex composables (auto-imported in Nuxt)
+vi.stubGlobal('useConvexClient', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+ query: queryMock,
+}))
+vi.stubGlobal('useConvexClientComposable', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+ query: queryMock,
+}))
+vi.stubGlobal('asConvexId', (id: string) => id)
+vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))
+vi.stubGlobal('cleanupFrontendIds', <T>(data: Record<string, T>, pendingUpdates: Record<string, T>) => {
+ const result = { ...data }
+ for (const id of Object.keys(result)) {
+ if (id.startsWith('local_') && !pendingUpdates[id])
+ delete result[id]
+ }
+ return result
+})
+vi.stubGlobal('useConvexApi', () => ({
+ api: {
+ trns: { create: 'trns.create', delta: 'trns.delta', ensureSyncMeta: 'trns.ensureSyncMeta', idsHash: 'trns.idsHash', list: 'trns.list', remove: 'trns.remove', update: 'trns.update' },
+ },
+}))
+vi.stubGlobal('useConvexClientWithApi', () => ({
+ api: {
+ trns: { create: 'trns.create', delta: 'trns.delta', ensureSyncMeta: 'trns.ensureSyncMeta', idsHash: 'trns.idsHash', list: 'trns.list', remove: 'trns.remove', update: 'trns.update' },
+ },
+ client: {
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+ query: queryMock,
+ },
+}))
+
+// Toast & i18n auto-imports
+const toastAddMock = vi.fn()
+vi.stubGlobal('useToast', () => ({ add: toastAddMock }))
+vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
+vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+
+// Emo helpers
+vi.mock('~/assets/js/emo', () => ({
+ errorEmo: ['😿'],
+ random: (items: any[]) => items[0],
+}))
+
+// Pinia auto-imports
+vi.stubGlobal('defineStore', (await import('pinia')).defineStore)
+vi.stubGlobal('shallowRef', (await import('vue')).shallowRef)
+vi.stubGlobal('computed', (await import('vue')).computed)
+
+// Mock demo composable
+vi.mock('~/components/demo/useDemo', () => ({
+ useDemo: () => ({
+ isDemo: { value: false },
+ }),
+}))
+
+// Mock dependent stores
+vi.mock('~/components/categories/useCategoriesStore', () => ({
+ useCategoriesStore: () => ({
+ getTransactibleIds: (ids: any) => ids,
+ items: { food: { color: '#f00', icon: 'mdi:food', name: 'Food', parentId: 0, showInLastUsed: true, showInQuickSelector: true }, transfer: { color: '#000', icon: 'mdi:repeat', name: 'Transfer', parentId: 0, showInLastUsed: false, showInQuickSelector: false } },
+ transferCategoriesIds: ['transfer'],
+ }),
+}))
+
+vi.mock('~/components/wallets/useWalletsStore', () => ({
+ useWalletsStore: () => ({
+ items: { wallet1: { color: '#0f0', currency: 'USD', desc: '', isArchived: false, isExcludeInTotal: false, isWithdrawal: false, name: 'Cash', order: 0, type: 'cash', updatedAt: 0 } },
+ }),
+}))
+
+vi.mock('~/components/offline/replay', () => ({
+ isReplaying: () => false,
+}))
+
+// Mock offline helpers — spy on real implementations
+const offlineHelpers = await import('~/components/offline/helpers')
+vi.mock('~/components/offline/helpers', async (importOriginal) => {
+ const actual = await importOriginal() as any
+ return {
+ clearOfflineQueue: vi.fn(actual.clearOfflineQueue),
+ getAllOfflineOps: vi.fn(actual.getAllOfflineOps),
+ getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),
+ pushOfflineOp: vi.fn(actual.pushOfflineOp),
+ removeOfflineOp: vi.fn(actual.removeOfflineOp),
+ removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),
+ removeOfflineOps: vi.fn(actual.removeOfflineOps),
+ }
+})
+
+// Re-import after mocks
+const { useTrnsStore } = await import('~/components/trns/useTrnsStore')
+
+// --- Helpers ---
+
+function makeTrn(overrides: Partial<TrnItem> = {}): TrnItem {
+ return {
+ amount: 100,
+ categoryId: 'food',
+ date: 1700000000000,
+ type: 0,
+ updatedAt: 1700000000000,
+ walletId: 'wallet1',
+ ...overrides,
+ } as TrnItem
+}
+
+// --- Tests ---
+
+describe('useTrnsStore', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ localforageStore.clear()
+ vi.clearAllMocks()
+ mutationMock.mockReturnValue(Promise.resolve())
+ toastAddMock.mockClear()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ describe('saveTrn — optimistic UI', () => {
+ it('updates items immediately', () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ const trn = makeTrn()
+ store.saveTrn({ id: 'trn1', values: trn })
+
+ expect(store.items).toHaveProperty('trn1')
+ expect(store.items!.trn1.amount).toBe(100)
+ })
+
+ it('saves to localforage', () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ expect(localforageStore.get('finapp.trns')).toHaveProperty('trn1')
+ })
+
+ it('pushes to offline queue immediately', () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'trns', id: 'trn1', type: 'create' }),
+ )
+ })
+
+ it('fires Convex create mutation for new trn', () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'trns.create',
+ expect.objectContaining({ amount: 100, type: 0 }),
+ )
+ })
+
+ it('fires Convex update mutation for existing trn', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ store.saveTrn({ id: 'trn1', values: makeTrn({ amount: 200 }) })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'trns.update',
+ expect.objectContaining({ amount: 200, id: 'trn1' }),
+ )
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ // Wait for .then() to resolve
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('trns', 'trn1')
+ })
+ })
+
+ it('keeps offline queue when mutation fails', async () => {
+ // Mutation returns a never-resolving promise to simulate offline
+ mutationMock.mockReturnValue(new Promise(() => {}))
+
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ // Give time for potential .then() — it shouldn't fire
+ await new Promise(r => setTimeout(r, 10))
+
+ expect(offlineHelpers.removeOfflineOp).not.toHaveBeenCalled()
+ })
+
+ it('adds updatedAt timestamp', () => {
+ const store = useTrnsStore()
+ store.items = {}
+ const before = Date.now()
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ expect(store.items!.trn1.updatedAt).toBeGreaterThanOrEqual(before)
+ })
+
+ it('shows toast on mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('network')))
+
+ const store = useTrnsStore()
+ store.items = {}
+
+ store.saveTrn({ id: 'trn1', values: makeTrn() })
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error', description: 'trns.errors.saveFailed' }),
+ )
+ })
+ })
+ })
+
+ describe('deleteTrn — optimistic UI', () => {
+ it('removes item from store immediately', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn(), trn2: makeTrn() }
+
+ store.deleteTrn('trn1')
+
+ expect(store.items).not.toHaveProperty('trn1')
+ expect(store.items).toHaveProperty('trn2')
+ })
+
+ it('pushes to offline queue', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ store.deleteTrn('trn1')
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'trns', id: 'trn1', type: 'delete' }),
+ )
+ })
+
+ it('fires Convex remove mutation', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ store.deleteTrn('trn1')
+
+ expect(mutationMock).toHaveBeenCalledWith('trns.remove', { id: 'trn1' })
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ store.deleteTrn('trn1')
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('trns', 'trn1')
+ })
+ })
+
+ it('shows toast on mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('network')))
+
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ store.deleteTrn('trn1')
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error', description: 'trns.errors.deleteFailed' }),
+ )
+ })
+ })
+ })
+
+ describe('deleteTrnsByIds', () => {
+ it('batch deletes all trns in single mutation', () => {
+ const store = useTrnsStore()
+ store.items = {
+ trn1: makeTrn(),
+ trn2: makeTrn(),
+ trn3: makeTrn(),
+ }
+
+ store.deleteTrnsByIds(['trn1', 'trn3'])
+
+ expect(store.items).not.toHaveProperty('trn1')
+ expect(store.items).toHaveProperty('trn2')
+ expect(store.items).not.toHaveProperty('trn3')
+ expect(mutationMock).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ describe('removeTrnsFromStore', () => {
+ it('removes trns from store without mutations or queue', () => {
+ const store = useTrnsStore()
+ store.items = {
+ trn1: makeTrn(),
+ trn2: makeTrn(),
+ trn3: makeTrn(),
+ }
+
+ store.removeTrnsFromStore(['trn1', 'trn3'])
+
+ expect(store.items).not.toHaveProperty('trn1')
+ expect(store.items).toHaveProperty('trn2')
+ expect(store.items).not.toHaveProperty('trn3')
+ expect(mutationMock).not.toHaveBeenCalled()
+ expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('initTrns — sync flow', () => {
+ it('performs full sync when no cached data', async () => {
+ queryMock.mockImplementation((queryName: string) => {
+ if (queryName === 'trns.list')
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })
+ return Promise.resolve(null)
+ })
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items).toHaveProperty('trn1')
+ const syncMeta = localforageStore.get('finapp.trns.syncMeta')
+ // Hash is computed locally from list result, not fetched from server
+ expect(syncMeta).toHaveProperty('idsHash')
+ expect(syncMeta.idsHash).toBeTruthy()
+ expect(syncMeta).not.toHaveProperty('serverIds')
+ })
+
+ it('performs full sync with multiple pages', async () => {
+ let callCount = 0
+ queryMock.mockImplementation((queryName: string) => {
+ if (queryName === 'trns.list') {
+ callCount++
+ if (callCount === 1) {
+ return Promise.resolve({ continueCursor: 'cursor1', isDone: false, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })
+ }
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn2', amount: 200, categoryId: 'food', date: 1700000001000, type: 0, updatedAt: 1700000001000, walletId: 'wallet1' }] })
+ }
+ return Promise.resolve(null)
+ })
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items).toHaveProperty('trn1')
+ expect(store.items).toHaveProperty('trn2')
+ })
+
+ it('performs delta sync with hash match (no deletion check)', async () => {
+ // Pre-populate cache and sync meta — compute real hash for trn1
+ const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')
+ const hash = computeHash(['trn1'])
+ localforageStore.set('finapp.trns', { trn1: makeTrn() })
+ localforageStore.set('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })
+
+ queryMock.mockImplementation((queryName: string) => {
+ if (queryName === 'trns.delta')
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [] })
+ if (queryName === 'trns.idsHash')
+ return Promise.resolve({ hash, serverTime: 1700000002000 })
+ return Promise.resolve(null)
+ })
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items).toHaveProperty('trn1')
+ })
+
+ it('performs delta sync with hash mismatch (falls back to fullSync)', async () => {
+ // Cache has trn1 and trn2, but trn2 was deleted on server
+ localforageStore.set('finapp.trns', { trn1: makeTrn(), trn2: makeTrn() })
+ localforageStore.set('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })
+
+ queryMock.mockImplementation((queryName: string) => {
+ if (queryName === 'trns.delta')
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [] })
+ if (queryName === 'trns.idsHash')
+ return Promise.resolve({ hash: 'new_hash', serverTime: 1700000002000 })
+ // fullSync fallback: list returns only trn1
+ if (queryName === 'trns.list')
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })
+ return Promise.resolve(null)
+ })
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items).toHaveProperty('trn1')
+ expect(store.items).not.toHaveProperty('trn2')
+ })
+
+ it('applies delta changes and updates hash', async () => {
+ const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')
+ const hash = computeHash(['trn1'])
+ localforageStore.set('finapp.trns', { trn1: makeTrn({ amount: 100 }) })
+ localforageStore.set('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })
+
+ queryMock.mockImplementation((queryName: string) => {
+ if (queryName === 'trns.delta')
+ return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 200, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000001000, walletId: 'wallet1' }] })
+ if (queryName === 'trns.idsHash')
+ return Promise.resolve({ hash, serverTime: 1700000002000 })
+ return Promise.resolve(null)
+ })
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items!.trn1.amount).toBe(200)
+ })
+
+ it('clears store when user has no trns (idsHash returns null)', async () => {
+ localforageStore.set('finapp.trns', { trn1: makeTrn() })
+ localforageStore.set('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })
+
+ queryMock.mockImplementation(() => Promise.resolve(null))
+
+ const store = useTrnsStore()
+ await store.initTrns()
+
+ expect(store.items).toBeNull()
+ })
+ })
+
+ describe('computeTrnItem', () => {
+ it('returns null when store not loaded', () => {
+ const store = useTrnsStore()
+ store.items = false as any
+
+ expect(store.computeTrnItem('trn1')).toBeNull()
+ })
+
+ it('returns null when trn not found', () => {
+ const store = useTrnsStore()
+ store.items = {}
+
+ expect(store.computeTrnItem('nonexistent')).toBeNull()
+ })
+
+ it('returns null when category not found', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn({ categoryId: 'nonexistent' }) }
+
+ expect(store.computeTrnItem('trn1')).toBeNull()
+ })
+
+ it('returns null when wallet not found', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn({ walletId: 'nonexistent' }) }
+
+ expect(store.computeTrnItem('trn1')).toBeNull()
+ })
+
+ it('returns full item for regular transaction', () => {
+ const store = useTrnsStore()
+ store.items = { trn1: makeTrn() }
+
+ const result = store.computeTrnItem('trn1')
+ expect(result).not.toBeNull()
+ expect(result!.id).toBe('trn1')
+ expect(result!.category).toEqual(expect.objectContaining({ name: 'Food' }))
+ expect((result as any).wallet).toEqual(expect.objectContaining({ name: 'Cash' }))
+ })
+
+ it('returns full item for transfer', () => {
+ const store = useTrnsStore()
+ store.items = {
+ trn1: makeTrn({
+ categoryId: 'transfer',
+ expenseAmount: 100,
+ expenseWalletId: 'wallet1',
+ incomeAmount: 100,
+ incomeWalletId: 'wallet1',
+ type: 2,
+ } as any),
+ }
+
+ const result = store.computeTrnItem('trn1')
+ expect(result).not.toBeNull()
+ expect(result!.id).toBe('trn1')
+ expect((result as any).expenseWallet).toEqual(expect.objectContaining({ name: 'Cash' }))
+ expect((result as any).incomeWallet).toEqual(expect.objectContaining({ name: 'Cash' }))
+ })
+
+ it('returns null when transfer expense wallet missing', () => {
+ const store = useTrnsStore()
+ store.items = {
+ trn1: makeTrn({
+ categoryId: 'transfer',
+ expenseAmount: 100,
+ expenseWalletId: 'nonexistent',
+ incomeAmount: 100,
+ incomeWalletId: 'wallet1',
+ type: 2,
+ } as any),
+ }
+
+ expect(store.computeTrnItem('trn1')).toBeNull()
+ })
+
+ it('returns null when transfer income wallet missing', () => {
+ const store = useTrnsStore()
+ store.items = {
+ trn1: makeTrn({
+ categoryId: 'transfer',
+ expenseAmount: 100,
+ expenseWalletId: 'wallet1',
+ incomeAmount: 100,
+ incomeWalletId: 'nonexistent',
+ type: 2,
+ } as any),
+ }
+
+ expect(store.computeTrnItem('trn1')).toBeNull()
+ })
+ })
+})
diff --git a/app/components/trns/useTrnsStore.ts b/app/components/trns/useTrnsStore.ts
index f1ebca61..4ecda7df 100644
--- a/app/components/trns/useTrnsStore.ts
+++ b/app/components/trns/useTrnsStore.ts
@@ -1,30 +1,62 @@
+import type { ConvexClient } from 'convex/browser'
+import type { FunctionReference } from 'convex/server'
+
import localforage from 'localforage'
-import { deepUnref } from 'vue-deepunref'
-import { getDataAndWatch, removeData, saveData, unsubscribeData, updateData } from '~~/services/firebase/api'
+import { convexTrnsToMap } from '~~/services/convex/api'
+import { xorIdsHash } from '~~/utils/fnv1a'
import type { Range } from '~/components/date/types'
-import type { TrnId, TrnItem, TrnItemFull, Trns, TrnsGetterProps,
-} from '~/components/trns/types'
+import type { TrnId, TrnItem, TrnItemFull, Trns, TrnsGetterProps } from '~/components/trns/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { getEndOf, getStartOf } from '~/components/date/utils'
import { useDemo } from '~/components/demo/useDemo'
+import { pushOfflineOp, removeOfflineOps } from '~/components/offline/helpers'
+import { isReplaying } from '~/components/offline/replay'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { getTrnsIds } from '~/components/trns/getTrns'
-import { removeTrnToAddLaterLocal, removeTrnToDeleteLaterLocal, saveTrnIdForDeleteWhenClientOnline, saveTrnToAddLaterLocal } from '~/components/trns/helpers'
-import { useUserStore } from '~/components/user/useUserStore'
+import { TrnType } from '~/components/trns/types'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { createDebouncedPersist, handleMutationResult, isPersistBlocked, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
type TrnsGetterParams = {
includesChildCategories?: boolean
}
+const logger = createLogger('trns')
+
+async function fetchAllPages<T>(
+ client: ConvexClient,
+ queryFn: FunctionReference<'query'>,
+ args: Record<string, unknown>,
+ pageSize = 5000,
+): Promise<T[]> {
+ const allItems: T[] = []
+ let cursor: string | null = null
+ let isDone = false
+
+ while (!isDone) {
+ const result = await client.query(queryFn, {
+ ...args,
+ paginationOpts: { cursor, numItems: pageSize },
+ })
+ if (!result)
+ return allItems
+ allItems.push(...result.page)
+ isDone = result.isDone
+ cursor = result.continueCursor
+ }
+
+ return allItems
+}
+
export const useTrnsStore = defineStore('trns', () => {
- const userStore = useUserStore()
const categoriesStore = useCategoriesStore()
const walletsStore = useWalletsStore()
- const { deleteDemoTrns, isDemo } = useDemo()
+ const { isDemo } = useDemo()
- const items = shallowRef<Trns | null | false>(false)
+ const items = shallowRef<Trns | null>(null)
function getStoreTrnsIds(props: TrnsGetterProps, params?: TrnsGetterParams) {
const categoriesIds = params?.includesChildCategories
@@ -34,7 +66,7 @@ export const useTrnsStore = defineStore('trns', () => {
return getTrnsIds({
...props,
categoriesIds,
- trnsItems: items.value,
+ trnsItems: items.value ?? undefined,
})
}
@@ -58,171 +90,305 @@ export const useTrnsStore = defineStore('trns', () => {
if (!hasItems.value)
return false
- return (
- Object.keys(items.value)
- .sort((a, b) => items.value[b].date - items.value[a].date)
- .find(trnId =>
- !categoriesStore.transferCategoriesIds.includes(items.value[trnId].categoryId) && items.value[trnId]?.type !== 2,
- ) ?? false
- )
+ const transferIds = new Set(categoriesStore.transferCategoriesIds)
+ let latestId: TrnId | false = false
+ let latestDate = -1
+
+ for (const trnId in items.value) {
+ const trn = items.value[trnId]
+ if (!trn || trn.type === TrnType.Transfer || trn.categoryId === 'adjustment' || transferIds.has(trn.categoryId))
+ continue
+ if (trn.date > latestDate) {
+ latestDate = trn.date
+ latestId = trnId
+ }
+ }
+
+ return latestId
})
const lastCreatedTrnItem = computed<TrnItem | false>(() => items.value?.[lastCreatedTrnId.value])
- function initTrns() {
- const path = `users/${userStore.uid}/trns`
- getDataAndWatch(path, (values: Trns | null) => setTrns(values))
+ type TrnsSyncMeta = {
+ idsHash: string
+ lastSyncedAt: number
+ }
+
+ async function fullSync(retried = false): Promise<void> {
+ const { api, client } = useConvexClientWithApi()
+ const trns = await fetchAllPages(client, api.trns.list, {})
+ let data: Trns | null = trns.length ? convexTrnsToMap(trns) : null
+
+ // Verify local hash against server + get server timestamp
+ const hashResult = await client.query(api.trns.idsHash, {})
+ const localHash = xorIdsHash(trns.map((t: { _id: string }) => t._id))
+
+ if (hashResult && localHash !== hashResult.hash) {
+ if (!retried) {
+ logger.log('fullSync hash mismatch, retrying')
+ return fullSync(true)
+ }
+ logger.log('fullSync hash still mismatched after retry, proceeding')
+ }
+
+ const lastSyncedAt = hashResult?.serverTime ?? Date.now()
+
+ if (data)
+ data = await mergeOfflineOps(data, 'trns')
+
+ setTrns(data)
+
+ const syncMeta: TrnsSyncMeta = {
+ idsHash: hashResult?.hash ?? localHash,
+ lastSyncedAt,
+ }
+ if (!isPersistBlocked())
+ await localforage.setItem(STORAGE_KEYS.trnsSyncMeta, syncMeta)
+ logger.log(`full sync: ${trns.length} trns`)
}
+ async function deltaSync(syncMeta: TrnsSyncMeta, cachedTrns: Trns): Promise<void> {
+ const { api, client } = useConvexClientWithApi()
+
+ // Fetch delta changes and current hash in parallel
+ const [changedTrns, hashResult] = await Promise.all([
+ fetchAllPages(client, api.trns.delta, { since: syncMeta.lastSyncedAt }),
+ client.query(api.trns.idsHash, {}),
+ ])
+
+ if (hashResult === null) {
+ setTrns(null)
+ await localforage.removeItem(STORAGE_KEYS.trnsSyncMeta)
+ return
+ }
+
+ const { hash: currentHash, serverTime } = hashResult
+
+ // Start with cached data and apply delta
+ let data: Trns = { ...cachedTrns }
+ if (changedTrns.length > 0) {
+ const changedMap = convexTrnsToMap(changedTrns)
+ data = { ...data, ...changedMap }
+ }
+
+ // Check if hash matches after applying delta
+ const localHash = xorIdsHash(Object.keys(data).filter(id => !isLocalId(id)))
+ if (localHash !== currentHash) {
+ // Hash mismatch = deletions or missed changes → fallback to fullSync
+ logger.log('hash mismatch after delta, falling back to fullSync')
+ throw new Error('hash mismatch')
+ }
+
+ data = await mergeOfflineOps(data, 'trns')
+
+ setTrns(Object.keys(data).length > 0 ? data : null)
+
+ // Update sync metadata (use server time to avoid client clock skew)
+ const newSyncMeta: TrnsSyncMeta = {
+ idsHash: currentHash,
+ lastSyncedAt: serverTime,
+ }
+ if (!isPersistBlocked())
+ await localforage.setItem(STORAGE_KEYS.trnsSyncMeta, newSyncMeta)
+ logger.log(`delta sync: ${changedTrns.length} changed`)
+ }
+
+ async function initTrns() {
+ try {
+ const syncMeta = await localforage.getItem<TrnsSyncMeta>(STORAGE_KEYS.trnsSyncMeta)
+ const cachedTrns = await localforage.getItem<Trns>(STORAGE_KEYS.trns)
+
+ if (syncMeta && cachedTrns) {
+ try {
+ await deltaSync(syncMeta, cachedTrns)
+ return
+ }
+ catch (e) {
+ logger.log('delta sync failed, falling back to full sync', e)
+ }
+ }
+
+ // Ensure syncMeta row exists before fullSync so subsequent idsHash queries are O(1)
+ // Fire-and-forget: don't block fullSync if auth token isn't ready yet
+ const { api, client } = useConvexClientWithApi()
+ client.mutation(api.trns.ensureSyncMeta, {}).catch(() => {})
+
+ await fullSync()
+ }
+ catch (e) {
+ logger.error('init failed', e)
+ }
+ }
+
+ const debouncedPersist = createDebouncedPersist<Trns | null>(STORAGE_KEYS.trns)
+
function setTrns(values: Trns | null) {
- const trns = values ? normalizeTrns(values) : null
- items.value = trns
- localforage.setItem('finapp.trns', deepUnref(trns))
+ items.value = values
+ debouncedPersist(values)
}
- function addTrn({ id, values }: { id: TrnId, values: TrnItem }) {
- let isTrnSavedOnline = false
+ function saveTrn({ id, values }: { id: TrnId, values: TrnItem }) {
const valuesWithEditDate = {
...values,
- edited: new Date().getTime(),
+ updatedAt: new Date().getTime(),
}
- localforage.setItem('finapp.trns', deepUnref({ ...items.value, [id]: valuesWithEditDate }))
+ // Check before setTrns so the new id isn't already in the store
+ // Frontend IDs are always treated as new creates (server generates real ID)
+ const isExisting = !isLocalId(id) && items.value && id in items.value
+
+ // Optimistic UI
setTrns({ ...items.value, [id]: valuesWithEditDate })
- if (isDemo.value) {
+ if (!pushSaveOp({ entity: 'trns', id, isDemo: isDemo.value, isExisting: !!isExisting, values: values as unknown as Record<string, unknown> }))
return
+
+ const { api, client } = useConvexClientWithApi()
+ const action = isExisting ? 'update' : 'create'
+
+ const base = {
+ date: valuesWithEditDate.date,
+ desc: valuesWithEditDate.desc || undefined,
+ type: valuesWithEditDate.type,
}
- saveData(`users/${userStore.uid}/trns/${id}`, valuesWithEditDate).then(() => {
- isTrnSavedOnline = true
- removeTrnToAddLaterLocal(id)
- })
+ const trnData = values.type === TrnType.Transfer
+ ? {
+ ...base,
+ categoryId: 'transfer',
+ expenseAmount: values.expenseAmount,
+ expenseWalletId: values.expenseWalletId,
+ incomeAmount: values.incomeAmount,
+ incomeWalletId: values.incomeWalletId,
+ }
+ : {
+ ...base,
+ amount: values.amount,
+ categoryId: values.categoryId,
+ walletId: values.walletId,
+ }
+
+ // Fire-and-forget mutation, cleanup on success
+ const mutation = isExisting
+ ? client.mutation(api.trns.update, { id: asConvexId<'trns'>(id), ...trnData })
+ : client.mutation(api.trns.create, trnData)
- setTimeout(() => {
- if (!isTrnSavedOnline)
- saveTrnToAddLaterLocal({ id, values })
- }, 1000)
+ return handleMutationResult({
+ action,
+ entity: 'trns',
+ errorMessage: 'trns.errors.saveFailed',
+ id,
+ items,
+ mutation,
+
+ })
}
function deleteTrn(id: TrnId) {
+ // Optimistic UI
const trns = { ...items.value }
-
delete trns[id]
setTrns(trns)
- localforage.setItem('finapp.trns', deepUnref(trns))
- saveTrnIdForDeleteWhenClientOnline(id)
+ if (!pushDeleteOp({ entity: 'trns', id, isDemo: isDemo.value }))
+ return
+
+ // Fire-and-forget mutation, cleanup on success
+ const { api, client } = useConvexClientWithApi()
+ return handleMutationResult({
+ action: 'delete',
+ entity: 'trns',
+ errorMessage: 'trns.errors.deleteFailed',
+ id,
+ items,
+ mutation: client.mutation(api.trns.remove, { id: asConvexId<'trns'>(id) }),
- removeData(`users/${userStore.uid}/trns/${id}`).then(() =>
- removeTrnToDeleteLaterLocal(id),
- )
+ })
}
function deleteTrnsByIds(trnsIds: TrnId[]) {
- const trnsForDelete: Trns = {}
- if (isDemo.value) {
- deleteDemoTrns(trnsIds)
+ if (trnsIds.length === 0)
return
- }
-
- for (const trnId of trnsIds) trnsForDelete[trnId] = null
- updateData(`users/${userStore.uid}/trns`, trnsForDelete)
- }
+ // Single optimistic update
+ const trns = { ...items.value }
+ for (const id of trnsIds)
+ delete trns[id]
+ setTrns(trns)
- function unsubscribeTrns() {
- unsubscribeData(`users/${userStore.uid}/trns`)
- setTrns(null)
- }
+ if (isDemo.value)
+ return
- function uploadOfflineTrns() {
- getDataAndWatch('.info/connected', async (isConnected: boolean) => {
- const walletsStore = useWalletsStore()
+ // Batch offline queue
+ logger.log(`optimistic batch delete: ${trnsIds.length} trns`)
+ if (!isReplaying()) {
+ for (const id of trnsIds)
+ pushOfflineOp({ entity: 'trns', id, type: 'delete' })
+ }
- if (isConnected) {
- const trnsArrayForDelete = (await localforage.getItem('finapp.trns.offline.delete')) || []
- const trnsItemsForUpdate = (await localforage.getItem('finapp.trns.offline.update')) || {}
+ const { api, client } = useConvexClientWithApi()
+ const convexIds = trnsIds.filter(id => !isLocalId(id)).map(id => asConvexId<'trns'>(id))
+
+ if (convexIds.length > 0) {
+ return handleMutationResult({
+ action: 'delete',
+ entity: 'trns',
+ errorMessage: 'trns.errors.deleteFailed',
+ id: trnsIds,
+ mutation: client.mutation(api.trns.removeBatch, { ids: convexIds }),
+ })
+ }
+ else {
+ // All frontend IDs — just clean up offline queue
+ removeOfflineOps('trns', trnsIds)
+ }
+ }
- // delete trns
- for (const trnId of trnsArrayForDelete) {
- deleteTrn(trnId)
- delete trnsItemsForUpdate[trnId]
- }
+ /**
+ * Remove trns from store only (optimistic UI cleanup).
+ * Does NOT fire mutations or push to offline queue.
+ */
+ function removeTrnsFromStore(trnsIds: TrnId[]) {
+ if (!items.value)
+ return
- await localforage.setItem('finapp.trns.offline.update', deepUnref(trnsItemsForUpdate))
-
- // add trns
- for (const trnId in trnsItemsForUpdate) {
- const wallet = walletsStore.items[trnsItemsForUpdate[trnId].walletId]
- const category = categoriesStore.items[trnsItemsForUpdate[trnId].categoryId]
-
- // delete trn from local storage if no wallet or category
- if (!wallet || !category) {
- delete trnsItemsForUpdate[trnId]
- await localforage.setItem('finapp.trns.offline.update', deepUnref(trnsItemsForUpdate))
- }
-
- // add
- else if (trnsItemsForUpdate[trnId] && trnsItemsForUpdate[trnId].amount) {
- addTrn({
- id: trnId,
- values: trnsItemsForUpdate[trnId],
- })
- }
- }
- }
- })
+ const trns = { ...items.value }
+ for (const id of trnsIds)
+ delete trns[id]
+ setTrns(trns)
}
- function computeTrnItem(id: TrnId): TrnItemFull | string {
+ function computeTrnItem(id: TrnId): TrnItemFull | null {
if (!items.value || !walletsStore?.items || !categoriesStore?.items)
- return 'Something missing'
+ return null
// Trn
const trn = items.value[id]
if (!trn)
- return 'Trn not found'
+ return null
// Category
const category = categoriesStore.items[trn.categoryId]
if (!category)
- return 'Category not found'
+ return null
// Parent category
let categoryParent
if (category.parentId) {
categoryParent = categoriesStore.items[category.parentId]
if (!categoryParent)
- return 'Parent Category not found'
+ return null
}
- // Transaction
- if (trn.type !== 2) {
- // Wallet
- const wallet = walletsStore.items[trn.walletId]
- if (!wallet)
- return 'Wallet not found'
-
- return {
- id,
- ...trn,
- category,
- categoryParent,
- wallet,
- }
- }
-
- if (trn.type === 2) {
- const expenseWalletId = trn.expenseWalletId || trn.walletFromId
- const expenseWallet = walletsStore.items[expenseWalletId]
+ // Transfer
+ if (trn.type === TrnType.Transfer) {
+ const expenseWallet = walletsStore.items[trn.expenseWalletId]
if (!expenseWallet)
- return 'Transfer expense Wallet not found'
+ return null
- const incomeWalletId = trn.incomeWalletId || trn.walletToId
- const incomeWallet = walletsStore.items[incomeWalletId]
+ const incomeWallet = walletsStore.items[trn.incomeWalletId]
if (!incomeWallet)
- return 'Transfer income Wallet not found'
+ return null
return {
id,
@@ -234,28 +400,22 @@ export const useTrnsStore = defineStore('trns', () => {
}
}
- return 'Trn type not found'
- }
-
- function normalizeTrns(trns: Trns) {
- const normTrns: Trns = {}
+ // Regular transaction
+ const wallet = walletsStore.items[trn.walletId]
+ if (!wallet)
+ return null
- for (const trnId in trns) {
- const trn = trns[trnId]!
- const desc = trn.desc || trn.description || ''
- delete trn.description
-
- normTrns[trnId] = {
- ...trn,
- desc,
- }
+ return {
+ id,
+ ...trn,
+ category,
+ categoryParent,
+ wallet,
}
-
- return normTrns
}
return {
- addTrn,
+ cancelPersist: () => debouncedPersist.cancel?.(),
computeTrnItem,
deleteTrn,
deleteTrnsByIds,
@@ -266,8 +426,8 @@ export const useTrnsStore = defineStore('trns', () => {
items,
lastCreatedTrnId,
lastCreatedTrnItem,
+ removeTrnsFromStore,
+ saveTrn,
setTrns,
- unsubscribeTrns,
- uploadOfflineTrns,
}
})
diff --git a/app/components/ui/ActionButton.vue b/app/components/ui/ActionButton.vue
new file mode 100644
index 00000000..6b231903
--- /dev/null
+++ b/app/components/ui/ActionButton.vue
@@ -0,0 +1,26 @@
+<script setup lang="ts">
+const { isActive = false, size = 'md', variant = 'icon' } = defineProps<{
+ isActive?: boolean
+ size?: 'sm' | 'md'
+ variant?: 'icon' | 'text'
+}>()
+
+const emit = defineEmits<{
+ click: [e: Event]
+}>()
+</script>
+
+<template>
+ <div
+ :class="cn(
+ 'interactive data-[state=open]:!bg-item-4 flex min-w-[42px] items-center justify-center rounded-sm',
+ size === 'md' ? 'min-h-[38px]' : 'min-h-[32px]',
+ variant === 'icon' && 'text-muted text-xl',
+ variant === 'text' && 'text-1 px-3 text-sm',
+ isActive && 'bg-item-3',
+ )"
+ @click="(e: Event) => emit('click', e)"
+ >
+ <slot />
+ </div>
+</template>
diff --git a/app/components/ui/ButtonWithRight.vue b/app/components/ui/ButtonWithRight.vue
index dc0a7c48..dfb1b408 100644
--- a/app/components/ui/ButtonWithRight.vue
+++ b/app/components/ui/ButtonWithRight.vue
@@ -10,12 +10,12 @@ const emit = defineEmits<{
<template>
<div>
- <UiTitle3
+ <UiTitleSection
v-if="props.isShowTitle"
class="pb-2"
>
<slot name="label" />
- </UiTitle3>
+ </UiTitleSection>
<UiElement
class="@container/element"
diff --git a/app/components/ui/TextSm1.vue b/app/components/ui/ChipButton.vue
similarity index 59%
rename from app/components/ui/TextSm1.vue
rename to app/components/ui/ChipButton.vue
index 4764555e..23d0d4b2 100644
--- a/app/components/ui/TextSm1.vue
+++ b/app/components/ui/ChipButton.vue
@@ -6,7 +6,7 @@ const emit = defineEmits<{
<template>
<div
- class="font-primary text-muted text-xs leading-none"
+ class="interactive bg-item-3 flex min-h-[38px] min-w-[42px] grow items-center justify-center rounded-sm px-2 py-1.5 text-sm"
@click="(e: Event) => emit('click', e)"
>
<slot />
diff --git a/app/components/ui/Element.vue b/app/components/ui/Element.vue
index b44d9239..76cbe144 100644
--- a/app/components/ui/Element.vue
+++ b/app/components/ui/Element.vue
@@ -1,8 +1,4 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
insideClasses?: string
isActive?: boolean
@@ -15,9 +11,8 @@ const emit = defineEmits<{
const slots = useSlots()
-const classes = computed(() => cn(
- getStyles('item', ['padding1', 'minh1', 'link']),
- 'uiElement flex grow items-center gap-3 overflow-hidden -my-[1px] border border-transparent rounded-sm',
+const elementClasses = computed(() => cn(
+ 'interactive uiElement flex grow items-center gap-3 overflow-hidden rounded-sm px-2 py-1.5 min-h-[42px] -my-[1px] border border-transparent',
props.insideClasses,
{ 'relative border-(--ui-primary)/60 z-10': props.isActive },
))
@@ -25,7 +20,7 @@ const classes = computed(() => cn(
<template>
<div @click="(e: Event) => emit('click', e)">
- <div :class="classes">
+ <div :class="elementClasses">
<div
v-if="slots.leftIcon"
class="flex-center min-w-8"
@@ -46,7 +41,7 @@ const classes = computed(() => cn(
'ml-[48px] group-last/item:hidden': lineWidth === 4,
'group-last:hidden': lineWidth !== 3 && lineWidth !== 4,
}"
- class="mx-2 h-px bg-[var(--item-5)]"
+ class="mx-2 h-px bg-(--item-5)"
/>
</div>
</template>
diff --git a/app/components/ui/IconBase.vue b/app/components/ui/IconBase.vue
index 82a89b01..af8400f8 100644
--- a/app/components/ui/IconBase.vue
+++ b/app/components/ui/IconBase.vue
@@ -1,6 +1,4 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
const props = defineProps<{
class?: string
color?: string
diff --git a/app/components/ui/Item1.vue b/app/components/ui/Item1.vue
deleted file mode 100644
index 52de6434..00000000
--- a/app/components/ui/Item1.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-const { isActive = false, variant = 'icon' } = defineProps<{
- isActive?: boolean
- variant?: 'icon' | 'text'
-}>()
-
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- class="data-[state=open]:!bg-item-4 justify-center" :class="[
- getStyles('item', ['link', 'center', 'minh2', 'minw1', 'rounded']),
- {
- 'text-muted text-xl': variant === 'icon',
- },
- {
- 'text-1 px-3 text-sm': variant === 'text',
- },
- {
- '!bg-item-3': isActive,
- },
- ]"
- @click="(e: Event) => emit('click', e)"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/Item2.vue b/app/components/ui/Item2.vue
deleted file mode 100644
index de2475d6..00000000
--- a/app/components/ui/Item2.vue
+++ /dev/null
@@ -1,17 +0,0 @@
-<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- :class="getStyles('item', ['link', 'alt', 'padding1', 'center', 'minh2', 'minw1', 'rounded'])"
- class="grow justify-center text-sm"
- @click="(e: Event) => emit('click', e)"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/Item4.vue b/app/components/ui/Item4.vue
deleted file mode 100644
index 7180de2d..00000000
--- a/app/components/ui/Item4.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { classes } from '~/components/ui/getStyles'
-
-const { isActive = false, variant = 'icon' } = defineProps<{
- isActive?: boolean
- variant?: 'icon' | 'text'
-}>()
-
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- :class="cn(
- 'justify-center data-[state=open]:!bg-item-4 min-h-[32px]',
- classes.item.link,
- classes.item.center,
- classes.item.minw1,
- classes.item.rounded,
- variant === 'icon' ? 'text-xl text-muted' : '',
- variant === 'text' ? 'px-3 text-sm text-1' : '',
- isActive ? '!bg-item-3' : '',
- )"
- @click="(e: Event) => emit('click', e)"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/PopoverWrap.vue b/app/components/ui/PopoverWrap.vue
index 67407899..8f268135 100644
--- a/app/components/ui/PopoverWrap.vue
+++ b/app/components/ui/PopoverWrap.vue
@@ -5,14 +5,15 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- (e: 'close'): void
+ close: []
}>()
</script>
<template>
<div
- class="grid max-h-[60dvh]"
- :class="{ 'grid-rows-[auto_1fr]': props.title || props.isShowCloseBtn }"
+ :class="cn('grid max-h-[60dvh]',
+ (props.title || props.isShowCloseBtn) && 'grid-rows-[auto_1fr]',
+ )"
>
<UiTitleModal v-if="props.title">
{{ props.title }}
@@ -20,7 +21,7 @@ const emit = defineEmits<{
<BottomSheetClose
v-if="props.isShowCloseBtn"
- @onClick="emit('close')"
+ @click="emit('close')"
/>
<div
diff --git a/app/components/ui/SettingsCard.vue b/app/components/ui/SettingsCard.vue
new file mode 100644
index 00000000..b90b3f20
--- /dev/null
+++ b/app/components/ui/SettingsCard.vue
@@ -0,0 +1,47 @@
+<script setup lang="ts">
+defineProps<{
+ danger?: boolean
+ description?: string
+ title: string
+}>()
+</script>
+
+<template>
+ <div
+ :class="cn('overflow-hidden rounded-lg border', danger ? 'border-alert-1/30' : 'border-item-6')"
+ >
+ <div :class="cn('px-4 pt-4', $slots.default || $slots.content || $slots.footer ? 'pb-2' : 'pb-4')">
+ <div class="text-lg font-semibold">
+ {{ title }}
+ </div>
+
+ <div
+ v-if="description"
+ class="text-muted py-1 text-xs"
+ >
+ {{ description }}
+ </div>
+ </div>
+
+ <div
+ v-if="$slots.default"
+ class="px-4 pb-4"
+ >
+ <slot />
+ </div>
+
+ <div
+ v-if="$slots.content"
+ class="px-4 pb-4"
+ >
+ <slot name="content" />
+ </div>
+
+ <div
+ v-if="$slots.footer"
+ :class="cn('flex items-center border-t px-4 py-3', danger ? 'border-alert-1/30' : 'border-item-6')"
+ >
+ <slot name="footer" />
+ </div>
+ </div>
+</template>
diff --git a/app/components/ui/Checkbox.vue b/app/components/ui/SwitchItem.vue
similarity index 90%
rename from app/components/ui/Checkbox.vue
rename to app/components/ui/SwitchItem.vue
index 28a4a94e..41741681 100644
--- a/app/components/ui/Checkbox.vue
+++ b/app/components/ui/SwitchItem.vue
@@ -6,18 +6,18 @@ const props = defineProps<{
const emit = defineEmits<{
click: [e: boolean]
- onClose: []
+ close: []
}>()
function handleClick() {
emit('click', props.checkboxValue)
- emit('onClose')
+ emit('close')
}
</script>
<template>
<div
- class="flex grow items-center gap-3 rounded-lg p-2 text-sm hover:bg-[var(--item-5)]"
+ class="flex grow items-center gap-3 rounded-lg p-2 text-sm hover:bg-(--item-5)"
@click="handleClick"
>
<FormSwitch
diff --git a/app/components/ui/Tabs2.global.vue b/app/components/ui/Tabs2.global.vue
deleted file mode 100644
index 729bf225..00000000
--- a/app/components/ui/Tabs2.global.vue
+++ /dev/null
@@ -1,9 +0,0 @@
-<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-</script>
-
-<template>
- <div :class="cn('overflow-hidden overflow-x-auto grow gap-x-1 flex items-center flex-nowrap')">
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/Tabs1.global.vue b/app/components/ui/TabsBar.global.vue
similarity index 76%
rename from app/components/ui/Tabs1.global.vue
rename to app/components/ui/TabsBar.global.vue
index 4f896ea1..257d3799 100644
--- a/app/components/ui/Tabs1.global.vue
+++ b/app/components/ui/TabsBar.global.vue
@@ -1,5 +1,5 @@
<template>
- <div class="flex grow items-center overflow-hidden overflow-x-auto rounded bg-[var(--item-3)]">
+ <div class="flex grow items-center overflow-hidden overflow-x-auto rounded bg-(--item-3)">
<slot />
</div>
</template>
diff --git a/app/components/ui/TabsItem3.vue b/app/components/ui/TabsItem3.vue
deleted file mode 100644
index a8368525..00000000
--- a/app/components/ui/TabsItem3.vue
+++ /dev/null
@@ -1,21 +0,0 @@
-<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-defineProps<{
- isActive?: boolean
-}>()
-
-const emit = defineEmits(['click'])
-</script>
-
-<template>
- <div
- :class="[getStyles('item', ['minh2']), {
- '!bg-item-4 !text-primary': isActive,
- }]"
- class="text-muted flex grow items-center justify-center gap-1 px-2 text-sm leading-none select-none hover:bg-[var(--item-5)]"
- @click="emit('click')"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/TabsItem4.vue b/app/components/ui/TabsItem4.vue
deleted file mode 100644
index 0d396c66..00000000
--- a/app/components/ui/TabsItem4.vue
+++ /dev/null
@@ -1,21 +0,0 @@
-<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-defineProps<{
- isActive?: boolean
-}>()
-
-const emit = defineEmits(['click'])
-</script>
-
-<template>
- <div
- :class="[getStyles('item', ['link', 'rounded', 'minh3', 'minw2']), {
- '!bg-item-4 !text-1': isActive,
- }]"
- class="text-muted flex shrink-0 items-center justify-center gap-1 rounded-lg border-1 px-3 text-sm leading-none"
- @click="emit('click')"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/TabsItem1.vue b/app/components/ui/TabsItemFill.vue
similarity index 51%
rename from app/components/ui/TabsItem1.vue
rename to app/components/ui/TabsItemFill.vue
index e895eb82..6a882894 100644
--- a/app/components/ui/TabsItem1.vue
+++ b/app/components/ui/TabsItemFill.vue
@@ -1,8 +1,4 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { classes } from '~/components/ui/getStyles'
-
const props = defineProps<{
isActive?: boolean
}>()
@@ -13,8 +9,7 @@ const emit = defineEmits(['click'])
<template>
<div
:class="cn(
- 'flex flex-1 grow select-none items-center justify-center gap-1 text-nowrap rounded px-2 text-sm text-3 hover:bg-[var(--item-5)]',
- [classes.item.minh3],
+ 'flex flex-1 min-h-[32px] select-none items-center justify-center gap-1 text-nowrap rounded px-2 text-sm text-3 hover:bg-(--item-5)',
props.isActive && 'bg-item-4',
)"
@click="emit('click')"
diff --git a/app/components/ui/TabsItemPill.vue b/app/components/ui/TabsItemPill.vue
new file mode 100644
index 00000000..cfde4e77
--- /dev/null
+++ b/app/components/ui/TabsItemPill.vue
@@ -0,0 +1,24 @@
+<script setup lang="ts">
+const { isActive = false, variant = 'default' } = defineProps<{
+ isActive?: boolean
+ variant?: 'default' | 'outline'
+}>()
+
+const emit = defineEmits(['click'])
+</script>
+
+<template>
+ <div
+ :class="cn(
+ 'flex items-center justify-center gap-1 text-sm leading-none',
+ variant === 'default' && 'min-h-[38px] grow select-none px-2 hover:bg-(--item-5)',
+ variant === 'outline' && 'interactive min-h-[32px] min-w-[60px] shrink-0 rounded-sm border-1 px-3',
+ isActive
+ ? variant === 'default' ? 'bg-item-4 text-primary' : 'bg-item-4 text-1'
+ : 'text-muted',
+ )"
+ @click="emit('click')"
+ >
+ <slot />
+ </div>
+</template>
diff --git a/app/components/ui/TabsScroll.global.vue b/app/components/ui/TabsScroll.global.vue
new file mode 100644
index 00000000..71cfebf4
--- /dev/null
+++ b/app/components/ui/TabsScroll.global.vue
@@ -0,0 +1,8 @@
+<script setup lang="ts">
+</script>
+
+<template>
+ <div :class="cn('overflow-x-auto overflow-y-hidden grow min-w-0 gap-x-1 flex items-center flex-nowrap')">
+ <slot />
+ </div>
+</template>
diff --git a/app/components/ui/Item3.vue b/app/components/ui/TextMuted.vue
similarity index 51%
rename from app/components/ui/Item3.vue
rename to app/components/ui/TextMuted.vue
index a46ccb81..92da7199 100644
--- a/app/components/ui/Item3.vue
+++ b/app/components/ui/TextMuted.vue
@@ -1,5 +1,7 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
+const { size = 'xs' } = defineProps<{
+ size?: 'xs' | 'sm'
+}>()
const emit = defineEmits<{
click: [e: Event]
@@ -8,8 +10,10 @@ const emit = defineEmits<{
<template>
<div
- :class="getStyles('item', ['link', '_alt', 'center', 'minh2', 'minw4', 'rounded'])"
- class="justify-center text-xl"
+ :class="cn(
+ 'font-primary text-muted leading-none',
+ size === 'xs' ? 'text-xs' : 'text-sm',
+ )"
@click="(e: Event) => emit('click', e)"
>
<slot />
diff --git a/app/components/ui/Title6.vue b/app/components/ui/TextSubtitle.vue
similarity index 100%
rename from app/components/ui/Title6.vue
rename to app/components/ui/TextSubtitle.vue
diff --git a/app/components/ui/Title3.vue b/app/components/ui/Title3.vue
deleted file mode 100644
index 5eddac60..00000000
--- a/app/components/ui/Title3.vue
+++ /dev/null
@@ -1,14 +0,0 @@
-<script setup lang="ts">
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- class="font-tertiary text-muted text-base leading-none font-semibold"
- @click="(e: Event) => emit('click', e)"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/Title7.vue b/app/components/ui/Title7.vue
deleted file mode 100644
index cf6cd57c..00000000
--- a/app/components/ui/Title7.vue
+++ /dev/null
@@ -1,31 +0,0 @@
-<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { classes } from '~/components/ui/getStyles'
-
-const props = defineProps<{
- isHideArrow?: boolean
-}>()
-const emit = defineEmits<{
- (e: 'click'): void
-}>()
-</script>
-
-<template>
- <div
- :class="cn(
- [classes.item.center, classes.item.minh2, classes.item.minw1, classes.item.rounded],
- 'group flex grow items-center justify-between px-4 gap-2 pb-0 !font-tertiary !text-base font-semibold leading-none tracking-wide',
- !props.isHideArrow && [classes.item.link],
- )"
- @click="emit('click')"
- >
- <div><slot /></div>
- <Icon
- v-if="!props.isHideArrow"
- name="lucide:chevron-right"
- size="22"
- class="text-2 group-hover:text-1 -ml-1"
- />
- </div>
-</template>
diff --git a/app/components/ui/Title8.vue b/app/components/ui/TitleCollapse.vue
similarity index 55%
rename from app/components/ui/Title8.vue
rename to app/components/ui/TitleCollapse.vue
index 96ab6ede..5681579d 100644
--- a/app/components/ui/Title8.vue
+++ b/app/components/ui/TitleCollapse.vue
@@ -1,33 +1,31 @@
<script setup lang="ts">
-import { cn } from '~~/lib/cn'
-
-import { classes } from '~/components/ui/getStyles'
-
const props = defineProps<{
+ arrow?: 'left' | 'right'
isHideArrow?: boolean
isOpen?: boolean
isShown?: boolean
}>()
const emit = defineEmits<{
- (e: 'click'): void
+ click: []
}>()
</script>
<template>
<div
:class="cn(
- [classes.item.center, classes.item.padding3, classes.item.minh2, classes.item.minw1, classes.item.rounded],
+ 'flex items-center rounded-sm min-h-[38px] min-w-[42px]',
'flex grow items-center gap-2 pb-0 !font-tertiary !text-base font-semibold leading-none tracking-wide',
- !props.isHideArrow && [classes.item.link],
+ props.arrow === 'right' ? 'justify-between px-4' : 'px-3',
+ !props.isHideArrow && 'interactive',
)"
@click="emit('click')"
>
<div><slot /></div>
<Icon
v-if="!props.isHideArrow && !props.isShown"
- name="lucide:chevron-left"
+ :name="props.arrow === 'right' ? 'lucide:chevron-right' : 'lucide:chevron-left'"
size="22"
- class="-ml-1"
+ :class="cn('-ml-1', props.arrow === 'right' && 'text-2 group-hover:text-1')"
/>
</div>
</template>
diff --git a/app/components/ui/TitleDropRight.vue b/app/components/ui/TitleDropRight.vue
index 8d669c93..0bbd78a6 100644
--- a/app/components/ui/TitleDropRight.vue
+++ b/app/components/ui/TitleDropRight.vue
@@ -1,18 +1,15 @@
<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
isShown?: boolean
}>()
const emit = defineEmits<{
- (e: 'click'): void
+ click: []
}>()
</script>
<template>
<div
- :class="getStyles('item', ['link', 'center', 'padding3', 'minh2', 'minw1', 'rounded'])"
- class="flex grow items-center gap-2 pb-0"
+ class="interactive flex min-h-[38px] min-w-[42px] grow items-center gap-2 rounded-sm px-3 pb-0"
@click="emit('click')"
>
<Icon
diff --git a/app/components/ui/TitleOption.vue b/app/components/ui/TitleOption.vue
deleted file mode 100644
index c4b81277..00000000
--- a/app/components/ui/TitleOption.vue
+++ /dev/null
@@ -1,14 +0,0 @@
-<script setup lang="ts">
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- class="font-tertiary text-muted leading-none font-semibold"
- @click="(e: Event) => emit('click', e)"
- >
- <slot />
- </div>
-</template>
diff --git a/app/components/ui/TextSm2.vue b/app/components/ui/TitleSection.vue
similarity index 50%
rename from app/components/ui/TextSm2.vue
rename to app/components/ui/TitleSection.vue
index d5b3d4b0..cef1d301 100644
--- a/app/components/ui/TextSm2.vue
+++ b/app/components/ui/TitleSection.vue
@@ -1,4 +1,8 @@
<script setup lang="ts">
+const { size = 'md' } = defineProps<{
+ size?: 'sm' | 'md'
+}>()
+
const emit = defineEmits<{
click: [e: Event]
}>()
@@ -6,7 +10,10 @@ const emit = defineEmits<{
<template>
<div
- class="font-primary text-muted text-sm leading-none"
+ :class="cn(
+ 'font-tertiary text-muted leading-none font-semibold',
+ size === 'md' && 'text-base',
+ )"
@click="(e: Event) => emit('click', e)"
>
<slot />
diff --git a/app/components/ui/ToggleAction.vue b/app/components/ui/ToggleAction.vue
deleted file mode 100644
index b62c09ff..00000000
--- a/app/components/ui/ToggleAction.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<script setup lang="ts">
-import { getStyles } from '~/components/ui/getStyles'
-
-const props = defineProps<{
- isShown: boolean
-}>()
-
-const emit = defineEmits<{
- click: [e: Event]
-}>()
-</script>
-
-<template>
- <div
- :class="getStyles('item', ['link', 'minh4', 'minw1', 'center2', 'rounded'])"
- class="z-10 !min-h-[44px]"
- @click="(e: Event) => emit('click', e)"
- >
- <Icon
- :name="props.isShown ? 'lucide:chevron-down' : 'lucide:chevron-right'"
- size="22"
- />
- </div>
-</template>
diff --git a/app/components/ui/Toggle3.vue b/app/components/ui/ToggleControlled.vue
similarity index 78%
rename from app/components/ui/Toggle3.vue
rename to app/components/ui/ToggleControlled.vue
index 115c5be6..03493cba 100644
--- a/app/components/ui/Toggle3.vue
+++ b/app/components/ui/ToggleControlled.vue
@@ -31,8 +31,10 @@ const emit = defineEmits<{
<div
v-if="lineWidth && !isShown"
- class="mx-2 h-px bg-[var(--item-5)] group-last:hidden"
- :class="{ 'ml-12': lineWidth === 3, 'ml-11': lineWidth === 2 }"
+ :class="cn('mx-2 h-px bg-(--item-5) group-last:hidden',
+ lineWidth === 3 && 'ml-12',
+ lineWidth === 2 && 'ml-11',
+ )"
/>
</div>
</template>
diff --git a/app/components/ui/ToggleWithStorage.vue b/app/components/ui/ToggleWithStorage.vue
index dd8b28ff..14dd08c0 100644
--- a/app/components/ui/ToggleWithStorage.vue
+++ b/app/components/ui/ToggleWithStorage.vue
@@ -1,8 +1,6 @@
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
-import { getStyles } from '~/components/ui/getStyles'
-
const props = defineProps<{
initStatus?: boolean
lineWidth?: number
@@ -22,7 +20,7 @@ const isShown = useStorage(`ui-toggle-${props.storageKey}`, props.initStatus)
>
<div class="-my-px overflow-hidden">
<div
- :class="getStyles('item', ['link', 'center', 'rounded', 'minh1'])"
+ class="interactive flex min-h-[42px] items-center rounded-sm"
>
<slot
name="header"
@@ -31,7 +29,7 @@ const isShown = useStorage(`ui-toggle-${props.storageKey}`, props.initStatus)
/>
</div>
- <div v-if="isShown" class="">
+ <div v-if="isShown">
<slot
:toggle="() => isShown = !isShown"
:close="() => isShown = false"
@@ -41,8 +39,10 @@ const isShown = useStorage(`ui-toggle-${props.storageKey}`, props.initStatus)
<div
v-if="lineWidth && !isShown"
- class="mx-2 h-px bg-[var(--item-5)] group-last:hidden"
- :class="{ 'ml-12': lineWidth === 3, 'ml-11': lineWidth === 2 }"
+ :class="cn('mx-2 h-px bg-(--item-5) group-last:hidden',
+ lineWidth === 3 && 'ml-12',
+ lineWidth === 2 && 'ml-11',
+ )"
/>
</div>
</template>
diff --git a/app/components/ui/getStyles.ts b/app/components/ui/getStyles.ts
deleted file mode 100644
index 34e966da..00000000
--- a/app/components/ui/getStyles.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-export const classes = {
- item: {
- alt: 'bg-item-3',
- base: '',
- bg: 'bg-item-2',
- bg2: 'bg-item-3',
- center: 'flex items-center',
- center2: 'flex items-center justify-center',
- center3: 'flex-center',
- gap1: 'gap-3',
- link: `
- select-none
- hover:bg-elevated
- `,
- minh1: 'min-h-[42px]',
- minh2: 'min-h-[38px]',
- minh3: 'min-h-[32px]',
- minh4: 'min-h-[44px]',
- minh5: 'min-h-[46px]',
-
- minw1: 'min-w-[42px]',
- minw2: 'min-w-[60px]',
- minw3: 'min-w-[32px]',
- minw4: 'min-w-[38px]',
-
- padding1: 'px-2 py-1.5',
- padding2: 'px-2',
- padding3: 'px-3',
- padding4: 'px-1',
-
- rounded: 'rounded-sm',
- rounded2: 'rounded-lg',
- rounded3: 'rounded-xl',
- simple: '',
- },
-
- modal: {
- bg: 'bg-item-3',
- padding1: 'px-2 pt-6 !pb-2',
- rounded: 'rounded-xl',
- },
-} as const
-
-export function getStyles(group: string, elements: string[]) {
- return elements.map(name => classes[group][name]).join(' ')
-}
diff --git a/app/components/user/ViewLogout.vue b/app/components/user/ViewLogout.vue
index 9cc5a29f..9b678c1a 100644
--- a/app/components/user/ViewLogout.vue
+++ b/app/components/user/ViewLogout.vue
@@ -1,4 +1,4 @@
-<script lang="ts" setup>
+<script setup lang="ts">
import { useUserStore } from '~/components/user/useUserStore'
const props = defineProps<{
diff --git a/app/components/user/useGuard.ts b/app/components/user/useGuard.ts
index 0828f65d..1aebdc94 100644
--- a/app/components/user/useGuard.ts
+++ b/app/components/user/useGuard.ts
@@ -6,27 +6,26 @@ export function useGuard() {
const router = useRouter()
const userStore = useUserStore()
- const localAuthUid = useCookie('finapp.localAuthUid')
const { clearLocalData } = useInitApp()
onMounted(() => {
- watch(() => userStore.currentUser, (user, prevUser) => {
- if (user?.uid && user?.uid !== localAuthUid.value) {
- clearLocalData()
- }
-
- if (user && route.path === '/login') {
- router.push('/dashboard')
- }
- else if (user && route.path === '/login') {
- router.push('/dashboard')
- }
- else if (prevUser && !user) {
- router.push('/login')
- }
- else if (user && typeof route.query.redirect === 'string') {
- router.push(route.query.redirect)
- }
- }, { immediate: true })
+ watch(
+ () => userStore.currentUser,
+ (user, prevUser) => {
+ if (user && route.path === '/login') {
+ router.push('/dashboard')
+ }
+ else if (prevUser && !user) {
+ if (userStore.isSigningOut)
+ return
+ clearLocalData()
+ router.push('/login')
+ }
+ else if (user && typeof route.query.redirect === 'string') {
+ router.push(getSafeRedirectPath(route.query.redirect))
+ }
+ },
+ { immediate: true },
+ )
})
}
diff --git a/app/components/user/useUserStore.test.ts b/app/components/user/useUserStore.test.ts
new file mode 100644
index 00000000..972659c2
--- /dev/null
+++ b/app/components/user/useUserStore.test.ts
@@ -0,0 +1,259 @@
+import { createPinia, setActivePinia } from 'pinia'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// --- Mocks ---
+
+const localforageStore = new Map<string, any>()
+vi.mock('localforage', () => ({
+ default: {
+ clear: vi.fn(() => {
+ localforageStore.clear()
+ return Promise.resolve()
+ }),
+ getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),
+ setItem: vi.fn((key: string, value: any) => {
+ localforageStore.set(key, value)
+ return Promise.resolve()
+ }),
+ },
+}))
+
+vi.mock('vue-deepunref', () => ({
+ deepUnref: (v: any) => v,
+}))
+
+const mutationMock = vi.fn(() => Promise.resolve())
+const queryMock = vi.fn(() => Promise.resolve(null))
+
+vi.stubGlobal('useConvexClient', () => ({
+ mutation: mutationMock,
+ query: queryMock,
+}))
+vi.stubGlobal('useConvexClientComposable', () => ({
+ mutation: mutationMock,
+ query: queryMock,
+}))
+vi.stubGlobal('useConvexApi', () => ({
+ api: {
+ userSettings: { get: 'userSettings.get', upsert: 'userSettings.upsert' },
+ },
+}))
+vi.stubGlobal('useConvexClientWithApi', () => ({
+ api: {
+ userSettings: { get: 'userSettings.get', upsert: 'userSettings.upsert' },
+ },
+ client: {
+ mutation: mutationMock,
+ query: queryMock,
+ },
+}))
+
+vi.stubGlobal('defineStore', (await import('pinia')).defineStore)
+const { computed, ref } = await import('vue')
+vi.stubGlobal('computed', computed)
+vi.stubGlobal('ref', ref)
+
+const setLocaleMock = vi.fn()
+vi.stubGlobal('useNuxtApp', () => ({
+ $i18n: { setLocale: setLocaleMock },
+}))
+vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+
+const useSessionMock = vi.fn(() => ref({ data: null, isPending: false }))
+vi.stubGlobal('useAuth', () => ({
+ signOut: vi.fn(),
+ useSession: useSessionMock,
+}))
+
+vi.mock('~/components/categories/useCategoriesStore', () => ({
+ useCategoriesStore: () => ({
+ setCategories: vi.fn(),
+ }),
+}))
+
+vi.mock('~/components/trns/useTrnsStore', () => ({
+ useTrnsStore: () => ({
+ setTrns: vi.fn(),
+ }),
+}))
+
+vi.mock('~/components/wallets/useWalletsStore', () => ({
+ useWalletsStore: () => ({
+ setWallets: vi.fn(),
+ }),
+}))
+
+vi.mock('~/components/demo/useDemo', () => ({
+ useDemo: () => ({
+ isDemo: { value: false },
+ }),
+}))
+
+vi.mock('~/composables/useAuthCookie', () => ({
+ clearAuthCookie: vi.fn(),
+}))
+
+const { useUserStore } = await import('~/components/user/useUserStore')
+
+// --- Tests ---
+
+describe('useUserStore', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ localforageStore.clear()
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ describe('setUserBaseCurrency', () => {
+ it('updates baseCurrency ref', () => {
+ const store = useUserStore()
+ store.setUserBaseCurrency('EUR')
+ expect(store.baseCurrency).toBe('EUR')
+ })
+
+ it('persists to localforage', () => {
+ const store = useUserStore()
+ store.setUserBaseCurrency('EUR')
+
+ const saved = localforageStore.get('finapp.userSettings')
+ expect(saved).toEqual({ baseCurrency: 'EUR', locale: 'en' })
+ })
+ })
+
+ describe('saveUserBaseCurrency', () => {
+ it('updates ref and calls Convex mutation', () => {
+ const store = useUserStore()
+ store.saveUserBaseCurrency('JPY')
+
+ expect(store.baseCurrency).toBe('JPY')
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'userSettings.upsert',
+ { baseCurrency: 'JPY' },
+ )
+ })
+
+ it('skips Convex mutation in demo mode', async () => {
+ // Override isDemo for this test
+ const demoModule = await import('~/components/demo/useDemo')
+ const original = demoModule.useDemo
+ ;(demoModule as any).useDemo = () => ({ ...original(), isDemo: { value: true } })
+
+ // Need fresh store to pick up new mock
+ setActivePinia(createPinia())
+ const store = useUserStore()
+ store.saveUserBaseCurrency('GBP')
+
+ expect(store.baseCurrency).toBe('GBP')
+ expect(mutationMock).not.toHaveBeenCalled()
+
+ // Restore
+ ;(demoModule as any).useDemo = original
+ })
+ })
+
+ describe('setUserLocale', () => {
+ it('updates locale ref and calls setLocale', () => {
+ const store = useUserStore()
+ store.setUserLocale('ru')
+
+ expect(store.locale).toBe('ru')
+ expect(setLocaleMock).toHaveBeenCalledWith('ru')
+ })
+
+ it('persists to localforage', () => {
+ const store = useUserStore()
+ store.setUserLocale('ru')
+
+ const saved = localforageStore.get('finapp.userSettings')
+ expect(saved).toEqual({ baseCurrency: 'USD', locale: 'ru' })
+ })
+ })
+
+ describe('saveUserLocale', () => {
+ it('calls Convex mutation when not in demo mode', () => {
+ const store = useUserStore()
+ store.saveUserLocale('ru')
+
+ expect(store.locale).toBe('ru')
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'userSettings.upsert',
+ { locale: 'ru' },
+ )
+ })
+
+ it('skips Convex mutation in demo mode', async () => {
+ const demoModule = await import('~/components/demo/useDemo')
+ const original = demoModule.useDemo
+ ;(demoModule as any).useDemo = () => ({ ...original(), isDemo: { value: true } })
+
+ setActivePinia(createPinia())
+ const store = useUserStore()
+ store.saveUserLocale('ru')
+
+ expect(store.locale).toBe('ru')
+ expect(setLocaleMock).toHaveBeenCalledWith('ru')
+ expect(mutationMock).not.toHaveBeenCalled()
+
+ // Restore
+ ;(demoModule as any).useDemo = original
+ })
+ })
+
+ describe('initUserSettings', () => {
+ it('sets baseCurrency and locale from Convex', async () => {
+ queryMock.mockResolvedValue({ baseCurrency: 'EUR', locale: 'ru' })
+
+ const store = useUserStore()
+ await store.initUserSettings()
+
+ expect(store.baseCurrency).toBe('EUR')
+ expect(store.locale).toBe('ru')
+ expect(setLocaleMock).toHaveBeenCalledWith('ru')
+ })
+
+ it('defaults to USD when baseCurrency is empty', async () => {
+ queryMock.mockResolvedValue({ baseCurrency: '', locale: null })
+
+ const store = useUserStore()
+ await store.initUserSettings()
+
+ expect(store.baseCurrency).toBe('USD')
+ })
+
+ it('does nothing when settings is null', async () => {
+ queryMock.mockResolvedValue(null)
+
+ const store = useUserStore()
+ await store.initUserSettings()
+
+ expect(store.baseCurrency).toBe('USD')
+ expect(store.locale).toBe('en')
+ })
+
+ it('skips locale when not set in settings', async () => {
+ queryMock.mockResolvedValue({ baseCurrency: 'GBP' })
+
+ const store = useUserStore()
+ await store.initUserSettings()
+
+ expect(store.baseCurrency).toBe('GBP')
+ expect(store.locale).toBe('en')
+ expect(setLocaleMock).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('persistUserSettings', () => {
+ it('saves both baseCurrency and locale together', () => {
+ const store = useUserStore()
+ store.setUserBaseCurrency('EUR')
+ store.setUserLocale('ru')
+
+ const saved = localforageStore.get('finapp.userSettings')
+ expect(saved).toEqual({ baseCurrency: 'EUR', locale: 'ru' })
+ })
+ })
+})
diff --git a/app/components/user/useUserStore.ts b/app/components/user/useUserStore.ts
index 3647f7a8..632cf345 100644
--- a/app/components/user/useUserStore.ts
+++ b/app/components/user/useUserStore.ts
@@ -1,13 +1,20 @@
-import { signOut as signOutFirebase } from 'firebase/auth'
import localforage from 'localforage'
import { deepUnref } from 'vue-deepunref'
-import { saveData } from '~~/services/firebase/api'
-import { useAppNav } from '~/components/app/useAppNav'
+import type { CurrencyCode } from '~/components/currencies/types'
+import type { LocaleSlug } from '~/components/locale/types'
+
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useDemo } from '~/components/demo/useDemo'
+import { getOfflineOpsByEntity, pushOfflineOp } from '~/components/offline/helpers'
+import { isReplaying } from '~/components/offline/replay'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
+import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { clearAuthCookie } from '~/composables/useAuthCookie'
+import { blockPersist, handleMutationResult, isPersistBlocked } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
export type User = {
displayName?: string | null
@@ -16,87 +23,235 @@ export type User = {
uid: string
}
+const logger = createLogger('user')
+
export const useUserStore = defineStore('user', () => {
- const auth = useFirebaseAuth()!
- const { $config } = useNuxtApp()
- const currentUser = useCurrentUser()
+ const authClient = useAuth()
+ const session = authClient.useSession()
const walletsStore = useWalletsStore()
const categoriesStore = useCategoriesStore()
const trnsStore = useTrnsStore()
- const { closeAllModals } = useAppNav()
const { isDemo } = useDemo()
+ const user = ref<User | null>(null)
+ const isSigningOut = ref(false)
+ const baseCurrency = ref<CurrencyCode>('USD')
+ const locale = ref<LocaleSlug>('en')
+
+ const currentUser = computed<User | null>(() => {
+ const s = session.value
+ const sessionUser = s?.data?.user
+ if (sessionUser) {
+ return {
+ displayName: sessionUser.name,
+ email: sessionUser.email,
+ photoURL: sessionUser.image,
+ uid: sessionUser.id,
+ }
+ }
+ if (s?.isPending)
+ return user.value // Not loaded yet — use Pinia cache
+ return null // Session checked, no user
+ })
- const user = ref<User | null>(currentUser.value || null)
- const isDevUser = computed(() => !!$config.public.ratesApiKey.includes(user.value?.email ?? ''))
- const uid = computed<string | null>(() => currentUser.value?.uid || user.value?.uid || null)
+ const sessionUid = computed(() => session.value?.data?.user?.id ?? null)
- watch(() => currentUser.value, user => setUser(user))
+ const uid = computed<string | null>(() => currentUser.value?.uid || null)
function setUser(values: User | null) {
- if (!values || values === null) {
+ if (!values) {
user.value = null
}
else {
user.value = {
- displayName: values?.displayName,
- email: values?.email,
- photoURL: values?.photoURL,
+ displayName: values.displayName,
+ email: values.email,
+ photoURL: values.photoURL,
uid: values.uid,
}
}
- localforage.setItem('finapp.user', deepUnref(user.value))
+ if (!isPersistBlocked())
+ localforage.setItem(STORAGE_KEYS.user, deepUnref(user.value))
+ }
+
+ function persistUserSettings() {
+ if (isPersistBlocked())
+ return
+ localforage.setItem(STORAGE_KEYS.userSettings, {
+ baseCurrency: baseCurrency.value,
+ locale: locale.value,
+ })
+ }
+
+ function setUserBaseCurrency(value: CurrencyCode) {
+ baseCurrency.value = value
+ persistUserSettings()
+ }
+
+ function saveUserBaseCurrency(value: CurrencyCode) {
+ setUserBaseCurrency(value)
+
+ if (isDemo.value || !uid.value)
+ return
+
+ logger.log(`optimistic update: baseCurrency → ${value}`)
+ if (!isReplaying())
+ pushOfflineOp({ data: { baseCurrency: value }, entity: 'userSettings', id: 'settings', type: 'update' })
+
+ const { api, client } = useConvexClientWithApi()
+ handleMutationResult({
+ action: 'update',
+ entity: 'userSettings',
+ errorMessage: 'settings.errors.saveFailed',
+ id: 'settings',
+ mutation: client.mutation(api.userSettings.upsert, { baseCurrency: value }),
+ })
+ }
+
+ function setUserLocale(value: LocaleSlug) {
+ locale.value = value
+ useNuxtApp().$i18n.setLocale(value)
+ persistUserSettings()
+ }
+
+ function saveUserLocale(value: LocaleSlug) {
+ setUserLocale(value)
+
+ if (isDemo.value || !uid.value)
+ return
+
+ logger.log(`optimistic update: locale → ${value}`)
+ if (!isReplaying())
+ pushOfflineOp({ data: { locale: value }, entity: 'userSettings', id: 'settings', type: 'update' })
+
+ const { api, client } = useConvexClientWithApi()
+ handleMutationResult({
+ action: 'update',
+ entity: 'userSettings',
+ errorMessage: 'settings.errors.saveFailed',
+ id: 'settings',
+ mutation: client.mutation(api.userSettings.upsert, { locale: value }),
+ })
+ }
+
+ async function initUserSettings() {
+ try {
+ const { api, client } = useConvexClientWithApi()
+
+ const settings = await client.query(api.userSettings.get, {})
+ if (!settings)
+ return
+
+ baseCurrency.value = settings.baseCurrency || 'USD'
+ if (settings.locale) {
+ locale.value = settings.locale as LocaleSlug
+ useNuxtApp().$i18n.setLocale(settings.locale as LocaleSlug)
+ }
+
+ // Apply pending offline ops (local changes win over server)
+ const pendingOps = await getOfflineOpsByEntity('userSettings')
+ for (const op of pendingOps) {
+ if (op.data?.baseCurrency)
+ baseCurrency.value = op.data.baseCurrency as CurrencyCode
+ if (op.data?.locale) {
+ locale.value = op.data.locale as LocaleSlug
+ useNuxtApp().$i18n.setLocale(op.data.locale as LocaleSlug)
+ }
+ }
+
+ persistUserSettings()
+ }
+ catch (e) {
+ logger.error('init user settings failed', e)
+ }
}
async function signOut() {
- closeAllModals()
+ isSigningOut.value = true
if (isDemo.value) {
await localforage.clear()
- isDemo.value = 'false'
+ isDemo.value = null
+ clearAuthCookie()
window.location.href = '/login'
return
}
+ // Block all persist operations — prevents in-flight mutation callbacks
+ // from re-writing data to localforage after clear().
+ blockPersist()
+
try {
- await localforage.clear()
- trnsStore.unsubscribeTrns()
- categoriesStore.unsubscribeCategories()
- walletsStore.unsubscribeWallets()
- setUser(null)
+ categoriesStore.cancelPersist()
+ trnsStore.cancelPersist()
+ walletsStore.cancelPersist()
- await signOutFirebase(auth)
- }
+ trnsStore.setTrns(null)
+ categoriesStore.setCategories(null)
+ walletsStore.setWallets(null)
+ useTrnsFormStore().$reset()
+ setUser(null)
+ clearAuthCookie()
+ await localforage.clear()
+ await authClient.signOut()
+ }
catch (error) {
- console.log(error)
+ logger.error('signOut failed:', error)
}
+ finally {
+ isSigningOut.value = false
+ }
+
+ // Clean up AFTER all async work completes — no race with guard redirect.
+ localStorage.removeItem('better-auth_cookie')
+ localStorage.removeItem('better-auth_session_data')
+
+ // Hard navigation creates clean page state. This runs only after all
+ // cleanup is done, so the next login won't be interrupted.
+ window.location.href = '/login'
}
- function removeUserData() {
- closeAllModals()
+ async function removeAllUserData() {
+ categoriesStore.cancelPersist()
+ trnsStore.cancelPersist()
+ walletsStore.cancelPersist()
- if (isDemo.value) {
- trnsStore.setTrns(null)
- categoriesStore.setCategories(null)
- walletsStore.setWallets(null)
- return
- }
+ trnsStore.setTrns(null)
+ categoriesStore.setCategories(null)
+ walletsStore.setWallets(null)
+ useTrnsFormStore().$reset()
- if (!uid.value) {
- return
- }
+ categoriesStore.cancelPersist()
+ trnsStore.cancelPersist()
+ walletsStore.cancelPersist()
- saveData(`users/${uid.value}/accounts/`, null)
- saveData(`users/${uid.value}/categories/`, null)
- saveData(`users/${uid.value}/trns/`, null)
+ const { clearOfflineQueue, setOfflineQueueUserId } = await import('~/components/offline/helpers')
+ await clearOfflineQueue()
+
+ // Restore in-memory userId — clearOfflineQueue resets it to null,
+ // but the user stays logged in and future pushes need ownership.
+ setOfflineQueueUserId(uid.value)
+
+ if (!isDemo.value) {
+ const { api, client } = useConvexClientWithApi()
+ await client.action(api.userSettings.removeAllUserData, {})
+ }
}
return {
+ baseCurrency,
currentUser,
- isDevUser,
- removeUserData,
+ initUserSettings,
+ isSigningOut,
+ locale,
+ removeAllUserData,
+ saveUserBaseCurrency,
+ saveUserLocale,
+ sessionUid,
setUser,
+ setUserBaseCurrency,
+ setUserLocale,
signOut,
uid,
user,
diff --git a/app/components/wallets/Currencies.vue b/app/components/wallets/Currencies.vue
index 5c9602fd..67600860 100644
--- a/app/components/wallets/Currencies.vue
+++ b/app/components/wallets/Currencies.vue
@@ -1,4 +1,4 @@
-<script lang="ts" setup>
+<script setup lang="ts">
import type { CurrencyCode } from '~/components/currencies/types'
import type { WalletsCurrencyFiltered } from '~/components/wallets/types'
@@ -9,7 +9,7 @@ defineProps<{
}>()
const emit = defineEmits<{
- onSelectFilterCurrency: [code: CurrencyCode]
+ selectFilterCurrency: [code: CurrencyCode]
}>()
const { t } = useI18n()
@@ -17,21 +17,21 @@ const walletsStore = useWalletsStore()
</script>
<template>
- <UiTabs2 class="flex gap-1 @xl/page:px-0">
- <UiTabsItem1
+ <UiTabsScroll class="flex gap-1 @xl/page:px-0">
+ <UiTabsItemFill
:isActive="currencyFiltered === 'all'"
- @click="emit('onSelectFilterCurrency', 'all')"
+ @click="emit('selectFilterCurrency', 'all')"
>
{{ t('common.all') }}
- </UiTabsItem1>
+ </UiTabsItemFill>
- <UiTabsItem1
+ <UiTabsItemFill
v-for="currency in walletsStore.currenciesUsed"
:key="currency"
:isActive="currencyFiltered === currency"
- @click="emit('onSelectFilterCurrency', currency)"
+ @click="emit('selectFilterCurrency', currency)"
>
{{ currency }}
- </UiTabsItem1>
- </UiTabs2>
+ </UiTabsItemFill>
+ </UiTabsScroll>
</template>
diff --git a/app/components/wallets/CurrenciesToggleDep.vue b/app/components/wallets/CurrenciesToggleDep.vue
index ede296ee..06829a9e 100644
--- a/app/components/wallets/CurrenciesToggleDep.vue
+++ b/app/components/wallets/CurrenciesToggleDep.vue
@@ -1,4 +1,4 @@
-<script lang="ts" setup>
+<script setup lang="ts">
import type { CurrencyCode } from '~/components/currencies/types'
import type { WalletsCurrencyFiltered } from '~/components/wallets/types'
@@ -9,7 +9,7 @@ defineProps<{
}>()
const emit = defineEmits<{
- onSelectFilterCurrency: [code: CurrencyCode]
+ selectFilterCurrency: [code: CurrencyCode]
}>()
const { t } = useI18n()
@@ -24,31 +24,31 @@ const walletsStore = useWalletsStore()
storageKey="finapp-wallets-currencies"
>
<template #header="{ toggle, isShown }">
- <UiTitle8
+ <UiTitleCollapse
:isShown
@click="toggle"
>
{{ t('wallets.filterByCurrency') }}
{{ (currencyFiltered !== 'all' && !isShown) ? currencyFiltered : '' }}
- </UiTitle8>
+ </UiTitleCollapse>
</template>
- <UiTabs2 class="flex gap-1 px-2 @xl/page:px-0">
- <UiTabsItem1
+ <UiTabsScroll class="flex gap-1 px-2 @xl/page:px-0">
+ <UiTabsItemFill
:isActive="currencyFiltered === 'all'"
- @click="emit('onSelectFilterCurrency', 'all')"
+ @click="emit('selectFilterCurrency', 'all')"
>
{{ t('common.all') }}
- </UiTabsItem1>
+ </UiTabsItemFill>
- <UiTabsItem1
+ <UiTabsItemFill
v-for="currency in walletsStore.currenciesUsed"
:key="currency"
:isActive="currencyFiltered === currency"
- @click="emit('onSelectFilterCurrency', currency)"
+ @click="emit('selectFilterCurrency', currency)"
>
{{ currency }}
- </UiTabsItem1>
- </UiTabs2>
+ </UiTabsItemFill>
+ </UiTabsScroll>
</UiToggleWithStorage>
</template>
diff --git a/app/components/wallets/Form.vue b/app/components/wallets/Form.vue
index 91f5c96d..4c3e78f6 100644
--- a/app/components/wallets/Form.vue
+++ b/app/components/wallets/Form.vue
@@ -4,9 +4,9 @@ import { generateId } from '~~/utils/generateId'
import type { CurrencyCode } from '~/components/currencies/types'
import type { WalletId, WalletItem, WalletType } from '~/components/wallets/types'
-import { errorEmo, random } from '~/assets/js/emo'
-import { types, walletItemSchema } from '~/components/wallets/types'
+import { walletItemSchema, walletTypes } from '~/components/wallets/types'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { showErrorToast } from '~/composables/useStoreSync'
const props = defineProps<{
walletForm: WalletItem
@@ -15,15 +15,14 @@ const props = defineProps<{
const emit = defineEmits<{
afterSave: []
- updateValue: [key: keyof WalletItem, value: WalletItem[keyof WalletItem]]
+ update: [key: keyof WalletItem, value: WalletItem[keyof WalletItem]]
}>()
const { t } = useI18n()
const walletsStore = useWalletsStore()
-const toast = useToast()
const editWalletId = props.walletId ?? generateId()
-const walletType = types.map(value => ({
+const walletType = walletTypes.map(value => ({
label: t(`money.types.${value}`),
value,
}))
@@ -39,61 +38,15 @@ const walletPlaceholder = computed(() => ({
name: props.walletForm.name ? props.walletForm.name : t('wallets.form.name.label'),
}))
-/**
- * Validate
- */
-// function validate(values: WalletItem) {
-// // name
-// if (!values.name) {
-// toast.add({
-// color: 'error',
-// description: t('wallets.form.name.error'),
-// title: random(errorEmo),
-// })
-
-// return false
-// }
-
-// // currency
-// if (!values.currency) {
-// toast.add({
-// color: 'error',
-// description: t('wallets.form.currency.error'),
-// title: random(errorEmo),
-// })
-
-// return false
-// }
-
-// // Check for duplicate wallet names
-// const existingWallet = Object.entries(walletsStore.items ?? {})
-// .find(([id, wallet]) => wallet.name === values.name && id !== editWalletId)
-
-// if (existingWallet) {
-// toast.add({
-// color: 'error',
-// description: t('wallets.form.name.exist'),
-// title: random(errorEmo),
-// })
-// return false
-// }
-
-// return true
-// }
-
async function onSave() {
const values = walletItemSchema.safeParse(props.walletForm)
if (!values.success) {
- toast.add({
- color: 'error',
- description: t('categories.form.name.error'),
- title: random(errorEmo),
- })
+ showErrorToast('wallets.form.name.error')
return
}
- await walletsStore.createOrUpdateWallet({
+ await walletsStore.saveWallet({
id: editWalletId,
values: values.data,
})
@@ -115,8 +68,8 @@ async function onSave() {
<FormInput
:placeholder="t('wallets.form.name.placeholder')"
- :value="props.walletForm.name ?? ''"
- @updateValue="(value: string) => emit('updateValue', 'name', value)"
+ :modelValue="props.walletForm.name ?? ''"
+ @update:modelValue="(value: string) => emit('update', 'name', value)"
/>
</FormElement>
@@ -152,21 +105,21 @@ async function onSave() {
</template>
<FormTextarea
:placeholder="t('wallets.form.description.placeholder')"
- :value="props.walletForm.desc ?? ''"
- @updateValue="(value: string) => emit('updateValue', 'desc', value)"
+ :modelValue="props.walletForm.desc ?? ''"
+ @update:modelValue="(value: string) => emit('update', 'desc', value)"
/>
</FormElement>
<!-- Type -->
<div>
- <UiTitle3 class="pb-2">
+ <UiTitleSection class="pb-2">
{{ t('money.type') }}
- </UiTitle3>
+ </UiTitleSection>
<FormSelect
:options="walletType"
:value="props.walletForm.type ?? 'cash'"
- @change="(value: WalletType) => emit('updateValue', 'type', value)"
+ @change="(value: WalletType) => emit('update', 'type', value)"
/>
</div>
@@ -177,28 +130,28 @@ async function onSave() {
</template>
<FormInput
:placeholder="t('wallets.form.credit.limit')"
- :value="props.walletForm.creditLimit ?? ''"
- @updateValue="(value: string) => emit('updateValue', 'creditLimit', +value)"
+ :modelValue="props.walletForm.creditLimit ?? ''"
+ @update:modelValue="(value: string) => emit('update', 'creditLimit', +value)"
/>
</FormElement>
<!-- Options -->
<div class="grid gap-1">
<div>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="props.walletForm.isWithdrawal ?? false"
:title="t('money.options.withdrawal')"
- @click="emit('updateValue', 'isWithdrawal', !props.walletForm.isWithdrawal)"
+ @click="emit('update', 'isWithdrawal', !props.walletForm.isWithdrawal)"
/>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="props.walletForm.isExcludeInTotal ?? false"
:title="t('money.options.isExcludeInTotal')"
- @click="emit('updateValue', 'isExcludeInTotal', !props.walletForm.isExcludeInTotal)"
+ @click="emit('update', 'isExcludeInTotal', !props.walletForm.isExcludeInTotal)"
/>
- <UiCheckbox
+ <UiSwitchItem
:checkboxValue="props.walletForm.isArchived ?? false"
:title="t('money.totals.archived')"
- @click="emit('updateValue', 'isArchived', !props.walletForm.isArchived)"
+ @click="emit('update', 'isArchived', !props.walletForm.isArchived)"
/>
</div>
</div>
@@ -206,6 +159,7 @@ async function onSave() {
<div class="flex-center">
<UiButtonAccent
+ class="sm:max-w-xs"
rounded
@click="onSave"
>
@@ -217,11 +171,11 @@ async function onSave() {
<CurrenciesModal
v-if="modals.currencies"
:activeCode="props.walletForm.currency"
- @onSelect="(c: CurrencyCode) => emit('updateValue', 'currency', c)"
- @onClose="modals.currencies = false"
+ @select="(c: CurrencyCode) => emit('update', 'currency', c)"
+ @close="modals.currencies = false"
/>
- <Teleport to="#teleports">
+ <Teleport to="body">
<!-- Colors -->
<BottomSheet
v-if="modals.colors"
@@ -231,7 +185,7 @@ async function onSave() {
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
@@ -249,7 +203,7 @@ async function onSave() {
<ColorPalette
:activeColor="props.walletForm.color"
isWallet
- @click="(color: string) => emit('updateValue', 'color', color)"
+ @click="(color: string) => emit('update', 'color', color)"
/>
</div>
diff --git a/app/components/wallets/Icon.vue b/app/components/wallets/Icon.vue
index 7a5a985e..249251fd 100644
--- a/app/components/wallets/Icon.vue
+++ b/app/components/wallets/Icon.vue
@@ -27,7 +27,3 @@ function getWalletIconName(name: string) {
{{ getWalletIconName(props.name) }}
</div>
</template>
-
-<style scoped>
-
-</style>
diff --git a/app/components/wallets/Item.vue b/app/components/wallets/Item.vue
index 9383d81c..2b4d0563 100644
--- a/app/components/wallets/Item.vue
+++ b/app/components/wallets/Item.vue
@@ -4,7 +4,6 @@ import { onLongPress, useStorage } from '@vueuse/core'
import type { WalletId, WalletItemComputed } from '~/components/wallets/types'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
-import { getStyles } from '~/components/ui/getStyles'
const props = defineProps<{
activeItemId?: WalletId | null
@@ -29,7 +28,7 @@ const currenciesStore = useCurrenciesStore()
const classes = computed(() => ([
'relative',
{
- [getStyles('item', ['bg2', 'rounded'])]: props.alt,
+ 'bg-item-3 rounded-sm': props.alt,
},
{
group: props.isSort,
@@ -183,7 +182,7 @@ if (!props.isSort) {
<div
v-if="isSort"
- class="sortHandle flex-center absolute right-0 h-full rounded-md px-3 group-hover:bg-[var(--item-6)]"
+ class="sortHandle flex-center absolute right-0 h-full rounded-md px-3 group-hover:bg-(--item-6)"
>
<Icon name="lucide:grip-vertical" size="20" />
</div>
diff --git a/app/components/wallets/List.vue b/app/components/wallets/List.vue
index 0176769d..e19e012f 100644
--- a/app/components/wallets/List.vue
+++ b/app/components/wallets/List.vue
@@ -1,15 +1,12 @@
<script setup lang="ts">
import type { WalletsComputed } from '~/components/wallets/types'
-import { getStyles } from '~/components/ui/getStyles'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-const props = withDefaults(defineProps<{
+const { isShowToggle, limit = 0 } = defineProps<{
isShowToggle?: boolean
limit?: number
-}>(), {
- limit: 0,
-})
+}>()
const { t } = useI18n()
const walletsStore = useWalletsStore()
@@ -30,10 +27,10 @@ const walletsItemsLimited = computed<WalletsComputed>(() => {
function toggle() {
stateLimit.value = stateLimit.value > 0
? 0
- : props.limit
+ : limit
}
-onMounted(() => stateLimit.value = props.limit)
+onMounted(() => stateLimit.value = limit)
</script>
<template>
@@ -51,8 +48,7 @@ onMounted(() => stateLimit.value = props.limit)
name="toggle"
>
<div
- :class="getStyles('item', ['rounded', 'minh1', 'link', 'padding1', 'center3'])"
- class="text-muted -mt-px text-xs"
+ class="interactive flex-center text-muted -mt-px min-h-[42px] rounded-sm px-2 py-1.5 text-xs"
@click="toggle"
>
<template v-if="stateLimit > 0">
diff --git a/app/components/wallets/Selector.vue b/app/components/wallets/Selector.vue
index bf09276e..e069b9f5 100644
--- a/app/components/wallets/Selector.vue
+++ b/app/components/wallets/Selector.vue
@@ -13,7 +13,7 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
- onSelected: [id: WalletId]
+ selected: [id: WalletId]
}>()
const walletsStore = useWalletsStore()
@@ -27,7 +27,7 @@ const selectedWalletsIdsWithCurrency = computed<WalletId[]>(() => {
})
function onClickWallet(walletId: WalletId) {
- emit('onSelected', walletId)
+ emit('selected', walletId)
if (props.hide)
props.hide()
@@ -36,8 +36,9 @@ function onClickWallet(walletId: WalletId) {
<template>
<div
- class="grid h-full gap-2 overflow-hidden"
- :class="{ 'grid-rows-[auto_1fr]': walletsStore.currenciesUsed.length > 1 }"
+ :class="cn('grid h-full gap-2 overflow-hidden',
+ walletsStore.currenciesUsed.length > 1 && 'grid-rows-[auto_1fr]',
+ )"
>
<div
v-if="walletsStore.currenciesUsed.length > 1"
@@ -45,7 +46,7 @@ function onClickWallet(walletId: WalletId) {
>
<WalletsCurrencies
:currencyFiltered
- @onSelectFilterCurrency="code => currencyFiltered = code"
+ @selectFilterCurrency="code => currencyFiltered = code"
/>
</div>
diff --git a/app/components/wallets/SortModal.vue b/app/components/wallets/SortModal.vue
index ee5487ea..b96033cb 100644
--- a/app/components/wallets/SortModal.vue
+++ b/app/components/wallets/SortModal.vue
@@ -1,32 +1,19 @@
<script setup lang="ts">
import { useDragAndDrop } from '@formkit/drag-and-drop/vue'
-import { errorEmo, random } from '~/assets/js/emo'
-import { useAppNav } from '~/components/app/useAppNav'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-const { closeAllModals, isModalOpen } = useAppNav()
+const emit = defineEmits<{ close: [] }>()
const walletsStore = useWalletsStore()
const { t } = useI18n()
-const toast = useToast()
const [parent, sortedWalletsIds] = useDragAndDrop([...walletsStore.sortedIds], {
dragHandle: '.sortHandle',
})
-async function saveWalletsOrder(close: () => void) {
- const result = await walletsStore.saveWalletsOrder(sortedWalletsIds.value)
-
- if (result !== 'ok') {
- toast.add({
- color: 'error',
- description: 'Error',
- title: random(errorEmo),
- })
- return
- }
-
+function saveWalletsOrder(close: () => void) {
+ walletsStore.saveWalletsOrder(sortedWalletsIds.value)
close()
}
</script>
@@ -34,14 +21,13 @@ async function saveWalletsOrder(close: () => void) {
<template>
<Teleport to="body">
<BottomSheet
- v-if="isModalOpen('walletsSort')"
isShow
drugClassesCustom="bottomSheetDrugClassesCustom"
- @closed="closeAllModals"
+ @closed="emit('close')"
>
<template #handler="{ close }">
<BottomSheetHandler />
- <BottomSheetClose @onClick="close" />
+ <BottomSheetClose @click="close" />
</template>
<template #default="{ close }">
diff --git a/app/components/wallets/Statistics.vue b/app/components/wallets/Statistics.vue
index 4a074cd9..e7f10a92 100644
--- a/app/components/wallets/Statistics.vue
+++ b/app/components/wallets/Statistics.vue
@@ -34,9 +34,9 @@ const itemsGrouped = computed(() => [
>
<template #header="{ toggle, isShown }">
<div class="flex grow items-center justify-between">
- <UiTitle8 :isShown @click="toggle">
+ <UiTitleCollapse :isShown @click="toggle">
{{ t('statistics.title') }}
- </UiTitle8>
+ </UiTitleCollapse>
</div>
</template>
diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vue
index 3cb15449..52d5d926 100644
--- a/app/components/wallets/page/List.vue
+++ b/app/components/wallets/page/List.vue
@@ -1,14 +1,16 @@
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
-import type { CurrencyCode } from '~/components/currencies/types'
-import type { WalletId, WalletItem, WalletsCurrencyFiltered, WalletsGroupedBy, WalletType, WalletViewTypes } from '~/components/wallets/types'
+import type { WalletsGroupedBy } from '~/components/wallets/types'
-import { useAmount } from '~/components/amount/useAmount'
-import { useAppNav } from '~/components/app/useAppNav'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { useUserStore } from '~/components/user/useUserStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { useWalletsPageCounts } from './useWalletsPageCounts'
+import { useWalletsPageFilter } from './useWalletsPageFilter'
+import { useWalletsPageGrouping } from './useWalletsPageGrouping'
+
const { t } = useI18n()
const router = useRouter()
@@ -19,479 +21,38 @@ useSeoMeta({
const walletsStore = useWalletsStore()
const currenciesStore = useCurrenciesStore()
-const { isModalOpen, openModal } = useAppNav()
-const { getAmountInBaseRate } = useAmount()
+const userStore = useUserStore()
+const isSortModalOpen = ref(false)
const isShowBaseCurrencyModal = ref(false)
-const currencyFiltered = useStorage<WalletsCurrencyFiltered>('finapp-wallets-active-currency', 'all')
-const walletViewType = useStorage<WalletViewTypes | 'total'>('finapp-wallets-active-type', 'total')
-
-function setWalletViewType(v: WalletType | 'total') {
- walletViewType.value = v
-}
+const isOpen = ref(false)
const groupedBy = useStorage<WalletsGroupedBy>('finapp-wallets-groupedBy', 'none')
-const groupedBySecondary = useStorage('finapp-wallets-groupedBySecondary', {
- currency: false,
- type: false,
-})
-
-const selectedWalletsIdsWithCurrency = computed<WalletId[]>(() => {
- return Object.keys(walletsStore.itemsComputed).filter((id) => {
- const wallet = walletsStore.itemsComputed[id]
- if (groupedBy.value === 'currency')
- return true
- return currencyFiltered.value === 'all' || currencyFiltered.value === wallet?.currency
- })
-})
-
-const selectedWalletsIds = computed<WalletId[]>(() => {
- return selectedWalletsIdsWithCurrency.value.filter((id) => {
- const wallet = walletsStore.itemsComputed[id]!
-
- if (walletViewType.value === 'isWithdrawal')
- return wallet.isWithdrawal && !wallet.isArchived
-
- if (walletViewType.value === 'isExcludeInTotal')
- return wallet.isExcludeInTotal
-
- if (walletViewType.value === 'isArchived')
- return wallet.isArchived
-
- if (walletViewType.value === 'isAvailable')
- return (wallet.type === 'credit' || wallet.isWithdrawal) && !wallet.isArchived
-
- if (walletViewType.value === 'total')
- return !wallet.isArchived && !wallet.isExcludeInTotal
-
- return wallet.type === walletViewType.value
- })
-})
-
-const isShowCurrencyFilter = ref(false)
-
-function onSelectFilterCurrency(code: CurrencyCode, toggle?: () => void) {
- if (currencyFiltered.value === code && toggle)
- toggle()
-
- walletViewType.value = 'total'
- currencyFiltered.value = code
- isShowCurrencyFilter.value = false
-}
-
-const counts = computed(() => {
- const sum = {
- archived: 0,
- available: 0,
- cash: 0,
- cashless: 0,
- credit: 0,
- creditPossible: 0,
- crypto: 0,
- debt: 0,
- deposit: 0,
- excludeInTotal: 0,
- total: 0,
- withdrawal: 0,
- }
-
- for (const walletId of selectedWalletsIdsWithCurrency.value) {
- const wallet = walletsStore.itemsComputed[walletId]
- if (!wallet)
- continue
-
- const itemValue
- = wallet.currency === currenciesStore.base
- ? (walletsStore.itemsComputed[walletId]?.amount ?? 0)
- : +getAmountInBaseRate({
- amount: walletsStore.itemsComputed[walletId]?.amount ?? 0,
- currencyCode: wallet.currency ?? 'USD',
- noFormat: true,
- })
-
- if (wallet.isExcludeInTotal) {
- sum.excludeInTotal += itemValue
- }
- else if (wallet.type !== 'credit') {
- sum.total += itemValue
- }
-
- if (wallet.type === 'cash')
- sum.cash += itemValue
-
- if (wallet.type === 'cashless')
- sum.cashless += itemValue
- if (wallet.type === 'crypto')
- sum.crypto += itemValue
-
- if (wallet.type === 'deposit')
- sum.deposit += itemValue
-
- if (wallet.type === 'debt')
- sum.debt += itemValue
-
- if (wallet.type === 'credit')
- sum.credit += itemValue
-
- if (wallet.type === 'credit' && wallet.creditLimit) {
- sum.creditPossible = sum.creditPossible + +getAmountInBaseRate({
- amount: wallet.creditLimit ?? 0,
- currencyCode: wallet.currency ?? 'USD',
- noFormat: true,
- })
- }
-
- if (wallet.isWithdrawal)
- sum.withdrawal += itemValue
-
- if (wallet.isArchived) {
- sum.archived += itemValue
- }
- }
-
- return {
- cash: {
- id: 'cash',
- isShow: Object.keys(walletsStore.itemsComputed).length > 1 && sum.cash !== 0,
- value: sum.cash,
- },
- // eslint-disable-next-line perfectionist/sort-objects
- available: {
- id: 'isAvailable',
- isShow: sum.withdrawal !== 0,
- value: sum.withdrawal - Math.abs(sum.credit),
- },
-
- cashless: {
- id: 'cashless',
- isShow: sum.cashless !== 0,
- value: sum.cashless,
- },
-
- credit: {
- id: 'credit',
- isShow: sum.credit !== 0,
- secondValue: sum.creditPossible,
- value: sum.credit,
- },
-
- crypto: {
- id: 'crypto',
- isShow: sum.crypto !== 0,
- value: sum.crypto,
- },
-
- debt: {
- id: 'debt',
- isShow: sum.debt !== 0,
- value: sum.debt,
- },
-
- deposit: {
- id: 'deposit',
- isShow: sum.deposit !== 0,
- value: sum.deposit,
- },
-
- total: {
- id: 'total',
- isShow: true,
- value: sum.total,
- },
-
- withdrawal: {
- id: 'isWithdrawal',
- isShow: sum.withdrawal !== 0,
- value: sum.withdrawal,
- },
- // eslint-disable-next-line perfectionist/sort-objects
- excludeInTotal: {
- id: 'isExcludeInTotal',
- isShow: sum.excludeInTotal !== 0,
- value: sum.excludeInTotal,
- },
- // eslint-disable-next-line perfectionist/sort-objects
- archived: {
- id: 'isArchived',
- isShow: selectedWalletsIdsWithCurrency.value.some(wallet => walletsStore.itemsComputed[wallet]?.isArchived),
- value: sum.archived,
- },
- }
-})
-
-type WalletsGroupedByExcludedNone = Exclude<WalletsGroupedBy, 'none'>
-type WalletGroup = {
- groups?: Record<string, WalletId[]>
- ids: WalletId[]
-}
-type GroupToggleState = {
- groups?: Record<string, boolean>
- show?: boolean
-}
-type ToggleMapByGroup = Record<string, GroupToggleState>
-type WalletsToggleMap = Partial<Record<WalletsGroupedByExcludedNone, ToggleMapByGroup>>
-type GroupedWallets = Record<string, WalletGroup>
-
-// Update the storage definition with proper type and default value
-const walletsToggledMap = useStorage<WalletsToggleMap>('finapp-wallets-toggle-map', {} as WalletsToggleMap, localStorage, {
- mergeDefaults: true,
-})
-
-// Helper functions to improve readability
-function groupWalletsByStrategy(ids: WalletId[], strategy: keyof WalletItem): Record<string, WalletId[]> {
- return Object.groupBy(ids, (id) => {
- const wallet = walletsStore.itemsComputed[id]
- return wallet ? String(wallet[strategy] || '') : ''
- }) as Record<string, WalletId[]>
-}
-
-function createPrimaryGroups(grouped: Record<string, WalletId[]>): GroupedWallets {
- return Object.entries(grouped).reduce<GroupedWallets>((acc, [key, ids]) => {
- acc[key] = { groups: {}, ids }
- return acc
- }, {})
-}
-function createSecondaryGroups(grouped: Record<string, WalletId[]>, secondaryStrategy: keyof WalletItem): GroupedWallets {
- return Object.entries(grouped).reduce<GroupedWallets>((acc, [key, ids]) => {
- acc[key] = {
- groups: groupWalletsByStrategy(ids, secondaryStrategy),
- ids,
- }
- return acc
- }, {})
-}
-
-const groupedWalletsWithIds = computed<GroupedWallets | false>(() => {
- if (groupedBy.value === 'none')
- return false
-
- const groupingStrategies = {
- currency: {
- primary: 'currency',
- secondary: 'type',
- },
- type: {
- primary: 'type',
- secondary: 'currency',
- },
- } as const
-
- const strategy = groupingStrategies[groupedBy.value as WalletsGroupedByExcludedNone]
- if (!strategy)
- return false
-
- const ids = selectedWalletsIds.value
- const primaryGrouped = groupWalletsByStrategy(ids, strategy.primary)
-
- let useSecondaryGrouping = false
- if (groupedBy.value === 'currency') {
- useSecondaryGrouping = !!groupedBySecondary.value.currency
- }
- else if (groupedBy.value === 'type') {
- useSecondaryGrouping = !!groupedBySecondary.value.type
- }
-
- return useSecondaryGrouping
- ? createSecondaryGroups(primaryGrouped, strategy.secondary)
- : createPrimaryGroups(primaryGrouped)
-})
-
-function toggleMap(groupPrimary: string, groupSecondary?: string) {
- const currentGroup = groupedBy.value
- if (currentGroup === 'none')
- return
-
- const currentToggleMap = { ...walletsToggledMap.value }
- currentToggleMap[currentGroup] ??= {}
-
- if (!currentToggleMap[currentGroup]![groupPrimary])
- currentToggleMap[currentGroup]![groupPrimary] = { groups: {} }
-
- if (groupSecondary) {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary]
- primaryGroup.groups ??= {}
-
- // Toggle the secondary group
- const currentValue = primaryGroup.groups[groupSecondary]
- primaryGroup.groups[groupSecondary] = currentValue === undefined ? false : !currentValue
- }
- // Handle primary group toggle
- else {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary]
- primaryGroup.groups ??= {}
- primaryGroup.show = primaryGroup.show === undefined ? false : !primaryGroup.show
- }
-
- walletsToggledMap.value = currentToggleMap
-}
-
-const typeGroupsStatus = computed(() => {
- const currentGroup = groupedBy.value
- if (currentGroup === 'none' || !walletsToggledMap.value[currentGroup])
- return { isAllOpen: false, isAllOpenInside: false, isAnyOpen: false, isAnyOpenInside: false }
-
- const groups = walletsToggledMap.value[currentGroup] || {}
-
- return {
- isAllOpen: Object.values(groups).every(group => !!group.show),
- isAllOpenInside: Object.values(groups).every(group =>
- Object.values(group.groups || {}).every(isOpen => !!isOpen),
- ),
- isAnyOpen: Object.values(groups).some(group => !!group.show),
- isAnyOpenInside: Object.values(groups).some(group =>
- Object.values(group.groups || {}).some(isOpen => !!isOpen),
- ),
- }
-})
-
-function toggleOpened() {
- const currentGroup = groupedBy.value
- if (currentGroup === 'none' || !groupedWalletsWithIds.value)
- return
-
- const currentToggleMap = { ...walletsToggledMap.value }
- currentToggleMap[currentGroup] ??= {}
-
- const { isAllOpen, isAllOpenInside } = typeGroupsStatus.value
- const groupPrimaries = Object.keys(groupedWalletsWithIds.value)
-
- // We know groupedWalletsWithIds.value is not false at this point
- const groupedWallets = groupedWalletsWithIds.value as GroupedWallets
-
- // Check if we're using secondary grouping
- let hasSecondaryGrouping = false
- if (currentGroup === 'currency') {
- hasSecondaryGrouping = !!groupedBySecondary.value.currency
- }
- else if (currentGroup === 'type') {
- hasSecondaryGrouping = !!groupedBySecondary.value.type
- }
-
- // If we don't have secondary grouping, just toggle the primary groups' show property
- if (!hasSecondaryGrouping) {
- // If all primary groups are open, close them all
- // Otherwise, open them all
- const newShowState = !isAllOpen
-
- groupPrimaries.forEach((groupPrimary) => {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary] || { groups: {} }
-
- currentToggleMap[currentGroup]![groupPrimary] = {
- ...primaryGroup,
- show: newShowState,
- }
- })
- }
- // If we have secondary grouping, handle the three cases as before
- else {
- // Case 1: All primary groups are open but not all inner groups are open
- // Set all inner groups to true
- if (isAllOpen && !isAllOpenInside) {
- groupPrimaries.forEach((groupPrimary) => {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary] || { groups: {}, show: true }
-
- // Get all secondary groups for this primary group
- const walletGroup = groupedWallets[groupPrimary]
- const secondaryGroups = walletGroup && walletGroup.groups ? walletGroup.groups : {}
-
- // Set all inner groups to true
- currentToggleMap[currentGroup]![groupPrimary] = {
- ...primaryGroup,
- groups: Object.keys(secondaryGroups).reduce((acc, groupSecondary) => {
- acc[groupSecondary] = true
- return acc
- }, { ...primaryGroup.groups }),
- show: true,
- }
- })
- }
- // Case 2: All primary groups and all inner groups are open
- // Set everything to false
- else if (isAllOpen && isAllOpenInside) {
- groupPrimaries.forEach((groupPrimary) => {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary] || { groups: {}, show: false }
-
- // Get all secondary groups for this primary group
- const walletGroup = groupedWallets[groupPrimary]
- const secondaryGroups = walletGroup && walletGroup.groups ? walletGroup.groups : {}
-
- // Set primary show to false and all inner groups to false
- currentToggleMap[currentGroup]![groupPrimary] = {
- ...primaryGroup,
- groups: Object.keys(secondaryGroups).reduce((acc, groupSecondary) => {
- acc[groupSecondary] = false
- return acc
- }, { ...primaryGroup.groups }),
- show: false,
- }
- })
- }
- // Case 3: Not all primary groups are open
- else {
- groupPrimaries.forEach((groupPrimary) => {
- const primaryGroup = currentToggleMap[currentGroup]![groupPrimary] || { groups: {} }
-
- currentToggleMap[currentGroup]![groupPrimary] = {
- ...primaryGroup,
- show: true,
- }
- })
- }
- }
-
- walletsToggledMap.value = currentToggleMap
-}
-
-const groupTabs = computed(() => {
- const items: {
- id: WalletsGroupedBy
- label: string
- }[] = [{
- id: 'none',
- label: t('wallets.page.none'),
- }, {
- id: 'type',
- label: t('wallets.page.type'),
- }]
-
- if (walletsStore.currenciesUsed.length > 1) {
- items.push({
- id: 'currency',
- label: t('wallets.page.currencies'),
- })
- }
-
- return items
-})
-
-function countWalletsSum(
- walletsIds: WalletId[],
- isConvert = true,
-) {
- return walletsIds.reduce((acc, id) => {
- const wallet = walletsStore.itemsComputed[id]
- if (!wallet)
- return acc
-
- if (isConvert) {
- return (
- acc
- + +getAmountInBaseRate({
- amount: wallet.amount,
- currencyCode: wallet.currency,
- noFormat: true,
- })
- )
- }
-
- if (wallet.isExcludeInTotal)
- return acc
- return acc + wallet.amount
- }, 0)
-}
-
-const isOpen = ref(false)
+const {
+ currencyFiltered,
+ isShowCurrencyFilter,
+ onSelectFilterCurrency,
+ selectedWalletsIds,
+ selectedWalletsIdsWithCurrency,
+ setWalletViewType,
+ walletViewType,
+} = useWalletsPageFilter(groupedBy)
+
+const {
+ counts,
+ countWalletsSum,
+} = useWalletsPageCounts(selectedWalletsIdsWithCurrency)
+
+const {
+ groupedBySecondary,
+ groupedWalletsWithIds,
+ groupTabs,
+ toggleMap,
+ toggleOpened,
+ typeGroupsStatus,
+ walletsToggledMap,
+} = useWalletsPageGrouping(selectedWalletsIds, groupedBy)
</script>
<template>
@@ -501,20 +62,20 @@ const isOpen = ref(false)
<UiHeaderTitle>{{ t('wallets.name') }}</UiHeaderTitle>
<template #actions>
- <UiItem3 @click="router.push('/wallets/new')">
+ <UiActionButton @click="router.push('/wallets/new')">
<Icon name="lucide:plus" size="24" />
- </UiItem3>
+ </UiActionButton>
<BottomSheetOrDropdown
:isOpen="isOpen"
isShowCloseBtn
- @onCloseModal="isOpen = false"
- @onOpenModal="isOpen = true"
+ @closeModal="isOpen = false"
+ @openModal="isOpen = true"
>
<template #trigger>
- <UiItem1>
+ <UiActionButton>
<Icon name="lucide:ellipsis-vertical" size="20" />
- </UiItem1>
+ </UiActionButton>
</template>
<template #content>
@@ -522,7 +83,7 @@ const isOpen = ref(false)
<UiHeaderLink
v-if="walletsStore.sortedIds.length > 1"
icon="lucide:arrow-down-up"
- @click="openModal('walletsSort')"
+ @click="isSortModalOpen = true"
>
{{ t('wallets.sortTitle') }}
</UiHeaderLink>
@@ -535,15 +96,17 @@ const isOpen = ref(false)
<!-- Empty -->
<div
v-if="!walletsStore.hasItems"
- class="pageWrapper"
+ class="flex-center grow flex-col"
>
- <div class="@xl/page:max-w-xs">
- <UiButtonAccent
- @click="router.push('/wallets/new')"
- >
- {{ t('wallets.new') }}
- </UiButtonAccent>
- </div>
+ <UiTitleSection class="pb-4">
+ {{ t('wallets.new') }}
+ </UiTitleSection>
+ <UiButtonAccent
+ rounded
+ @click="router.push('/wallets/new')"
+ >
+ {{ t('wallets.new') }}
+ </UiButtonAccent>
</div>
<!-- Content -->
@@ -557,7 +120,7 @@ const isOpen = ref(false)
<WalletsCurrencies
v-if="walletsStore.currenciesUsed.length > 1 && groupedBy !== 'currency'"
:currencyFiltered
- @onSelectFilterCurrency="code => currencyFiltered = code"
+ @selectFilterCurrency="code => currencyFiltered = code"
/>
<!-- Total -->
@@ -589,22 +152,23 @@ const isOpen = ref(false)
<!-- Left content -->
<div class="@3xl/main:max-w-sm">
<div class="mb-2 flex min-h-12 items-center gap-2 md:pt-2 ">
- <UiTabs2>
- <UiTabsItem4
+ <UiTabsScroll>
+ <UiTabsItemPill
v-for="item in groupTabs"
:key="item.id"
+ variant="outline"
:isActive="item.id === groupedBy"
@click="groupedBy = item.id"
>
{{ item.label }}
- </UiTabsItem4>
- </UiTabs2>
+ </UiTabsItemPill>
+ </UiTabsScroll>
<div
v-if="groupedBy !== 'none'"
class="ml-auto flex items-center gap-1"
>
- <UiItem1
+ <UiActionButton
@click="
groupedBy === 'currency'
? groupedBySecondary.currency = !groupedBySecondary.currency
@@ -622,9 +186,9 @@ const isOpen = ref(false)
"
size="18"
/>
- </UiItem1>
+ </UiActionButton>
- <UiItem1 @click="toggleOpened">
+ <UiActionButton @click="toggleOpened">
<Icon
v-if="typeGroupsStatus.isAllOpen"
name="lucide:folder-open"
@@ -637,7 +201,7 @@ const isOpen = ref(false)
v-else
name="lucide:folder"
/>
- </UiItem1>
+ </UiActionButton>
</div>
</div>
@@ -668,7 +232,7 @@ const isOpen = ref(false)
v-if="groupedBy !== 'none' && groupedWalletsWithIds"
class="grid gap-4"
>
- <UiToggle3
+ <UiToggleControlled
v-for="(content, groupPrimary) in groupedWalletsWithIds"
:key="groupPrimary"
:class="{
@@ -709,7 +273,7 @@ const isOpen = ref(false)
v-if="Object.keys(content.groups ?? {}).length > 0"
class="grid gap-2"
>
- <UiToggle3
+ <UiToggleControlled
v-for="(ids, groupSecondary) in content.groups"
:key="groupSecondary"
:isShown="
@@ -755,7 +319,7 @@ const isOpen = ref(false)
isShowRate
@click="router.push(`/wallets/${walletId}`)"
/>
- </UiToggle3>
+ </UiToggleControlled>
</div>
<template v-else>
@@ -773,7 +337,7 @@ const isOpen = ref(false)
@click="router.push(`/wallets/${walletId}`)"
/>
</template>
- </UiToggle3>
+ </UiToggleControlled>
</div>
</div>
</div>
@@ -781,14 +345,14 @@ const isOpen = ref(false)
</UiPage>
<!-- Sort Modal -->
- <WalletsSortModal v-if="isModalOpen('walletsSort')" />
+ <WalletsSortModal v-if="isSortModalOpen" @close="isSortModalOpen = false" />
<!-- Base Currency Modal -->
<CurrenciesModal
v-if="isShowBaseCurrencyModal"
:activeCode="currenciesStore.base"
- @onSelect="currenciesStore.setBase"
- @onClose="isShowBaseCurrencyModal = false"
+ @select="userStore.setUserBaseCurrency"
+ @close="isShowBaseCurrencyModal = false"
/>
<!-- Currency Filter Modal -->
@@ -797,7 +361,7 @@ const isOpen = ref(false)
:activeCode="currencyFiltered"
isShowAllButton
isHideUnused
- @onSelect="onSelectFilterCurrency"
- @onClose="isShowCurrencyFilter = false"
+ @select="onSelectFilterCurrency"
+ @close="isShowCurrencyFilter = false"
/>
</template>
diff --git a/app/components/wallets/page/New.vue b/app/components/wallets/page/New.vue
index 9d486ad3..bf2e81dc 100644
--- a/app/components/wallets/page/New.vue
+++ b/app/components/wallets/page/New.vue
@@ -4,9 +4,12 @@ import type { WalletItem } from '~/components/wallets/types'
import { walletItemSchema } from '~/components/wallets/types'
const { t } = useI18n()
+const route = useRoute()
const router = useRouter()
const walletForm = ref(walletItemSchema.parse({ type: 'cash' }))
+const isOnboarding = computed(() => 'onboarding' in route.query)
+
useHead({
title: `${t('base.add')}: ${walletForm.value.name ? walletForm.value.name : t('wallets.form.name.label')}`,
})
@@ -14,14 +17,23 @@ useHead({
<template>
<UiPage class="flex h-full flex-col">
- <UiHeader>
- <UiHeaderTitle>{{ t('wallets.createNewTitle') }}</UiHeaderTitle>
+ <h1
+ v-if="isOnboarding"
+ class="pt-2 pb-6 text-center text-2xl font-bold"
+ >
+ {{ t('wallets.createNewTitle') }}
+ </h1>
+
+ <UiHeader v-else>
+ <UiHeaderTitle>
+ {{ t('wallets.createNewTitle') }}
+ </UiHeaderTitle>
</UiHeader>
<WalletsForm
:walletForm="walletForm"
- @afterSave="() => router.replace('/wallets')"
- @updateValue="(id: keyof WalletItem, value: WalletItem[keyof WalletItem]) => walletForm[id] = value"
+ @afterSave="() => router.replace('/dashboard')"
+ @update="(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 25719e59..14eb2e2c 100644
--- a/app/components/wallets/page/id/Edit.vue
+++ b/app/components/wallets/page/id/Edit.vue
@@ -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 WalletItem, value: WalletItem[keyof WalletItem]) => walletForm[key] = value"
+ @update="(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) => walletForm[key] = value"
/>
</UiPage>
</template>
diff --git a/app/components/wallets/page/id/Index.vue b/app/components/wallets/page/id/Index.vue
index 94a8c043..0b4eef1e 100644
--- a/app/components/wallets/page/id/Index.vue
+++ b/app/components/wallets/page/id/Index.vue
@@ -5,14 +5,15 @@ import type { StatTabSlug } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
-import { random, successEmo } from '~/assets/js/emo'
import { useStatDate } from '~/components/date/useStatDate'
import { useFilter } from '~/components/stat/filter/useFilter'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useStatConfig } from '~/components/stat/useStatConfig'
import { getTypesMapping } from '~/components/stat/utils'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+import { showSuccessToast } from '~/composables/useStoreSync'
const { t } = useI18n()
const route = useRoute()
@@ -20,11 +21,8 @@ const router = useRouter()
const trnsFormStore = useTrnsFormStore()
const trnsStore = useTrnsStore()
const walletsStore = useWalletsStore()
-const walletStore = useWalletsStore()
-const toast = useToast()
-
const filter = useFilter()
-provide('filter', filter)
+provide(filterKey, filter)
const walletId = computed(() => route.params.id as WalletId)
const wallet = computed(() => walletsStore.items?.[walletId.value])
@@ -49,14 +47,14 @@ const statConfig = useStatConfig({
},
storageKey: storageKey.value,
})
-provide('statConfig', statConfig)
+provide(statConfigKey, statConfig)
const statDate = useStatDate({
key: storageKey.value,
maxRange,
queryParams: route.query,
})
-provide('statDate', statDate)
+provide(statDateKey, statDate)
watch(filter.categoriesIds, () => {
statConfig.config.value.isShowEmptyCategories = filter.categoriesIds.value.length > 0
@@ -85,26 +83,20 @@ function onClickDelete(close: () => void) {
}
async function onDeleteConfirm() {
- console.log('onDeleteConfirm')
-
- const trnsIdsS: TrnId[] = JSON.parse(JSON.stringify(
- trnsStore.getStoreTrnsIds({
- walletsIds: [walletId.value],
- }),
- ))
+ const trnsIdsS: TrnId[] = [...trnsStore.getStoreTrnsIds({
+ walletsIds: [walletId.value],
+ })]
router.push('/wallets')
- await walletStore.deleteWallet(JSON.parse(JSON.stringify(walletId.value)), trnsIdsS)
+ await walletsStore.deleteWallet(walletId.value, trnsIdsS)
// Give some time to complete redirect
- setTimeout(async () => {
- toast.add({
- color: 'success',
- description: trnsIdsS?.length > 0
- ? t('wallets.form.delete.okWithTrns', { length: trnsIdsS.length, trns: t('trns.plural', trnsIdsS.length) })
- : t('wallets.form.delete.okWithoutTrns'),
- title: random(successEmo),
- })
+ setTimeout(() => {
+ showSuccessToast(trnsIdsS?.length > 0
+ ? 'wallets.form.delete.okWithTrns'
+ : 'wallets.form.delete.okWithoutTrns', trnsIdsS?.length > 0
+ ? { length: trnsIdsS.length, trns: t('trns.plural', trnsIdsS.length) }
+ : undefined)
}, 300)
}
</script>
@@ -154,7 +146,7 @@ async function onDeleteConfirm() {
v-if="isShowDeleteConfirm"
:description="deleteDescText"
@closed="isShowDeleteConfirm = false"
- @onConfirm="onDeleteConfirm"
+ @confirm="onDeleteConfirm"
/>
<div class="px-3 pb-2 lg:gap-8 lg:px-4 2xl:px-8">
@@ -187,12 +179,13 @@ async function onDeleteConfirm() {
/>
</div>
- <UiTextSm2
+ <UiTextMuted
v-if="wallet.desc"
+ size="sm"
class="pt-2 whitespace-pre"
>
{{ wallet.desc }}
- </UiTextSm2>
+ </UiTextMuted>
</div>
<StatWrap
diff --git a/app/components/wallets/page/useWalletsPageCounts.ts b/app/components/wallets/page/useWalletsPageCounts.ts
new file mode 100644
index 00000000..f2633d8a
--- /dev/null
+++ b/app/components/wallets/page/useWalletsPageCounts.ts
@@ -0,0 +1,186 @@
+import type { ComputedRef } from 'vue'
+
+import type { WalletId } from '~/components/wallets/types'
+
+import { useAmount } from '~/components/amount/useAmount'
+import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+
+export function useWalletsPageCounts(
+ selectedWalletsIdsWithCurrency: ComputedRef<WalletId[]>,
+) {
+ const walletsStore = useWalletsStore()
+ const currenciesStore = useCurrenciesStore()
+ const { getAmountInBaseRate } = useAmount()
+
+ const counts = computed(() => {
+ const sum = {
+ archived: 0,
+ available: 0,
+ cash: 0,
+ cashless: 0,
+ credit: 0,
+ creditPossible: 0,
+ crypto: 0,
+ debt: 0,
+ deposit: 0,
+ excludeInTotal: 0,
+ total: 0,
+ withdrawal: 0,
+ }
+
+ for (const walletId of selectedWalletsIdsWithCurrency.value) {
+ const wallet = walletsStore.itemsComputed[walletId]
+ if (!wallet)
+ continue
+
+ const itemValue
+ = wallet.currency === currenciesStore.base
+ ? (walletsStore.itemsComputed[walletId]?.amount ?? 0)
+ : +getAmountInBaseRate({
+ amount: walletsStore.itemsComputed[walletId]?.amount ?? 0,
+ currencyCode: wallet.currency ?? 'USD',
+ noFormat: true,
+ })
+
+ if (wallet.isExcludeInTotal) {
+ sum.excludeInTotal += itemValue
+ }
+ else if (wallet.type !== 'credit') {
+ sum.total += itemValue
+ }
+
+ if (wallet.type === 'cash')
+ sum.cash += itemValue
+
+ if (wallet.type === 'cashless')
+ sum.cashless += itemValue
+ if (wallet.type === 'crypto')
+ sum.crypto += itemValue
+
+ if (wallet.type === 'deposit')
+ sum.deposit += itemValue
+
+ if (wallet.type === 'debt')
+ sum.debt += itemValue
+
+ if (wallet.type === 'credit')
+ sum.credit += itemValue
+
+ if (wallet.type === 'credit' && wallet.creditLimit) {
+ sum.creditPossible = sum.creditPossible + +getAmountInBaseRate({
+ amount: wallet.creditLimit ?? 0,
+ currencyCode: wallet.currency ?? 'USD',
+ noFormat: true,
+ })
+ }
+
+ if (wallet.isWithdrawal)
+ sum.withdrawal += itemValue
+
+ if (wallet.isArchived) {
+ sum.archived += itemValue
+ }
+ }
+
+ return {
+ cash: {
+ id: 'cash',
+ isShow: Object.keys(walletsStore.itemsComputed).length > 1 && sum.cash !== 0,
+ value: sum.cash,
+ },
+ // eslint-disable-next-line perfectionist/sort-objects
+ available: {
+ id: 'isAvailable',
+ isShow: sum.withdrawal !== 0,
+ value: sum.withdrawal - Math.abs(sum.credit),
+ },
+
+ cashless: {
+ id: 'cashless',
+ isShow: sum.cashless !== 0,
+ value: sum.cashless,
+ },
+
+ credit: {
+ id: 'credit',
+ isShow: sum.credit !== 0,
+ secondValue: sum.creditPossible,
+ value: sum.credit,
+ },
+
+ crypto: {
+ id: 'crypto',
+ isShow: sum.crypto !== 0,
+ value: sum.crypto,
+ },
+
+ debt: {
+ id: 'debt',
+ isShow: sum.debt !== 0,
+ value: sum.debt,
+ },
+
+ deposit: {
+ id: 'deposit',
+ isShow: sum.deposit !== 0,
+ value: sum.deposit,
+ },
+
+ total: {
+ id: 'total',
+ isShow: true,
+ value: sum.total,
+ },
+
+ withdrawal: {
+ id: 'isWithdrawal',
+ isShow: sum.withdrawal !== 0,
+ value: sum.withdrawal,
+ },
+ // eslint-disable-next-line perfectionist/sort-objects
+ excludeInTotal: {
+ id: 'isExcludeInTotal',
+ isShow: sum.excludeInTotal !== 0,
+ value: sum.excludeInTotal,
+ },
+ // eslint-disable-next-line perfectionist/sort-objects
+ archived: {
+ id: 'isArchived',
+ isShow: selectedWalletsIdsWithCurrency.value.some(wallet => walletsStore.itemsComputed[wallet]?.isArchived),
+ value: sum.archived,
+ },
+ }
+ })
+
+ function countWalletsSum(
+ walletsIds: WalletId[],
+ isConvert = true,
+ ) {
+ return walletsIds.reduce((acc, id) => {
+ const wallet = walletsStore.itemsComputed[id]
+ if (!wallet)
+ return acc
+
+ if (isConvert) {
+ return (
+ acc
+ + +getAmountInBaseRate({
+ amount: wallet.amount,
+ currencyCode: wallet.currency,
+ noFormat: true,
+ })
+ )
+ }
+
+ if (wallet.isExcludeInTotal)
+ return acc
+ return acc + wallet.amount
+ }, 0)
+ }
+
+ return {
+ counts,
+ countWalletsSum,
+ }
+}
diff --git a/app/components/wallets/page/useWalletsPageFilter.ts b/app/components/wallets/page/useWalletsPageFilter.ts
new file mode 100644
index 00000000..bfa24de2
--- /dev/null
+++ b/app/components/wallets/page/useWalletsPageFilter.ts
@@ -0,0 +1,72 @@
+import type { Ref } from 'vue'
+
+import { useStorage } from '@vueuse/core'
+
+import type { CurrencyCode } from '~/components/currencies/types'
+import type { WalletId, WalletsCurrencyFiltered, WalletsGroupedBy, WalletType, WalletViewTypes } from '~/components/wallets/types'
+
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+
+export function useWalletsPageFilter(groupedBy: Ref<WalletsGroupedBy>) {
+ const walletsStore = useWalletsStore()
+
+ const currencyFiltered = useStorage<WalletsCurrencyFiltered>('finapp-wallets-active-currency', 'all')
+ const walletViewType = useStorage<WalletViewTypes | 'total'>('finapp-wallets-active-type', 'total')
+
+ function setWalletViewType(v: WalletType | 'total') {
+ walletViewType.value = v
+ }
+
+ const selectedWalletsIdsWithCurrency = computed<WalletId[]>(() => {
+ return Object.keys(walletsStore.itemsComputed).filter((id) => {
+ const wallet = walletsStore.itemsComputed[id]
+ if (groupedBy.value === 'currency')
+ return true
+ return currencyFiltered.value === 'all' || currencyFiltered.value === wallet?.currency
+ })
+ })
+
+ const selectedWalletsIds = computed<WalletId[]>(() => {
+ return selectedWalletsIdsWithCurrency.value.filter((id) => {
+ const wallet = walletsStore.itemsComputed[id]!
+
+ if (walletViewType.value === 'isWithdrawal')
+ return wallet.isWithdrawal && !wallet.isArchived
+
+ if (walletViewType.value === 'isExcludeInTotal')
+ return wallet.isExcludeInTotal
+
+ if (walletViewType.value === 'isArchived')
+ return wallet.isArchived
+
+ if (walletViewType.value === 'isAvailable')
+ return (wallet.type === 'credit' || wallet.isWithdrawal) && !wallet.isArchived
+
+ if (walletViewType.value === 'total')
+ return !wallet.isArchived
+
+ return wallet.type === walletViewType.value
+ })
+ })
+
+ const isShowCurrencyFilter = ref(false)
+
+ function onSelectFilterCurrency(code: CurrencyCode, toggle?: () => void) {
+ if (currencyFiltered.value === code && toggle)
+ toggle()
+
+ walletViewType.value = 'total'
+ currencyFiltered.value = code
+ isShowCurrencyFilter.value = false
+ }
+
+ return {
+ currencyFiltered,
+ isShowCurrencyFilter,
+ onSelectFilterCurrency,
+ selectedWalletsIds,
+ selectedWalletsIdsWithCurrency,
+ setWalletViewType,
+ walletViewType,
+ }
+}
diff --git a/app/components/wallets/page/useWalletsPageGrouping.ts b/app/components/wallets/page/useWalletsPageGrouping.ts
new file mode 100644
index 00000000..c87d19bf
--- /dev/null
+++ b/app/components/wallets/page/useWalletsPageGrouping.ts
@@ -0,0 +1,221 @@
+import type { ComputedRef, Ref } from 'vue'
+
+import { useStorage } from '@vueuse/core'
+
+import type { WalletId, WalletItem, WalletsGroupedBy } from '~/components/wallets/types'
+
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
+
+type WalletsGroupedByExcludedNone = Exclude<WalletsGroupedBy, 'none'>
+type WalletGroup = {
+ groups?: Record<string, WalletId[]>
+ ids: WalletId[]
+}
+type GroupToggleState = {
+ groups?: Record<string, boolean>
+ show?: boolean
+}
+type ToggleMapByGroup = Record<string, GroupToggleState>
+type WalletsToggleMap = Partial<Record<WalletsGroupedByExcludedNone, ToggleMapByGroup>>
+export type GroupedWallets = Record<string, WalletGroup>
+
+export function useWalletsPageGrouping(
+ selectedWalletsIds: ComputedRef<WalletId[]>,
+ groupedBy: Ref<WalletsGroupedBy>,
+) {
+ const { t } = useI18n()
+ const walletsStore = useWalletsStore()
+
+ const groupedBySecondary = useStorage('finapp-wallets-groupedBySecondary', {
+ currency: false,
+ type: false,
+ })
+
+ const walletsToggledMap = useStorage<WalletsToggleMap>('finapp-wallets-toggle-map', {} as WalletsToggleMap, localStorage, {
+ mergeDefaults: true,
+ })
+
+ // Helper functions
+ function groupWalletsByStrategy(ids: WalletId[], strategy: keyof WalletItem): Record<string, WalletId[]> {
+ return Object.groupBy(ids, (id) => {
+ const wallet = walletsStore.itemsComputed[id]
+ return wallet ? String(wallet[strategy] || '') : ''
+ }) as Record<string, WalletId[]>
+ }
+
+ function createPrimaryGroups(grouped: Record<string, WalletId[]>): GroupedWallets {
+ return Object.entries(grouped).reduce<GroupedWallets>((acc, [key, ids]) => {
+ acc[key] = { groups: {}, ids }
+ return acc
+ }, {})
+ }
+
+ function createSecondaryGroups(grouped: Record<string, WalletId[]>, secondaryStrategy: keyof WalletItem): GroupedWallets {
+ return Object.entries(grouped).reduce<GroupedWallets>((acc, [key, ids]) => {
+ acc[key] = {
+ groups: groupWalletsByStrategy(ids, secondaryStrategy),
+ ids,
+ }
+ return acc
+ }, {})
+ }
+
+ const groupedWalletsWithIds = computed<GroupedWallets | false>(() => {
+ if (groupedBy.value === 'none')
+ return false
+
+ const groupingStrategies = {
+ currency: {
+ primary: 'currency',
+ secondary: 'type',
+ },
+ type: {
+ primary: 'type',
+ secondary: 'currency',
+ },
+ } as const
+
+ const strategy = groupingStrategies[groupedBy.value as WalletsGroupedByExcludedNone]
+ if (!strategy)
+ return false
+
+ const ids = selectedWalletsIds.value
+ const primaryGrouped = groupWalletsByStrategy(ids, strategy.primary)
+
+ let useSecondaryGrouping = false
+ if (groupedBy.value === 'currency') {
+ useSecondaryGrouping = !!groupedBySecondary.value.currency
+ }
+ else if (groupedBy.value === 'type') {
+ useSecondaryGrouping = !!groupedBySecondary.value.type
+ }
+
+ return useSecondaryGrouping
+ ? createSecondaryGroups(primaryGrouped, strategy.secondary)
+ : createPrimaryGroups(primaryGrouped)
+ })
+
+ function toggleMap(groupPrimary: string, groupSecondary?: string) {
+ const currentGroup = groupedBy.value
+ if (currentGroup === 'none')
+ return
+
+ const currentToggleMap = { ...walletsToggledMap.value }
+ currentToggleMap[currentGroup] ??= {}
+
+ if (!currentToggleMap[currentGroup]![groupPrimary])
+ currentToggleMap[currentGroup]![groupPrimary] = { groups: {} }
+
+ if (groupSecondary) {
+ const primaryGroup = currentToggleMap[currentGroup]![groupPrimary]
+ primaryGroup.groups ??= {}
+
+ const currentValue = primaryGroup.groups[groupSecondary]
+ primaryGroup.groups[groupSecondary] = currentValue === undefined ? false : !currentValue
+ }
+ else {
+ const primaryGroup = currentToggleMap[currentGroup]![groupPrimary]
+ primaryGroup.groups ??= {}
+ primaryGroup.show = primaryGroup.show === undefined ? false : !primaryGroup.show
+ }
+
+ walletsToggledMap.value = currentToggleMap
+ }
+
+ const typeGroupsStatus = computed(() => {
+ const currentGroup = groupedBy.value
+ if (currentGroup === 'none' || !walletsToggledMap.value[currentGroup])
+ return { isAllOpen: false, isAllOpenInside: false, isAnyOpen: false, isAnyOpenInside: false }
+
+ const groups = walletsToggledMap.value[currentGroup] || {}
+
+ return {
+ isAllOpen: Object.values(groups).every(group => !!group.show),
+ isAllOpenInside: Object.values(groups).every(group =>
+ Object.values(group.groups || {}).every(isOpen => !!isOpen),
+ ),
+ isAnyOpen: Object.values(groups).some(group => !!group.show),
+ isAnyOpenInside: Object.values(groups).some(group =>
+ Object.values(group.groups || {}).some(isOpen => !!isOpen),
+ ),
+ }
+ })
+
+ function toggleOpened() {
+ const currentGroup = groupedBy.value
+ if (currentGroup === 'none' || !groupedWalletsWithIds.value)
+ return
+
+ const currentToggleMap = { ...walletsToggledMap.value }
+ currentToggleMap[currentGroup] ??= {}
+
+ const { isAllOpen, isAllOpenInside } = typeGroupsStatus.value
+ const groupedWallets = groupedWalletsWithIds.value as GroupedWallets
+ const hasSecondaryGrouping = !!groupedBySecondary.value[currentGroup]
+
+ // Determine target state
+ const newShow = !hasSecondaryGrouping ? !isAllOpen : !(isAllOpen && isAllOpenInside)
+ const updateSecondary = hasSecondaryGrouping && isAllOpen && !isAllOpenInside
+
+ for (const groupPrimary of Object.keys(groupedWallets)) {
+ const primaryGroup = currentToggleMap[currentGroup]![groupPrimary] || { groups: {} }
+
+ if (updateSecondary) {
+ const secondaryKeys = Object.keys(groupedWallets[groupPrimary]?.groups ?? {})
+ currentToggleMap[currentGroup]![groupPrimary] = {
+ ...primaryGroup,
+ groups: Object.fromEntries(secondaryKeys.map(k => [k, true])),
+ show: true,
+ }
+ }
+ else if (hasSecondaryGrouping && !newShow) {
+ const secondaryKeys = Object.keys(groupedWallets[groupPrimary]?.groups ?? {})
+ currentToggleMap[currentGroup]![groupPrimary] = {
+ ...primaryGroup,
+ groups: Object.fromEntries(secondaryKeys.map(k => [k, false])),
+ show: false,
+ }
+ }
+ else {
+ currentToggleMap[currentGroup]![groupPrimary] = {
+ ...primaryGroup,
+ show: newShow,
+ }
+ }
+ }
+
+ walletsToggledMap.value = currentToggleMap
+ }
+
+ const groupTabs = computed(() => {
+ const items: {
+ id: WalletsGroupedBy
+ label: string
+ }[] = [{
+ id: 'none',
+ label: t('wallets.page.none'),
+ }, {
+ id: 'type',
+ label: t('wallets.page.type'),
+ }]
+
+ if (walletsStore.currenciesUsed.length > 1) {
+ items.push({
+ id: 'currency',
+ label: t('wallets.page.currencies'),
+ })
+ }
+
+ return items
+ })
+
+ return {
+ groupedBySecondary,
+ groupedWalletsWithIds,
+ groupTabs,
+ toggleMap,
+ toggleOpened,
+ typeGroupsStatus,
+ walletsToggledMap,
+ }
+}
diff --git a/app/components/wallets/types.ts b/app/components/wallets/types.ts
index 1f623b5c..bdb6549f 100644
--- a/app/components/wallets/types.ts
+++ b/app/components/wallets/types.ts
@@ -5,96 +5,44 @@ import type { CurrencyCode } from '~/components/currencies/types'
import { random } from '~/assets/js/emo'
import { colorsArray } from '~/components/color/colors'
-export const types = [
- 'cash',
- 'credit',
- 'cashless',
- 'deposit',
- 'crypto',
- 'debt',
-] as const
-
-export const viewTypes = [
- ...types,
- 'isAvailable',
- 'isWithdrawal',
- 'isArchived',
- 'isExcludeInTotal',
-] as const
+export const walletTypes = ['cash', 'credit', 'cashless', 'deposit', 'crypto', 'debt'] as const
+export type WalletType = typeof walletTypes[number]
export type WalletId = string
-export type WalletType = typeof types[number]
-
-export type WalletViewTypes = typeof viewTypes[number]
-export const icons: Record<WalletType, string> = {
- cash: 'lucide:banknote',
- cashless: 'lucide:landmark',
- credit: 'lucide:piggy-bank',
- crypto: 'lucide:coins',
- debt: 'lucide:hand-coins',
- deposit: 'lucide:diamond-percent',
-} as const
+export type WalletViewTypes = WalletType | 'isAvailable' | 'isWithdrawal' | 'isArchived' | 'isExcludeInTotal'
-export const walletBaseSchema = z.object({
+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),
+ name: z.string().trim().min(1).default(''),
+ order: z.number().default(0),
+ updatedAt: z.number().default(() => new Date().getTime()),
})
-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')),
+ type: z.literal('credit'),
}),
z.object({
...walletBaseSchema.shape,
- type: z.enum(types.filter(t => t !== 'credit')),
+ type: z.enum(walletTypes.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.test.ts b/app/components/wallets/useWalletsStore.test.ts
new file mode 100644
index 00000000..38c697b1
--- /dev/null
+++ b/app/components/wallets/useWalletsStore.test.ts
@@ -0,0 +1,403 @@
+import { createPinia, setActivePinia } from 'pinia'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { WalletItem } from '~/components/wallets/types'
+
+// --- Mocks ---
+
+const localforageStore = new Map<string, any>()
+vi.mock('localforage', () => ({
+ default: {
+ getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),
+ removeItem: vi.fn((key: string) => {
+ localforageStore.delete(key)
+ return Promise.resolve()
+ }),
+ setItem: vi.fn((key: string, value: any) => {
+ localforageStore.set(key, value)
+ return Promise.resolve()
+ }),
+ },
+}))
+
+vi.mock('@vueuse/core', () => ({
+ useDebounceFn: (fn: (...args: any[]) => any) => fn,
+}))
+
+vi.mock('vue-deepunref', () => ({
+ deepUnref: (v: any) => v,
+}))
+
+vi.mock('~~/services/convex/api', () => ({
+ convexWalletsToMap: (v: any) => v,
+}))
+
+vi.mock('~~/utils/simple', () => ({
+ uniqueElementsBy: () => [],
+}))
+
+const mutationMock = vi.fn(() => Promise.resolve())
+const onUpdateMock = vi.fn()
+
+vi.stubGlobal('useConvexClient', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+}))
+vi.stubGlobal('useConvexClientComposable', () => ({
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+}))
+vi.stubGlobal('asConvexId', (id: string) => id)
+vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))
+vi.stubGlobal('useConvexApi', () => ({
+ api: {
+ wallets: { create: 'wallets.create', list: 'wallets.list', remove: 'wallets.remove', update: 'wallets.update', updateOrder: 'wallets.updateOrder' },
+ },
+}))
+vi.stubGlobal('useConvexClientWithApi', () => ({
+ api: {
+ wallets: { create: 'wallets.create', list: 'wallets.list', remove: 'wallets.remove', update: 'wallets.update', updateOrder: 'wallets.updateOrder' },
+ },
+ client: {
+ mutation: mutationMock,
+ onUpdate: onUpdateMock,
+ },
+}))
+
+const toastAddMock = vi.fn()
+vi.stubGlobal('useToast', () => ({ add: toastAddMock }))
+vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
+vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))
+
+vi.mock('~/assets/js/emo', () => ({
+ errorEmo: ['😿'],
+ random: (items: any[]) => items[0],
+}))
+
+vi.stubGlobal('defineStore', (await import('pinia')).defineStore)
+const { computed, ref, shallowRef } = await import('vue')
+vi.stubGlobal('computed', computed)
+vi.stubGlobal('ref', ref)
+vi.stubGlobal('shallowRef', shallowRef)
+
+const removeTrnsFromStoreMock = vi.fn()
+vi.mock('~/components/trns/useTrnsStore', () => ({
+ useTrnsStore: () => ({
+ deleteTrnsByIds: vi.fn(),
+ getStoreTrnsIds: () => [],
+ items: {},
+ removeTrnsFromStore: removeTrnsFromStoreMock,
+ }),
+}))
+
+vi.mock('~/components/currencies/useCurrenciesStore', () => ({
+ useCurrenciesStore: () => ({
+ base: 'USD',
+ rates: {},
+ }),
+}))
+
+vi.mock('~/components/user/useUserStore', () => ({
+ useUserStore: () => ({
+ baseCurrency: 'USD',
+ saveUserBaseCurrency: vi.fn(),
+ }),
+}))
+
+vi.mock('~/components/demo/useDemo', () => ({
+ useDemo: () => ({
+ isDemo: { value: false },
+ }),
+}))
+
+vi.mock('~/components/offline/replay', () => ({
+ isReplaying: () => false,
+}))
+
+const offlineHelpers = await import('~/components/offline/helpers')
+vi.mock('~/components/offline/helpers', async (importOriginal) => {
+ const actual = await importOriginal() as any
+ return {
+ clearOfflineQueue: vi.fn(actual.clearOfflineQueue),
+ getAllOfflineOps: vi.fn(actual.getAllOfflineOps),
+ getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),
+ pushOfflineOp: vi.fn(actual.pushOfflineOp),
+ removeOfflineOp: vi.fn(actual.removeOfflineOp),
+ removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),
+ }
+})
+
+const { useWalletsStore } = await import('~/components/wallets/useWalletsStore')
+
+// --- Helpers ---
+
+function makeWallet(overrides: Partial<WalletItem> = {}): WalletItem {
+ return {
+ color: '#0f0',
+ currency: 'USD',
+ desc: '',
+ isArchived: false,
+ isExcludeInTotal: false,
+ isWithdrawal: false,
+ name: 'Cash',
+ order: 0,
+ type: 'cash',
+ updatedAt: 1700000000000,
+ ...overrides,
+ } as WalletItem
+}
+
+// --- Tests ---
+
+describe('useWalletsStore', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ localforageStore.clear()
+ vi.clearAllMocks()
+ mutationMock.mockReturnValue(Promise.resolve())
+ toastAddMock.mockClear()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ describe('saveWallet — optimistic UI', () => {
+ it('updates items immediately', () => {
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ expect(store.items).toHaveProperty('w1')
+ expect(store.items!.w1.name).toBe('Cash')
+ })
+
+ it('saves to localforage', () => {
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ expect(localforageStore.get('finapp.wallets')).toHaveProperty('w1')
+ })
+
+ it('pushes to offline queue immediately', () => {
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'wallets', id: 'w1', type: 'create' }),
+ )
+ })
+
+ it('fires Convex create mutation for new wallet', () => {
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'wallets.create',
+ expect.objectContaining({ currency: 'USD', name: 'Cash' }),
+ )
+ })
+
+ it('fires Convex update mutation for existing wallet', () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.saveWallet({ id: 'w1', values: makeWallet({ name: 'Updated Cash' }) })
+
+ expect(mutationMock).toHaveBeenCalledWith(
+ 'wallets.update',
+ expect.objectContaining({ id: 'w1', name: 'Updated Cash' }),
+ )
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('wallets', 'w1')
+ })
+ })
+
+ it('keeps offline queue when mutation pending', async () => {
+ mutationMock.mockReturnValue(new Promise(() => {}))
+
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ await new Promise(r => setTimeout(r, 10))
+
+ expect(offlineHelpers.removeOfflineOp).not.toHaveBeenCalled()
+ })
+
+ it('shows toast on mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('network')))
+
+ const store = useWalletsStore()
+ store.items = {}
+
+ store.saveWallet({ id: 'w1', values: makeWallet() })
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error', description: 'wallets.errors.saveFailed' }),
+ )
+ })
+ })
+ })
+
+ describe('deleteWallet — optimistic UI', () => {
+ it('removes item from store immediately', () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet(), w2: makeWallet({ name: 'Card' }) }
+
+ store.deleteWallet('w1')
+
+ expect(store.items).not.toHaveProperty('w1')
+ expect(store.items).toHaveProperty('w2')
+ })
+
+ it('pushes to offline queue', () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.deleteWallet('w1')
+
+ expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'wallets', id: 'w1', type: 'delete' }),
+ )
+ })
+
+ it('fires Convex remove mutation', () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.deleteWallet('w1')
+
+ expect(mutationMock).toHaveBeenCalledWith('wallets.remove', { id: 'w1' })
+ })
+
+ it('cleans up offline queue on mutation success', async () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.deleteWallet('w1')
+
+ await vi.waitFor(() => {
+ expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('wallets', 'w1')
+ })
+ })
+
+ it('removes trns from store immediately (optimistic)', () => {
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.deleteWallet('w1', ['trn1', 'trn2'])
+
+ expect(removeTrnsFromStoreMock).toHaveBeenCalledWith(['trn1', 'trn2'])
+ })
+
+ it('shows toast on delete mutation failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('network')))
+ const store = useWalletsStore()
+ store.items = { w1: makeWallet() }
+
+ store.deleteWallet('w1')
+
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error', description: 'wallets.errors.deleteFailed' }),
+ )
+ })
+ })
+ })
+
+ describe('saveWalletsOrder', () => {
+ it('updates order in store optimistically', () => {
+ const store = useWalletsStore()
+ store.items = {
+ w1: makeWallet({ name: 'First', order: 0 }),
+ w2: makeWallet({ name: 'Second', order: 1 }),
+ }
+
+ // Reorder: w2 first, w1 second
+ mutationMock.mockReturnValue(new Promise(() => {})) // never resolves
+ store.saveWalletsOrder(['w2', 'w1'])
+
+ expect(store.items!.w2.order).toBe(0)
+ expect(store.items!.w1.order).toBe(1)
+ })
+
+ it('fires atomic updateOrder mutation', () => {
+ const store = useWalletsStore()
+ store.items = {
+ w1: makeWallet({ name: 'First', order: 0 }),
+ w2: makeWallet({ name: 'Second', order: 1 }),
+ }
+
+ store.saveWalletsOrder(['w2', 'w1'])
+
+ expect(mutationMock).toHaveBeenCalledWith('wallets.updateOrder', {
+ orders: [
+ { id: 'w2', order: 0 },
+ { id: 'w1', order: 1 },
+ ],
+ })
+ })
+
+ it('shows toast on failure', async () => {
+ mutationMock.mockReturnValue(Promise.reject(new Error('network')))
+
+ const store = useWalletsStore()
+ store.items = {
+ w1: makeWallet({ order: 0 }),
+ w2: makeWallet({ order: 1 }),
+ }
+
+ store.saveWalletsOrder(['w2', 'w1'])
+ await vi.waitFor(() => {
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ color: 'error', description: 'wallets.errors.orderFailed' }),
+ )
+ })
+ })
+ })
+
+ describe('saveWallet — new wallet order', () => {
+ it('sets order to max+1 for new wallets', () => {
+ const store = useWalletsStore()
+ store.items = {
+ w1: makeWallet({ order: 0 }),
+ w2: makeWallet({ order: 3 }),
+ }
+
+ store.saveWallet({ id: 'w3', values: makeWallet({ order: 0 }) })
+
+ expect(store.items!.w3.order).toBe(4)
+ })
+
+ it('does not change order for existing wallets', () => {
+ const store = useWalletsStore()
+ store.items = {
+ w1: makeWallet({ order: 0 }),
+ w2: makeWallet({ order: 3 }),
+ }
+
+ store.saveWallet({ id: 'w1', values: makeWallet({ order: 5 }) })
+
+ expect(store.items!.w1.order).toBe(5)
+ })
+ })
+})
diff --git a/app/components/wallets/useWalletsStore.ts b/app/components/wallets/useWalletsStore.ts
index 57cffb97..2c214235 100644
--- a/app/components/wallets/useWalletsStore.ts
+++ b/app/components/wallets/useWalletsStore.ts
@@ -1,75 +1,148 @@
-import localforage from 'localforage'
-import { deepUnref } from 'vue-deepunref'
-import { getDataAndWatch, removeData, saveData, unsubscribeData, updateData } from '~~/services/firebase/api'
+import { convexWalletsToMap } from '~~/services/convex/api'
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, WalletsDirty } from '~/components/wallets/types'
+import type { WalletId, WalletItem, WalletItemComputed, Wallets, WalletsComputed } from '~/components/wallets/types'
import { getAmountInRate, getTotal } from '~/components/amount/getTotal'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
import { useDemo } from '~/components/demo/useDemo'
+import { pushOfflineOp } from '~/components/offline/helpers'
+import { isReplaying } from '~/components/offline/replay'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useUserStore } from '~/components/user/useUserStore'
-import { normalizeWalletItem } from '~/components/wallets/utils'
+import { createDebouncedPersist, handleMutationResult, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('wallets')
export const useWalletsStore = defineStore('wallets', () => {
const trnsStore = useTrnsStore()
- const userStore = useUserStore()
const currenciesStore = useCurrenciesStore()
- const { deleteDemoWallet, isDemo, sortDemoWallets } = useDemo()
+ const { isDemo } = useDemo()
- const items = ref<Wallets | null | false>(false)
+ const items = shallowRef<Wallets | null>(null)
const hasItems = computed(() => Object.keys(items.value ?? {}).length > 0)
- function initWallets() {
- getDataAndWatch(`users/${userStore.uid}/accounts`, (wallets: Wallets) => setWallets(wallets || null))
+ async function initWallets() {
+ try {
+ const { api, client } = useConvexClientWithApi()
+ const wallets = await client.query(api.wallets.list, {})
+ let data: Wallets | null = wallets?.length ? convexWalletsToMap(wallets) : null
+
+ if (data)
+ data = await mergeOfflineOps(data, 'wallets')
+
+ setWallets(data)
+ }
+ catch (e) {
+ logger.error('init failed', e)
+ }
}
+ const debouncedPersist = createDebouncedPersist<Wallets | null>(STORAGE_KEYS.wallets)
+
function setWallets(values: Wallets | null) {
- const wallets = values ? normalizeWallets(values) : null
- items.value = wallets
- localforage.setItem('finapp.wallets', deepUnref(wallets))
+ items.value = values
+ debouncedPersist(values)
}
- async function createOrUpdateWallet({ id, values }: { id: WalletId, values: WalletItem }) {
+ function saveWallet({ id, values }: { id: WalletId, values: WalletItem }) {
// Set default currency based on first created wallet
if (!hasItems.value)
- currenciesStore.updateBase(values.currency)
+ useUserStore().saveUserBaseCurrency(values.currency)
+
+ // Check before optimistic update so the new id isn't already in the store
+ // Frontend IDs are always treated as new creates (server generates real ID)
+ const isExisting = !isLocalId(id) && items.value && id in items.value
+
+ // Set order to max+1 for new wallets
+ if (!isExisting) {
+ const maxOrder = Object.values(items.value ?? {}).reduce(
+ (max, w) => Math.max(max, w.order ?? 0),
+ -1,
+ )
+ values = { ...values, order: maxOrder + 1 }
+ }
- if (isDemo.value) {
- items.value = {
- ...items.value,
- [id]: values,
- }
- localforage.setItem('finapp.wallets', deepUnref(items.value))
+ // Optimistic UI
+ setWallets({
+ ...items.value,
+ [id]: values,
+ })
+
+ if (!pushSaveOp({ entity: 'wallets', id, isDemo: isDemo.value, isExisting: !!isExisting, values: values as unknown as Record<string, unknown> }))
return
+
+ const { api, client } = useConvexClientWithApi()
+ const action = isExisting ? 'update' : 'create'
+
+ const walletData = {
+ color: values.color,
+ creditLimit: 'creditLimit' in values ? values.creditLimit : undefined,
+ currency: values.currency,
+ desc: values.desc || undefined,
+ isArchived: values.isArchived,
+ isExcludeInTotal: values.isExcludeInTotal,
+ isWithdrawal: values.isWithdrawal,
+ name: values.name,
+ order: values.order,
+ type: values.type,
}
- await saveData(`users/${userStore.uid}/accounts/${id}`, values)
+ // Fire-and-forget mutation, cleanup on success
+ const mutation = isExisting
+ ? client.mutation(api.wallets.update, { id: asConvexId<'wallets'>(id), ...walletData })
+ : client.mutation(api.wallets.create, walletData)
+
+ return handleMutationResult({
+ action,
+ entity: 'wallets',
+ errorMessage: 'wallets.errors.saveFailed',
+ id,
+ items,
+ mutation,
+
+ })
}
- async function saveWalletsOrder(ids: WalletId[]) {
- if (isDemo.value) {
- return await sortDemoWallets(ids, items.value || {})
+ function saveWalletsOrder(ids: WalletId[]) {
+ // Optimistic update
+ const updated = { ...items.value } as Wallets
+ for (let i = 0; i < ids.length; i++) {
+ if (updated[ids[i]])
+ updated[ids[i]] = { ...updated[ids[i]], order: i }
}
+ setWallets(updated)
- const updates = ids.reduce(
- (acc, walletId, index) => {
- acc[`${walletId}/order`] = index
- return acc
- },
- {} as Record<string, number>,
- )
-
- let result: string | null = null
+ if (isDemo.value)
+ return
- await updateData(`users/${userStore.uid}/accounts`, updates)
- .then(() => result = 'ok')
- .catch(error => result = error)
+ // Save to offline queue immediately (skip during replay)
+ logger.log('optimistic update: order')
+ if (!isReplaying()) {
+ for (const id of ids) {
+ if (updated[id])
+ pushOfflineOp({ data: updated[id] as unknown as Record<string, unknown>, entity: 'wallets', id, type: 'update' })
+ }
+ }
- return result
+ const { api, client } = useConvexClientWithApi()
+
+ return handleMutationResult({
+ action: 'update',
+ entity: 'wallets',
+ errorMessage: 'wallets.errors.orderFailed',
+ id: ids,
+ mutation: client.mutation(api.wallets.updateOrder, {
+ orders: ids.map((walletId, index) => ({
+ id: asConvexId<'wallets'>(walletId),
+ order: index,
+ })),
+ }),
+ })
}
function getWalletTotal(walletId: WalletId) {
@@ -77,19 +150,14 @@ export const useWalletsStore = defineStore('wallets', () => {
walletsIds: [walletId],
})
- const { sum, sumTransfers } = getTotal({
+ const { adjustment, sum, sumTransfers } = getTotal({
trnsIds,
- trnsItems: trnsStore.items || {},
+ trnsItems: trnsStore.items ?? {},
walletsIds: [walletId],
- walletsItems: items.value || {},
+ walletsItems: items.value ?? {},
})
- return sum + sumTransfers
- }
-
- function unsubscribeWallets() {
- unsubscribeData(`users/${userStore.uid}/accounts`)
- setWallets(null)
+ return sum + sumTransfers + adjustment
}
const sortedIds = computed(() => {
@@ -119,33 +187,34 @@ export const useWalletsStore = defineStore('wallets', () => {
const currenciesUsed = computed<CurrencyCode[]>(() => uniqueElementsBy(itemsComputed.value, 'currency'))
- async function deleteWallet(id: WalletId, trnsIds?: TrnId[]) {
- if (isDemo.value) {
- deleteDemoWallet(id, trnsIds)
- }
- else {
- await removeData(`users/${userStore.uid}/accounts/${id}`)
- if (trnsIds)
- await trnsStore.deleteTrnsByIds(trnsIds)
- }
- }
+ function deleteWallet(id: WalletId, trnsIds?: TrnId[]) {
+ // Optimistic UI
+ const wallets = { ...items.value }
+ delete wallets[id]
+ setWallets(wallets)
- function 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)
+ // Optimistic: remove trns from store immediately (backend cascade handles actual deletion)
+ if (trnsIds?.length)
+ trnsStore.removeTrnsFromStore(trnsIds)
+
+ if (!pushDeleteOp({ entity: 'wallets', id, isDemo: isDemo.value }))
+ return
+
+ // Fire-and-forget mutation, cleanup on success
+ const { api, client } = useConvexClientWithApi()
+ return handleMutationResult({
+ action: 'delete',
+ entity: 'wallets',
+ errorMessage: 'wallets.errors.deleteFailed',
+ id,
+ items,
+ mutation: client.mutation(api.wallets.remove, { id: asConvexId<'wallets'>(id) }),
+
+ })
}
return {
- createOrUpdateWallet,
+ cancelPersist: () => debouncedPersist.cancel?.(),
currenciesUsed,
deleteWallet,
getWalletTotal,
@@ -153,9 +222,9 @@ export const useWalletsStore = defineStore('wallets', () => {
initWallets,
items,
itemsComputed,
+ saveWallet,
saveWalletsOrder,
setWallets,
sortedIds,
- unsubscribeWallets,
}
})
diff --git a/app/components/wallets/utils.ts b/app/components/wallets/utils.ts
deleted file mode 100644
index 681c6de6..00000000
--- a/app/components/wallets/utils.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-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,
- }
- }
-
- 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,
- })
-
- 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,
- }
-}
diff --git a/app/composables/useAuth.ts b/app/composables/useAuth.ts
new file mode 100644
index 00000000..59da4886
--- /dev/null
+++ b/app/composables/useAuth.ts
@@ -0,0 +1,20 @@
+import { crossDomainClient } from '@convex-dev/better-auth/client/plugins'
+import { createAuthClient } from 'better-auth/vue'
+
+let authClient: ReturnType<typeof createAuthClient> | null = null
+
+export function useAuth() {
+ if (!authClient) {
+ const config = useRuntimeConfig()
+ const siteUrl = config.public.convexSiteUrl as string
+
+ authClient = createAuthClient({
+ baseURL: siteUrl,
+ plugins: [
+ crossDomainClient(),
+ ],
+ })
+ }
+
+ return authClient
+}
diff --git a/app/composables/useAuthCookie.ts b/app/composables/useAuthCookie.ts
new file mode 100644
index 00000000..285bebd6
--- /dev/null
+++ b/app/composables/useAuthCookie.ts
@@ -0,0 +1,17 @@
+export function hasAuthCookie(): boolean {
+ return document.cookie.includes('finapp.localAuthUid')
+}
+
+const secureSuffix = globalThis.location?.protocol === 'https:' ? ';Secure' : ''
+
+export function setAuthCookie(uid: string) {
+ document.cookie = `finapp.localAuthUid=${encodeURIComponent(uid)};path=/;max-age=31536000;SameSite=Lax${secureSuffix}`
+}
+
+export function clearAuthCookie() {
+ document.cookie = `finapp.localAuthUid=;path=/;max-age=0;SameSite=Lax${secureSuffix}`
+}
+
+export function useAuthCookieSSR() {
+ return useCookie('finapp.localAuthUid')
+}
diff --git a/lib/cn.ts b/app/composables/useCn.ts
similarity index 100%
rename from lib/cn.ts
rename to app/composables/useCn.ts
diff --git a/app/composables/useConvex.ts b/app/composables/useConvex.ts
new file mode 100644
index 00000000..9abe14cd
--- /dev/null
+++ b/app/composables/useConvex.ts
@@ -0,0 +1,19 @@
+import type { ConvexClient, ConvexHttpClient } from 'convex/browser'
+
+import { api } from '~~/convex/_generated/api'
+
+export function useConvexClient(): ConvexClient | ConvexHttpClient {
+ const { $convex } = useNuxtApp()
+ return $convex as ConvexClient | ConvexHttpClient
+}
+
+export function useConvexClientComposable(): ConvexClient {
+ return useConvexClient() as ConvexClient
+}
+
+export function useConvexClientWithApi() {
+ return {
+ api,
+ client: useConvexClientComposable(),
+ }
+}
diff --git a/app/composables/useStoreSync.ts b/app/composables/useStoreSync.ts
new file mode 100644
index 00000000..f7c0efeb
--- /dev/null
+++ b/app/composables/useStoreSync.ts
@@ -0,0 +1,196 @@
+import type { ShallowRef } from 'vue'
+
+import { useDebounceFn } from '@vueuse/core'
+import localforage from 'localforage'
+import { deepUnref } from 'vue-deepunref'
+
+import type { EntityType } from '~/components/offline/types'
+
+import { errorEmo, random, successEmo, warningEmo } from '~/assets/js/emo'
+import { getOfflineOpsByEntity, pushOfflineOp, removeOfflineOp, removeOfflineOps } from '~/components/offline/helpers'
+import { isReplaying } from '~/components/offline/replay'
+import { STORAGE_KEYS } from '~/components/offline/storageKeys'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('store-sync')
+
+/**
+ * When true, all localforage persist operations are skipped.
+ * Set by clearLocalData() to prevent in-flight store inits and mutation callbacks
+ * from re-writing data after cleanup. Reset by loadDataFromDB().
+ */
+let _persistBlocked = false
+
+export function blockPersist(): void {
+ _persistBlocked = true
+}
+
+export function unblockPersist(): void {
+ _persistBlocked = false
+}
+
+export function isPersistBlocked(): boolean {
+ return _persistBlocked
+}
+
+export function createDebouncedPersist<T>(storageKey: string) {
+ return useDebounceFn((values: T) => {
+ if (_persistBlocked)
+ return
+ localforage.setItem(storageKey, deepUnref(values))
+ }, 300)
+}
+
+export function pushSaveOp(opts: {
+ entity: EntityType
+ id: string
+ isDemo: boolean
+ isExisting: boolean
+ values: Record<string, unknown>
+}): boolean {
+ if (opts.isDemo)
+ return false
+
+ const action = opts.isExisting ? 'update' : 'create'
+ logger.log(`optimistic ${action}: ${opts.id}`)
+ if (!isReplaying())
+ pushOfflineOp({ data: opts.values, entity: opts.entity, id: opts.id, type: action })
+
+ return true
+}
+
+export function pushDeleteOp(opts: {
+ entity: EntityType
+ id: string
+ isDemo: boolean
+}): boolean {
+ if (opts.isDemo)
+ return false
+
+ logger.log(`optimistic delete: ${opts.id}`)
+ if (!isReplaying())
+ pushOfflineOp({ entity: opts.entity, id: opts.id, type: 'delete' })
+
+ return true
+}
+
+/**
+ * Merge pending offline ops on top of server data during store init.
+ * Handles updates, deletes, and cleanup of stale frontend IDs.
+ */
+export async function mergeOfflineOps<T>(
+ data: Record<string, T>,
+ entity: EntityType,
+): Promise<Record<string, T>> {
+ const pendingOps = await getOfflineOpsByEntity(entity)
+
+ const pendingUpdates: Record<string, T> = {}
+ const pendingDeleteIds: string[] = []
+
+ for (const op of pendingOps) {
+ if (op.type === 'delete')
+ pendingDeleteIds.push(op.id)
+ else if (op.data)
+ pendingUpdates[op.id] = op.data as unknown as T
+ }
+
+ const hasUpdates = Object.keys(pendingUpdates).length > 0
+ const hasDeletes = pendingDeleteIds.length > 0
+
+ if (hasUpdates || hasDeletes) {
+ const merged = { ...data }
+ for (const id in pendingUpdates)
+ merged[id] = pendingUpdates[id]
+ for (const id of pendingDeleteIds)
+ delete merged[id]
+ data = merged
+ logger.log(`init: merged ${Object.keys(pendingUpdates).length} updates, ${pendingDeleteIds.length} deletes`)
+ }
+
+ return cleanupFrontendIds(data, pendingUpdates)
+}
+
+export type RemapInfo = { convexId: string, localId: string }
+
+/**
+ * Handle mutation .then/.catch: remove offline op, remap frontend ID, toast errors.
+ * Returns a promise that resolves with remap info (for creates) or void.
+ */
+export function handleMutationResult<T>(opts: {
+ action: 'create' | 'delete' | 'update'
+ entity: EntityType
+ errorMessage: string
+ id: string | string[]
+ items?: ShallowRef<Record<string, T> | null>
+ mutation: Promise<unknown>
+}): Promise<RemapInfo | void> {
+ const ids = Array.isArray(opts.id) ? opts.id : [opts.id]
+
+ return opts.mutation
+ .then(async (result): Promise<RemapInfo | void> => {
+ logger.log(`confirmed ${opts.action}: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`)
+
+ if (ids.length === 1)
+ await removeOfflineOp(opts.entity, ids[0])
+ else
+ await removeOfflineOps(opts.entity, ids)
+
+ // Remap frontend ID to Convex ID for new items (single create only)
+ if (opts.action === 'create' && !Array.isArray(opts.id) && result && opts.items) {
+ const convexId = String(result)
+ const current = opts.items.value
+ if (current && opts.id in current && opts.id !== convexId) {
+ const { [opts.id]: item, ...rest } = current
+ const remapped = { ...rest, [convexId]: item }
+ opts.items.value = remapped
+ if (!_persistBlocked)
+ localforage.setItem(STORAGE_KEYS[opts.entity], deepUnref(remapped))
+ logger.log(`remapped ID: ${opts.id} → ${convexId}`)
+ return { convexId, localId: opts.id }
+ }
+ }
+ })
+ .catch((e) => {
+ logger.error(`${opts.action} failed: ${ids.length > 1 ? `${ids.length} items` : ids[0]}`, e)
+ showErrorToast(opts.errorMessage)
+ })
+}
+
+let _toast: ReturnType<typeof useToast> | null = null
+let _t: ((key: string, params?: Record<string, unknown>) => string) | null = null
+
+function getToast() {
+ if (!_toast)
+ _toast = useToast()
+ return _toast
+}
+
+function getT() {
+ if (!_t) {
+ const app = tryUseNuxtApp()
+ if (app?.$i18n?.t)
+ _t = app.$i18n.t
+ }
+ return _t
+}
+
+export function showErrorToast(key: string, params?: Record<string, unknown>) {
+ const toast = getToast()
+ const t = getT()
+ const id = toast.add({ color: 'error', description: t ? t(key, params ?? {}) : key, title: random(errorEmo) })
+ return id
+}
+
+export function showSuccessToast(key: string, params?: Record<string, unknown>) {
+ const toast = getToast()
+ const t = getT()
+ const id = toast.add({ color: 'success', description: t ? t(key, params ?? {}) : key, title: random(successEmo) })
+ return id
+}
+
+export function showWarningToast(key: string, params?: Record<string, unknown>) {
+ const toast = getToast()
+ const t = getT()
+ const id = toast.add({ color: 'warning', description: t ? t(key, params ?? {}) : key, title: random(warningEmo) })
+ return id
+}
diff --git a/app/layouts/default.vue b/app/layouts/default.vue
index eb28380d..fef7dc95 100644
--- a/app/layouts/default.vue
+++ b/app/layouts/default.vue
@@ -1,10 +1,10 @@
<script setup lang="ts">
-import { useStorage, useWindowSize } from '@vueuse/core'
+import { useWindowSize } from '@vueuse/core'
-import { useAppNav } from '~/components/app/useAppNav'
import { useInitApp } from '~/components/app/useInitApp'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useDemo } from '~/components/demo/useDemo'
+import { useMenuData } from '~/components/layout/useMenuData'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
import { useUserStore } from '~/components/user/useUserStore'
@@ -18,28 +18,29 @@ const userStore = useUserStore()
const walletsStore = useWalletsStore()
const trnsStore = useTrnsStore()
const { isDemo } = useDemo()
-const { isModalOpen } = useAppNav()
+const { isMenuOpen } = useMenuData()
const { loadDataFromCache, loadDataFromDB } = useInitApp()
const { t } = useI18n()
const { width } = useWindowSize()
-const isShowSidebar = useStorage('isShowSidebar', true)
+const isShowSidebar = useCookie('finapp.isShowSidebar', { default: () => true })
+const isOnboarded = computed(() => walletsStore.hasItems && categoriesStore.hasItems && trnsStore.hasItems)
const { error, status } = useAsyncData(
'app',
async () => {
- const localAuthUid = await useCookie('finapp.localAuthUid')
-
if (isDemo.value) {
- await loadDataFromCache()
+ // Skip cache load if stores already have data (just generated by openDemo)
+ if (!categoriesStore.hasItems)
+ await loadDataFromCache()
}
- else if (userStore.currentUser || localAuthUid.value) {
+ else if (userStore.currentUser || hasAuthCookie()) {
await loadDataFromCache()
loadDataFromDB()
}
},
{
- lazy: false,
+ lazy: true,
server: false,
},
)
@@ -62,10 +63,11 @@ defineShortcuts({
<template>
<div
- class="min-h-dvh transition-all duration-300 ease-in-out sm:pl-12"
+ class="flex min-h-dvh flex-col transition-all duration-300 ease-in-out"
:class="{
- 'md:pl-72': isShowSidebar && width >= 767,
- 'md:pr-[360px]': trnsFormStore.ui.isShow && width >= 767,
+ 'sm:pl-12': isOnboarded,
+ 'md:pl-72': isOnboarded && isShowSidebar && width >= 767,
+ 'md:pr-[360px]': isOnboarded && trnsFormStore.ui.isShow && width >= 767,
}"
style="margin-left: env(safe-area-inset-left)"
>
@@ -73,35 +75,39 @@ defineShortcuts({
<pre>{{ error }}</pre>
</div>
- <div v-else-if="status === 'pending' || trnsStore.items === false || walletsStore.items === false" class="p-4">
- {{ t('base.loading') }}
- </div>
-
<template v-else-if="status === 'success'">
- <LayoutSidebar
- :isShowTrnForm="trnsFormStore.ui.isShow"
- :isShowSidebar
- @toggleSidebar="isShowSidebar = !isShowSidebar"
- />
+ <template v-if="isOnboarded">
+ <LayoutSidebar
+ :isShowTrnForm="trnsFormStore.ui.isShow"
+ :isShowSidebar
+ @toggleSidebar="isShowSidebar = !isShowSidebar"
+ />
+ </template>
- <div class="md:py-4 md:pr-4">
- <div class="bg-default sm:border-item-4 relative z-10 max-w-5xl contain-paint sm:rounded-md sm:border lg:rounded-2xl">
+ <div :class="isOnboarded ? 'flex min-h-dvh flex-col md:py-4 md:pr-4' : 'flex flex-1 items-center justify-center'">
+ <div :class="isOnboarded ? 'bg-default sm:border-item-4 relative z-10 flex max-w-5xl flex-1 flex-col contain-paint sm:rounded-md sm:border lg:rounded-2xl' : 'w-full max-w-lg px-4'">
<main
id="pageScroll"
- style="padding-bottom: calc(50px + env(safe-area-inset-bottom))"
- class="@container/main contain-paint"
+ :style="isOnboarded ? 'padding-bottom: calc(50px + env(safe-area-inset-bottom))' : ''"
+ class="@container/main flex-1 contain-paint"
>
<slot :keepalive="{ include: keepalive }" />
</main>
</div>
</div>
- <TrnFormFloatOpener />
+ <template v-if="isOnboarded">
+ <TrnFormFloatOpener v-if="width >= 767" />
- <LayoutMenuBottom />
- <LayoutMenuBottomModal v-if="isModalOpen('menu')" />
+ <LayoutMenuBottom />
+ <LayoutMenuBottomModal v-if="isMenuOpen" @close="isMenuOpen = false" />
+ </template>
</template>
+ <div v-else class="flex min-h-svh items-center justify-center">
+ <UiLogo class="!text-6xl" />
+ </div>
+
<Teleport
v-if="categoriesStore.hasItems && walletsStore.hasItems"
to="body"
diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.ts
index 1c82d468..0c84de09 100644
--- a/app/middleware/auth.global.ts
+++ b/app/middleware/auth.global.ts
@@ -1,38 +1,115 @@
import { useDemo } from '~/components/demo/useDemo'
+import { clearAuthCookie, hasAuthCookie, setAuthCookie, useAuthCookieSSR } from '~/composables/useAuthCookie'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('auth/middleware')
export default defineNuxtRouteMiddleware(async (to) => {
- const user = await getCurrentUser()
- const localAuthUid = useCookie('finapp.localAuthUid')
- const { isDemo } = useDemo()
+ // Skip auth during static prerender — no session context available
+ if (import.meta.prerender)
+ return
- // Update local auth UID
- if (!localAuthUid.value || localAuthUid.value !== user?.uid) {
- localAuthUid.value = user?.uid || null
+ // OTT can arrive on any route (callbackURL is not always preserved).
+ // Redirect to /auth/callback which handles OTT verification on the client.
+ if (to.query.ott && to.path !== '/auth/callback') {
+ return navigateTo({
+ path: '/auth/callback',
+ query: { ott: to.query.ott },
+ }, { replace: true })
}
+ // Auth callback page handles OTT verification — skip all auth checks
+ if (to.path === '/auth/callback')
+ return
+
+ const { isDemo } = useDemo()
+
// Handle demo mode routing
if (isDemo.value) {
if (to.path === '/login') {
- const redirectPath = typeof to.query.redirect === 'string'
- ? to.query.redirect
- : '/dashboard'
- return navigateTo(redirectPath)
+ return navigateTo(getSafeRedirectPath(to.query.redirect))
}
- return // Allow access to all routes in demo mode
+ return
}
- // Handle regular auth routing
+ // SSR: use cached cookie to avoid flash of login page
+ if (import.meta.server) {
+ const ssrCookie = useAuthCookieSSR()
+ const isLoginPage = to.path === '/login'
+ const hasCachedAuth = !!ssrCookie.value
+
+ if (!hasCachedAuth && !isLoginPage) {
+ const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
+ return navigateTo({
+ path: '/login',
+ query: redirect,
+ })
+ }
+ if (hasCachedAuth && isLoginPage) {
+ return navigateTo('/dashboard')
+ }
+ return
+ }
+
+ // Client: verify auth with Better Auth
+ const authClient = useAuth()
const isLoginPage = to.path === '/login'
- const isAuthenticated = !!user
- if (!isAuthenticated && !isLoginPage) {
+ // Has cached auth: let user through immediately, initialize session in background.
+ // The getSession() call is needed to establish the cross-domain session
+ // so that useSession() reactive ref updates in the app.
+ // On network errors (offline) — do nothing, let the user work with cached data.
+ // On invalid session (server says no user) — clear cookie and redirect to login.
+ if (hasAuthCookie()) {
+ const handleSessionResult = (session: { data?: { user?: unknown } | null }) => {
+ if (!session.data?.user) {
+ logger.error('Session invalid, clearing auth')
+ clearAuthCookie()
+ navigateTo('/login')
+ }
+ }
+
+ authClient.getSession()
+ .then(handleSessionResult)
+ .catch((error) => {
+ logger.error('Background getSession failed, retrying:', error)
+ setTimeout(() => {
+ authClient.getSession()
+ .then(handleSessionResult)
+ .catch((retryError) => {
+ logger.error('Background getSession retry failed (offline?):', retryError)
+ })
+ }, 2000)
+ })
+
+ if (isLoginPage) {
+ return navigateTo('/dashboard')
+ }
+ return
+ }
+
+ // No cached auth: must verify (blocking)
+ try {
+ const session = await authClient.getSession()
+ const user = session.data?.user || null
+
+ if (user) {
+ setAuthCookie(user.id)
+ if (isLoginPage) {
+ return navigateTo('/dashboard')
+ }
+ return
+ }
+ }
+ catch (error) {
+ logger.error(' getSession failed (no cached auth):', error)
+ }
+
+ if (!isLoginPage) {
+ const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
return navigateTo({
path: '/login',
- query: { redirect: to.fullPath },
+ query: redirect,
})
}
-
- if (isAuthenticated && isLoginPage) {
- return navigateTo('/dashboard')
- }
})
diff --git a/app/pages/auth/callback.vue b/app/pages/auth/callback.vue
new file mode 100644
index 00000000..eb302f33
--- /dev/null
+++ b/app/pages/auth/callback.vue
@@ -0,0 +1,98 @@
+<script setup lang="ts">
+import { showErrorToast } from '~/composables/useStoreSync'
+
+definePageMeta({
+ layout: 'empty',
+})
+
+const route = useRoute()
+const logger = createLogger('auth/callback')
+
+onMounted(async () => {
+ const ott = route.query.ott as string
+ if (!ott) {
+ navigateTo('/login', { replace: true })
+ return
+ }
+
+ const authClient = useAuth()
+
+ // Clear stale cookies left by signIn.social (e.g., empty convex_jwt, state).
+ // OTT verify's onSuccess hook will write fresh cookies from the server response.
+ localStorage.removeItem('better-auth_cookie')
+ localStorage.removeItem('better-auth_session_data')
+
+ try {
+ const result = await authClient.$fetch<{
+ session: { expiresAt: number, token: string }
+ }>('/cross-domain/one-time-token/verify', {
+ body: { token: ott },
+ method: 'POST',
+ })
+
+ if (!result.data?.session?.token) {
+ navigateTo('/login', { replace: true })
+ return
+ }
+
+ // crossDomainClient's onSuccess hook already processed Set-Better-Auth-Cookie
+ // from the OTT verify response and wrote cookies to localStorage (including
+ // convex_jwt and session_token). Only add session_token if it's missing —
+ // don't overwrite the entire localStorage as that would wipe convex_jwt.
+ const cookieKey = 'better-auth_cookie'
+ let afterOtt: Record<string, { expires?: string, value?: string }> = {}
+ try {
+ afterOtt = JSON.parse(localStorage.getItem(cookieKey) || '{}')
+ }
+ catch {
+ localStorage.removeItem(cookieKey)
+ }
+
+ if (!afterOtt['__Secure-better-auth.session_token']?.value) {
+ afterOtt['__Secure-better-auth.session_token'] = {
+ expires: new Date(result.data.session.expiresAt).toISOString(),
+ value: result.data.session.token,
+ }
+ localStorage.setItem(cookieKey, JSON.stringify(afterOtt))
+ }
+
+ // Call getSession with Authorization header first.
+ // crossDomainClient's onSuccess hook will process Set-Better-Auth-Cookie
+ // from the response and update localStorage with server-issued cookies.
+ // Do NOT call $store.notify before this — it triggers a background refetch
+ // that races with this call and can overwrite localStorage with empty values.
+ const session = await authClient.getSession({
+ fetchOptions: {
+ headers: { Authorization: `Bearer ${result.data.session.token}` },
+ },
+ })
+
+ if (session.data?.user) {
+ const uid = session.data.user.id
+
+ setAuthCookie(uid)
+
+ const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
+ localStorage.removeItem('finapp.authRedirect')
+
+ // Hard navigation creates a fresh app with the cookie already set.
+ // This ensures Convex plugin initializes with auth from the start.
+ window.location.href = redirectTo
+ return
+ }
+ }
+ catch (error: unknown) {
+ logger.error('Error:', error)
+ showErrorToast('login.error')
+ }
+
+ localStorage.removeItem('finapp.authRedirect')
+ navigateTo('/login', { replace: true })
+})
+</script>
+
+<template>
+ <div class="flex-center h-dvh">
+ <UIcon name="lucide:loader-circle" class="text-muted size-6 animate-spin" />
+ </div>
+</template>
diff --git a/app/pages/dashboard.vue b/app/pages/dashboard.vue
index 5b83bf11..1252804e 100644
--- a/app/pages/dashboard.vue
+++ b/app/pages/dashboard.vue
@@ -1,10 +1,18 @@
<script setup lang="ts">
+import { useInitApp } from '~/components/app/useInitApp'
+import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+import { useWalletsStore } from '~/components/wallets/useWalletsStore'
defineOptions({ name: 'Dashboard' })
const { t } = useI18n()
const trnsStore = useTrnsStore()
+const walletsStore = useWalletsStore()
+const categoriesStore = useCategoriesStore()
+const { isDbLoading } = useInitApp()
+
+const isOnboarded = computed(() => walletsStore.hasItems && categoriesStore.hasItems && trnsStore.hasItems)
useSeoMeta({
ogTitle: t('stat.title'),
@@ -13,6 +21,6 @@ useSeoMeta({
</script>
<template>
- <StatPage v-if="trnsStore.hasItems" />
- <LazyAppWelcome v-else />
+ <StatPage v-if="isOnboarded" />
+ <LazyAppOnboarding v-else-if="!isDbLoading" />
</template>
diff --git a/app/pages/dev.vue b/app/pages/dev.vue
index 0e77f6f8..93838997 100644
--- a/app/pages/dev.vue
+++ b/app/pages/dev.vue
@@ -1,6 +1,3 @@
-<script lang="ts" setup>
-</script>
-
<template>
<UiPage>
<div class="grid grid-cols-[1fr_auto] items-start gap-8 p-3">
@@ -17,7 +14,7 @@
Backgrounds
</div>
<div class="flex flex-wrap gap-0">
- <div class="flex-center size-20 bg-[var(--item-1)]">
+ <div class="flex-center size-20 bg-(--item-1)">
1
</div>
<div class="flex-center bg-item-2 size-20">
@@ -29,7 +26,7 @@
<div class="flex-center bg-item-4 size-20">
4
</div>
- <div class="flex-center size-20 bg-[var(--item-5)]">
+ <div class="flex-center size-20 bg-(--item-5)">
5
</div>
<div class="flex-center bg-item-6 size-20">
@@ -110,10 +107,10 @@
</h1>
<div class="flex flex-wrap">
- <div class="size-20 bg-[var(--chart-line)]" />
- <div class="size-20 bg-[var(--chart-splitLine)]" />
- <div class="size-20 bg-[var(--chart-label)]" />
- <div class="size-20 bg-[var(--chart-tooltip)]" />
+ <div class="size-20 bg-(--chart-line)" />
+ <div class="size-20 bg-(--chart-splitLine)" />
+ <div class="size-20 bg-(--chart-label)" />
+ <div class="size-20 bg-(--chart-tooltip)" />
</div>
</div>
</div>
@@ -126,17 +123,17 @@
</h1>
<div class="grid gap-4">
- <UiTitle3>
- UiTitle3
- </UiTitle3>
+ <UiTitleSection>
+ UiTitleSection
+ </UiTitleSection>
- <UiTitle6>
- UiTitle6
- </UiTitle6>
+ <UiTextSubtitle>
+ UiTextSubtitle
+ </UiTextSubtitle>
- <UiTitle8>
- UiTitle8
- </UiTitle8>
+ <UiTitleCollapse>
+ UiTitleCollapse
+ </UiTitleCollapse>
<UiTitleDropRight>
UiTitleDropRight
@@ -146,9 +143,9 @@
UiTitleModal
</UiTitleModal>
- <UiTitleOption>
- UiTitleOption
- </UiTitleOption>
+ <UiTitleSection size="sm">
+ UiTitleSection sm
+ </UiTitleSection>
</div>
</div>
@@ -158,13 +155,13 @@
</h1>
<div class="grid gap-4">
- <UiTextSm1>
- UiTextSm1
- </UiTextSm1>
+ <UiTextMuted>
+ UiTextMuted
+ </UiTextMuted>
- <UiTextSm2>
- UiTextSm2
- </UiTextSm2>
+ <UiTextMuted size="sm">
+ UiTextMuted sm
+ </UiTextMuted>
</div>
</div>
@@ -182,13 +179,9 @@
UiToggleWithStorage
</UiToggleWithStorage>
- <UiToggle3 isShown>
- UiToggle3
- </UiToggle3>
-
- <UiToggleAction isShown>
- UiToggleAction
- </UiToggleAction>
+ <UiToggleControlled isShown>
+ UiToggleControlled
+ </UiToggleControlled>
</div>
</div>
@@ -198,17 +191,17 @@
</h1>
<div class="grid gap-4">
- <UiItem1>
- UiItem1
- </UiItem1>
+ <UiActionButton>
+ UiActionButton
+ </UiActionButton>
- <UiItem2>
- UiItem2
- </UiItem2>
+ <UiChipButton>
+ UiChipButton
+ </UiChipButton>
- <UiItem3>
- UiItem3
- </UiItem3>
+ <UiActionButton>
+ UiActionButton
+ </UiActionButton>
</div>
</div>
@@ -218,13 +211,13 @@
</h1>
<div class="grid gap-4">
- <UiTabs1>
- UiTabs1
- </UiTabs1>
+ <UiTabsBar>
+ UiTabsBar
+ </UiTabsBar>
- <UiTabs2>
- UiTabs2
- </UiTabs2>
+ <UiTabsScroll>
+ UiTabsScroll
+ </UiTabsScroll>
</div>
</div>
@@ -235,31 +228,34 @@
<div class="grid grid-cols-2 gap-2">
<div class="grid gap-4">
- <UiTabsItem1>
- UiTabsItem1
- </UiTabsItem1>
+ <UiTabsItemFill>
+ UiTabsItemFill
+ </UiTabsItemFill>
- <UiTabsItem3>
- UiTabsItem3
- </UiTabsItem3>
+ <UiTabsItemPill>
+ UiTabsItemPill
+ </UiTabsItemPill>
- <UiTabsItem4>
- UiTabsItem4
- </UiTabsItem4>
+ <UiTabsItemPill variant="outline">
+ UiTabsItemPill outline
+ </UiTabsItemPill>
</div>
<div class="grid gap-4">
- <UiTabsItem1 isActive>
- UiTabsItem1
- </UiTabsItem1>
-
- <UiTabsItem3 isActive>
- UiTabsItem3
- </UiTabsItem3>
-
- <UiTabsItem4 isActive>
- UiTabsItem4
- </UiTabsItem4>
+ <UiTabsItemFill isActive>
+ UiTabsItemFill
+ </UiTabsItemFill>
+
+ <UiTabsItemPill isActive>
+ UiTabsItemPill
+ </UiTabsItemPill>
+
+ <UiTabsItemPill
+ variant="outline"
+ isActive
+ >
+ UiTabsItemPill outline
+ </UiTabsItemPill>
</div>
</div>
</div>
diff --git a/app/pages/index.vue b/app/pages/index.vue
index 7353d223..fcdcb3bc 100644
--- a/app/pages/index.vue
+++ b/app/pages/index.vue
@@ -1,5 +1,7 @@
<script setup lang="ts">
-useRouter().replace('/dashboard')
+definePageMeta({
+ redirect: '/dashboard',
+})
</script>
<template>
diff --git a/app/pages/login.vue b/app/pages/login.vue
index 6c86fdcb..5b380438 100644
--- a/app/pages/login.vue
+++ b/app/pages/login.vue
@@ -1,10 +1,9 @@
<script setup lang="ts">
-import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth'
-
import { useDemo } from '~/components/demo/useDemo'
+import { showErrorToast } from '~/composables/useStoreSync'
-const auth = useFirebaseAuth()!
-const toast = useToast()
+const { signIn } = useAuth()
+const logger = createLogger('login')
definePageMeta({
layout: 'empty',
@@ -21,41 +20,56 @@ const { generateDemoData } = useDemo()
const route = useRoute()
const router = useRouter()
const { isDemo } = useDemo()
-const isLoading = ref(false)
-if (route.query?.loading)
- isLoading.value = true
+const isLoading = ref(false)
-function signInWithGoogle() {
- isDemo.value = 'false'
- router.push({ query: { loading: 'true' } })
+async function signInWithGoogle() {
+ isDemo.value = null
isLoading.value = true
- signInWithPopup(auth, new GoogleAuthProvider()).catch((e) => {
- toast.add({
- color: 'error',
- description: e.message,
- title: 'Error',
- })
+ // Unregister service workers before OAuth flow.
+ // A stale SW with navigateFallback intercepts the callback page navigation
+ // at the network level and serves cached content instead of the real page.
+ // Our OTT verification code never runs → auth fails on re-login.
+ if ('serviceWorker' in navigator) {
+ const registrations = await navigator.serviceWorker.getRegistrations()
+ for (const reg of registrations)
+ await reg.unregister()
+ }
+ // Remember where user wanted to go, so callback page can redirect back.
+ // Using localStorage (synchronous) instead of cookie — cookie may not flush
+ // before signIn.social() triggers full-page navigation to Google.
+ const redirectTo = getSafeRedirectPath(route.query.redirect)
+ localStorage.setItem('finapp.authRedirect', redirectTo)
+
+ // Clear stale cross-domain cookies before initiating OAuth.
+ // After signOut, background responses (getSession, atom refetch) can race
+ // with localStorage.removeItem and re-write stale cookies. The stale
+ // __Secure-better-auth.state confuses the OAuth flow.
+ localStorage.removeItem('better-auth_cookie')
+ localStorage.removeItem('better-auth_session_data')
+
+ try {
+ const result = await signIn.social({ callbackURL: `${window.location.origin}/auth/callback`, provider: 'google' })
+
+ // crossDomainClient returns {url, redirect: true} instead of auto-redirecting.
+ // Manually redirect to the Google OAuth URL.
+ if (result.data?.url) {
+ window.location.href = result.data.url
+ }
+ }
+ catch (e: unknown) {
+ logger.error('signIn.social error:', e)
+ showErrorToast('login.error')
isLoading.value = false
- })
-}
-
-onMounted(() => {
- if (route.query?.loading) {
- isLoading.value = true
- const newRoute = { ...route }
- delete newRoute.query?.loading
- router.replace(newRoute)
- setTimeout(() => (isLoading.value = false), 10000)
}
-})
+}
async function openDemo() {
isDemo.value = 'true'
await generateDemoData(locale.value)
- router.push(typeof route.query.redirect === 'string' ? route.query.redirect : '/dashboard')
+ router.push(getSafeRedirectPath(route.query.redirect))
}
</script>
diff --git a/app/pages/settings.vue b/app/pages/settings.vue
index 837ebc45..d2075e57 100644
--- a/app/pages/settings.vue
+++ b/app/pages/settings.vue
@@ -1,9 +1,12 @@
<script setup lang="ts">
import pkg from '~~/package.json'
+import type { LocaleSlug } from '~/components/locale/types'
+
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
import { useDemo } from '~/components/demo/useDemo'
import { useUserStore } from '~/components/user/useUserStore'
+import { showSuccessToast } from '~/composables/useStoreSync'
const { locale, t } = useI18n()
const userStore = useUserStore()
@@ -11,7 +14,6 @@ const currenciesStore = useCurrenciesStore()
const { generateDemoData } = useDemo()
const { isDemo } = useDemo()
const isShowBaseCurrencyModal = ref(false)
-const toast = useToast()
useSeoMeta({
ogTitle: t('settings.title'),
@@ -21,15 +23,18 @@ useSeoMeta({
const version = pkg.version
const confirmRemoveUserData = ref(false)
-function removeUserData() {
+const router = useRouter()
+
+function removeAllUserData() {
confirmRemoveUserData.value = false
- userStore.removeUserData()
- toast.add({ color: 'success', description: t('alerts.removedUserData') })
+ userStore.removeAllUserData()
+ showSuccessToast('alerts.removedUserData')
+ router.replace('/dashboard')
}
function onGenerateDemoData() {
generateDemoData(locale.value)
- toast.add({ color: 'success', description: t('demo.updated') })
+ showSuccessToast('demo.updated')
}
</script>
@@ -37,94 +42,96 @@ function onGenerateDemoData() {
<UiPage>
<UiHeader>
<UiHeaderTitle>{{ t('settings.title') }}</UiHeaderTitle>
-
- <div class="flex items-center gap-1">
- <ThemeSwitcher />
- <ThemePicker />
- </div>
</UiHeader>
<div class="pageWrapper">
- <div class="grid gap-8 pt-2 @3xl/main:max-w-md">
- <!-- User -->
- <div class="pb-6">
- <UserViewLogout isShowSignOut />
- </div>
-
- <LocaleSwitcher isShowTitle />
+ <div class="grid gap-4 pt-2 pb-12 @3xl/main:max-w-lg">
+ <!-- Theme -->
+ <ThemePicker inline />
+
+ <!-- Language -->
+ <UiSettingsCard :title="t('locale.title')">
+ <FormSelect
+ :options="[
+ { label: t('locale.ru'), value: 'ru' },
+ { label: t('locale.en'), value: 'en' },
+ ]"
+ :value="locale"
+ @change="(loc: string) => userStore.saveUserLocale(loc as LocaleSlug)"
+ />
+ </UiSettingsCard>
<!-- Currency -->
- <UiButtonWithRight
- isShowTitle
- @click="isShowBaseCurrencyModal = true"
- >
- <template #label>
- {{ t('currencies.base') }}
- </template>
-
- <template #value>
+ <UiSettingsCard :title="t('currencies.base')">
+ <button
+ class="bg-item-3 block min-h-[42px] w-full cursor-pointer items-center overflow-hidden rounded-md border border-transparent px-4 py-2 pr-10 text-left outline-none hover:bg-(--item-5) focus:border-(--ui-primary)"
+ style="appearance: none; background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM4MDgwODAiIHN0cm9rZS13aWR0aD0iMS41IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLWNoZXZyb25zLXVwLWRvd24iPjxwYXRoIGQ9Im03IDE1IDUgNSA1LTUiLz48cGF0aCBkPSJtNyA5IDUtNSA1IDUiLz48L3N2Zz4='); background-position: right 0.7rem center; background-repeat: no-repeat; background-size: 1.25em 1.25em;"
+ @click="isShowBaseCurrencyModal = true"
+ >
{{ currenciesStore.base }}
- </template>
- </UiButtonWithRight>
+ </button>
+ </UiSettingsCard>
- <!-- Delete -->
- <div class="py-8">
- <UiTitle3 class="pb-2">
- {{ t('settings.caution') }}
- </UiTitle3>
- <div class="text-alert-1 pb-4 text-xs leading-none">
- {{ t('alerts.willDeleteEverything') }}
- </div>
-
- <div class="grid gap-2 pb-4">
- <UiElement
- v-if="isDemo"
- class="group"
- insideClasses="min-h-[44px] bg-item-3 max-w-lg"
+ <!-- Demo -->
+ <UiSettingsCard
+ v-if="isDemo"
+ :title="t('demo.update')"
+ >
+ <template #content>
+ <UButton
+ variant="outline"
+ color="secondary"
+ size="md"
@click="onGenerateDemoData"
>
- <template #leftIcon>
- <Icon name="lucide:database-backup" size="20" />
- </template>
- <div>{{ t('demo.update') }}</div>
- </UiElement>
-
- <UiElement
- class="group"
- insideClasses="min-h-[44px] bg-item-3 max-w-lg"
+ {{ t('demo.update') }}
+ </UButton>
+ </template>
+ </UiSettingsCard>
+
+ <!-- Delete -->
+ <UiSettingsCard
+ danger
+ :title="t('settings.deleteButton')"
+ :description="t('alerts.willDeleteEverything')"
+ >
+ <template #footer>
+ <UButton
+ variant="soft"
+ color="error"
+ size="md"
@click="confirmRemoveUserData = true"
>
- <template #leftIcon>
- <Icon name="lucide:trash" size="20" />
- </template>
- <div>{{ t('settings.deleteButton') }}</div>
- </UiElement>
- </div>
+ {{ t('settings.deleteButton') }}
+ </UButton>
+ </template>
+ </UiSettingsCard>
+
+ <!-- User -->
+ <div class="py-4">
+ <UserViewLogout isShowSignOut />
</div>
<!-- About -->
- <div class="pb-12">
- {{ t('app.about') }}
- <div class="text-muted pt-4 text-xs">
- {{ t('app.version') }} {{ version }}
- <!-- <About /> -->
- </div>
+ <div class="text-muted pt-4 text-xs">
+ {{ t('app.version') }} {{ version }}
</div>
</div>
</div>
<LayoutConfirmModal
v-if="confirmRemoveUserData"
+ :title="t('settings.deleteButton')"
:description="t('alerts.willDeleteEverything')"
@closed="confirmRemoveUserData = false"
- @onConfirm="removeUserData"
+ @confirm="removeAllUserData"
/>
<CurrenciesModal
v-if="isShowBaseCurrencyModal"
:activeCode="currenciesStore.base"
- @onSelect="currenciesStore.updateBase"
- @onClose="isShowBaseCurrencyModal = false"
+ @select="userStore.saveUserBaseCurrency"
+ @close="isShowBaseCurrencyModal = false"
/>
</UiPage>
</template>
diff --git a/app/plugins/convex.ts b/app/plugins/convex.ts
new file mode 100644
index 00000000..579af16b
--- /dev/null
+++ b/app/plugins/convex.ts
@@ -0,0 +1,101 @@
+import type { ConvexClient, ConvexHttpClient } from 'convex/browser'
+
+import { createConvexClient, createConvexHttpClient } from '~~/services/convex/client'
+
+import { hasAuthCookie } from '~/composables/useAuthCookie'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('convex')
+
+export default defineNuxtPlugin(() => {
+ const config = useRuntimeConfig()
+ const convexUrl = config.public.convexUrl as string
+
+ if (!convexUrl) {
+ if (import.meta.prerender)
+ return
+ throw new Error('CONVEX_URL is not set in environment variables')
+ }
+
+ let convex: ConvexClient | ConvexHttpClient
+ let convexHttp: ConvexHttpClient
+
+ if (import.meta.server) {
+ const httpClient = createConvexHttpClient(convexUrl)
+ convex = httpClient
+ convexHttp = httpClient
+ }
+ else {
+ const client = createConvexClient(convexUrl)
+ const authClient = useAuth()
+ const session = authClient.useSession()
+
+ const fetchConvexToken = async (forceRefreshToken: boolean) => {
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), 5000)
+
+ try {
+ const { data } = await authClient.$fetch<{ token: string }>('/convex/token', {
+ method: 'GET',
+ query: forceRefreshToken ? { forceRefresh: 'true' } : undefined,
+ signal: controller.signal,
+ })
+ return data?.token ?? null
+ }
+ finally {
+ clearTimeout(timeout)
+ }
+ }
+
+ const fetchToken = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
+ if (!hasAuthCookie()) {
+ authClient.getSession().catch(() => {})
+ return null
+ }
+
+ try {
+ return await fetchConvexToken(forceRefreshToken)
+ }
+ catch (error) {
+ logger.error('fetchToken failed, retrying:', error)
+ try {
+ await new Promise(r => setTimeout(r, 1000))
+ return await fetchConvexToken(forceRefreshToken)
+ }
+ catch {
+ logger.error('fetchToken retry failed')
+ authClient.getSession().catch(() => {})
+ return null
+ }
+ }
+ }
+
+ // Only set auth when user is logged in to avoid 401 in console
+ if (hasAuthCookie())
+ client.setAuth(fetchToken)
+
+ // Watch session state for auth transitions
+ watch(
+ () => session.value?.isPending === false
+ ? (session.value?.data?.user?.id ?? null)
+ : undefined,
+ (resolvedUid) => {
+ if (resolvedUid === undefined)
+ return // still pending
+ if (resolvedUid)
+ client.setAuth(fetchToken)
+ else client.client.clearAuth()
+ },
+ )
+
+ convex = client
+ convexHttp = createConvexHttpClient(convexUrl)
+ }
+
+ return {
+ provide: {
+ convex,
+ convexHttp,
+ },
+ }
+})
diff --git a/app/utils/convexId.ts b/app/utils/convexId.ts
new file mode 100644
index 00000000..ec018fdc
--- /dev/null
+++ b/app/utils/convexId.ts
@@ -0,0 +1,26 @@
+import type { GenericId } from 'convex/values'
+import type { TableNames } from '~~/convex/_generated/dataModel'
+
+export function asConvexId<T extends TableNames>(id: string): GenericId<T> {
+ return id as unknown as GenericId<T>
+}
+
+export function isLocalId(id: string): boolean {
+ return id.startsWith('local_')
+}
+
+/**
+ * Remove stale frontend-generated IDs from data.
+ * Keeps IDs that are in the pending offline queue (awaiting creation).
+ */
+export function cleanupFrontendIds<T>(
+ data: Record<string, T>,
+ pendingUpdates: Record<string, T>,
+): Record<string, T> {
+ const result = { ...data }
+ for (const id of Object.keys(result)) {
+ if (isLocalId(id) && !pendingUpdates[id])
+ delete result[id]
+ }
+ return result
+}
diff --git a/app/utils/logger.ts b/app/utils/logger.ts
new file mode 100644
index 00000000..f733a104
--- /dev/null
+++ b/app/utils/logger.ts
@@ -0,0 +1,8 @@
+const isDev = import.meta.dev
+
+export function createLogger(prefix: string) {
+ return {
+ error: (...args: unknown[]) => console.error(`[${prefix}]`, ...args),
+ log: isDev ? (...args: unknown[]) => console.log(`[${prefix}]`, ...args) : () => {},
+ }
+}
diff --git a/app/utils/redirect.ts b/app/utils/redirect.ts
new file mode 100644
index 00000000..ac24906b
--- /dev/null
+++ b/app/utils/redirect.ts
@@ -0,0 +1,9 @@
+/**
+ * Validates a redirect path to prevent open redirect attacks.
+ * Only allows relative paths starting with `/` (not `//` which browsers treat as protocol-relative URLs).
+ */
+export function getSafeRedirectPath(value: unknown): string {
+ if (typeof value === 'string' && value.startsWith('/') && !value.startsWith('//'))
+ return value
+ return '/dashboard'
+}
diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts
new file mode 100644
index 00000000..7391bdce
--- /dev/null
+++ b/convex/_generated/api.d.ts
@@ -0,0 +1,2049 @@
+/* eslint-disable */
+/**
+ * Generated `api` utility.
+ *
+ * THIS CODE IS AUTOMATICALLY GENERATED.
+ *
+ * To regenerate, run `npx convex dev`.
+ * @module
+ */
+
+import type * as auth from "../auth.js";
+import type * as categories from "../categories.js";
+import type * as crons from "../crons.js";
+import type * as http from "../http.js";
+import type * as migrate from "../migrate.js";
+import type * as rates from "../rates.js";
+import type * as shared from "../shared.js";
+import type * as trns from "../trns.js";
+import type * as trnsHash from "../trnsHash.js";
+import type * as userSettings from "../userSettings.js";
+import type * as validators from "../validators.js";
+import type * as wallets from "../wallets.js";
+
+import type {
+ ApiFromModules,
+ FilterApi,
+ FunctionReference,
+} from "convex/server";
+
+declare const fullApi: ApiFromModules<{
+ auth: typeof auth;
+ categories: typeof categories;
+ crons: typeof crons;
+ http: typeof http;
+ migrate: typeof migrate;
+ rates: typeof rates;
+ shared: typeof shared;
+ trns: typeof trns;
+ trnsHash: typeof trnsHash;
+ userSettings: typeof userSettings;
+ validators: typeof validators;
+ wallets: typeof wallets;
+}>;
+
+/**
+ * A utility for referencing Convex functions in your app's public API.
+ *
+ * Usage:
+ * ```js
+ * const myFunctionReference = api.myModule.myFunction;
+ * ```
+ */
+export declare const api: FilterApi<
+ typeof fullApi,
+ FunctionReference<any, "public">
+>;
+
+/**
+ * A utility for referencing Convex functions in your app's internal API.
+ *
+ * Usage:
+ * ```js
+ * const myFunctionReference = internal.myModule.myFunction;
+ * ```
+ */
+export declare const internal: FilterApi<
+ typeof fullApi,
+ FunctionReference<any, "internal">
+>;
+
+export declare const components: {
+ betterAuth: {
+ adapter: {
+ create: FunctionReference<
+ "mutation",
+ "internal",
+ {
+ input:
+ | {
+ data: {
+ createdAt: number;
+ displayUsername?: null | string;
+ email: string;
+ emailVerified: boolean;
+ image?: null | string;
+ isAnonymous?: null | boolean;
+ name: string;
+ phoneNumber?: null | string;
+ phoneNumberVerified?: null | boolean;
+ twoFactorEnabled?: null | boolean;
+ updatedAt: number;
+ userId?: null | string;
+ username?: null | string;
+ };
+ model: "user";
+ }
+ | {
+ data: {
+ createdAt: number;
+ expiresAt: number;
+ ipAddress?: null | string;
+ token: string;
+ updatedAt: number;
+ userAgent?: null | string;
+ userId: string;
+ };
+ model: "session";
+ }
+ | {
+ data: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ accountId: string;
+ createdAt: number;
+ idToken?: null | string;
+ password?: null | string;
+ providerId: string;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scope?: null | string;
+ updatedAt: number;
+ userId: string;
+ };
+ model: "account";
+ }
+ | {
+ data: {
+ createdAt: number;
+ expiresAt: number;
+ identifier: string;
+ updatedAt: number;
+ value: string;
+ };
+ model: "verification";
+ }
+ | {
+ data: { backupCodes: string; secret: string; userId: string };
+ model: "twoFactor";
+ }
+ | {
+ data: {
+ aaguid?: null | string;
+ backedUp: boolean;
+ counter: number;
+ createdAt?: null | number;
+ credentialID: string;
+ deviceType: string;
+ name?: null | string;
+ publicKey: string;
+ transports?: null | string;
+ userId: string;
+ };
+ model: "passkey";
+ }
+ | {
+ data: {
+ clientId?: null | string;
+ clientSecret?: null | string;
+ createdAt?: null | number;
+ disabled?: null | boolean;
+ icon?: null | string;
+ metadata?: null | string;
+ name?: null | string;
+ redirectURLs?: null | string;
+ type?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ model: "oauthApplication";
+ }
+ | {
+ data: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ clientId?: null | string;
+ createdAt?: null | number;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ model: "oauthAccessToken";
+ }
+ | {
+ data: {
+ clientId?: null | string;
+ consentGiven?: null | boolean;
+ createdAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ model: "oauthConsent";
+ }
+ | {
+ data: {
+ createdAt: number;
+ privateKey: string;
+ publicKey: string;
+ };
+ model: "jwks";
+ }
+ | {
+ data: {
+ count?: null | number;
+ key?: null | string;
+ lastRequest?: null | number;
+ };
+ model: "rateLimit";
+ };
+ onCreateHandle?: string;
+ select?: Array<string>;
+ },
+ any
+ >;
+ deleteMany: FunctionReference<
+ "mutation",
+ "internal",
+ {
+ input:
+ | {
+ model: "user";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "email"
+ | "emailVerified"
+ | "image"
+ | "createdAt"
+ | "updatedAt"
+ | "twoFactorEnabled"
+ | "isAnonymous"
+ | "username"
+ | "displayUsername"
+ | "phoneNumber"
+ | "phoneNumberVerified"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "session";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "expiresAt"
+ | "token"
+ | "createdAt"
+ | "updatedAt"
+ | "ipAddress"
+ | "userAgent"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "account";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accountId"
+ | "providerId"
+ | "userId"
+ | "accessToken"
+ | "refreshToken"
+ | "idToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "scope"
+ | "password"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "verification";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "identifier"
+ | "value"
+ | "expiresAt"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "twoFactor";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "secret" | "backupCodes" | "userId" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "passkey";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "publicKey"
+ | "userId"
+ | "credentialID"
+ | "counter"
+ | "deviceType"
+ | "backedUp"
+ | "transports"
+ | "createdAt"
+ | "aaguid"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthApplication";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "icon"
+ | "metadata"
+ | "clientId"
+ | "clientSecret"
+ | "redirectURLs"
+ | "type"
+ | "disabled"
+ | "userId"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthAccessToken";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accessToken"
+ | "refreshToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthConsent";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "consentGiven"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "jwks";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "publicKey" | "privateKey" | "createdAt" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "rateLimit";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "key" | "count" | "lastRequest" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ };
+ onDeleteHandle?: string;
+ paginationOpts: {
+ cursor: string | null;
+ endCursor?: string | null;
+ id?: number;
+ maximumBytesRead?: number;
+ maximumRowsRead?: number;
+ numItems: number;
+ };
+ },
+ any
+ >;
+ deleteOne: FunctionReference<
+ "mutation",
+ "internal",
+ {
+ input:
+ | {
+ model: "user";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "email"
+ | "emailVerified"
+ | "image"
+ | "createdAt"
+ | "updatedAt"
+ | "twoFactorEnabled"
+ | "isAnonymous"
+ | "username"
+ | "displayUsername"
+ | "phoneNumber"
+ | "phoneNumberVerified"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "session";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "expiresAt"
+ | "token"
+ | "createdAt"
+ | "updatedAt"
+ | "ipAddress"
+ | "userAgent"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "account";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accountId"
+ | "providerId"
+ | "userId"
+ | "accessToken"
+ | "refreshToken"
+ | "idToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "scope"
+ | "password"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "verification";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "identifier"
+ | "value"
+ | "expiresAt"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "twoFactor";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "secret" | "backupCodes" | "userId" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "passkey";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "publicKey"
+ | "userId"
+ | "credentialID"
+ | "counter"
+ | "deviceType"
+ | "backedUp"
+ | "transports"
+ | "createdAt"
+ | "aaguid"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthApplication";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "icon"
+ | "metadata"
+ | "clientId"
+ | "clientSecret"
+ | "redirectURLs"
+ | "type"
+ | "disabled"
+ | "userId"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthAccessToken";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accessToken"
+ | "refreshToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthConsent";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "consentGiven"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "jwks";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "publicKey" | "privateKey" | "createdAt" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "rateLimit";
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "key" | "count" | "lastRequest" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ };
+ onDeleteHandle?: string;
+ },
+ any
+ >;
+ findMany: FunctionReference<
+ "query",
+ "internal",
+ {
+ join?: any;
+ limit?: number;
+ model:
+ | "user"
+ | "session"
+ | "account"
+ | "verification"
+ | "twoFactor"
+ | "passkey"
+ | "oauthApplication"
+ | "oauthAccessToken"
+ | "oauthConsent"
+ | "jwks"
+ | "rateLimit";
+ offset?: number;
+ paginationOpts: {
+ cursor: string | null;
+ endCursor?: string | null;
+ id?: number;
+ maximumBytesRead?: number;
+ maximumRowsRead?: number;
+ numItems: number;
+ };
+ sortBy?: { direction: "asc" | "desc"; field: string };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: string;
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ },
+ any
+ >;
+ findOne: FunctionReference<
+ "query",
+ "internal",
+ {
+ join?: any;
+ model:
+ | "user"
+ | "session"
+ | "account"
+ | "verification"
+ | "twoFactor"
+ | "passkey"
+ | "oauthApplication"
+ | "oauthAccessToken"
+ | "oauthConsent"
+ | "jwks"
+ | "rateLimit";
+ select?: Array<string>;
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: string;
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ },
+ any
+ >;
+ updateMany: FunctionReference<
+ "mutation",
+ "internal",
+ {
+ input:
+ | {
+ model: "user";
+ update: {
+ createdAt?: number;
+ displayUsername?: null | string;
+ email?: string;
+ emailVerified?: boolean;
+ image?: null | string;
+ isAnonymous?: null | boolean;
+ name?: string;
+ phoneNumber?: null | string;
+ phoneNumberVerified?: null | boolean;
+ twoFactorEnabled?: null | boolean;
+ updatedAt?: number;
+ userId?: null | string;
+ username?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "email"
+ | "emailVerified"
+ | "image"
+ | "createdAt"
+ | "updatedAt"
+ | "twoFactorEnabled"
+ | "isAnonymous"
+ | "username"
+ | "displayUsername"
+ | "phoneNumber"
+ | "phoneNumberVerified"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "session";
+ update: {
+ createdAt?: number;
+ expiresAt?: number;
+ ipAddress?: null | string;
+ token?: string;
+ updatedAt?: number;
+ userAgent?: null | string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "expiresAt"
+ | "token"
+ | "createdAt"
+ | "updatedAt"
+ | "ipAddress"
+ | "userAgent"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "account";
+ update: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ accountId?: string;
+ createdAt?: number;
+ idToken?: null | string;
+ password?: null | string;
+ providerId?: string;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scope?: null | string;
+ updatedAt?: number;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accountId"
+ | "providerId"
+ | "userId"
+ | "accessToken"
+ | "refreshToken"
+ | "idToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "scope"
+ | "password"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "verification";
+ update: {
+ createdAt?: number;
+ expiresAt?: number;
+ identifier?: string;
+ updatedAt?: number;
+ value?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "identifier"
+ | "value"
+ | "expiresAt"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "twoFactor";
+ update: {
+ backupCodes?: string;
+ secret?: string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "secret" | "backupCodes" | "userId" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "passkey";
+ update: {
+ aaguid?: null | string;
+ backedUp?: boolean;
+ counter?: number;
+ createdAt?: null | number;
+ credentialID?: string;
+ deviceType?: string;
+ name?: null | string;
+ publicKey?: string;
+ transports?: null | string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "publicKey"
+ | "userId"
+ | "credentialID"
+ | "counter"
+ | "deviceType"
+ | "backedUp"
+ | "transports"
+ | "createdAt"
+ | "aaguid"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthApplication";
+ update: {
+ clientId?: null | string;
+ clientSecret?: null | string;
+ createdAt?: null | number;
+ disabled?: null | boolean;
+ icon?: null | string;
+ metadata?: null | string;
+ name?: null | string;
+ redirectURLs?: null | string;
+ type?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "icon"
+ | "metadata"
+ | "clientId"
+ | "clientSecret"
+ | "redirectURLs"
+ | "type"
+ | "disabled"
+ | "userId"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthAccessToken";
+ update: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ clientId?: null | string;
+ createdAt?: null | number;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accessToken"
+ | "refreshToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthConsent";
+ update: {
+ clientId?: null | string;
+ consentGiven?: null | boolean;
+ createdAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "consentGiven"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "jwks";
+ update: {
+ createdAt?: number;
+ privateKey?: string;
+ publicKey?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "publicKey" | "privateKey" | "createdAt" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "rateLimit";
+ update: {
+ count?: null | number;
+ key?: null | string;
+ lastRequest?: null | number;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "key" | "count" | "lastRequest" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ };
+ onUpdateHandle?: string;
+ paginationOpts: {
+ cursor: string | null;
+ endCursor?: string | null;
+ id?: number;
+ maximumBytesRead?: number;
+ maximumRowsRead?: number;
+ numItems: number;
+ };
+ },
+ any
+ >;
+ updateOne: FunctionReference<
+ "mutation",
+ "internal",
+ {
+ input:
+ | {
+ model: "user";
+ update: {
+ createdAt?: number;
+ displayUsername?: null | string;
+ email?: string;
+ emailVerified?: boolean;
+ image?: null | string;
+ isAnonymous?: null | boolean;
+ name?: string;
+ phoneNumber?: null | string;
+ phoneNumberVerified?: null | boolean;
+ twoFactorEnabled?: null | boolean;
+ updatedAt?: number;
+ userId?: null | string;
+ username?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "email"
+ | "emailVerified"
+ | "image"
+ | "createdAt"
+ | "updatedAt"
+ | "twoFactorEnabled"
+ | "isAnonymous"
+ | "username"
+ | "displayUsername"
+ | "phoneNumber"
+ | "phoneNumberVerified"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "session";
+ update: {
+ createdAt?: number;
+ expiresAt?: number;
+ ipAddress?: null | string;
+ token?: string;
+ updatedAt?: number;
+ userAgent?: null | string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "expiresAt"
+ | "token"
+ | "createdAt"
+ | "updatedAt"
+ | "ipAddress"
+ | "userAgent"
+ | "userId"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "account";
+ update: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ accountId?: string;
+ createdAt?: number;
+ idToken?: null | string;
+ password?: null | string;
+ providerId?: string;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scope?: null | string;
+ updatedAt?: number;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accountId"
+ | "providerId"
+ | "userId"
+ | "accessToken"
+ | "refreshToken"
+ | "idToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "scope"
+ | "password"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "verification";
+ update: {
+ createdAt?: number;
+ expiresAt?: number;
+ identifier?: string;
+ updatedAt?: number;
+ value?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "identifier"
+ | "value"
+ | "expiresAt"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "twoFactor";
+ update: {
+ backupCodes?: string;
+ secret?: string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "secret" | "backupCodes" | "userId" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "passkey";
+ update: {
+ aaguid?: null | string;
+ backedUp?: boolean;
+ counter?: number;
+ createdAt?: null | number;
+ credentialID?: string;
+ deviceType?: string;
+ name?: null | string;
+ publicKey?: string;
+ transports?: null | string;
+ userId?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "publicKey"
+ | "userId"
+ | "credentialID"
+ | "counter"
+ | "deviceType"
+ | "backedUp"
+ | "transports"
+ | "createdAt"
+ | "aaguid"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthApplication";
+ update: {
+ clientId?: null | string;
+ clientSecret?: null | string;
+ createdAt?: null | number;
+ disabled?: null | boolean;
+ icon?: null | string;
+ metadata?: null | string;
+ name?: null | string;
+ redirectURLs?: null | string;
+ type?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "name"
+ | "icon"
+ | "metadata"
+ | "clientId"
+ | "clientSecret"
+ | "redirectURLs"
+ | "type"
+ | "disabled"
+ | "userId"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthAccessToken";
+ update: {
+ accessToken?: null | string;
+ accessTokenExpiresAt?: null | number;
+ clientId?: null | string;
+ createdAt?: null | number;
+ refreshToken?: null | string;
+ refreshTokenExpiresAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "accessToken"
+ | "refreshToken"
+ | "accessTokenExpiresAt"
+ | "refreshTokenExpiresAt"
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "oauthConsent";
+ update: {
+ clientId?: null | string;
+ consentGiven?: null | boolean;
+ createdAt?: null | number;
+ scopes?: null | string;
+ updatedAt?: null | number;
+ userId?: null | string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field:
+ | "clientId"
+ | "userId"
+ | "scopes"
+ | "createdAt"
+ | "updatedAt"
+ | "consentGiven"
+ | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "jwks";
+ update: {
+ createdAt?: number;
+ privateKey?: string;
+ publicKey?: string;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "publicKey" | "privateKey" | "createdAt" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ }
+ | {
+ model: "rateLimit";
+ update: {
+ count?: null | number;
+ key?: null | string;
+ lastRequest?: null | number;
+ };
+ where?: Array<{
+ connector?: "AND" | "OR";
+ field: "key" | "count" | "lastRequest" | "_id";
+ operator?:
+ | "lt"
+ | "lte"
+ | "gt"
+ | "gte"
+ | "eq"
+ | "in"
+ | "not_in"
+ | "ne"
+ | "contains"
+ | "starts_with"
+ | "ends_with";
+ value:
+ | string
+ | number
+ | boolean
+ | Array<string>
+ | Array<number>
+ | null;
+ }>;
+ };
+ onUpdateHandle?: string;
+ },
+ any
+ >;
+ };
+ adapterTest: {
+ runCustomTests: FunctionReference<"action", "internal", any, any>;
+ runTests: FunctionReference<"action", "internal", any, any>;
+ };
+ };
+};
diff --git a/convex/_generated/api.js b/convex/_generated/api.js
new file mode 100644
index 00000000..44bf9858
--- /dev/null
+++ b/convex/_generated/api.js
@@ -0,0 +1,23 @@
+/* eslint-disable */
+/**
+ * Generated `api` utility.
+ *
+ * THIS CODE IS AUTOMATICALLY GENERATED.
+ *
+ * To regenerate, run `npx convex dev`.
+ * @module
+ */
+
+import { anyApi, componentsGeneric } from "convex/server";
+
+/**
+ * A utility for referencing Convex functions in your app's API.
+ *
+ * Usage:
+ * ```js
+ * const myFunctionReference = api.myModule.myFunction;
+ * ```
+ */
+export const api = anyApi;
+export const internal = anyApi;
+export const components = componentsGeneric();
diff --git a/convex/_generated/dataModel.d.ts b/convex/_generated/dataModel.d.ts
new file mode 100644
index 00000000..f97fd194
--- /dev/null
+++ b/convex/_generated/dataModel.d.ts
@@ -0,0 +1,60 @@
+/* eslint-disable */
+/**
+ * Generated data model types.
+ *
+ * THIS CODE IS AUTOMATICALLY GENERATED.
+ *
+ * To regenerate, run `npx convex dev`.
+ * @module
+ */
+
+import type {
+ DataModelFromSchemaDefinition,
+ DocumentByName,
+ TableNamesInDataModel,
+ SystemTableNames,
+} from "convex/server";
+import type { GenericId } from "convex/values";
+import schema from "../schema.js";
+
+/**
+ * The names of all of your Convex tables.
+ */
+export type TableNames = TableNamesInDataModel<DataModel>;
+
+/**
+ * The type of a document stored in Convex.
+ *
+ * @typeParam TableName - A string literal type of the table name (like "users").
+ */
+export type Doc<TableName extends TableNames> = DocumentByName<
+ DataModel,
+ TableName
+>;
+
+/**
+ * An identifier for a document in Convex.
+ *
+ * Convex documents are uniquely identified by their `Id`, which is accessible
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
+ *
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
+ *
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
+ * strings when type checking.
+ *
+ * @typeParam TableName - A string literal type of the table name (like "users").
+ */
+export type Id<TableName extends TableNames | SystemTableNames> =
+ GenericId<TableName>;
+
+/**
+ * A type describing your Convex data model.
+ *
+ * This type includes information about what tables you have, the type of
+ * documents stored in those tables, and the indexes defined on them.
+ *
+ * This type is used to parameterize methods like `queryGeneric` and
+ * `mutationGeneric` to make them type-safe.
+ */
+export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
diff --git a/convex/_generated/server.d.ts b/convex/_generated/server.d.ts
new file mode 100644
index 00000000..bec05e68
--- /dev/null
+++ b/convex/_generated/server.d.ts
@@ -0,0 +1,143 @@
+/* eslint-disable */
+/**
+ * Generated utilities for implementing server-side Convex query and mutation functions.
+ *
+ * THIS CODE IS AUTOMATICALLY GENERATED.
+ *
+ * To regenerate, run `npx convex dev`.
+ * @module
+ */
+
+import {
+ ActionBuilder,
+ HttpActionBuilder,
+ MutationBuilder,
+ QueryBuilder,
+ GenericActionCtx,
+ GenericMutationCtx,
+ GenericQueryCtx,
+ GenericDatabaseReader,
+ GenericDatabaseWriter,
+} from "convex/server";
+import type { DataModel } from "./dataModel.js";
+
+/**
+ * Define a query in this Convex app's public API.
+ *
+ * This function will be allowed to read your Convex database and will be accessible from the client.
+ *
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
+ */
+export declare const query: QueryBuilder<DataModel, "public">;
+
+/**
+ * Define a query that is only accessible from other Convex functions (but not from the client).
+ *
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
+ *
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
+ */
+export declare const internalQuery: QueryBuilder<DataModel, "internal">;
+
+/**
+ * Define a mutation in this Convex app's public API.
+ *
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
+ *
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
+ */
+export declare const mutation: MutationBuilder<DataModel, "public">;
+
+/**
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
+ *
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
+ *
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
+ */
+export declare const internalMutation: MutationBuilder<DataModel, "internal">;
+
+/**
+ * Define an action in this Convex app's public API.
+ *
+ * An action is a function which can execute any JavaScript code, including non-deterministic
+ * code and code with side-effects, like calling third-party services.
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
+ *
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
+ */
+export declare const action: ActionBuilder<DataModel, "public">;
+
+/**
+ * Define an action that is only accessible from other Convex functions (but not from the client).
+ *
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
+ */
+export declare const internalAction: ActionBuilder<DataModel, "internal">;
+
+/**
+ * Define an HTTP action.
+ *
+ * The wrapped function will be used to respond to HTTP requests received
+ * by a Convex deployment if the requests matches the path and method where
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
+ *
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
+ * and a Fetch API `Request` object as its second.
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
+ */
+export declare const httpAction: HttpActionBuilder;
+
+/**
+ * A set of services for use within Convex query functions.
+ *
+ * The query context is passed as the first argument to any Convex query
+ * function run on the server.
+ *
+ * This differs from the {@link MutationCtx} because all of the services are
+ * read-only.
+ */
+export type QueryCtx = GenericQueryCtx<DataModel>;
+
+/**
+ * A set of services for use within Convex mutation functions.
+ *
+ * The mutation context is passed as the first argument to any Convex mutation
+ * function run on the server.
+ */
+export type MutationCtx = GenericMutationCtx<DataModel>;
+
+/**
+ * A set of services for use within Convex action functions.
+ *
+ * The action context is passed as the first argument to any Convex action
+ * function run on the server.
+ */
+export type ActionCtx = GenericActionCtx<DataModel>;
+
+/**
+ * An interface to read from the database within Convex query functions.
+ *
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
+ * building a query.
+ */
+export type DatabaseReader = GenericDatabaseReader<DataModel>;
+
+/**
+ * An interface to read from and write to the database within Convex mutation
+ * functions.
+ *
+ * Convex guarantees that all writes within a single mutation are
+ * executed atomically, so you never have to worry about partial writes leaving
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
+ * for the guarantees Convex provides your functions.
+ */
+export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
diff --git a/convex/_generated/server.js b/convex/_generated/server.js
new file mode 100644
index 00000000..bf3d25ad
--- /dev/null
+++ b/convex/_generated/server.js
@@ -0,0 +1,93 @@
+/* eslint-disable */
+/**
+ * Generated utilities for implementing server-side Convex query and mutation functions.
+ *
+ * THIS CODE IS AUTOMATICALLY GENERATED.
+ *
+ * To regenerate, run `npx convex dev`.
+ * @module
+ */
+
+import {
+ actionGeneric,
+ httpActionGeneric,
+ queryGeneric,
+ mutationGeneric,
+ internalActionGeneric,
+ internalMutationGeneric,
+ internalQueryGeneric,
+} from "convex/server";
+
+/**
+ * Define a query in this Convex app's public API.
+ *
+ * This function will be allowed to read your Convex database and will be accessible from the client.
+ *
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
+ */
+export const query = queryGeneric;
+
+/**
+ * Define a query that is only accessible from other Convex functions (but not from the client).
+ *
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
+ *
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
+ */
+export const internalQuery = internalQueryGeneric;
+
+/**
+ * Define a mutation in this Convex app's public API.
+ *
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
+ *
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
+ */
+export const mutation = mutationGeneric;
+
+/**
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
+ *
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
+ *
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
+ */
+export const internalMutation = internalMutationGeneric;
+
+/**
+ * Define an action in this Convex app's public API.
+ *
+ * An action is a function which can execute any JavaScript code, including non-deterministic
+ * code and code with side-effects, like calling third-party services.
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
+ *
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
+ */
+export const action = actionGeneric;
+
+/**
+ * Define an action that is only accessible from other Convex functions (but not from the client).
+ *
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
+ */
+export const internalAction = internalActionGeneric;
+
+/**
+ * Define an HTTP action.
+ *
+ * The wrapped function will be used to respond to HTTP requests received
+ * by a Convex deployment if the requests matches the path and method where
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
+ *
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
+ * and a Fetch API `Request` object as its second.
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
+ */
+export const httpAction = httpActionGeneric;
diff --git a/convex/auth.config.ts b/convex/auth.config.ts
new file mode 100644
index 00000000..68b60e9c
--- /dev/null
+++ b/convex/auth.config.ts
@@ -0,0 +1,7 @@
+import type { AuthConfig } from 'convex/server'
+
+import { getAuthConfigProvider } from '@convex-dev/better-auth/auth-config'
+
+export default {
+ providers: [getAuthConfigProvider()],
+} satisfies AuthConfig
diff --git a/convex/auth.ts b/convex/auth.ts
new file mode 100644
index 00000000..41dd288d
--- /dev/null
+++ b/convex/auth.ts
@@ -0,0 +1,55 @@
+import type { GenericCtx } from '@convex-dev/better-auth'
+
+import { createClient } from '@convex-dev/better-auth'
+import { convex, crossDomain } from '@convex-dev/better-auth/plugins'
+import { betterAuth } from 'better-auth'
+
+import type { DataModel } from './_generated/dataModel'
+
+import { components } from './_generated/api'
+import { query } from './_generated/server'
+import authConfig from './auth.config'
+
+const siteUrl = process.env.SITE_URL!
+const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3050'
+
+const trustedOrigins = [
+ 'https://finapp.ilko.me',
+ 'https://finapp-git-convex-ilkome2.vercel.app',
+ 'https://main-git-convex-ilkome2.vercel.app',
+ 'http://localhost:3050',
+]
+
+export const authComponent = createClient<DataModel>(components.betterAuth)
+
+function createAuth(ctx: GenericCtx<DataModel>) {
+ return betterAuth({
+ baseURL: siteUrl,
+ database: authComponent.adapter(ctx),
+ plugins: [
+ convex({
+ authConfig,
+ jwksRotateOnTokenGenerationError: true,
+ }),
+ crossDomain({
+ siteUrl: frontendUrl,
+ }),
+ ],
+ socialProviders: {
+ google: {
+ clientId: process.env.GOOGLE_CLIENT_ID!,
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
+ },
+ },
+ trustedOrigins,
+ })
+}
+
+export { createAuth }
+
+export const getCurrentUser = query({
+ args: {},
+ handler: async (ctx) => {
+ return await authComponent.safeGetAuthUser(ctx)
+ },
+})
diff --git a/convex/categories.ts b/convex/categories.ts
new file mode 100644
index 00000000..137890c6
--- /dev/null
+++ b/convex/categories.ts
@@ -0,0 +1,233 @@
+import { v } from 'convex/values'
+
+import type { Id } from './_generated/dataModel'
+import type { MutationCtx } from './_generated/server'
+
+import { mutation, query } from './_generated/server'
+import { getAuthUser, getOwnEntity, requireAuthUser } from './shared'
+import { removeTrnsFromHash } from './trnsHash'
+
+// --- Shared helpers ---
+
+async function validateParentId(ctx: MutationCtx, parentId: Id<'categories'> | 0, userId: string, selfId?: Id<'categories'>) {
+ if (parentId === 0)
+ return
+ if (selfId && parentId === selfId)
+ throw new Error('Category cannot be its own parent')
+ const parent = await getOwnEntity(ctx, parentId, userId, 'Parent category not found')
+ if (parent.parentId !== 0)
+ throw new Error('Cannot nest more than 2 levels deep')
+}
+
+async function validateNameUniqueness(ctx: MutationCtx, name: string, parentId: Id<'categories'> | 0, userId: string, excludeId?: Id<'categories'>) {
+ const duplicates = await ctx.db
+ .query('categories')
+ .withIndex('by_user_name_parent', q => q.eq('userId', userId).eq('name', name).eq('parentId', parentId))
+ .collect()
+ if (duplicates.some(c => c._id !== excludeId))
+ throw new Error('Category with this name already exists')
+}
+
+async function syncChildIdsOnParentChange(ctx: MutationCtx, id: Id<'categories'>, oldParentId: Id<'categories'> | 0, newParentId: Id<'categories'> | 0, userId: string) {
+ if (newParentId === oldParentId)
+ return
+
+ if (oldParentId !== 0) {
+ const oldParent = await ctx.db.get(oldParentId)
+ if (oldParent && oldParent.userId === userId) {
+ const updatedChildIds = (oldParent.childIds ?? []).filter(cid => cid !== id)
+ await ctx.db.patch(oldParentId, {
+ childIds: updatedChildIds.length ? updatedChildIds : undefined,
+ })
+ }
+ }
+
+ if (newParentId !== 0) {
+ const newParent = await ctx.db.get(newParentId)
+ if (newParent && newParent.userId === userId) {
+ await ctx.db.patch(newParentId, {
+ childIds: [...(newParent.childIds ?? []), id],
+ })
+ }
+ }
+}
+
+async function removeFromParentChildIds(ctx: MutationCtx, id: Id<'categories'>, parentId: Id<'categories'> | 0, userId: string) {
+ if (parentId === 0)
+ return
+ const parent = await ctx.db.get(parentId)
+ if (parent && parent.userId === userId) {
+ const updatedChildIds = (parent.childIds ?? []).filter(cid => cid !== id)
+ await ctx.db.patch(parentId, {
+ childIds: updatedChildIds.length ? updatedChildIds : undefined,
+ })
+ }
+}
+
+async function updateCategoryCore(
+ ctx: MutationCtx,
+ id: Id<'categories'>,
+ args: {
+ childIds?: Id<'categories'>[]
+ color?: string
+ icon?: string
+ name?: string
+ parentId?: Id<'categories'> | 0
+ showInLastUsed?: boolean
+ showInQuickSelector?: boolean
+ },
+ userId: string,
+) {
+ if (args.icon !== undefined && !args.icon.trim())
+ throw new Error('Icon is required')
+ if (args.name !== undefined && !args.name.trim())
+ throw new Error('Name is required')
+
+ const category = await getOwnEntity(ctx, id, userId)
+
+ if (args.parentId !== undefined && args.parentId !== 0)
+ await validateParentId(ctx, args.parentId, userId, id)
+ if (args.name !== undefined)
+ await validateNameUniqueness(ctx, args.name, args.parentId ?? category.parentId, userId, id)
+ if (args.parentId !== undefined)
+ await syncChildIdsOnParentChange(ctx, id, category.parentId, args.parentId, userId)
+
+ const now = Date.now()
+ await ctx.db.patch(id, { ...args, updatedAt: now })
+ return now
+}
+
+// --- Queries & Mutations ---
+
+export const list = query({
+ args: {},
+ handler: async (ctx) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ return await ctx.db
+ .query('categories')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .collect()
+ },
+})
+
+export const create = mutation({
+ args: {
+ childIds: v.optional(v.array(v.id('categories'))),
+ color: v.string(),
+ icon: v.string(),
+ name: v.string(),
+ parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
+ showInLastUsed: v.boolean(),
+ showInQuickSelector: v.boolean(),
+ },
+ handler: async (ctx, args) => {
+ const user = await requireAuthUser(ctx)
+ if (!args.icon.trim())
+ throw new Error('Icon is required')
+ if (!args.name.trim())
+ throw new Error('Name is required')
+
+ const parentId = args.parentId ?? 0
+
+ await validateNameUniqueness(ctx, args.name, parentId, user._id)
+ if (parentId !== 0)
+ await validateParentId(ctx, parentId, user._id)
+
+ const newId = await ctx.db.insert('categories', {
+ ...args,
+ parentId,
+ updatedAt: Date.now(),
+ userId: user._id,
+ })
+
+ if (parentId !== 0) {
+ const parent = await ctx.db.get(parentId)
+ if (parent && parent.userId === user._id) {
+ await ctx.db.patch(parentId, {
+ childIds: [...(parent.childIds ?? []), newId],
+ })
+ }
+ }
+
+ return newId
+ },
+})
+
+export const update = mutation({
+ args: {
+ childIds: v.optional(v.array(v.id('categories'))),
+ color: v.optional(v.string()),
+ icon: v.optional(v.string()),
+ id: v.id('categories'),
+ name: v.optional(v.string()),
+ parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
+ showInLastUsed: v.optional(v.boolean()),
+ showInQuickSelector: v.optional(v.boolean()),
+ },
+ handler: async (ctx, { id, ...args }) => {
+ const user = await requireAuthUser(ctx)
+ await updateCategoryCore(ctx, id, args, user._id)
+ },
+})
+
+export const remove = mutation({
+ args: { id: v.id('categories') },
+ handler: async (ctx, { id }) => {
+ const user = await requireAuthUser(ctx)
+ const category = await getOwnEntity(ctx, id, user._id)
+
+ if (category.childIds?.length)
+ throw new Error('Cannot delete category with children')
+
+ // Cascade delete all trns in this category (paginated)
+ const deletedIds: string[] = []
+ let cursor: string | null = null
+ let isDone = false
+ while (!isDone) {
+ const page = await ctx.db
+ .query('trns')
+ .withIndex('by_user_category', q => q.eq('userId', user._id).eq('categoryId', id))
+ .paginate({ cursor, numItems: 500 })
+ for (const trn of page.page) {
+ await ctx.db.delete(trn._id)
+ deletedIds.push(trn._id)
+ }
+ isDone = page.isDone
+ cursor = page.continueCursor
+ }
+
+ if (deletedIds.length)
+ await removeTrnsFromHash(ctx, user._id, deletedIds)
+
+ await removeFromParentChildIds(ctx, id, category.parentId, user._id)
+ await ctx.db.delete(id)
+ },
+})
+
+export const updateWithChildren = mutation({
+ args: {
+ childIds: v.array(v.id('categories')),
+ color: v.string(),
+ icon: v.optional(v.string()),
+ id: v.id('categories'),
+ name: v.optional(v.string()),
+ parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
+ showInLastUsed: v.optional(v.boolean()),
+ showInQuickSelector: v.optional(v.boolean()),
+ },
+ handler: async (ctx, { childIds, id, ...args }) => {
+ const user = await requireAuthUser(ctx)
+ const now = await updateCategoryCore(ctx, id, args, user._id)
+
+ for (const childId of childIds) {
+ const child = await ctx.db.get(childId)
+ if (!child || child.userId !== user._id)
+ continue
+ if (child.parentId !== id)
+ throw new Error('Child does not belong to this parent')
+ await ctx.db.patch(childId, { color: args.color, updatedAt: now })
+ }
+ },
+})
diff --git a/convex/convex.config.ts b/convex/convex.config.ts
new file mode 100644
index 00000000..979b556b
--- /dev/null
+++ b/convex/convex.config.ts
@@ -0,0 +1,7 @@
+import betterAuth from '@convex-dev/better-auth/convex.config'
+import { defineApp } from 'convex/server'
+
+const app = defineApp()
+app.use(betterAuth)
+
+export default app
diff --git a/convex/crons.ts b/convex/crons.ts
new file mode 100644
index 00000000..84b8771b
--- /dev/null
+++ b/convex/crons.ts
@@ -0,0 +1,13 @@
+import { cronJobs } from 'convex/server'
+
+import { internal } from './_generated/api'
+
+const crons = cronJobs()
+
+crons.daily(
+ 'fetch exchange rates',
+ { hourUTC: 6, minuteUTC: 0 },
+ internal.rates.fetchAndSaveRates,
+)
+
+export default crons
diff --git a/convex/http.ts b/convex/http.ts
new file mode 100644
index 00000000..6415e11a
--- /dev/null
+++ b/convex/http.ts
@@ -0,0 +1,24 @@
+import { httpRouter } from 'convex/server'
+
+import { authComponent, createAuth } from './auth'
+
+const http = httpRouter()
+
+authComponent.registerRoutes(http, createAuth, {
+ cors: {
+ allowedOrigins: [
+ 'https://finapp.ilko.me',
+ 'https://finapp-git-convex-ilkome2.vercel.app',
+ 'https://main-git-convex-ilkome2.vercel.app',
+ 'https://tacit-kingfisher-781.convex.site',
+ 'https://tacit-kingfisher-781.convex.cloud',
+ 'https://frugal-hornet-995.eu-west-1.convex.site',
+ 'https://frugal-hornet-995.eu-west-1.convex.cloud',
+ 'https://proficient-elk-135.eu-west-1.convex.site',
+ 'https://proficient-elk-135.eu-west-1.convex.cloud',
+ 'http://localhost:3050',
+ ],
+ },
+})
+
+export default http
diff --git a/convex/migrate.ts b/convex/migrate.ts
new file mode 100644
index 00000000..4cb8fd40
--- /dev/null
+++ b/convex/migrate.ts
@@ -0,0 +1,215 @@
+import { v } from 'convex/values'
+
+import { components, internal } from './_generated/api'
+import { internalAction, internalMutation } from './_generated/server'
+import { addTrnsToHash, fnv1aNum, getOrCreateSyncMeta } from './trnsHash'
+
+export const deleteTablePage = internalMutation({
+ args: {
+ table: v.string(),
+ userId: v.string(),
+ },
+ handler: async (ctx, { table, userId }) => {
+ const page = await ctx.db
+ .query(table as 'categories' | 'wallets' | 'trns' | 'userSettings' | 'syncMeta')
+ .withIndex('by_user', q => q.eq('userId', userId))
+ .paginate({ cursor: null, numItems: 500 })
+ for (const row of page.page)
+ await ctx.db.delete(row._id)
+ return { count: page.page.length, hasMore: !page.isDone }
+ },
+})
+
+export const deleteUserData = internalAction({
+ args: {
+ userId: v.string(),
+ },
+ handler: async (ctx, { userId }) => {
+ const tables = ['categories', 'wallets', 'trns', 'userSettings', 'syncMeta'] as const
+ const counts: Record<string, number> = {}
+
+ for (const table of tables) {
+ let total = 0
+ let hasMore = true
+ while (hasMore) {
+ const result = await ctx.runMutation(internal.migrate.deleteTablePage, { table, userId })
+ total += result.count
+ hasMore = result.hasMore
+ }
+ counts[table] = total
+ if (total > 0)
+ console.log(`deleted ${total} rows from ${table}`)
+ }
+
+ console.log('deleteUserData: done', counts)
+ return counts
+ },
+})
+
+export const deleteAuthTablePage = internalMutation({
+ args: {
+ model: v.string(),
+ userId: v.string(),
+ },
+ handler: async (ctx, { model, userId }) => {
+ const field = model === 'user' ? '_id' : 'userId'
+ const result = await ctx.runMutation(components.betterAuth.adapter.deleteMany, {
+ input: {
+ model: model as any,
+ where: [{ field, operator: 'eq', value: userId }],
+ },
+ paginationOpts: { cursor: null, numItems: 500 },
+ })
+ return { count: result?.deletedCount ?? 0 }
+ },
+})
+
+export const deleteUserDataFull = internalAction({
+ args: {
+ userId: v.string(),
+ },
+ handler: async (ctx, { userId }) => {
+ // Delete app tables
+ const appResult = await ctx.runAction(internal.migrate.deleteUserData, { userId })
+ console.log('App data deleted:', appResult)
+
+ // Delete auth tables
+ const authTables = ['session', 'account', 'twoFactor', 'passkey', 'oauthApplication', 'oauthAccessToken', 'oauthConsent', 'user']
+ for (const model of authTables) {
+ const result = await ctx.runMutation(internal.migrate.deleteAuthTablePage, { model, userId })
+ if (result.count > 0)
+ console.log(`Deleted ${result.count} rows from auth:${model}`)
+ }
+
+ console.log('deleteUserDataFull: done for', userId)
+ },
+})
+
+export const insertWallets = internalMutation({
+ args: {
+ userId: v.string(),
+ wallets: v.any(),
+ },
+ handler: async (ctx, { userId, wallets }) => {
+ const idMap: Record<string, string> = {}
+ for (const { oldId, ...data } of wallets) {
+ const id = await ctx.db.insert('wallets', { ...data, userId })
+ idMap[oldId] = id
+ }
+ return idMap
+ },
+})
+
+export const insertCategories = internalMutation({
+ args: {
+ categories: v.any(),
+ userId: v.string(),
+ },
+ handler: async (ctx, { categories, userId }) => {
+ const idMap: Record<string, string> = {}
+ const inserts: Array<{ id: string, oldChildIds?: string[], oldParentId?: string }> = []
+
+ for (const { oldChildIds, oldId, oldParentId, ...data } of categories) {
+ const id = await ctx.db.insert('categories', { ...data, userId })
+ idMap[oldId] = id
+ inserts.push({ id, oldChildIds, oldParentId })
+ }
+
+ for (const { id, oldChildIds, oldParentId } of inserts) {
+ const patch: Record<string, unknown> = {}
+ if (oldParentId && idMap[oldParentId]) {
+ patch.parentId = idMap[oldParentId]
+ }
+ if (oldChildIds && oldChildIds.length > 0) {
+ const mapped = oldChildIds.filter((cid: string) => idMap[cid]).map((cid: string) => idMap[cid])
+ if (mapped.length > 0)
+ patch.childIds = mapped
+ }
+ if (Object.keys(patch).length > 0) {
+ await ctx.db.patch(id as any, patch)
+ }
+ }
+
+ return idMap
+ },
+})
+
+export const insertTrnsBatch = internalMutation({
+ args: {
+ trns: v.any(),
+ userId: v.string(),
+ },
+ handler: async (ctx, { trns, userId }) => {
+ const newIds: string[] = []
+ for (const data of trns) {
+ const id = await ctx.db.insert('trns', { ...data, userId })
+ newIds.push(id)
+ }
+ await addTrnsToHash(ctx, userId, newIds)
+ return (trns as any[]).length
+ },
+})
+
+export const insertUserSettings = internalMutation({
+ args: {
+ baseCurrency: v.string(),
+ locale: v.optional(v.string()),
+ userId: v.string(),
+ },
+ handler: async (ctx, args) => {
+ await ctx.db.insert('userSettings', args)
+ },
+})
+
+export const recalcHashPage = internalMutation({
+ args: {
+ cursor: v.union(v.string(), v.null()),
+ runningHash: v.number(),
+ userId: v.string(),
+ },
+ handler: async (ctx, { cursor, runningHash, userId }) => {
+ const page = await ctx.db
+ .query('trns')
+ .withIndex('by_user', q => q.eq('userId', userId))
+ .paginate({ cursor, numItems: 5000 })
+
+ let hash = runningHash
+ for (const t of page.page)
+ hash = (hash ^ fnv1aNum(t._id)) >>> 0
+
+ if (page.isDone) {
+ const meta = await getOrCreateSyncMeta(ctx, userId)
+ await ctx.db.patch(meta._id, { trnsIdsHash: hash.toString(36) })
+ return { isDone: true as const }
+ }
+
+ return {
+ continueCursor: page.continueCursor,
+ hash,
+ isDone: false as const,
+ }
+ },
+})
+
+export const recalcHashForUser = internalAction({
+ args: { userId: v.string() },
+ handler: async (ctx, { userId }) => {
+ let cursor: string | null = null
+ let hash = 0
+
+ while (true) {
+ const result: { isDone: true } | { continueCursor: string, hash: number, isDone: false }
+ = await ctx.runMutation(internal.migrate.recalcHashPage, {
+ cursor,
+ runningHash: hash,
+ userId,
+ })
+
+ if (result.isDone)
+ break
+
+ cursor = result.continueCursor
+ hash = result.hash
+ }
+ },
+})
diff --git a/convex/rates.ts b/convex/rates.ts
new file mode 100644
index 00000000..7fe4dfcb
--- /dev/null
+++ b/convex/rates.ts
@@ -0,0 +1,76 @@
+import { v } from 'convex/values'
+
+import { internal } from './_generated/api'
+import { action, internalAction, internalMutation, query } from './_generated/server'
+
+const appId = process.env.OPENEXCHANGERATES_APP_ID
+
+export const getLatest = query({
+ args: {},
+ handler: async (ctx) => {
+ return await ctx.db
+ .query('rates')
+ .withIndex('by_date')
+ .order('desc')
+ .first()
+ },
+})
+
+export const getByDate = query({
+ args: { date: v.string() },
+ handler: async (ctx, { date }) => {
+ return await ctx.db
+ .query('rates')
+ .withIndex('by_date', q => q.eq('date', date))
+ .first()
+ },
+})
+
+export const saveRates = internalMutation({
+ args: {
+ date: v.string(),
+ rates: v.any(),
+ },
+ handler: async (ctx, { date, rates }) => {
+ const existing = await ctx.db
+ .query('rates')
+ .withIndex('by_date', q => q.eq('date', date))
+ .first()
+
+ if (existing) {
+ await ctx.db.patch(existing._id, { rates, updatedAt: Date.now() })
+ }
+ else {
+ await ctx.db.insert('rates', { date, rates, updatedAt: Date.now() })
+ }
+ },
+})
+
+export const refreshRates = action({
+ args: {},
+ handler: async (ctx) => {
+ await ctx.runAction(internal.rates.fetchAndSaveRates, {})
+ },
+})
+
+export const fetchAndSaveRates = internalAction({
+ args: {},
+ handler: async (ctx) => {
+ if (!appId) {
+ console.error('OPENEXCHANGERATES_APP_ID not set')
+ return
+ }
+
+ const res = await fetch(
+ `https://openexchangerates.org/api/latest.json?app_id=${appId}`,
+ )
+ const data = await res.json()
+
+ const today = new Date().toISOString().slice(0, 10)
+
+ await ctx.runMutation(internal.rates.saveRates, {
+ date: today,
+ rates: data.rates,
+ })
+ },
+})
diff --git a/convex/schema.ts b/convex/schema.ts
new file mode 100644
index 00000000..ba871f8d
--- /dev/null
+++ b/convex/schema.ts
@@ -0,0 +1,78 @@
+import { defineSchema, defineTable } from 'convex/server'
+import { v } from 'convex/values'
+
+import { TrnType, walletTypeValidator } from './validators'
+
+export default defineSchema({
+ categories: defineTable({
+ childIds: v.optional(v.array(v.id('categories'))),
+ color: v.string(),
+ icon: v.string(),
+ name: v.string(),
+ parentId: v.union(v.id('categories'), v.literal(0)),
+ showInLastUsed: v.boolean(),
+ showInQuickSelector: v.boolean(),
+ updatedAt: v.optional(v.number()),
+ userId: v.string(),
+ })
+ .index('by_user', ['userId'])
+ .index('by_user_name_parent', ['userId', 'name', 'parentId']),
+
+ rates: defineTable({
+ date: v.string(),
+ rates: v.any(),
+ updatedAt: v.number(),
+ }).index('by_date', ['date']),
+
+ syncMeta: defineTable({
+ trnsIdsHash: v.optional(v.string()),
+ userId: v.string(),
+ }).index('by_user', ['userId']),
+
+ trns: defineTable({
+ amount: v.optional(v.number()),
+ categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
+ date: v.number(),
+ desc: v.optional(v.string()),
+ expenseAmount: v.optional(v.number()),
+ expenseWalletId: v.optional(v.id('wallets')),
+ incomeAmount: v.optional(v.number()),
+ incomeWalletId: v.optional(v.id('wallets')),
+ type: v.union(
+ v.literal(TrnType.Expense),
+ v.literal(TrnType.Income),
+ v.literal(TrnType.Transfer),
+ ),
+ updatedAt: v.number(),
+ userId: v.string(),
+ walletId: v.optional(v.id('wallets')),
+ })
+ .index('by_user', ['userId'])
+ .index('by_user_date', ['userId', 'date'])
+ .index('by_user_wallet', ['userId', 'walletId'])
+ .index('by_user_expenseWallet', ['userId', 'expenseWalletId'])
+ .index('by_user_incomeWallet', ['userId', 'incomeWalletId'])
+ .index('by_user_category', ['userId', 'categoryId'])
+ .index('by_user_updatedAt', ['userId', 'updatedAt']),
+
+ userSettings: defineTable({
+ baseCurrency: v.string(),
+ locale: v.optional(v.string()),
+ userId: v.string(),
+ }).index('by_user', ['userId']),
+
+ wallets: defineTable({
+ color: v.string(),
+ creditLimit: v.optional(v.number()),
+ currency: v.string(),
+ desc: v.optional(v.string()),
+ isArchived: v.boolean(),
+ isExcludeInTotal: v.boolean(),
+ isWithdrawal: v.boolean(),
+ name: v.string(),
+ order: v.number(),
+ type: walletTypeValidator,
+ updatedAt: v.optional(v.number()),
+ userId: v.string(),
+ }).index('by_user', ['userId']),
+})
diff --git a/convex/shared.ts b/convex/shared.ts
new file mode 100644
index 00000000..3aa5f5e3
--- /dev/null
+++ b/convex/shared.ts
@@ -0,0 +1,40 @@
+import type { Doc, Id, TableNames } from './_generated/dataModel'
+import type { MutationCtx, QueryCtx } from './_generated/server'
+
+import { authComponent } from './auth'
+
+export { TrnType, walletTypes, walletTypeValidator } from './validators'
+export type { WalletType } from './validators'
+
+/**
+ * Get authenticated user or return null (for queries).
+ */
+export async function getAuthUser(ctx: QueryCtx) {
+ return await authComponent.safeGetAuthUser(ctx)
+}
+
+/**
+ * Get authenticated user or throw (for mutations/actions).
+ */
+export async function requireAuthUser(ctx: QueryCtx) {
+ const user = await authComponent.safeGetAuthUser(ctx)
+ if (!user)
+ throw new Error('Unauthorized')
+ return user
+}
+
+type OwnedTable = {
+ [K in TableNames]: Doc<K> extends { userId: string } ? K : never
+}[TableNames]
+
+export async function getOwnEntity<T extends OwnedTable>(
+ ctx: MutationCtx,
+ id: Id<T>,
+ userId: string,
+ errorMessage = 'Not found',
+): Promise<Doc<T>> {
+ const entity = await ctx.db.get(id)
+ if (!entity || entity.userId !== userId)
+ throw new Error(errorMessage)
+ return entity
+}
diff --git a/convex/trns.ts b/convex/trns.ts
new file mode 100644
index 00000000..7b893e62
--- /dev/null
+++ b/convex/trns.ts
@@ -0,0 +1,200 @@
+import { paginationOptsValidator } from 'convex/server'
+import { v } from 'convex/values'
+
+import type { Id } from './_generated/dataModel'
+import type { MutationCtx } from './_generated/server'
+
+import { internal } from './_generated/api'
+import { mutation, query } from './_generated/server'
+import { getAuthUser, getOwnEntity, requireAuthUser, TrnType } from './shared'
+import { addTrnToHash, fnv1aNum, removeTrnFromHash, removeTrnsFromHash } from './trnsHash'
+
+async function validateTrnFields(ctx: MutationCtx, args: Record<string, any>, userId: string) {
+ if (args.type === TrnType.Transfer) {
+ if (!args.expenseWalletId || !args.incomeWalletId)
+ throw new Error('Transfer requires both wallets')
+ if (args.expenseWalletId === args.incomeWalletId)
+ throw new Error('Transfer wallets must be different')
+ if (!args.expenseAmount || args.expenseAmount <= 0)
+ throw new Error('Transfer expense amount must be positive')
+ if (!args.incomeAmount || args.incomeAmount <= 0)
+ throw new Error('Transfer income amount must be positive')
+ await Promise.all([
+ getOwnEntity(ctx, args.expenseWalletId as Id<'wallets'>, userId, 'Expense wallet not found'),
+ getOwnEntity(ctx, args.incomeWalletId as Id<'wallets'>, userId, 'Income wallet not found'),
+ ])
+ }
+ else {
+ if (!args.amount || args.amount <= 0)
+ throw new Error('Amount must be positive')
+ if (!args.walletId)
+ throw new Error('Wallet is required')
+ if (!args.categoryId)
+ throw new Error('Category is required')
+ await getOwnEntity(ctx, args.walletId as Id<'wallets'>, userId, 'Wallet not found')
+ if (args.categoryId !== 'transfer' && args.categoryId !== 'adjustment')
+ await getOwnEntity(ctx, args.categoryId as Id<'categories'>, userId, 'Category not found')
+ }
+}
+
+const trnTypeValidator = v.union(
+ v.literal(TrnType.Expense),
+ v.literal(TrnType.Income),
+ v.literal(TrnType.Transfer),
+)
+
+export const delta = query({
+ args: { paginationOpts: paginationOptsValidator, since: v.number() },
+ handler: async (ctx, { paginationOpts, since }) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ return ctx.db
+ .query('trns')
+ .withIndex('by_user_updatedAt', q =>
+ q.eq('userId', user._id).gt('updatedAt', since))
+ .paginate(paginationOpts)
+ },
+})
+
+export const ensureSyncMeta = mutation({
+ args: {},
+ handler: async (ctx) => {
+ const user = await requireAuthUser(ctx)
+ const existing = await ctx.db
+ .query('syncMeta')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .first()
+ if (existing?.trnsIdsHash)
+ return
+ await ctx.scheduler.runAfter(0, internal.migrate.recalcHashForUser, { userId: user._id })
+ },
+})
+
+export const idsHash = query({
+ args: {},
+ handler: async (ctx) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ const serverTime = Date.now()
+ const meta = await ctx.db
+ .query('syncMeta')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .first()
+ if (meta?.trnsIdsHash)
+ return { hash: meta.trnsIdsHash, serverTime }
+ // Fallback: compute XOR hash via pagination (before syncMeta row exists)
+ let hash = 0
+ let isDone = false
+ let cursor: string | null = null
+ while (!isDone) {
+ const page = await ctx.db
+ .query('trns')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .paginate({ cursor, numItems: 5000 })
+ for (const t of page.page)
+ hash = (hash ^ fnv1aNum(t._id)) >>> 0
+ isDone = page.isDone
+ cursor = page.continueCursor
+ }
+ return { hash: hash.toString(36), serverTime }
+ },
+})
+
+export const list = query({
+ args: { paginationOpts: paginationOptsValidator },
+ handler: async (ctx, { paginationOpts }) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ return ctx.db
+ .query('trns')
+ .withIndex('by_user_date', q => q.eq('userId', user._id))
+ .order('desc')
+ .paginate(paginationOpts)
+ },
+})
+
+export const create = mutation({
+ args: {
+ amount: v.optional(v.number()),
+ categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
+ date: v.number(),
+ desc: v.optional(v.string()),
+ expenseAmount: v.optional(v.number()),
+ expenseWalletId: v.optional(v.id('wallets')),
+ incomeAmount: v.optional(v.number()),
+ incomeWalletId: v.optional(v.id('wallets')),
+ type: trnTypeValidator,
+ walletId: v.optional(v.id('wallets')),
+ },
+ handler: async (ctx, args) => {
+ const user = await requireAuthUser(ctx)
+ await validateTrnFields(ctx, args, user._id)
+ const id = await ctx.db.insert('trns', {
+ ...args,
+ updatedAt: Date.now(),
+ userId: user._id,
+ })
+ await addTrnToHash(ctx, user._id, id)
+ return id
+ },
+})
+
+export const update = mutation({
+ args: {
+ amount: v.optional(v.number()),
+ categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
+ date: v.optional(v.number()),
+ desc: v.optional(v.string()),
+ expenseAmount: v.optional(v.number()),
+ expenseWalletId: v.optional(v.id('wallets')),
+ id: v.id('trns'),
+ incomeAmount: v.optional(v.number()),
+ incomeWalletId: v.optional(v.id('wallets')),
+ type: v.optional(trnTypeValidator),
+ walletId: v.optional(v.id('wallets')),
+ },
+ handler: async (ctx, { id, ...args }) => {
+ const user = await requireAuthUser(ctx)
+ const trn = await getOwnEntity(ctx, id, user._id)
+ if (args.type !== undefined)
+ await validateTrnFields(ctx, { ...trn, ...args }, user._id)
+ await ctx.db.patch(id, { ...args, updatedAt: Date.now() })
+ },
+})
+
+async function removeUserTrn(ctx: MutationCtx, id: Id<'trns'>, userId: string): Promise<boolean> {
+ const trn = await ctx.db.get(id)
+ if (trn && trn.userId === userId) {
+ await ctx.db.delete(id)
+ return true
+ }
+ return false
+}
+
+export const remove = mutation({
+ args: { id: v.id('trns') },
+ handler: async (ctx, { id }) => {
+ const user = await requireAuthUser(ctx)
+ const deleted = await removeUserTrn(ctx, id, user._id)
+ if (deleted)
+ await removeTrnFromHash(ctx, user._id, id)
+ },
+})
+
+export const removeBatch = mutation({
+ args: { ids: v.array(v.id('trns')) },
+ handler: async (ctx, { ids }) => {
+ const user = await requireAuthUser(ctx)
+ const deletedIds: string[] = []
+ for (const id of ids) {
+ const deleted = await removeUserTrn(ctx, id, user._id)
+ if (deleted)
+ deletedIds.push(id)
+ }
+ if (deletedIds.length)
+ await removeTrnsFromHash(ctx, user._id, deletedIds)
+ },
+})
diff --git a/convex/trnsHash.ts b/convex/trnsHash.ts
new file mode 100644
index 00000000..7af73a96
--- /dev/null
+++ b/convex/trnsHash.ts
@@ -0,0 +1,66 @@
+import type { MutationCtx } from './_generated/server'
+
+export function fnv1aNum(str: string): number {
+ let hash = 0x811C9DC5
+ for (let i = 0; i < str.length; i++) {
+ hash ^= str.charCodeAt(i)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return hash >>> 0
+}
+
+export async function getOrCreateSyncMeta(ctx: MutationCtx, userId: string) {
+ const existing = await ctx.db
+ .query('syncMeta')
+ .withIndex('by_user', q => q.eq('userId', userId))
+ .first()
+ if (existing)
+ return existing
+ const id = await ctx.db.insert('syncMeta', { userId })
+ return (await ctx.db.get(id))!
+}
+
+export async function addTrnToHash(ctx: MutationCtx, userId: string, trnId: string) {
+ const meta = await getOrCreateSyncMeta(ctx, userId)
+ const current = meta.trnsIdsHash ? Number.parseInt(meta.trnsIdsHash, 36) : 0
+ const updated = (current ^ fnv1aNum(trnId)) >>> 0
+ await ctx.db.patch(meta._id, { trnsIdsHash: updated.toString(36) })
+}
+
+export async function removeTrnFromHash(ctx: MutationCtx, userId: string, trnId: string) {
+ await addTrnToHash(ctx, userId, trnId)
+}
+
+export async function addTrnsToHash(ctx: MutationCtx, userId: string, trnIds: string[]) {
+ if (trnIds.length === 0)
+ return
+ const meta = await getOrCreateSyncMeta(ctx, userId)
+ let hash = meta.trnsIdsHash ? Number.parseInt(meta.trnsIdsHash, 36) : 0
+ for (const id of trnIds)
+ hash = (hash ^ fnv1aNum(id)) >>> 0
+ await ctx.db.patch(meta._id, { trnsIdsHash: hash.toString(36) })
+}
+
+export async function removeTrnsFromHash(ctx: MutationCtx, userId: string, trnIds: string[]) {
+ await addTrnsToHash(ctx, userId, trnIds)
+}
+
+export async function recalcTrnsHash(ctx: MutationCtx, userId: string) {
+ let hash = 0
+ let isDone = false
+ let cursor: string | null = null
+
+ while (!isDone) {
+ const page = await ctx.db
+ .query('trns')
+ .withIndex('by_user', q => q.eq('userId', userId))
+ .paginate({ cursor, numItems: 5000 })
+ for (const t of page.page)
+ hash = (hash ^ fnv1aNum(t._id)) >>> 0
+ isDone = page.isDone
+ cursor = page.continueCursor
+ }
+
+ const meta = await getOrCreateSyncMeta(ctx, userId)
+ await ctx.db.patch(meta._id, { trnsIdsHash: hash.toString(36) })
+}
diff --git a/convex/tsconfig.json b/convex/tsconfig.json
new file mode 100644
index 00000000..849f5e16
--- /dev/null
+++ b/convex/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "jsx": "react-jsx",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "types": ["node"],
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true
+ },
+ "include": ["./**/*.ts"]
+}
diff --git a/convex/userSettings.ts b/convex/userSettings.ts
new file mode 100644
index 00000000..a25b88e6
--- /dev/null
+++ b/convex/userSettings.ts
@@ -0,0 +1,61 @@
+import { v } from 'convex/values'
+
+import { internal } from './_generated/api'
+import { action, internalQuery, mutation, query } from './_generated/server'
+import { getAuthUser, requireAuthUser } from './shared'
+
+export const get = query({
+ args: {},
+ handler: async (ctx) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ return await ctx.db
+ .query('userSettings')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .first()
+ },
+})
+
+export const upsert = mutation({
+ args: {
+ baseCurrency: v.optional(v.string()),
+ locale: v.optional(v.string()),
+ },
+ handler: async (ctx, args) => {
+ const user = await requireAuthUser(ctx)
+
+ const existing = await ctx.db
+ .query('userSettings')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .first()
+
+ if (existing) {
+ await ctx.db.patch(existing._id, args)
+ return existing._id
+ }
+
+ return await ctx.db.insert('userSettings', {
+ baseCurrency: args.baseCurrency ?? 'USD',
+ locale: args.locale,
+ userId: user._id,
+ })
+ },
+})
+
+export const removeAllUserData = action({
+ args: {},
+ handler: async (ctx) => {
+ const user = await ctx.runQuery(internal.userSettings.getCurrentUser)
+ if (!user)
+ throw new Error('Unauthorized')
+ await ctx.runAction(internal.migrate.deleteUserData, { userId: user._id })
+ },
+})
+
+export const getCurrentUser = internalQuery({
+ args: {},
+ handler: async (ctx) => {
+ return await getAuthUser(ctx)
+ },
+})
diff --git a/convex/validators.ts b/convex/validators.ts
new file mode 100644
index 00000000..4b500e70
--- /dev/null
+++ b/convex/validators.ts
@@ -0,0 +1,18 @@
+import { v } from 'convex/values'
+
+export const walletTypes = ['cash', 'credit', 'cashless', 'deposit', 'crypto', 'debt'] as const
+export type WalletType = typeof walletTypes[number]
+
+export const walletTypeValidator = v.union(
+ ...walletTypes.map(t => v.literal(t)) as [
+ ReturnType<typeof v.literal>,
+ ReturnType<typeof v.literal>,
+ ...ReturnType<typeof v.literal>[],
+ ],
+)
+
+export enum TrnType {
+ Expense = 0,
+ Income = 1,
+ Transfer = 2,
+}
diff --git a/convex/wallets.ts b/convex/wallets.ts
new file mode 100644
index 00000000..a1437046
--- /dev/null
+++ b/convex/wallets.ts
@@ -0,0 +1,131 @@
+import { v } from 'convex/values'
+
+import { mutation, query } from './_generated/server'
+import { getAuthUser, getOwnEntity, requireAuthUser, walletTypeValidator } from './shared'
+import { removeTrnsFromHash } from './trnsHash'
+
+export const list = query({
+ args: {},
+ handler: async (ctx) => {
+ const user = await getAuthUser(ctx)
+ if (!user)
+ return null
+ return await ctx.db
+ .query('wallets')
+ .withIndex('by_user', q => q.eq('userId', user._id))
+ .collect()
+ },
+})
+
+export const create = mutation({
+ args: {
+ color: v.string(),
+ creditLimit: v.optional(v.number()),
+ currency: v.string(),
+ desc: v.optional(v.string()),
+ isArchived: v.optional(v.boolean()),
+ isExcludeInTotal: v.optional(v.boolean()),
+ isWithdrawal: v.optional(v.boolean()),
+ name: v.string(),
+ order: v.number(),
+ type: walletTypeValidator,
+ },
+ handler: async (ctx, args) => {
+ const user = await requireAuthUser(ctx)
+ if (!args.name.trim())
+ throw new Error('Name is required')
+ return await ctx.db.insert('wallets', {
+ ...args,
+ isArchived: args.isArchived ?? false,
+ isExcludeInTotal: args.isExcludeInTotal ?? false,
+ isWithdrawal: args.isWithdrawal ?? false,
+ updatedAt: Date.now(),
+ userId: user._id,
+ })
+ },
+})
+
+export const update = mutation({
+ args: {
+ color: v.optional(v.string()),
+ creditLimit: v.optional(v.number()),
+ currency: v.optional(v.string()),
+ desc: v.optional(v.string()),
+ id: v.id('wallets'),
+ isArchived: v.optional(v.boolean()),
+ isExcludeInTotal: v.optional(v.boolean()),
+ isWithdrawal: v.optional(v.boolean()),
+ name: v.optional(v.string()),
+ order: v.optional(v.number()),
+ type: v.optional(walletTypeValidator),
+ },
+ handler: async (ctx, { id, ...args }) => {
+ const user = await requireAuthUser(ctx)
+ if (args.name !== undefined && !args.name.trim())
+ throw new Error('Name is required')
+ await getOwnEntity(ctx, id, user._id)
+ await ctx.db.patch(id, { ...args, updatedAt: Date.now() })
+ },
+})
+
+export const updateOrder = mutation({
+ args: {
+ orders: v.array(v.object({
+ id: v.id('wallets'),
+ order: v.number(),
+ })),
+ },
+ handler: async (ctx, { orders }) => {
+ const user = await requireAuthUser(ctx)
+ for (const { id, order } of orders) {
+ await getOwnEntity(ctx, id, user._id)
+ await ctx.db.patch(id, { order, updatedAt: Date.now() })
+ }
+ },
+})
+
+export const remove = mutation({
+ args: { id: v.id('wallets') },
+ handler: async (ctx, { id }) => {
+ const user = await requireAuthUser(ctx)
+ const userId = user._id
+ await getOwnEntity(ctx, id, userId)
+
+ const deletedIds: string[] = []
+ const deletedSet = new Set<string>()
+
+ // Paginated helper to delete trns by index
+ async function deleteTrnsByIndex(indexName: 'by_user_wallet' | 'by_user_expenseWallet' | 'by_user_incomeWallet', fieldValue: typeof id) {
+ let cursor: string | null = null
+ let isDone = false
+ while (!isDone) {
+ const page = await ctx.db
+ .query('trns')
+ .withIndex(indexName, q => q.eq('userId', userId).eq(
+ indexName === 'by_user_wallet' ? 'walletId' : indexName === 'by_user_expenseWallet' ? 'expenseWalletId' : 'incomeWalletId',
+ fieldValue,
+ ))
+ .paginate({ cursor, numItems: 500 })
+ for (const trn of page.page) {
+ if (deletedSet.has(trn._id))
+ continue
+ await ctx.db.delete(trn._id)
+ deletedIds.push(trn._id)
+ deletedSet.add(trn._id)
+ }
+ isDone = page.isDone
+ cursor = page.continueCursor
+ }
+ }
+
+ // Delete regular trns and transfers referencing this wallet
+ await deleteTrnsByIndex('by_user_wallet', id)
+ await deleteTrnsByIndex('by_user_expenseWallet', id)
+ await deleteTrnsByIndex('by_user_incomeWallet', id)
+
+ await ctx.db.delete(id)
+
+ if (deletedIds.length)
+ await removeTrnsFromHash(ctx, userId, deletedIds)
+ },
+})
diff --git a/eslint.config.js b/eslint.config.js
index 4271ec09..d4035945 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -32,4 +32,19 @@ export default [
},
}),
)),
+ {
+ ignores: ['convex/_generated/**', 'docs/**'],
+ },
+ {
+ files: ['convex/**/*.ts', 'scripts/**/*.mjs'],
+ rules: {
+ 'node/prefer-global/process': 'off',
+ },
+ },
+ {
+ files: ['app/layouts/**/*.vue'],
+ rules: {
+ 'vue/no-multiple-template-root': 'off',
+ },
+ },
]
diff --git a/firebase.json b/firebase.json
deleted file mode 100644
index 2c33c295..00000000
--- a/firebase.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "hosting": {
- "public": "dist",
- "ignore": [
- "firebase.json",
- "**/.*",
- "**/node_modules/**"
- ],
- "rewrites": [
- {
- "source": "**",
- "destination": "/index.html"
- }
- ]
- }
-}
diff --git a/i18n/locales/en-US.js b/i18n/locales/en-US.js
index d5ce29f9..052a8a70 100644
--- a/i18n/locales/en-US.js
+++ b/i18n/locales/en-US.js
@@ -7,7 +7,7 @@ export default {
alerts: {
removedUserData: 'All data removed.',
- willDeleteEverything: 'This will delete all your wallets, categories and transactions',
+ willDeleteEverything: 'All data will be permanently deleted, including wallets, categories and transactions',
},
app: {
@@ -26,12 +26,14 @@ export default {
base: {
add: 'Create',
apply: 'Apply',
+ cancel: 'Cancel',
close: 'Close',
delete: 'Delete',
duplicate: 'Duplicate',
edit: 'Edit',
loading: 'Loading...',
no: 'No',
+ noData: 'No data',
save: 'Save',
sure: 'Confirm action',
yes: 'Yes',
@@ -39,7 +41,11 @@ export default {
categories: {
allTitle: 'All',
- createNewTitle: 'Add category',
+ createNewTitle: 'New category',
+ errors: {
+ deleteFailed: 'Failed to delete category',
+ saveFailed: 'Failed to save category',
+ },
favoriteCategories: 'Favorite categories',
filter: 'Filter categories',
form: {
@@ -58,9 +64,9 @@ export default {
placeholder: 'Icon name...',
},
name: {
- error: 'Please enter a category name',
+ error: 'Please enter a name',
exist: 'A category with this name already exists',
- label: 'Category name',
+ label: 'Name',
placeholder: 'Write...',
},
parent: {
@@ -68,8 +74,8 @@ export default {
no: 'Without parent',
},
recentCategory: 'Recent category',
- selectColor: 'Category color',
- selectIcon: 'Category icon',
+ selectColor: 'Color',
+ selectIcon: 'Icon',
selectParent: 'Parent category',
},
name: 'Categories',
@@ -176,6 +182,7 @@ export default {
login: {
description: 'Powerful open-source finance application',
+ error: 'Login failed. Please try again.',
openDemo: 'Open Demo',
or: 'or',
title: 'Login',
@@ -219,6 +226,9 @@ export default {
settings: {
caution: 'With caution',
deleteButton: 'Delete my data',
+ errors: {
+ saveFailed: 'Failed to save settings',
+ },
title: 'Settings',
},
@@ -298,13 +308,13 @@ export default {
dark: 'Dark',
light: 'Light',
picker: {
- neutral: 'Neutral color',
+ neutral: 'Background color',
primary: 'Primary color',
- radius: 'Radius',
+ radius: 'Rounding',
theme: 'Theme',
},
system: 'System',
- title: 'Theme',
+ title: 'Appearance',
},
transfer: {
@@ -312,6 +322,7 @@ export default {
},
trnForm: {
+ adjustmentTitle: 'Adjustment',
category: {
select: 'Select category',
},
@@ -348,6 +359,11 @@ export default {
},
trns: {
+ errors: {
+ deleteFailed: 'Failed to delete transaction',
+ orphanedSkipped: '{count} transactions skipped (wallet or category was deleted)',
+ saveFailed: 'Failed to save transaction',
+ },
filter: {
showTrnsWithDesc: 'Only with description',
},
@@ -361,7 +377,12 @@ export default {
userLogout: 'Logout',
wallets: {
- createNewTitle: 'Add wallet',
+ createNewTitle: 'New wallet',
+ errors: {
+ deleteFailed: 'Failed to delete wallet',
+ orderFailed: 'Failed to save wallet order',
+ saveFailed: 'Failed to save wallet',
+ },
filter: 'Filter wallets',
filterByCurrency: 'Filter by',
form: {
@@ -379,11 +400,12 @@ export default {
okWithTrns: `Wallet deleted and {trns}`,
},
description: {
- label: 'Wallet description (optional)',
+ label: 'Description (optional)',
placeholder: 'Write...',
},
name: {
- label: 'Wallet name',
+ error: 'Please enter a name',
+ label: 'Name',
placeholder: 'Write...',
},
},
@@ -400,10 +422,12 @@ export default {
title: 'Wallets',
},
- welcome: {
- createTrn: 'Create your first Transaction',
- intro: 'To see statistics',
- introCategories: 'To see statistics add your first Category',
- introWallets: 'To see statistics add your first Wallet',
+ onboarding: {
+ actionCategory: 'Add category',
+ actionTrn: 'Add transaction',
+ actionWallet: 'Add wallet',
+ intro: 'Add your first income or expense',
+ introCategories: 'Add a category, for example, "Food" or "Salary"',
+ introWallets: 'Start tracking your finances by adding your first wallet',
},
}
diff --git a/i18n/locales/ru-RU.js b/i18n/locales/ru-RU.js
index c9de8bee..09ecd49b 100644
--- a/i18n/locales/ru-RU.js
+++ b/i18n/locales/ru-RU.js
@@ -7,7 +7,7 @@ export default {
alerts: {
removedUserData: 'Все данные удалены.',
- willDeleteEverything: 'Все кошельки, категории и транзакции будут удалены',
+ willDeleteEverything: 'Все данные будут безвозвратно удалены, включая кошельки, категории и транзакции',
},
app: {
@@ -26,12 +26,14 @@ export default {
base: {
add: 'Создать',
apply: 'Применить',
+ cancel: 'Отмена',
close: 'Закрыть',
delete: 'Удалить',
duplicate: 'Дублировать',
edit: 'Редактировать',
loading: 'Загрузка...',
no: 'Нет',
+ noData: 'Нет данных',
save: 'Сохранить',
sure: 'Удалить?',
yes: 'Да',
@@ -39,7 +41,11 @@ export default {
categories: {
allTitle: 'Все',
- createNewTitle: 'Добавить категорию',
+ createNewTitle: 'Добавление категории',
+ errors: {
+ deleteFailed: 'Не удалось удалить категорию',
+ saveFailed: 'Не удалось сохранить категорию',
+ },
favoriteCategories: 'Избранные категории',
filter: 'Фильтр по категориям',
form: {
@@ -58,9 +64,9 @@ export default {
placeholder: 'Название иконки...',
},
name: {
- error: 'Напишите название категории',
+ error: 'Напишите название',
exist: 'Категория с таким именем уже существует',
- label: 'Название категории',
+ label: 'Название',
placeholder: 'Напишите...',
},
parent: {
@@ -68,8 +74,8 @@ export default {
no: 'Без родителя',
},
recentCategory: 'Показывать в недавно использованных',
- selectColor: 'Цвет категории',
- selectIcon: 'Иконка категории',
+ selectColor: 'Цвет',
+ selectIcon: 'Иконка',
selectParent: 'Родительская категория',
},
name: 'Категории',
@@ -176,6 +182,7 @@ export default {
login: {
description: 'Персональный финансовый ассистент',
+ error: 'Ошибка входа. Попробуйте ещё раз.',
openDemo: 'Открыть демо',
or: 'или',
title: 'Вход',
@@ -219,6 +226,9 @@ export default {
settings: {
caution: 'C осторожностью',
deleteButton: 'Удалить все мои данные',
+ errors: {
+ saveFailed: 'Не удалось сохранить настройки',
+ },
title: 'Настройки',
},
@@ -298,13 +308,13 @@ export default {
dark: 'Темная',
light: 'Светлая',
picker: {
- neutral: 'Нейтральный цвет',
+ neutral: 'Фоновый цвет',
primary: 'Основной цвет',
- radius: 'Радиус',
+ radius: 'Скругление',
theme: 'Тема',
},
system: 'Авто',
- title: 'Тема',
+ title: 'Оформление',
},
transfer: {
@@ -312,6 +322,7 @@ export default {
},
trnForm: {
+ adjustmentTitle: 'Корректировка',
category: {
select: 'Выбрать категорию',
},
@@ -348,6 +359,11 @@ export default {
},
trns: {
+ errors: {
+ deleteFailed: 'Не удалось удалить транзакцию',
+ orphanedSkipped: '{count} транзакций пропущено (кошелёк или категория были удалены)',
+ saveFailed: 'Не удалось сохранить транзакцию',
+ },
filter: {
showTrnsWithDesc: 'Только с описанием',
},
@@ -358,10 +374,15 @@ export default {
title: 'Транзакции',
},
- userLogout: 'Выход',
+ userLogout: 'Выйти из аккаунта',
wallets: {
- createNewTitle: 'Добавить кошелек',
+ createNewTitle: 'Добавление кошелька',
+ errors: {
+ deleteFailed: 'Не удалось удалить кошелек',
+ orderFailed: 'Не удалось сохранить порядок кошельков',
+ saveFailed: 'Не удалось сохранить кошелек',
+ },
filter: 'Фильтровать кошельки',
filterByCurrency: 'Валюты кошельков',
form: {
@@ -379,11 +400,12 @@ export default {
okWithTrns: `Кошелек удален и {trns}`,
},
description: {
- label: 'Описание кошелька (не обязательно)',
+ label: 'Описание (не обязательно)',
placeholder: 'Напишите...',
},
name: {
- label: 'Название кошелька',
+ error: 'Напишите название',
+ label: 'Название',
placeholder: 'Напишите...',
},
},
@@ -400,10 +422,12 @@ export default {
title: 'Кошельки',
},
- welcome: {
- createTrn: 'Создайте свою первую Транзакцию',
- intro: 'Чтобы увидеть статистику',
- introCategories: 'Чтобы увидеть статистику добавьте первую категорию',
- introWallets: 'Чтобы увидеть статистику добавьте первый кошелек',
+ onboarding: {
+ actionCategory: 'Добавить категорию',
+ actionTrn: 'Добавить транзакцию',
+ actionWallet: 'Добавить кошелек',
+ intro: 'Добавьте свой первый доход или расход',
+ introCategories: 'Добавьте категорию, например, «Еда» или «Зарплата»',
+ introWallets: 'Начните учёт финансов, добавив первый кошелёк',
},
}
diff --git a/mocks/trns.ts b/mocks/trns.ts
index 209881e1..605b315a 100644
--- a/mocks/trns.ts
+++ b/mocks/trns.ts
@@ -1,14 +1,14 @@
-import type { TrnId, TrnItemDirty } from '~/components/trns/types'
+import type { TrnId, TrnItem } from '~/components/trns/types'
import { TrnType } from '~/components/trns/types'
-export const trnsItems: Record<TrnId, TrnItemDirty> = {
+export const trnsItems: Record<TrnId, TrnItem> = {
transactionExpenseWalletCashUSD400: {
amount: 400,
categoryId: 'expense',
date: 123456,
- edited: 12,
type: TrnType.Expense,
+ updatedAt: 12,
walletId: 'walletCashUSD',
},
@@ -16,8 +16,8 @@ export const trnsItems: Record<TrnId, TrnItemDirty> = {
amount: 900,
categoryId: 'category1',
date: 123456,
- edited: 12,
type: TrnType.Expense,
+ updatedAt: 12,
walletId: 'walletOneRUB',
},
@@ -25,8 +25,8 @@ export const trnsItems: Record<TrnId, TrnItemDirty> = {
amount: 1000,
categoryId: 'income',
date: 123456,
- edited: 12,
type: TrnType.Income,
+ updatedAt: 12,
walletId: 'walletCashUSD',
},
@@ -34,8 +34,8 @@ export const trnsItems: Record<TrnId, TrnItemDirty> = {
amount: 700,
categoryId: 'category1',
date: 123456,
- edited: 12,
type: TrnType.Income,
+ updatedAt: 12,
walletId: 'walletOneRUB',
},
@@ -43,62 +43,51 @@ export const trnsItems: Record<TrnId, TrnItemDirty> = {
amount: 30,
categoryId: 'transfer',
date: 123456,
- edited: 12,
type: TrnType.Expense,
+ updatedAt: 12,
walletId: 'walletCashUSD',
},
- transferCategoryNameIncomeWalletCashUSD30: {
+ transferCategoryIncomeWalletCashUSD30: {
amount: 30,
- categoryId: 'transfer3',
+ categoryId: 'transfer',
date: 123456,
- edited: 12,
type: TrnType.Income,
+ updatedAt: 12,
walletId: 'walletCashUSD',
},
transferExpenseWalletCashUSD10IncomeWalletRUB700: {
categoryId: 'transfer',
date: 123456,
- edited: 12,
expenseAmount: 10,
expenseWalletId: 'walletCashUSD',
incomeAmount: 700,
incomeWalletId: 'walletRUB',
type: TrnType.Transfer,
+ updatedAt: 12,
},
transferExpenseWalletCreditUSD40IncomeWalletCashUSD40: {
categoryId: 'transfer',
date: 123456,
- edited: 12,
expenseAmount: 40,
expenseWalletId: 'walletCreditUSD',
incomeAmount: 40,
incomeWalletId: 'walletCashUSD',
type: TrnType.Transfer,
+ updatedAt: 12,
},
transferExpenseWalletRUB300IncomeWalletCreditUSD10: {
categoryId: 'transfer',
date: 123456,
- edited: 12,
expenseAmount: 300,
expenseWalletId: 'walletRUB',
incomeAmount: 10,
incomeWalletId: 'walletCreditUSD',
type: TrnType.Transfer,
+ updatedAt: 12,
},
- // @deprecated: use New Transaction type instead or Transfer CategoryId
- transferOLDExpense2500Income3500: {
- amountFrom: 2500,
- amountTo: 3500,
- categoryId: 'transfer',
- date: 123456,
- edited: 12,
- type: TrnType.Transfer,
- walletFromId: 'walletDeprecatedTransferExpense',
- walletToId: 'walletDeprecatedTransferIncome',
- },
}
diff --git a/nuxt.config.ts b/nuxt.config.ts
index ea7caaa6..b35d96e5 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -1,7 +1,5 @@
import process from 'node:process'
-import { config } from './services/firebase/config'
-
const sw = process.env.SW === 'true'
export default defineNuxtConfig({
@@ -92,7 +90,6 @@ export default defineNuxtConfig({
'@pinia/nuxt',
'@vite-pwa/nuxt',
'@nuxt/ui',
- 'nuxt-vuefire',
'@nuxt/eslint',
],
@@ -103,6 +100,7 @@ export default defineNuxtConfig({
pwa: {
client: {
installPrompt: true,
+ registerPlugin: true,
},
devOptions: {
enabled: false,
@@ -161,7 +159,9 @@ export default defineNuxtConfig({
workbox: {
globIgnores: ['**/200*', '**/404*'],
- globPatterns: ['**/*.{js,css,html,png,svg,ico,woff2}'],
+ globPatterns: ['**/*.{js,json,css,html,png,svg,ico,woff2}'],
+ navigateFallback: null,
+ navigateFallbackDenylist: [/^\/auth/, /^\/login/],
runtimeCaching: [{
handler: 'CacheFirst',
urlPattern: 'https://api.iconify.design/',
@@ -177,17 +177,11 @@ export default defineNuxtConfig({
runtimeConfig: {
public: {
- ratesApiKey: process.env.OPEN_EXCHANGE_RATES,
+ convexSiteUrl: process.env.VITE_CONVEX_SITE_URL,
+ convexUrl: process.env.VITE_CONVEX_URL,
},
},
- ssr: false,
+ ssr: true,
telemetry: false,
-
- vuefire: {
- auth: {
- enabled: true,
- },
- config,
- },
})
diff --git a/package.json b/package.json
index 22e8f08f..f6b025eb 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@ilkome/finapp",
"type": "module",
- "version": "6.6.4",
+ "version": "7.0.0-alpha.2",
"packageManager": "[email protected]",
"description": "Finapp helps you easily track and manage personal finances.",
"author": "Ilya Komichev @ilkome",
@@ -9,28 +9,35 @@
"homepage": "https://ilko.me",
"repository": "ilkome/finapp",
"keywords": [
- "vue, nuxt, firebase, tailwind, pwa, echarts, swiper"
+ "vue, nuxt, convex, tailwind, pwa, echarts, swiper"
],
"engines": {
"node": ">=v24.12.0"
},
"scripts": {
- "build": "nuxt generate",
+ "build": "nuxt build",
+ "dev:convex": "npx convex dev",
"dev": "nuxt dev -p 3050 --public",
+ "dev:prod": "nuxt dev -p 3050 --public --dotenv .env.prod",
+ "generate": "nuxt generate",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"preview": "nuxt generate && nuxt preview",
"test": "vitest",
- "test:coverage": "vitest run --coverage"
+ "test:coverage": "vitest run --coverage",
+ "docs:dev": "pnpm --dir docs dev",
+ "docs:build": "pnpm --dir docs build"
},
"dependencies": {
+ "@convex-dev/better-auth": "^0.10.10",
"@formkit/drag-and-drop": "^0.5.3",
"@iconify-json/mdi": "^1.2.3",
"@internationalized/date": "^3.10.0",
"@pinia/nuxt": "^0.11.3",
- "currency.js": "^2.0.4",
+ "better-auth": "^1.4.9",
+ "convex": "^1.22.0",
+ "convex-helpers": "^0.1.111",
"echarts": "^6.0.0",
- "firebase": "^12.6.0",
"fuse.js": "^7.1.0",
"localforage": "^1.10.0",
"pinia": "^3.0.4",
@@ -47,6 +54,7 @@
"@nuxt/eslint": "^1.11.0",
"@nuxt/ui": "^4.2.1",
"@nuxtjs/i18n": "^10.2.1",
+ "@types/node": "^25.2.3",
"@vite-pwa/nuxt": "^1.1.0",
"@vitest/coverage-v8": "^4.0.15",
"@vueuse/core": "^13.9.0",
@@ -62,7 +70,6 @@
"eslint-plugin-perfectionist": "^4.15.1",
"eslint-plugin-tailwindcss": "4.0.0-beta.0",
"nuxt": "^4.2.1",
- "nuxt-vuefire": "^1.1.0",
"prettier": "^3.7.4",
"prettier-plugin-tailwindcss": "^0.7.2",
"tailwind-merge": "^3.4.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 90623c16..1f62b0df 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
+ '@convex-dev/better-auth':
+ specifier: ^0.10.10
'@formkit/drag-and-drop':
specifier: ^0.5.3
version: 0.5.3
@@ -20,15 +23,18 @@ importers:
'@pinia/nuxt':
specifier: ^0.11.3
- currency.js:
- specifier: ^2.0.4
- version: 2.0.4
+ better-auth:
+ specifier: ^1.4.9
+ convex:
+ specifier: ^1.22.0
+ version: 1.31.7([email protected])
+ convex-helpers:
+ specifier: ^0.1.111
echarts:
specifier: ^6.0.0
version: 6.0.0
- firebase:
- specifier: ^12.6.0
- version: 12.6.0
fuse.js:
specifier: ^7.1.0
version: 7.1.0
@@ -46,7 +52,7 @@ importers:
vite:
specifier: ^7.2.6
vue:
specifier: ^3.5.25
version: 3.5.25([email protected])
@@ -59,31 +65,34 @@ importers:
devDependencies:
'@antfu/eslint-config':
specifier: ^6.4.1
'@iconify-json/lucide':
specifier: ^1.2.78
version: 1.2.78
'@nuxt/eslint':
specifier: ^1.11.0
'@nuxt/ui':
specifier: ^4.2.1
'@nuxtjs/i18n':
specifier: ^10.2.1
+ '@types/node':
+ specifier: ^25.2.3
+ version: 25.2.3
'@vite-pwa/nuxt':
specifier: ^1.1.0
'@vitest/coverage-v8':
specifier: ^4.0.15
'@vueuse/core':
specifier: ^13.9.0
'@vueuse/nuxt':
specifier: ^13.9.0
clsx:
specifier: ^2.1.1
version: 2.1.1
@@ -116,10 +125,7 @@ importers:
version: 4.0.0-beta.0([email protected])
nuxt:
specifier: ^4.2.1
- nuxt-vuefire:
- specifier: ^1.1.0
prettier:
specifier: ^3.7.4
version: 3.7.4
@@ -137,7 +143,7 @@ importers:
version: 5.9.3
vitest:
specifier: ^4.0.15
zod:
specifier: ^4.1.13
version: 4.1.13
@@ -289,8 +295,8 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0
- '@babel/[email protected]':
- resolution: {integrity: sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-mOAsxeeKkUKayvZR3HeTYD/fICpCPLJrU5ZjelT/PA6WHtNDBOE436YiaEUvHN454bRM3CebhDsIpieCc4texA==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
@@ -384,8 +390,8 @@ packages:
resolution: {integrity: sha512-PTNtvUQihsAsDHMOP5pfobP8C6CM4JWXmP8DrEIt46c3r2bf87Ua1zoqevsMo9g+tWDwgWrFP5EIxuBx5RudAw==}
engines: {node: '>=6.9.0'}
- '@babel/[email protected]':
- resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-xOBvwq86HHdB7WUDTfKfT/Vuxh7gElQ+Sfti2Cy6yIWNW05P8iUslOVcZ4/sKbE+/jQaukQAdz/gf3724kYdqw==}
engines: {node: '>=6.9.0'}
@@ -398,8 +404,8 @@ packages:
engines: {node: '>=6.0.0'}
hasBin: true
- '@babel/[email protected]':
- resolution: {integrity: sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==}
engines: {node: '>=6.0.0'}
hasBin: true
@@ -781,8 +787,8 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0
- '@babel/[email protected]':
- resolution: {integrity: sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-fNEdfc0yi16lt6IZo2Qxk3knHVdfMYX33czNb4v8yWhemoBhibCpQK/uYHtSKIiO+p/zd3+8fYVXhQdOVV608w==}
engines: {node: '>=6.9.0'}
peerDependencies:
'@babel/core': ^7.0.0-0
@@ -792,8 +798,8 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0-0 || ^8.0.0-0 <8.0.0
- '@babel/[email protected]':
- resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}
engines: {node: '>=6.9.0'}
@@ -828,6 +834,47 @@ packages:
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-q+awYgC7nkLEBdx2sW0iJjkzgSHlIxGnOpsN1r/O1+a4m7osJNHtfK2mKJSL1I+GfNyIlxJF8WvD/NLuYMpmcg==}
+ peerDependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ better-call: 1.1.8
+ jose: ^6.1.0
+ kysely: ^0.28.5
+ nanostores: ^1.0.1
+
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-JT2q4NDkQzN22KclUEoZ7qU6tl9HUTfK1ctg2oWlT87SEagkwJcnrUwS9VznL+u9ziOIfY27P0f7/jSnmvLcoQ==}
+ peerDependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ better-call: 1.1.7
+ jose: ^6.1.0
+ kysely: ^0.28.5
+ nanostores: ^1.0.1
+
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-fPsV0LYbmPytxrTaltM2RXbJnmSttX9UWr4wkZtJYgCBGeFqN8+8ZzBTZXOymWDJTVQ0kVZrD7c7/HyxXEG1zA==}
+ peerDependencies:
+ '@better-auth/core': 1.4.9
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ better-auth: 1.4.9
+ better-call: 1.1.7
+ nanostores: ^1.0.1
+
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-Tthy1/Gmx+pYlbvRQPBTKfVei8+pJwvH1NZp+5SbhwA6K2EXIaoonx/K6N/AXYs2aKUpyR4/gzqDesDjL7zd6A==}
+ peerDependencies:
+ '@better-auth/core': 1.4.9
+
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw==}
+
+ '@better-fetch/[email protected]':
+ resolution: {integrity: sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A==}
+
'@capsizecss/[email protected]':
resolution: {integrity: sha512-8XqW8xGn++Eqqbz3e9wKuK7mxryeRjs4LOHLxbh2lwKeSbuNR4NFifDZT4KzvjU6HMOPbiNTsWpniK5EJfTWkg==}
engines: {node: '>=18'}
@@ -842,6 +889,14 @@ packages:
resolution: {integrity: sha512-+tv3z+SPp+gqTIcImN9o0hqE9xyfQjI1XD9pL6NuKjua9B1y7mNYv0S9cP+QEbA4ppVgGZEmKOvHX5G5Ei1CVA==}
engines: {node: '>=18.0.0'}
+ '@convex-dev/[email protected]':
+ resolution: {integrity: sha512-BpwQ2kph43O7hmtGQAJ+ie3KrjONp83659QDjKDdH+X8yIdGevgehaqS5GHB0iJo7zQTtvs687GnAeLZ4Xx3/w==}
+ peerDependencies:
+ better-auth: 1.4.9
+ convex: ^1.25.0
+ react: ^18.3.1 || ^19.0.0
+ react-dom: ^18.3.1 || ^19.0.0
+
'@dprint/[email protected]':
resolution: {integrity: sha512-N9fxCxbaBOrDkteSOzaCqwWjso5iAe+WJPsHC021JfHNj2ThInPNEF13ORDKta3llq5D1TlclODCvOvipH7bWQ==}
@@ -890,6 +945,12 @@ packages:
cpu: [ppc64]
os: [aix]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==}
engines: {node: '>=18'}
@@ -908,6 +969,12 @@ packages:
cpu: [arm64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==}
engines: {node: '>=18'}
@@ -926,6 +993,12 @@ packages:
cpu: [arm]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==}
engines: {node: '>=18'}
@@ -944,6 +1017,12 @@ packages:
cpu: [x64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==}
engines: {node: '>=18'}
@@ -962,6 +1041,12 @@ packages:
cpu: [arm64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-veg7fL8eMSCVKL7IW4pxb54QERtedFDfY/ASrumK/SbFsXnRazxY4YykN/THYqFnFwJ0aVjiUrVG2PwcdAEqQQ==}
engines: {node: '>=18'}
@@ -980,6 +1065,12 @@ packages:
cpu: [x64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==}
engines: {node: '>=18'}
@@ -998,6 +1089,12 @@ packages:
cpu: [arm64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==}
engines: {node: '>=18'}
@@ -1016,6 +1113,12 @@ packages:
cpu: [x64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==}
engines: {node: '>=18'}
@@ -1034,6 +1137,12 @@ packages:
cpu: [arm64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==}
engines: {node: '>=18'}
@@ -1052,6 +1161,12 @@ packages:
cpu: [arm]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==}
engines: {node: '>=18'}
@@ -1070,6 +1185,12 @@ packages:
cpu: [ia32]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==}
engines: {node: '>=18'}
@@ -1088,6 +1209,12 @@ packages:
cpu: [loong64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==}
engines: {node: '>=18'}
@@ -1106,6 +1233,12 @@ packages:
cpu: [mips64el]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==}
engines: {node: '>=18'}
@@ -1124,6 +1257,12 @@ packages:
cpu: [ppc64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==}
engines: {node: '>=18'}
@@ -1142,6 +1281,12 @@ packages:
cpu: [riscv64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==}
engines: {node: '>=18'}
@@ -1160,6 +1305,12 @@ packages:
cpu: [s390x]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==}
engines: {node: '>=18'}
@@ -1178,6 +1329,12 @@ packages:
cpu: [x64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==}
engines: {node: '>=18'}
@@ -1196,6 +1353,12 @@ packages:
cpu: [arm64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==}
engines: {node: '>=18'}
@@ -1214,6 +1377,12 @@ packages:
cpu: [x64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==}
engines: {node: '>=18'}
@@ -1232,6 +1401,12 @@ packages:
cpu: [arm64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==}
engines: {node: '>=18'}
@@ -1250,6 +1425,12 @@ packages:
cpu: [x64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==}
engines: {node: '>=18'}
@@ -1268,6 +1449,12 @@ packages:
cpu: [arm64]
os: [openharmony]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==}
engines: {node: '>=18'}
@@ -1286,6 +1473,12 @@ packages:
cpu: [x64]
os: [sunos]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==}
engines: {node: '>=18'}
@@ -1304,6 +1497,12 @@ packages:
cpu: [arm64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==}
engines: {node: '>=18'}
@@ -1322,6 +1521,12 @@ packages:
cpu: [ia32]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==}
engines: {node: '>=18'}
@@ -1340,6 +1545,12 @@ packages:
cpu: [x64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==}
engines: {node: '>=18'}
@@ -1412,216 +1623,6 @@ packages:
'@fastify/[email protected]':
resolution: {integrity: sha512-m9FVDXU3GT2ITSe0UaMA5rU3QkfC/UXtCU8y0gSN/GugTqtVldOBWIB5V6V3sbmenVZUIpU6f+mPEO2+m5iTaA==}
- '@firebase/[email protected]':
- resolution: {integrity: sha512-NGyE7NQDFznOv683Xk4+WoUv39iipa9lEfrwvvPz33ChzVbCCiB69FJQTK2BI/11pRtzYGbHo1/xMz7gxWWhJw==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
- '@firebase/app-types': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-fdzoaG0BEKbqksRDhmf4JoyZf16Wosrl0Y7tbZtJyVDOOwziE0vrFjmZuTdviL0yhak+Nco6rMsUUbkbD+qb6Q==}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-VrIp/d8iq2g501qO46uGz3hjbDb8xzYMrbu8Tp0ovzIzrvJZ2fvmj649gTjge/b7cCCcjT0H37g1gVtlNhnkbg==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-3wU676fh60gaiVYQEEXsbGS4HbF2XsiBphyvvqDbtC1U4/dO4coshbYktcCHq+HFaGIK07iHOh4pME0hEq1fcg==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-UfK2Q8RJNjYM/8MFORltZRG9lJj11k0nW84rrffiKvcJxLf1jf6IEjCIkCamykHE73C6BwqhVfhIBs69GXQV0g==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-gAlxfPLT2j8bTI/qfe3ahl2I2YcBQ8cFIBdhAQA4I2f3TndcO+22YizyGYuttLHPQEpWkhmpFW60VCFEPg4g5A==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-hyl5rKSj0QmwPdsAxrI5x1otDlByQ7bvNvVt8G/XPO2CSwE++rmSVf3VEhaeOR4J8ZFaF0Z0NDSmLejPweZ3ng==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-XAvALQayUMBJo58U/rxW02IhsesaxxfWVmVkauZvGEz3vOAjMEQnzFlyblqkc2iAaO82uJ2ZVyZv9XzPfxjJ6w==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-YYGARbutghQY4zZUWMYia0ib0Y/rb52y72/N0z3vglRHL7ii/AaK9SA7S/dzScVOlCdnbHXz+sc5Dq+r8fwFAg==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-kRVpIl4vVGJ4baogMDINbyrIOtOxqhkZQg4jTq3l8Lw6WSk0xfpEYzezFu+Kl4ve4fbPl79dvwRtaFqAC/ucCw==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-4uyt8BOrBsSq6i4yiOV/gG6BnnrvTeyymlNcaN/dKvyU1GoolxAafvIvaNP1RCGPlNab3OuE4MKUQuv2lH+PLQ==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-I0o2ZiZMnMTOQfqT22ur+zcGDVSAfdNZBHo26/Tfi8EllfR1BO7aTVo2rt/ts8o/FWsK8pOALLeVBGhZt8w/vg==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-JPgcXKCuO+CWqGDnigBtvo09HeBs5u/Ktc2GaFj2m01hLarbxthLNm7Fk8iOP1aqAtXV+fnnGj7U28xmk7IwVA==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-S/PuIjni0AQRLF+l9ck0YpsMOdE8GO2KU6ubmBB7P+7TJUCQDa3R1dlgYm9UzGbbePMZsp0xzB93f2b/CgxMOg==}
- peerDependencies:
- '@firebase/app-types': 0.x
- '@firebase/util': 1.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-Mea0G/BwC1D0voSG+60Ylu3KZchXAFilXQ/hJXWCw3gebAu+RDINZA0dJMNeym7HFxBaBaByX8jSa7ys5+F2VA==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
- '@react-native-async-storage/async-storage': ^1.18.1
- peerDependenciesMeta:
- '@react-native-async-storage/async-storage':
- optional: true
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-wR9En2A+WESUHexjmRHkqtaVH94WLNKt6rmeqZhSLBybg4Wyf0Umk04SZsS6sBq4102ZsDBFwoqMqJYj2IoDSg==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-baPddcoNLj/+vYo+HSJidJUdr5W4OkhT109c5qhR8T1dJoZcyJpkv/dFpYlw/VJ3dV66vI8GHQFrmAZw/xUS4g==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-8nYc43RqxScsePVd1qe1xxvWNf0OBnbwHxmXJ7MHSuuTVYFO3eLyLW3PiCKJ9fHnmIz4p4LbieXwz+qtr9PZDg==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-xkQLQfU5De7+SPhEGAXFBnDryUWhhlFXelEg2YeZOQMCdoe7dL64DDAd77SQsR+6uoXIZY5MB4y/inCs4GTfcw==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-gM6MJFae3pTyNLoc9VcJNuaUDej0ctdjn3cVtILo3D5lpp0dmUHHLFN/pUKe7ImyeB1KAvRlEYxvIHNF04Filg==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-cy7ov6SpFBx+PHwFdOOjbI7kH00uNKmIFurAn560WiPCZXy9EMnil1SOG7VF4hHZKdenC+AHtL4r3fNpirpm0w==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-hD2jGdiWRxB/eZWF89xcK9gF8wvENDJkzpVFb4aGkzfEaKxVRD1kjz1t1Wj8VZEp2LCB53Yx1zD8mrhQu87R6Q==}
- peerDependencies:
- '@firebase/app-types': 0.x
- '@firebase/util': 1.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-iuA5+nVr/IV/Thm0Luoqf2mERUvK9g791FZpUJV1ZGXO6RL2/i/WFJUj5ZTVXy5pRjpWYO+ZzPcReNrlilmztA==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-AxxUBXKuPrWaVNQ8o1cG1GaCAtXT8a0eaTDfqgS5VsRYLAR0ALcfqDLwo/QyijZj1w8Qf8n3Qrfy/+Im245hOQ==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-EZoDKQLUHFKNx6VLipQwrSMh01A1SaL3Wg6Hpi//x6/fJ6Ee4hrAeswK99I5Ht8roiniKHw4iO0B1Oxj5I4plg==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-sUeWSb0rw5T+6wuV2o9XNmh9yHxjFI9zVGFnjFi+n7drTEWpl7ZTz1nROgGrSu472r+LAaj+2YaSicD4R8wfbw==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-khfzIY3EI5LePePo7vT19/VEIH1E3iYsHknI/6ek9T8QCozAZshWT9CjlwOzZrKvTHMeNcbpo/VSOSIWDSjWdQ==}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-2FJI7gkLqIE0iYsNQ1P751lO3hER+Umykel+TkLwHj6plzWVxqvfclPUZhcKFVQObqloEBTmpi2Ozn7EkCABAA==}
- peerDependencies:
- '@firebase/app-types': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-nGDmiwKLI1lerhwfwSHvMR9RZuIH5/8E3kgUWnVRqqL7kGVSktjLTWEMva7oh5yxQ3zXfIlIwJwMcaM5bK5j8Q==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-cGskaAvkrnh42b3BA3doDWeBmuHFO/Mx5A83rbRDYakPjO9bJtRL3dX7javzc2Rr/JHZf4HlterTW2lUkfeN4g==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-SN857v/kBUvlQ9X/UjAqBoQ2FEaL1ZozpnmL1ByTe57iXkmnVVFm9KqAsTfmf+OEwWI4kJJe9NObtN/w22lUgg==}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-xfzFaJpzcmtDjycpDeCUj0Ge10ATFi/VHVIvEEjDNc3hodVBQADZ7BWQU7CuFpjSHE+eLuBI13z5F/9xOoGX8Q==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-cfuzv47XxqW4HH/OcR5rM+AlQd1xL/VhuaeW/wzMW1LFrsFcTn0GND/hak1vkQc2th8UisBcrkVcQAnOnKwYxg==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-xLKxaSAl/FVi10wDX/CHIYEUP13jXUjinL+UaNXT9ByIvxII5Ne5150mx6IgM8G6Q3V+sPiw9C8/kygkyHUVxg==}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-IgkyTz6QZVPAq8GSkLYJvwSLr3LS9+V6vNPQr0x4YozZJiLF5jYixj0amDtATf1X0EtYHqoPO48a9ija8GocxQ==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-UzybENl1EdM2I1sjYm74xGt/0JzRnU/0VmfMAKo2LSpHJzaj77FCLZXmYQ4oOuE+Pxtt8Wy2BVJEENiZkaZAzQ==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-P/ULS9vU35EL9maG7xp66uljkZgcPMQOxLj3Zx2F289baTKSInE6+YIkgHEi1TwHoddC/AFePXPpshPlEFkbgg==}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-vI3bqLoF14L/GchtgayMiFpZJF+Ao3uR8WCde0XpYNkSokDpAKca2DxvcfeZv7lZUqkUwQPL2wD83d3vQ4vvrg==}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-dX95X6WlW7QlgNd7aaGdjAIZUiQkgWgNS+aKNu4Wv92H1T8Ue/NDUjZHd9xb8fHxLXIHNZeco9/qbZzr500MjQ==}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-vDzhgGczr1OfcOy285YAPur5pWDEvD67w4thyeCUh6Ys0izN9fNYtA1MJERmNBfqjqu0lg0FM5GLbw0Il21M+g==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app-compat': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-+Muk7g9uwngTpd8xn9OdF/D48uiQ7I1Fae7ULsWPuKoCH3HU7bfFPhxtJYzyhjdniowhuDpQcfPmuNRAqZEfvg==}
- peerDependencies:
- '@firebase/app-types': 0.x
- '@firebase/util': 1.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-xWWbb15o6/pWEw8H01UQ1dC5U3rf8QTAzOChYyCpafV6Xki7KVp3Yaw2nSklUwHEziSWE9KoZJS7iYeyqWnYFA==}
- engines: {node: '>=20.0.0'}
- peerDependencies:
- '@firebase/app': 0.x
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-0AZUyYUfpMNcztR5l09izHwXkZpghLgCUaAGjtMwXnCg3bj4ml5VgiwqOMOxJ+Nw4qN/zJAaOQBcJ7KGkWStqQ==}
- engines: {node: '>=20.0.0'}
-
- '@firebase/[email protected]':
- resolution: {integrity: sha512-+uGNN7rkfn41HLO0vekTFhTxk61eKa8mTpRGLO0QSqlQdKvIoGAvLp3ppdVIWbTGYJWM6Kp0iN+PjMIOcnVqTw==}
-
'@floating-ui/[email protected]':
resolution: {integrity: sha512-wNB5ooIKHQc+Kui96jE/n69rHFWAVoxn5CAzL1Xdd8FG03cgY3MLO+GF9U3W737fYDSgPWA6MReKhBQBop6Pcw==}
@@ -1637,14 +1638,8 @@ packages:
'@formkit/[email protected]':
resolution: {integrity: sha512-VGQsKYc350OOMbz7wYt69YqDbn49x7RJ32eqiJieNke54nGZYmx18XEqTw0lBiJmH3RaiH6V45gB1u+tvI/TNw==}
- resolution: {integrity: sha512-nqE7Hc0AzI+euzUwDAy0aY5hCp10r734gMGRdU+qOPX0XSceI2ULrcXB5U2xSc5VkWwalCj4M7GzCAygZl2KoQ==}
- engines: {node: ^8.13.0 || >=10.10.0}
-
- resolution: {integrity: sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==}
- engines: {node: '>=6'}
- hasBin: true
+ '@hexagon/[email protected]':
+ resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==}
'@humanfs/[email protected]':
resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==}
@@ -1804,6 +1799,9 @@ packages:
'@kwsites/[email protected]':
resolution: {integrity: sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==}
+ '@levischuck/[email protected]':
+ resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==}
+
'@mapbox/[email protected]':
resolution: {integrity: sha512-llMXd39jtP0HpQLVI37Bf1m2ADlEb35GYSh1SDSLsBhR+5iCxiNGlT31yqbNtVHygHAtMy6dWFERpU2JgufhPg==}
engines: {node: '>=18'}
@@ -1828,14 +1826,22 @@ packages:
resolution: {integrity: sha512-5XUvZuffe3KetyhbWwd4n2ktd7wraocCYw10tlM+/u/95iAz29GjNiuNxbCD1T6Bn1MyGc4QLVNKOWhzJkVFAw==}
engines: {node: ^14.16.0 || >=16.0.0}
- '@netlify/[email protected]':
- resolution: {integrity: sha512-QkWQu0vz3uBcxjSslA0N6Njo0x1ndkhEIVEmdwcmxfufX8wA0d9WjiU2sWuHYw11Mrf5pkMUQHvZy+6V4A9TYQ==}
+ '@netlify/[email protected]':
+ resolution: {integrity: sha512-zr8dElQUsZo+gqZh3SA2NYv44IKaASwYBC97pO7sPI9GKaDW6dbeJ8P+fOI3VuQaodQSuIcyda0sM3dZAyqHnA==}
engines: {node: '>=14.8.0'}
'@netlify/[email protected]':
resolution: {integrity: sha512-7/vIJlMYrPJPlEW84V2yeRuG3QBu66dmlv9neTmZ5nXzwylhBEOhy11ai+34A8mHCSZI4mKns25w3HM9kaDdJg==}
engines: {node: '>=16.0.0'}
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==}
+ engines: {node: '>= 20.19.0'}
+
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==}
+ engines: {node: '>= 20.19.0'}
+
'@nodelib/[email protected]':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -1917,10 +1923,6 @@ packages:
resolution: {integrity: sha512-m+XQrgzeK5gQ1HkB7G7u1os6egoD07fiHKijG7NPxqT5yZUGOjKJ7X/Le10l3QWRKyCB+IiU0t+eUqSvh+SULg==}
- resolution: {integrity: sha512-JLno3ur7Pix2o/StxIMlEHRkMawA6h7uzjZBDgxdeKXRWTYY8ID9YekSkN4PBlEFGXBfCBOcPd5+YqcyBUAMkw==}
- engines: {node: '>=18.12.0'}
-
resolution: {integrity: sha512-ze46EW5xW+UxDvinvPkYt2MzR355Az1lA3bpX8KDialgnCwr+IbkBij/udbUEC6ZFbidPkfK1eKl4ESN7gMY+w==}
engines: {node: '>=18.12.0'}
@@ -2576,6 +2578,43 @@ packages:
resolution: {integrity: sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==}
engines: {node: '>= 10.0.0'}
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-7WVNHpWx4qAEzOlnyrRC88kYrwnlR/PrThWT0XI1dSNyUAXu/KBv9oR37uCgYkZroqP5jn8DfzbkNF3BtKvE9w==}
peerDependencies:
@@ -2604,40 +2643,6 @@ packages:
'@poppinss/[email protected]':
resolution: {integrity: sha512-m7bpKCD4QMlFCjA/nKTs23fuvoVFoA83brRKmObCUNmi/9tVu8Ve3w4YQAnJu4q3Tjf5fr685HYIC/IA2zHRSg==}
- '@posva/[email protected]':
- resolution: {integrity: sha512-8rksr4MD7zNltsgerU9sx3OfOo8l9lABXf8/tII6XijgvTqFO+e+P+cSyfSQhAPgi458LMx75kUTLX3Zxwdc+g==}
- engines: {node: 14 || >=16.14}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}
-
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==}
-
'@rolldown/[email protected]':
resolution: {integrity: sha512-NIJgOsMjbxAXvoGq/X0gD7VPMQ8j9g0BiDaNjVNVjvl+iKXxL3Jre0v31RmBYeLEmkbj2s02v8vFTbUXi5XS2Q==}
@@ -2895,6 +2900,13 @@ packages:
cpu: [x64]
os: [win32]
+ '@simplewebauthn/[email protected]':
+ resolution: {integrity: sha512-FNW1oLQpTJyqG5kkDg5ZsotvWgmBaC6jCHR7Ej0qUNep36Wl9tj2eZu7J5rP+uhXgHaLk+QQ3lqcw2vS5MX1IA==}
+
+ '@simplewebauthn/[email protected]':
+ resolution: {integrity: sha512-HcWLW28yTMGXpwE9VLx9J+N2KEUaELadLrkPEEI9tpI5la70xNEVEsu/C+m3u7uoq4FulLqZQhgBCzR9IZhFpA==}
+ engines: {node: '>=20.0.0'}
+
'@sindresorhus/[email protected]':
resolution: {integrity: sha512-TeheYy0ILzBEI/CO55CP6zJCSdSWeRtGnHy8U8dWSUH4I68iqTsy7HkMktR4xakThc9jotkPQUXT4ITdbV7cHA==}
engines: {node: '>=18'}
@@ -2916,6 +2928,9 @@ packages:
'@standard-schema/[email protected]':
resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
'@stylistic/[email protected]':
resolution: {integrity: sha512-JCs+MqoXfXrRPGbGmho/zGS/jMcn3ieKl/A8YImqib76C8kjgZwq5uUFzc30lJkMvcchuRn6/v8IApLxli3Jyw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -3070,8 +3085,8 @@ packages:
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-ut5FthK5moxFKH2T1CUOC6ctR67rQRvvHdFLCD2Ql6KXmMuCrjsSsRI9UsLCm9M18BMwClv4pn327UvB7eeO1w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==}
resolution: {integrity: sha512-EULJ8LApcVEPbrfND0cRQqutIOdiIgJ1Mgrhpy755r14xMohPTEpkV/k28SJvuOs9bHRFW8x+KeDAEPiGQPB9Q==}
@@ -3710,6 +3725,10 @@ packages:
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==}
engines: {node: '>=20.19.0'}
@@ -3749,18 +3768,18 @@ packages:
resolution: {integrity: sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==}
- resolution: {integrity: sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==}
+ resolution: {integrity: sha512-hR3GwrRwHUfYwGfrisXPIDP3JcYfBrW7wKE7+Au6wDYl7fm/ka1NEII6kORzxNU556JjfidZeBsO10kYvtV1aw==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
- resolution: {integrity: sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==}
+ resolution: {integrity: sha512-AvDcMxJ34W4Wgy4KBIIePQTAOP1Ie2WFwkQp3dB7FQ/f0lI5+nM96zUnYEOE1P9sEg0es5VCP0HxiWu5fUHZAQ==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
- resolution: {integrity: sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==}
+ resolution: {integrity: sha512-hYm+XLYRMvupxiQzrvXUj7YyvFFVfv5gI0R71AJzudg1g2AI2vyCPPIFEBjk162/wFzti3inBHo7isWFuEVS/A==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
@@ -3777,14 +3796,84 @@ packages:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
- resolution: {integrity: sha512-sUoJ3IMxx4AyRqO4MLeHlnGDkyXRoUG0/AI9fjK+vS72ekpV0yWVY7O0BVjmBcRtkNcsAO2QDZ4tdKKGoI6YaQ==}
- engines: {node: '>=6.0.0'}
+ resolution: {integrity: sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==}
hasBin: true
- resolution: {integrity: sha512-sXdt2elaVnhpDNRDz+1BDx1JQoJRuNk7oVlAlbGiFkLikHCAQiccexF/9e91zVi6RCgqspl04aP+6Cnl9zRLrA==}
- hasBin: true
+ resolution: {integrity: sha512-usSdjuyTzZwIvM8fjF8YGhPncxV3MAg3dHUO9uPUnf0yklXUSYISiH1+imk6/Z+UBqsscyyPRnbIyjyK97p7YA==}
+ peerDependencies:
+ '@lynx-js/react': '*'
+ '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
+ '@sveltejs/kit': ^2.0.0
+ '@tanstack/react-start': ^1.0.0
+ better-sqlite3: ^12.0.0
+ drizzle-kit: '>=0.31.4'
+ drizzle-orm: '>=0.41.0'
+ mongodb: ^6.0.0 || ^7.0.0
+ mysql2: ^3.0.0
+ next: ^14.0.0 || ^15.0.0 || ^16.0.0
+ pg: ^8.0.0
+ prisma: ^5.0.0 || ^6.0.0 || ^7.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ solid-js: ^1.0.0
+ svelte: ^4.0.0 || ^5.0.0
+ vitest: ^2.0.0 || ^3.0.0 || ^4.0.0
+ vue: ^3.0.0
+ peerDependenciesMeta:
+ '@lynx-js/react':
+ optional: true
+ '@prisma/client':
+ optional: true
+ '@sveltejs/kit':
+ optional: true
+ '@tanstack/react-start':
+ optional: true
+ better-sqlite3:
+ optional: true
+ drizzle-kit:
+ optional: true
+ drizzle-orm:
+ optional: true
+ mongodb:
+ optional: true
+ mysql2:
+ optional: true
+ next:
+ optional: true
+ pg:
+ optional: true
+ prisma:
+ optional: true
+ react:
+ optional: true
+ react-dom:
+ optional: true
+ solid-js:
+ optional: true
+ svelte:
+ optional: true
+ vitest:
+ optional: true
+ vue:
+ optional: true
+
+ resolution: {integrity: sha512-6gaJe1bBIEgVebQu/7q9saahVzvBsGaByEnE8aDVncZEDiJO7sdNB28ot9I6iXSbR25egGmmZ6aIURXyQHRraQ==}
+ peerDependencies:
+ zod: ^4.0.0
+ peerDependenciesMeta:
+ zod:
+ optional: true
+
+ resolution: {integrity: sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw==}
+ peerDependencies:
+ zod: ^4.0.0
+ peerDependenciesMeta:
+ zod:
+ optional: true
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
@@ -3854,14 +3943,6 @@ packages:
peerDependencies:
esbuild: '>=0.18'
- resolution: {integrity: sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==}
- peerDependencies:
- magicast: ^0.3.5
- peerDependenciesMeta:
- magicast:
- optional: true
-
resolution: {integrity: sha512-K9ZkuyeJQeqLEyqldbYLG3wjqwpw4BVaAqvmxq3GYKK0b1A/yYQdIcJxkzAOWcNVWhJpRXAPfZFueekiY/L8Dw==}
peerDependencies:
@@ -3904,11 +3985,8 @@ packages:
resolution: {integrity: sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==}
- resolution: {integrity: sha512-pB68nIHmbN6L/4C6MH1DokyR3bYqFwjaSs/sWDHGj4CTcFtQUQMuJftVwWkXq7mNWOybD3KhUv3oWHoGxgP14Q==}
-
- resolution: {integrity: sha512-44V+Jm6ctPj7R52Na4TLi3Zri4dWUljJd+RDm+j8LtNCc/ihLCT+X1TzoOAkRETEWqjuLnh9581Tl80FvK7jVA==}
+ resolution: {integrity: sha512-x/2CLQ1jHENRbHg5PSId2sXq1CIO1CISvwWAj027ltMVG2UNgW+w9oH2+HzgEIRFembL8bUlXtfbBHR1fCg2xw==}
resolution: {integrity: sha512-RdwNCyMsNBftLjW6w01z8bKEvT6e/5tpPVEgtn22TiLGlstHOVecsX2KHFkD5e/vRnIE4EGzpuIODb3mtswtkw==}
@@ -4027,6 +4105,44 @@ packages:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+ resolution: {integrity: sha512-0O59Ohi8HVc3+KULxSC6JHsw8cQJyc8gZ7OAfNRVX7T5Wy6LhPx3l8veYN9avKg7UiPlO7m1eBiQMHKclIyXyQ==}
+ hasBin: true
+ peerDependencies:
+ '@standard-schema/spec': ^1.0.0
+ convex: ^1.25.4
+ hono: ^4.0.5
+ react: ^17.0.2 || ^18.0.0 || ^19.0.0
+ typescript: ^5.5
+ zod: ^3.25.0 || ^4.0.0
+ peerDependenciesMeta:
+ '@standard-schema/spec':
+ optional: true
+ hono:
+ optional: true
+ react:
+ optional: true
+ typescript:
+ optional: true
+ zod:
+ optional: true
+
+ resolution: {integrity: sha512-PtNMe1mAIOvA8Yz100QTOaIdgt2rIuWqencVXrb4McdhxBHZ8IJ1eXTnrgCC9HydyilGT1pOn+KNqT14mqn9fQ==}
+ engines: {node: '>=18.0.0', npm: '>=7.0.0'}
+ hasBin: true
+ peerDependencies:
+ '@auth0/auth0-react': ^2.0.1
+ '@clerk/clerk-react': ^4.12.8 || ^5.0.0
+ react: ^18.0.0 || ^19.0.0-0 || ^19.0.0
+ peerDependenciesMeta:
+ '@auth0/auth0-react':
+ optional: true
+ '@clerk/clerk-react':
+ optional: true
+ react:
+ optional: true
+
resolution: {integrity: sha512-+W7VmiVINB+ywl1HGXJXmrqkOhpKrIiVZV6tQuV54ZyQC7MMuBt81Vc336GMLoHBq5hV/F9eXgt5Mnx0Rha5Fg==}
@@ -4047,8 +4163,8 @@ packages:
resolution: {integrity: sha512-p9hObIIEENxSV8xIu+V68JjSeARg6UVMG5mR+JEUguG3sI6MsiS1njz2jHmyJDvA+8jX/sytkBHup6kxhM9law==}
- resolution: {integrity: sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==}
+ resolution: {integrity: sha512-OM4cAF3D6VtH/WkLtWvyNC56EZVXsZdU3iqaMG2B4WvYrlqU831pc4UtG5yp0sE9z8Y02wVN7PjW5Zf9Gt0f1Q==}
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
@@ -4128,10 +4244,6 @@ packages:
resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
- resolution: {integrity: sha512-6/OplJYgJ0RUlli74d93HJ/OsKVBi8lB1+Z6eJYS1YZzBuIp4qKKHpJ7ad+GvTlWmLR/hLJOWTykN5Nm8NJ7+w==}
- engines: {node: '>=4'}
-
resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
engines: {node: '>= 12'}
@@ -4329,8 +4441,8 @@ packages:
resolution: {integrity: sha512-Z9oIp4HrFF/cZkDPMpz2XSuVpc1THDpT4dlmATFlJUIBVCy9Vap5/rIXsASP1CscBacBqhabwh8vLctqBwEerQ==}
- resolution: {integrity: sha512-vFU34OcrvMcH66T+dYC3G4nURmgfDVewMIu6Q2urXpumAPSMmzvcn04KVVV8Opikq8Vs5nUbO/8laNhNRqSzYw==}
+ resolution: {integrity: sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==}
resolution: {integrity: sha512-/HrJQOEM6aol/oF33gd2QlINcXy3e19fJWvHDuHWp2bpyTa+2dm9tVVJak30m2Qy6QyQ6Fc8DkImtv7pxWOJUQ==}
@@ -4448,6 +4560,11 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-yY35KZckJJuVVPXpvjgxiCuVEJT67F6zDeVTv4rizyPrfGBUpZQsvmxnN+C371c2esD/hNMjj4tpBhuueLN7aA==}
engines: {node: '>=18'}
@@ -4788,18 +4905,6 @@ packages:
resolution: {integrity: sha512-WtySTkS4OKev5JtpHXnib4Gxiurzh5NCGvWrFaZ34m6JehfTUhKZvn9njTfw48t6JumVQOmrKqpmGcdwxnhqBQ==}
- resolution: {integrity: sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==}
- engines: {node: '>=0.8.0'}
-
- resolution: {integrity: sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==}
- peerDependencies:
- picomatch: ^3 || ^4
- peerDependenciesMeta:
- picomatch:
- optional: true
-
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
engines: {node: '>=12.0.0'}
@@ -4843,9 +4948,6 @@ packages:
resolution: {integrity: sha512-JGG8pvDi2C+JxidYdIwQDyS/CgcrIdh18cvgxcBge3wSHRQOrooMD3GlFBcmMJAN9M42SAZjDp5zv1dglJjwww==}
engines: {node: '>=20'}
- resolution: {integrity: sha512-8ZD1Gcv916Qp8/nsFH2+QMIrfX/76ti6cJwxQUENLXXnKlOX/IJZaU2Y3bdYf5r1mbownrQKfnWtrt+MVgdwLA==}
-
resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==}
engines: {node: '>=16'}
@@ -5086,9 +5188,6 @@ packages:
resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==}
-
resolution: {integrity: sha512-S9wWkJ/VSY9/k4qcjG318bqJNruzE4HySUhFYknwmu6LBP97KLLfwNf+n4V1BHurvFNkSKLFnK/RsuUnRTf9Vw==}
engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}
@@ -5382,6 +5481,9 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
+ resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==}
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -5475,6 +5577,10 @@ packages:
resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}
+ resolution: {integrity: sha512-zpGIFg0HuoC893rIjYX1BETkVWdDnzTzF5e0kWXJFg5lE0k1/LfNWBejrcnOFu8Q2Rfq/hTDTU7XLUM8QOrpzg==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-giOHXoOtifjdHqUamwKq6c49GzBdLjvxrd2D+Q4V6uOHopJv7p9VJxikDsQ/CBXZbEITgUqSVHXLTG3VhPP1Dg==}
@@ -5605,9 +5711,6 @@ packages:
resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==}
- resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==}
-
resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}
@@ -5632,8 +5735,8 @@ packages:
resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}
- resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
+ resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
@@ -5909,8 +6012,12 @@ packages:
engines: {node: ^18 || >=20}
hasBin: true
- resolution: {integrity: sha512-MUrzzDUcIOPbv7ubhDV/L4CIfVTATd9XhDE2ixFeCrM5yp9AlzUpn91JrnN0HD6hksdxvz9IW9aKANz0Bta0GA==}
+ resolution: {integrity: sha512-yJBmDJr18xy47dbNVlHcgdPrulSn1nhSE6Ns9vTG+Nx9VPT6iV1MD6aQFp/t52zpf82FhLLTXAXr30NuCnxvwA==}
+ engines: {node: ^20.0.0 || >=22.0.0}
+
+ resolution: {integrity: sha512-9ca1h0Xjvo9bEkE4UOxgAzLV0jHKe6LMaxo37ND2DAhhAtd0j8pR1Wxz+/goMrZO8AEZTWCmyaOsFI/W5AdpCQ==}
resolution: {integrity: sha512-tWVJxJHmBWLy69PvO96TZMZDrzmw5KeiZBz3RHmiM2XZ9grBJ2WgMAFVVg25nqp3ZjTFUs2Ftw1JhscL3Teliw==}
@@ -6009,22 +6116,6 @@ packages:
resolution: {integrity: sha512-CYZ2WjU+KCyCDVzjYUM4eEpMF0rkPmkpiFrybTqqQCRpUbPt2h3snswWIpFPXTi+osRCY6Og0W/XLAQgDL4FfQ==}
- resolution: {integrity: sha512-Sotrsw94+MvxyI5RQMAkgEbxlSIMUTJILEBOSgvNq/qFSCwzKPLA/Kx7PRCgbcReUffrRklbNbOtXZeSqrxoIg==}
- peerDependencies:
- '@firebase/app-types': '>=0.8.1'
- firebase: ^9.0.0 || ^10.0.0 || ^11.1.0 || ^12.0.0
- firebase-admin: ^11.3.0 || ^12.2.0 || ^13.0.1
- firebase-functions: ^4.1.0 || ^5.0.0 || ^6.1.2
- vuefire: '>=3.2.2'
- peerDependenciesMeta:
- '@firebase/app-types':
- optional: true
- firebase-admin:
- optional: true
- firebase-functions:
- optional: true
-
resolution: {integrity: sha512-OE5ONizgwkKhjTGlUYB3ksE+2q2/I30QIYFl3N1yYz1r2rwhunGA3puUvqkzXwgLQ3AdsNcigPDmyQsqjbSdoQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -6555,10 +6646,6 @@ packages:
resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}
engines: {node: '>= 6'}
- resolution: {integrity: sha512-sildjKwVqOI2kmFDiXQ6aEB0fjYTafpEvIBs8tOR8qI4spuL9OPROLVu2qZqi/xgCfsHIwVqlaF8JBjWFHnKbw==}
- engines: {node: '>=12.0.0'}
-
resolution: {integrity: sha512-hHVTzba3wboROl0/aWRRG9dMytgH6ow//STBZh43l/wQgmMhYhOFi0EHWAPtoCz9IAUymsyP0TSBHkhgMEGNnQ==}
@@ -6566,6 +6653,13 @@ packages:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==}
+
+ resolution: {integrity: sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==}
+ engines: {node: '>=16.0.0'}
+
resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}
engines: {node: '>=0.6'}
@@ -6592,6 +6686,15 @@ packages:
resolution: {integrity: sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==}
+ resolution: {integrity: sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==}
+ peerDependencies:
+ react: ^19.2.4
+
+ resolution: {integrity: sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==}
@@ -6622,6 +6725,9 @@ packages:
resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
+ resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
+
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -6661,6 +6767,9 @@ packages:
peerDependencies:
vue: '>= 3.2.0'
+ resolution: {integrity: sha512-tazDGH7s75kUPGBKLvhgBEHMgW+TdDFhjUAMdQj57IoWz6HsGa5D2RX5yDUz6IIqiRRvZiaEHzCzWdTeixc/Kg==}
+
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -6727,6 +6836,9 @@ packages:
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
+ resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==}
+
resolution: {integrity: sha512-9by4Ij99JUr/MCFBUkDKLWK3G9HVXmabKz9U5MlIAIuvuzkiOicRYs8XJLxX+xahD+mLiiCYDqF9dKAgtzKP1A==}
engines: {node: '>=18'}
@@ -6759,6 +6871,9 @@ packages:
resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}
engines: {node: '>=11.0.0'}
+ resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
+
resolution: {integrity: sha512-3A6sD0WYP7+QrjbfNA2FN3FsOaGGFoekCVgTyypy53gPxhbkCIjtO6YWgdrfM+n/8sI8JeXZOIxsHjMTNxQ4nQ==}
engines: {node: ^14.0.0 || >=16.0.0}
@@ -6798,6 +6913,9 @@ packages:
resolution: {integrity: sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==}
engines: {node: '>= 18'}
+ resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
+
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
engines: {node: '>= 0.4'}
@@ -6996,13 +7114,6 @@ packages:
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-4X2FR3UwhNUE9G49aIsJW5hRRR3GXGTBTZRMfv568O60ojM8HcWjV/VxAxCDW3SUND33O6ZY66ZuRcdkj73q2g==}
- engines: {node: '>=14.16'}
-
- resolution: {integrity: sha512-TcccoMhJOM3OebGhSBEmp3UZ2SfDMZUEBdRA/9ynfLi8yYajyWX3JiXArcJt4Umh4vISpspkQIY8ZZoCqjbviA==}
-
resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
@@ -7116,10 +7227,6 @@ packages:
resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==}
- engines: {node: '>=12.0.0'}
-
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
engines: {node: '>=12.0.0'}
@@ -7169,12 +7276,19 @@ packages:
peerDependencies:
typescript: '>=4.0.0'
+ resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
+
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+ resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==}
+ engines: {node: '>= 6.0.0'}
+
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
engines: {node: '>= 0.8.0'}
@@ -7234,8 +7348,8 @@ packages:
resolution: {integrity: sha512-AbaYw0Nm4mK4qjhns67C+kgxR2YWiwlDBPzxrN8h8C6VtAdCgditAY5Dezu3IJy4XVqAnbrXt9oQJvsn3fyozg==}
- resolution: {integrity: sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==}
+ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
@@ -7276,10 +7390,6 @@ packages:
resolution: {integrity: sha512-5Fx50fFQMQL5aeHyWnZX9122sSLckcDvcfFiBf3QYeHa7a1MKJooUy52b67moi2MJYkrfo/TWY+CoLdr/w0tTA==}
- resolution: {integrity: sha512-bTuAMMOOqIAyjV4i4UH7P07pO+EsVxmhOzQ2YJ290J6mkLUdozNhb5I/YoOEheeNADC03ent3Qj07X0fWfUpmw==}
- engines: {node: '>=18.12.0'}
-
resolution: {integrity: sha512-wMZ2JKUCleCK2zfRHeWcbrUHKXOC3SVBYkyn/wTGzh0THX6sT4hSjuKXxKANN4/WMbT6ZPM4JzcDcnhD2x9Bpg==}
engines: {node: '>=18.12.0'}
@@ -7757,29 +7867,10 @@ packages:
typescript:
optional: true
- resolution: {integrity: sha512-JARgY9HhLs7xrdotQ4QA1SAmFDfSvAwUmOjx9e9lRJnmrsSW7H8ddfCQTVEHhU5NPyPJ/qKBv18Y5N13L60TGg==}
- engines: {node: '>=20'}
- peerDependencies:
- '@vue/composition-api': '*'
- consola: ^3.2.3
- firebase: ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0
- vue: ^2.7.0 || ^3.2.0
- peerDependenciesMeta:
- '@vue/composition-api':
- optional: true
- consola:
- optional: true
- firebase:
- optional: true
-
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
- resolution: {integrity: sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==}
-
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
@@ -7789,14 +7880,6 @@ packages:
resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}
- resolution: {integrity: sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==}
- engines: {node: '>=0.8.0'}
-
- resolution: {integrity: sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==}
- engines: {node: '>=0.8.0'}
-
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
@@ -7987,6 +8070,9 @@ packages:
resolution: {integrity: sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==}
+ resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
+
resolution: {integrity: sha512-41dFXEEXuJpNecuUQq6JlbybmnHaqqpGlbH1yxnA5V9MMP4SbohSVZsJIwz+zdjQXSSlR1Vc34EgH1zxyTDvhg==}
@@ -8002,7 +8088,7 @@ snapshots:
'@jridgewell/gen-mapping': 0.3.12
'@jridgewell/trace-mapping': 0.3.29
dependencies:
'@antfu/install-pkg': 1.1.0
'@clack/prompts': 0.11.0
@@ -8011,7 +8097,7 @@ snapshots:
'@stylistic/eslint-plugin': 5.6.1([email protected]([email protected]))
'@typescript-eslint/parser': 8.48.1([email protected]([email protected]))([email protected])
ansis: 4.2.0
cac: 6.7.14
eslint: 9.39.1([email protected])
@@ -8111,8 +8197,8 @@ snapshots:
'@babel/generator': 7.29.1
'@babel/helper-compilation-targets': 7.28.6
'@babel/helper-module-transforms': 7.28.6(@babel/[email protected])
- '@babel/helpers': 7.29.2
- '@babel/parser': 7.29.2
+ '@babel/helpers': 7.28.6
+ '@babel/parser': 7.29.0
'@babel/template': 7.28.6
'@babel/traverse': 7.29.0
'@babel/types': 7.29.0
@@ -8143,7 +8229,7 @@ snapshots:
dependencies:
- '@babel/parser': 7.29.2
+ '@babel/parser': 7.29.0
'@babel/types': 7.29.0
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
@@ -8202,7 +8288,7 @@ snapshots:
regexpu-core: 6.4.0
semver: 6.3.1
dependencies:
'@babel/core': 7.29.0
'@babel/helper-compilation-targets': 7.28.6
@@ -8324,7 +8410,7 @@ snapshots:
'@babel/template': 7.27.2
'@babel/types': 7.28.4
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/template': 7.28.6
'@babel/types': 7.29.0
@@ -8337,7 +8423,7 @@ snapshots:
dependencies:
'@babel/types': 7.28.5
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/types': 7.29.0
@@ -8750,7 +8836,7 @@ snapshots:
'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
'@babel/helper-plugin-utils': 7.28.6
dependencies:
'@babel/compat-data': 7.29.0
'@babel/core': 7.29.0
@@ -8818,10 +8904,10 @@ snapshots:
'@babel/plugin-transform-unicode-regex': 7.27.1(@babel/[email protected])
'@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/[email protected])
'@babel/preset-modules': 0.1.6-no-external-plugins(@babel/[email protected])
- babel-plugin-polyfill-corejs2: 0.4.17(@babel/[email protected])
- babel-plugin-polyfill-corejs3: 0.14.2(@babel/[email protected])
- babel-plugin-polyfill-regenerator: 0.6.8(@babel/[email protected])
- core-js-compat: 3.49.0
+ babel-plugin-polyfill-corejs2: 0.4.15(@babel/[email protected])
+ babel-plugin-polyfill-corejs3: 0.14.0(@babel/[email protected])
+ babel-plugin-polyfill-regenerator: 0.6.6(@babel/[email protected])
+ core-js-compat: 3.48.0
semver: 6.3.1
transitivePeerDependencies:
- supports-color
@@ -8833,7 +8919,7 @@ snapshots:
'@babel/types': 7.29.0
esutils: 2.0.3
- '@babel/[email protected]': {}
+ '@babel/[email protected]': {}
dependencies:
@@ -8844,7 +8930,7 @@ snapshots:
dependencies:
'@babel/code-frame': 7.29.0
- '@babel/parser': 7.29.2
+ '@babel/parser': 7.29.0
'@babel/types': 7.29.0
@@ -8864,7 +8950,7 @@ snapshots:
'@babel/code-frame': 7.29.0
'@babel/generator': 7.29.1
'@babel/helper-globals': 7.28.0
- '@babel/parser': 7.29.2
+ '@babel/parser': 7.29.0
'@babel/template': 7.28.6
'@babel/types': 7.29.0
debug: 4.4.3
@@ -8888,6 +8974,50 @@ snapshots:
'@bcoe/[email protected]': {}
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ '@standard-schema/spec': 1.1.0
+ better-call: 1.1.8([email protected])
+ jose: 6.1.3
+ kysely: 0.28.11
+ nanostores: 1.1.0
+ zod: 4.3.6
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ '@standard-schema/spec': 1.0.0
+ better-call: 1.1.7([email protected])
+ jose: 6.1.3
+ kysely: 0.28.11
+ nanostores: 1.1.0
+ zod: 4.3.6
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ '@simplewebauthn/browser': 13.2.2
+ '@simplewebauthn/server': 13.2.2
+ better-call: 1.1.8([email protected])
+ nanostores: 1.1.0
+ zod: 4.3.6
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+
+ '@better-auth/[email protected]': {}
+
+ '@better-fetch/[email protected]': {}
+
'@capsizecss/[email protected]':
dependencies:
fontkit: 2.0.4
@@ -8907,6 +9037,30 @@ snapshots:
dependencies:
mime: 3.0.0
+ dependencies:
+ '@better-fetch/fetch': 1.1.21
+ common-tags: 1.8.2
+ convex: 1.31.7([email protected])
+ jose: 6.1.3
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ remeda: 2.33.6
+ semver: 7.7.3
+ type-fest: 4.41.0
+ zod: 4.3.6
+ transitivePeerDependencies:
+ - '@better-auth/core'
+ - '@better-auth/utils'
+ - '@standard-schema/spec'
+ - better-call
+ - hono
+ - nanostores
+ - typescript
+
'@dprint/[email protected]': {}
'@dprint/[email protected]': {}
@@ -8965,6 +9119,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -8974,6 +9131,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -8983,6 +9143,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -8992,6 +9155,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9001,6 +9167,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9010,6 +9179,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9019,6 +9191,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9028,6 +9203,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9037,6 +9215,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9046,6 +9227,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9055,6 +9239,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9064,6 +9251,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9073,6 +9263,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9082,6 +9275,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9091,6 +9287,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9100,6 +9299,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9109,6 +9311,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9118,6 +9323,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9127,6 +9335,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9136,6 +9347,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9145,6 +9359,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9154,6 +9371,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9163,6 +9383,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9172,6 +9395,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9181,6 +9407,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9190,6 +9419,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -9232,372 +9464,54 @@ snapshots:
eslint: 9.39.1([email protected])
h3: 1.15.10
tinyglobby: 0.2.15
- ws: 8.18.3
- transitivePeerDependencies:
- - bufferutil
- - utf-8-validate
-
- '@eslint/[email protected]':
- dependencies:
- '@types/json-schema': 7.0.15
-
- '@eslint/[email protected]':
- dependencies:
- ajv: 6.14.0
- debug: 4.4.3
- espree: 10.4.0
- globals: 14.0.0
- ignore: 5.3.2
- import-fresh: 3.3.1
- js-yaml: 4.1.1
- minimatch: 3.1.5
- strip-json-comments: 3.1.1
- transitivePeerDependencies:
- - supports-color
-
- '@eslint/[email protected]': {}
-
- '@eslint/[email protected]':
- dependencies:
- '@eslint/core': 0.17.0
- '@eslint/plugin-kit': 0.4.1
- github-slugger: 2.0.0
- mdast-util-from-markdown: 2.0.2
- mdast-util-frontmatter: 2.0.1
- mdast-util-gfm: 3.1.0
- micromark-extension-frontmatter: 2.0.0
- micromark-extension-gfm: 3.0.0
- micromark-util-normalize-identifier: 2.0.1
- transitivePeerDependencies:
- - supports-color
-
- '@eslint/[email protected]': {}
-
- '@eslint/[email protected]':
- dependencies:
- '@eslint/core': 0.17.0
- levn: 0.4.1
-
- '@fastify/[email protected]':
- optional: true
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/app-check-interop-types': 0.3.3
- '@firebase/app-types': 0.9.3
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/analytics': 0.10.19(@firebase/[email protected])
- '@firebase/analytics-types': 0.8.3
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-check': 0.11.0(@firebase/[email protected])
- '@firebase/app-check-types': 0.5.3
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- idb: 7.1.1
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/auth': 1.11.1(@firebase/[email protected])
- '@firebase/auth-types': 0.13.0(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/component': 0.7.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
- - '@firebase/app-types'
- - '@react-native-async-storage/async-storage'
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-types': 0.9.3
- '@firebase/util': 1.13.0
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/auth-interop-types': 0.2.4
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/component': 0.7.0
- '@firebase/database': 1.1.0
- '@firebase/database-types': 1.0.16
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/app-types': 0.9.3
- '@firebase/util': 1.13.0
-
- '@firebase/[email protected]':
- dependencies:
- '@firebase/app-check-interop-types': 0.3.3
- '@firebase/auth-interop-types': 0.2.4
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- faye-websocket: 0.11.4
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/firestore': 4.9.2(@firebase/[email protected])
- '@firebase/firestore-types': 3.0.3(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
- - '@firebase/app-types'
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-types': 0.9.3
- '@firebase/util': 1.13.0
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- '@firebase/webchannel-wrapper': 1.0.5
- '@grpc/grpc-js': 1.9.15
- '@grpc/proto-loader': 0.7.15
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/functions': 0.13.1(@firebase/[email protected])
- '@firebase/functions-types': 0.6.3
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/app-check-interop-types': 0.3.3
- '@firebase/auth-interop-types': 0.2.4
- '@firebase/component': 0.7.0
- '@firebase/messaging-interop-types': 0.2.3
- '@firebase/util': 1.13.0
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/installations-types': 0.5.3(@firebase/[email protected])
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
- - '@firebase/app-types'
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app-types': 0.9.3
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/util': 1.13.0
- idb: 7.1.1
- tslib: 2.8.1
-
- '@firebase/[email protected]':
- dependencies:
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/messaging': 0.12.23(@firebase/[email protected])
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
-
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/messaging-interop-types': 0.2.3
- '@firebase/util': 1.13.0
- idb: 7.1.1
- tslib: 2.8.1
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/performance': 0.7.9(@firebase/[email protected])
- '@firebase/performance-types': 0.2.3
- '@firebase/util': 1.13.0
- tslib: 2.8.1
+ ws: 8.18.3
transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
+ - bufferutil
+ - utf-8-validate
- '@firebase/[email protected](@firebase/[email protected])':
+ '@eslint/[email protected]':
dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
- web-vitals: 4.2.4
+ '@types/json-schema': 7.0.15
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
+ '@eslint/[email protected]':
dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/logger': 0.5.0
- '@firebase/remote-config': 0.7.0(@firebase/[email protected])
- '@firebase/remote-config-types': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
+ ajv: 6.14.0
+ debug: 4.4.3
+ espree: 10.4.0
+ globals: 14.0.0
+ ignore: 5.3.2
+ import-fresh: 3.3.1
+ js-yaml: 4.1.1
+ minimatch: 3.1.5
+ strip-json-comments: 3.1.1
transitivePeerDependencies:
- - '@firebase/app'
-
- '@firebase/[email protected]': {}
+ - supports-color
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/logger': 0.5.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
+ '@eslint/[email protected]': {}
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])':
+ '@eslint/[email protected]':
dependencies:
- '@firebase/app-compat': 0.5.6
- '@firebase/component': 0.7.0
- '@firebase/storage': 0.14.0(@firebase/[email protected])
- '@firebase/storage-types': 0.8.3(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/util': 1.13.0
- tslib: 2.8.1
+ '@eslint/core': 0.17.0
+ '@eslint/plugin-kit': 0.4.1
+ github-slugger: 2.0.0
+ mdast-util-from-markdown: 2.0.2
+ mdast-util-frontmatter: 2.0.1
+ mdast-util-gfm: 3.1.0
+ micromark-extension-frontmatter: 2.0.0
+ micromark-extension-gfm: 3.0.0
+ micromark-util-normalize-identifier: 2.0.1
transitivePeerDependencies:
- - '@firebase/app'
- - '@firebase/app-types'
-
- '@firebase/[email protected](@firebase/[email protected])(@firebase/[email protected])':
- dependencies:
- '@firebase/app-types': 0.9.3
- '@firebase/util': 1.13.0
+ - supports-color
- '@firebase/[email protected](@firebase/[email protected])':
- dependencies:
- '@firebase/app': 0.14.6
- '@firebase/component': 0.7.0
- '@firebase/util': 1.13.0
- tslib: 2.8.1
+ '@eslint/[email protected]': {}
- '@firebase/[email protected]':
+ '@eslint/[email protected]':
dependencies:
- tslib: 2.8.1
+ '@eslint/core': 0.17.0
+ levn: 0.4.1
- '@firebase/[email protected]': {}
+ '@fastify/[email protected]':
+ optional: true
'@floating-ui/[email protected]':
dependencies:
@@ -9621,17 +9535,7 @@ snapshots:
'@formkit/[email protected]': {}
- dependencies:
- '@grpc/proto-loader': 0.7.15
- '@types/node': 24.1.0
-
- dependencies:
- lodash.camelcase: 4.3.0
- long: 5.3.2
- protobufjs: 7.5.3
- yargs: 17.7.2
+ '@hexagon/[email protected]': {}
'@humanfs/[email protected]': {}
@@ -9816,6 +9720,8 @@ snapshots:
'@kwsites/[email protected]': {}
+ '@levischuck/[email protected]': {}
+
'@mapbox/[email protected]':
dependencies:
consola: 3.4.2
@@ -9870,12 +9776,16 @@ snapshots:
write-file-atomic: 6.0.0
optional: true
- '@netlify/[email protected]':
+ '@netlify/[email protected]':
optional: true
'@netlify/[email protected]':
optional: true
+ '@noble/[email protected]': {}
+
+ '@noble/[email protected]': {}
+
'@nodelib/[email protected]':
dependencies:
'@nodelib/fs.stat': 2.0.5
@@ -9919,27 +9829,27 @@ snapshots:
'@nuxt/[email protected]': {}
dependencies:
'@nuxt/kit': 3.19.3([email protected])
execa: 8.0.1
transitivePeerDependencies:
- magicast
dependencies:
'@nuxt/kit': 4.2.1([email protected])
execa: 8.0.1
transitivePeerDependencies:
- magicast
dependencies:
'@nuxt/kit': 4.2.1([email protected])
execa: 8.0.1
transitivePeerDependencies:
- magicast
@@ -9954,12 +9864,12 @@ snapshots:
prompts: 2.4.2
semver: 7.7.3
dependencies:
'@nuxt/devtools-wizard': 3.1.0
'@nuxt/kit': 4.2.1([email protected])
'@vue/devtools-kit': 8.0.5
birpc: 2.8.0
consola: 3.4.2
@@ -9984,9 +9894,9 @@ snapshots:
sirv: 3.0.2
structured-clone-es: 1.0.0
tinyglobby: 0.2.15
which: 5.0.0
ws: 8.18.3
transitivePeerDependencies:
@@ -10037,10 +9947,10 @@ snapshots:
- supports-color
- typescript
dependencies:
'@eslint/config-inspector': 1.4.2([email protected]([email protected]))
'@nuxt/eslint-plugin': 1.11.0([email protected]([email protected]))([email protected])
'@nuxt/kit': 4.2.1([email protected])
@@ -10065,17 +9975,17 @@ snapshots:
- utf-8-validate
- vite
dependencies:
'@nuxt/kit': 4.2.1([email protected])
consola: 3.4.2
css-tree: 3.1.0
defu: 6.1.4
esbuild: 0.25.12
fontaine: 0.7.0
- h3: 1.15.10
+ h3: 1.15.4
jiti: 2.6.1
magic-regexp: 0.10.0
magic-string: 0.30.21
@@ -10111,13 +10021,13 @@ snapshots:
- uploadthing
- vite
dependencies:
'@iconify/collections': 1.0.621
'@iconify/types': 2.0.0
'@iconify/utils': 3.0.2
'@iconify/vue': 5.0.0([email protected]([email protected]))
'@nuxt/kit': 4.2.1([email protected])
consola: 3.4.2
local-pkg: 1.1.2
@@ -10133,33 +10043,6 @@ snapshots:
- vite
- vue
- dependencies:
- c12: 3.1.0([email protected])
- consola: 3.4.2
- defu: 6.1.4
- destr: 2.0.5
- errx: 0.1.0
- exsolve: 1.0.7
- ignore: 7.0.5
- jiti: 2.5.1
- klona: 2.0.6
- knitwork: 1.2.0
- mlly: 1.7.4
- ohash: 2.0.11
- pathe: 2.0.3
- pkg-types: 2.2.0
- scule: 1.3.0
- semver: 7.7.2
- std-env: 3.9.0
- tinyglobby: 0.2.14
- ufo: 1.6.1
- unctx: 2.4.1
- unimport: 5.2.0
- untyped: 2.0.0
- transitivePeerDependencies:
- - magicast
-
dependencies:
c12: 3.3.0([email protected])
@@ -10240,7 +10123,7 @@ snapshots:
transitivePeerDependencies:
- magicast
dependencies:
'@nuxt/devalue': 2.0.2
'@nuxt/kit': 4.2.1([email protected])
@@ -10258,7 +10141,7 @@ snapshots:
klona: 2.0.6
mocked-exports: 0.1.1
nitropack: 2.12.9(@netlify/[email protected])
pathe: 2.0.3
pkg-types: 2.3.0
radix3: 1.1.2
@@ -10327,19 +10210,19 @@ snapshots:
transitivePeerDependencies:
- magicast
dependencies:
'@iconify/vue': 5.0.0([email protected]([email protected]))
'@internationalized/date': 3.10.0
'@internationalized/number': 3.6.5
'@nuxt/kit': 4.2.1([email protected])
'@nuxt/schema': 4.2.1
'@nuxtjs/color-mode': 3.5.2([email protected])
'@standard-schema/spec': 1.0.0
'@tailwindcss/postcss': 4.1.17
'@tanstack/vue-table': 8.21.3([email protected]([email protected]))
'@tanstack/vue-virtual': 3.13.12([email protected]([email protected]))
'@unhead/vue': 2.0.19([email protected]([email protected]))
@@ -10360,7 +10243,7 @@ snapshots:
knitwork: 1.3.0
magic-string: 0.30.21
mlly: 1.8.0
ohash: 2.0.11
pathe: 2.0.3
@@ -10372,7 +10255,7 @@ snapshots:
typescript: 5.9.3
unplugin: 2.3.10
vue-component-type-helpers: 3.1.5
optionalDependencies:
@@ -10419,12 +10302,12 @@ snapshots:
- vite
- vue
dependencies:
'@nuxt/kit': 4.2.1([email protected])
'@rollup/plugin-replace': 6.0.3([email protected])
autoprefixer: 10.4.21([email protected])
consola: 3.4.2
cssnano: 7.1.2([email protected])
@@ -10439,7 +10322,7 @@ snapshots:
magic-string: 0.30.21
mlly: 1.8.0
mocked-exports: 0.1.1
pathe: 2.0.3
pkg-types: 2.3.0
postcss: 8.5.6
@@ -10448,9 +10331,9 @@ snapshots:
std-env: 3.10.0
ufo: 1.6.1
unenv: 2.0.0-rc.24
vue: 3.5.25([email protected])
vue-bundle-renderer: 2.2.0
transitivePeerDependencies:
@@ -10853,6 +10736,102 @@ snapshots:
'@parcel/watcher-win32-ia32': 2.5.1
'@parcel/watcher-win32-x64': 2.5.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ '@peculiar/asn1-x509-attr': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.6.0
+ '@peculiar/asn1-pkcs8': 2.6.0
+ '@peculiar/asn1-rsa': 2.6.0
+ '@peculiar/asn1-schema': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.6.0
+ '@peculiar/asn1-pfx': 2.6.0
+ '@peculiar/asn1-pkcs8': 2.6.0
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ '@peculiar/asn1-x509-attr': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ asn1js: 3.0.7
+ pvtsutils: 1.3.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ asn1js: 3.0.7
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.6.0
+ asn1js: 3.0.7
+ pvtsutils: 1.3.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.6.0
+ '@peculiar/asn1-csr': 2.6.0
+ '@peculiar/asn1-ecc': 2.6.0
+ '@peculiar/asn1-pkcs9': 2.6.0
+ '@peculiar/asn1-rsa': 2.6.0
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ pvtsutils: 1.3.6
+ reflect-metadata: 0.2.2
+ tslib: 2.8.1
+ tsyringe: 4.10.0
+
dependencies:
'@nuxt/kit': 4.2.1([email protected])
@@ -10885,31 +10864,6 @@ snapshots:
'@poppinss/[email protected]': {}
- '@posva/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]':
- dependencies:
- '@protobufjs/aspromise': 1.1.2
- '@protobufjs/inquire': 1.1.0
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
- '@protobufjs/[email protected]': {}
-
'@rolldown/[email protected]': {}
'@rolldown/[email protected]': {}
@@ -10918,12 +10872,12 @@ snapshots:
optionalDependencies:
rollup: 4.53.2
dependencies:
'@babel/core': 7.29.0
'@babel/helper-module-imports': 7.28.6
- '@rollup/pluginutils': 3.1.0([email protected])
- rollup: 2.80.0
+ '@rollup/pluginutils': 3.1.0([email protected])
+ rollup: 2.79.2
transitivePeerDependencies:
- supports-color
@@ -10955,7 +10909,7 @@ snapshots:
dependencies:
- '@rollup/pluginutils': 5.3.0([email protected])
+ '@rollup/pluginutils': 5.3.0([email protected])
'@types/resolve': 1.20.2
deepmerge: 4.3.1
is-module: 1.0.0
@@ -11021,8 +10975,8 @@ snapshots:
dependencies:
'@types/estree': 0.0.39
estree-walker: 1.0.1
- picomatch: 2.3.2
- rollup: 2.80.0
+ picomatch: 2.3.1
+ rollup: 2.79.2
dependencies:
@@ -11032,13 +10986,13 @@ snapshots:
optionalDependencies:
rollup: 4.53.2
dependencies:
'@types/estree': 1.0.8
estree-walker: 2.0.2
- picomatch: 4.0.4
+ picomatch: 4.0.3
optionalDependencies:
- rollup: 2.80.0
+ rollup: 2.79.2
'@rollup/[email protected]':
optional: true
@@ -11106,6 +11060,19 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ '@simplewebauthn/[email protected]': {}
+
+ '@simplewebauthn/[email protected]':
+ dependencies:
+ '@hexagon/base64': 1.1.28
+ '@levischuck/tiny-cbor': 0.2.11
+ '@peculiar/asn1-android': 2.6.0
+ '@peculiar/asn1-ecc': 2.6.0
+ '@peculiar/asn1-rsa': 2.6.0
+ '@peculiar/asn1-schema': 2.6.0
+ '@peculiar/asn1-x509': 2.6.0
+ '@peculiar/x509': 1.14.3
+
'@sindresorhus/[email protected]': {}
'@sindresorhus/[email protected]': {}
@@ -11118,6 +11085,8 @@ snapshots:
'@standard-schema/[email protected]': {}
+ '@standard-schema/[email protected]': {}
+
dependencies:
'@eslint-community/eslint-utils': 4.9.0([email protected]([email protected]))
@@ -11208,12 +11177,12 @@ snapshots:
postcss: 8.5.6
tailwindcss: 4.1.17
dependencies:
'@tailwindcss/node': 4.1.17
'@tailwindcss/oxide': 4.1.17
tailwindcss: 4.1.17
'@tanstack/[email protected]': {}
@@ -11256,9 +11225,9 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
- undici-types: 7.8.0
+ undici-types: 7.16.0
dependencies:
@@ -11554,12 +11523,12 @@ snapshots:
- rollup
- supports-color
dependencies:
'@nuxt/kit': 3.19.3([email protected])
pathe: 1.1.2
ufo: 1.6.1
transitivePeerDependencies:
- magicast
- supports-color
@@ -11567,25 +11536,25 @@ snapshots:
- workbox-build
- workbox-window
dependencies:
'@babel/core': 7.28.3
'@babel/plugin-syntax-typescript': 7.27.1(@babel/[email protected])
'@babel/plugin-transform-typescript': 7.28.0(@babel/[email protected])
'@rolldown/pluginutils': 1.0.0-beta.35
'@vue/babel-plugin-jsx': 1.5.0(@babel/[email protected])
vue: 3.5.25([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@rolldown/pluginutils': 1.0.0-beta.29
vue: 3.5.25([email protected])
dependencies:
'@bcoe/v8-coverage': 1.0.2
'@vitest/utils': 4.0.15
@@ -11598,18 +11567,18 @@ snapshots:
obug: 2.1.1
std-env: 3.10.0
tinyrainbow: 3.0.3
transitivePeerDependencies:
- supports-color
dependencies:
'@typescript-eslint/scope-manager': 8.47.0
'@typescript-eslint/utils': 8.47.0([email protected]([email protected]))([email protected])
eslint: 9.39.1([email protected])
optionalDependencies:
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
@@ -11622,13 +11591,13 @@ snapshots:
chai: 6.2.1
tinyrainbow: 3.0.3
dependencies:
'@vitest/spy': 4.0.15
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -11763,14 +11732,14 @@ snapshots:
dependencies:
'@vue/devtools-kit': 7.7.7
dependencies:
'@vue/devtools-kit': 8.0.5
'@vue/devtools-shared': 8.0.5
mitt: 3.0.1
nanoid: 5.1.5
pathe: 2.0.3
vue: 3.5.25([email protected])
transitivePeerDependencies:
- vite
@@ -11885,13 +11854,13 @@ snapshots:
'@vueuse/[email protected]': {}
dependencies:
'@nuxt/kit': 3.19.3([email protected])
'@vueuse/core': 13.9.0([email protected]([email protected]))
'@vueuse/metadata': 13.9.0
local-pkg: 1.1.2
vue: 3.5.25([email protected])
transitivePeerDependencies:
- magicast
@@ -12042,6 +12011,12 @@ snapshots:
get-intrinsic: 1.3.0
is-array-buffer: 3.0.5
+ dependencies:
+ pvtsutils: 1.3.6
+ pvutils: 1.1.5
+ tslib: 2.8.1
+
dependencies:
'@babel/parser': 7.28.5
@@ -12069,7 +12044,7 @@ snapshots:
dependencies:
browserslist: 4.25.1
- caniuse-lite: 1.0.30001727
+ caniuse-lite: 1.0.30001770
fraction.js: 4.3.7
normalize-range: 0.1.2
picocolors: 1.1.1
@@ -12082,27 +12057,27 @@ snapshots:
dependencies:
'@babel/compat-data': 7.29.0
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
+ '@babel/helper-define-polyfill-provider': 0.6.6(@babel/[email protected])
semver: 6.3.1
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
- core-js-compat: 3.49.0
+ '@babel/helper-define-polyfill-provider': 0.6.6(@babel/[email protected])
+ core-js-compat: 3.48.0
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
+ '@babel/helper-define-polyfill-provider': 0.6.6(@babel/[email protected])
transitivePeerDependencies:
- supports-color
@@ -12115,9 +12090,45 @@ snapshots:
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ '@noble/ciphers': 2.1.1
+ '@noble/hashes': 2.0.1
+ better-call: 1.1.7([email protected])
+ defu: 6.1.4
+ jose: 6.1.3
+ kysely: 0.28.11
+ nanostores: 1.1.0
+ zod: 4.3.6
+ optionalDependencies:
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ vue: 3.5.25([email protected])
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ rou3: 0.7.12
+ set-cookie-parser: 2.7.2
+ optionalDependencies:
+ zod: 4.3.6
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.21
+ rou3: 0.7.12
+ set-cookie-parser: 2.7.2
+ optionalDependencies:
+ zod: 4.1.13
dependencies:
@@ -12152,25 +12163,25 @@ snapshots:
dependencies:
- caniuse-lite: 1.0.30001727
+ caniuse-lite: 1.0.30001770
electron-to-chromium: 1.5.191
node-releases: 2.0.19
update-browserslist-db: 1.1.3([email protected])
dependencies:
- baseline-browser-mapping: 2.8.29
- caniuse-lite: 1.0.30001755
+ baseline-browser-mapping: 2.9.19
+ caniuse-lite: 1.0.30001770
electron-to-chromium: 1.5.255
node-releases: 2.0.27
update-browserslist-db: 1.1.4([email protected])
dependencies:
- baseline-browser-mapping: 2.10.10
- caniuse-lite: 1.0.30001781
- electron-to-chromium: 1.5.322
- node-releases: 2.0.36
+ baseline-browser-mapping: 2.9.19
+ caniuse-lite: 1.0.30001770
+ electron-to-chromium: 1.5.286
+ node-releases: 2.0.27
update-browserslist-db: 1.2.3([email protected])
@@ -12193,23 +12204,6 @@ snapshots:
esbuild: 0.27.1
load-tsconfig: 0.2.5
- dependencies:
- chokidar: 4.0.3
- confbox: 0.2.2
- defu: 6.1.4
- dotenv: 16.6.1
- exsolve: 1.0.7
- giget: 2.0.0
- jiti: 2.5.1
- ohash: 2.0.11
- pathe: 2.0.3
- perfect-debounce: 1.0.0
- pkg-types: 2.2.0
- rc9: 2.1.2
- optionalDependencies:
- magicast: 0.5.1
-
dependencies:
chokidar: 4.0.3
@@ -12271,13 +12265,11 @@ snapshots:
dependencies:
browserslist: 4.28.0
- caniuse-lite: 1.0.30001727
+ caniuse-lite: 1.0.30001770
lodash.memoize: 4.1.2
lodash.uniq: 4.5.0
-
@@ -12372,6 +12364,31 @@ snapshots:
+ dependencies:
+ convex: 1.31.7([email protected])
+ optionalDependencies:
+ '@standard-schema/spec': 1.1.0
+ react: 19.2.4
+ typescript: 5.9.3
+ zod: 4.1.13
+
+ dependencies:
+ convex: 1.31.7([email protected])
+ optionalDependencies:
+ '@standard-schema/spec': 1.1.0
+ react: 19.2.4
+ typescript: 5.9.3
+ zod: 4.3.6
+
+ dependencies:
+ esbuild: 0.27.0
+ prettier: 3.7.4
+ optionalDependencies:
+ react: 19.2.4
+
@@ -12390,7 +12407,7 @@ snapshots:
dependencies:
browserslist: 4.28.0
dependencies:
browserslist: 4.28.1
@@ -12493,8 +12510,6 @@ snapshots:
-
optional: true
@@ -12646,7 +12661,7 @@ snapshots:
dependencies:
@@ -12847,6 +12862,35 @@ snapshots:
'@esbuild/win32-ia32': 0.25.12
'@esbuild/win32-x64': 0.25.12
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.27.0
+ '@esbuild/android-arm': 0.27.0
+ '@esbuild/android-arm64': 0.27.0
+ '@esbuild/android-x64': 0.27.0
+ '@esbuild/darwin-arm64': 0.27.0
+ '@esbuild/darwin-x64': 0.27.0
+ '@esbuild/freebsd-arm64': 0.27.0
+ '@esbuild/freebsd-x64': 0.27.0
+ '@esbuild/linux-arm': 0.27.0
+ '@esbuild/linux-arm64': 0.27.0
+ '@esbuild/linux-ia32': 0.27.0
+ '@esbuild/linux-loong64': 0.27.0
+ '@esbuild/linux-mips64el': 0.27.0
+ '@esbuild/linux-ppc64': 0.27.0
+ '@esbuild/linux-riscv64': 0.27.0
+ '@esbuild/linux-s390x': 0.27.0
+ '@esbuild/linux-x64': 0.27.0
+ '@esbuild/netbsd-arm64': 0.27.0
+ '@esbuild/netbsd-x64': 0.27.0
+ '@esbuild/openbsd-arm64': 0.27.0
+ '@esbuild/openbsd-x64': 0.27.0
+ '@esbuild/openharmony-arm64': 0.27.0
+ '@esbuild/sunos-x64': 0.27.0
+ '@esbuild/win32-arm64': 0.27.0
+ '@esbuild/win32-ia32': 0.27.0
+ '@esbuild/win32-x64': 0.27.0
+
optionalDependencies:
'@esbuild/aix-ppc64': 0.27.1
@@ -13294,14 +13338,6 @@ snapshots:
dependencies:
format: 0.2.2
- dependencies:
- websocket-driver: 0.7.4
-
- optionalDependencies:
- picomatch: 4.0.3
-
optionalDependencies:
picomatch: 4.0.3
@@ -13345,39 +13381,6 @@ snapshots:
locate-path: 8.0.0
unicorn-magic: 0.3.0
- dependencies:
- '@firebase/ai': 2.6.0(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/analytics': 0.10.19(@firebase/[email protected])
- '@firebase/analytics-compat': 0.2.25(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/app': 0.14.6
- '@firebase/app-check': 0.11.0(@firebase/[email protected])
- '@firebase/app-check-compat': 0.4.0(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/app-compat': 0.5.6
- '@firebase/app-types': 0.9.3
- '@firebase/auth': 1.11.1(@firebase/[email protected])
- '@firebase/auth-compat': 0.6.1(@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/data-connect': 0.3.12(@firebase/[email protected])
- '@firebase/database': 1.1.0
- '@firebase/database-compat': 2.1.0
- '@firebase/firestore': 4.9.2(@firebase/[email protected])
- '@firebase/firestore-compat': 0.4.2(@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/functions': 0.13.1(@firebase/[email protected])
- '@firebase/functions-compat': 0.4.1(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/installations': 0.6.19(@firebase/[email protected])
- '@firebase/installations-compat': 0.2.19(@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/messaging': 0.12.23(@firebase/[email protected])
- '@firebase/messaging-compat': 0.2.23(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/performance': 0.7.9(@firebase/[email protected])
- '@firebase/performance-compat': 0.2.22(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/remote-config': 0.7.0(@firebase/[email protected])
- '@firebase/remote-config-compat': 0.2.20(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/storage': 0.14.0(@firebase/[email protected])
- '@firebase/storage-compat': 0.4.0(@firebase/[email protected])(@firebase/[email protected])(@firebase/[email protected])
- '@firebase/util': 1.13.0
- transitivePeerDependencies:
- - '@react-native-async-storage/async-storage'
-
dependencies:
flatted: 3.4.2
@@ -13407,7 +13410,7 @@ snapshots:
unicode-properties: 1.4.1
unicode-trie: 2.0.0
dependencies:
consola: 3.4.2
css-tree: 3.1.0
@@ -13423,7 +13426,7 @@ snapshots:
unifont: 0.6.0
optionalDependencies:
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -13463,11 +13466,14 @@ snapshots:
dependencies:
motion-dom: 12.23.12
motion-utils: 12.23.6
tslib: 2.8.1
+ optionalDependencies:
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
@@ -13670,8 +13676,6 @@ snapshots:
statuses: 2.0.1
toidentifier: 1.0.1
-
@@ -13948,13 +13952,15 @@ snapshots:
dependencies:
async: 3.2.6
- filelist: 1.0.6
+ filelist: 1.0.4
picocolors: 1.1.1
+
@@ -14029,6 +14035,8 @@ snapshots:
+
dependencies:
picocolors: 1.1.1
@@ -14152,9 +14160,8 @@ snapshots:
dependencies:
p-locate: 6.0.0
-
+ optional: true
@@ -14172,7 +14179,7 @@ snapshots:
@@ -14611,10 +14618,10 @@ snapshots:
dependencies:
'@vueuse/core': 13.9.0([email protected]([email protected]))
- framer-motion: 12.23.12
hey-listen: 1.0.8
motion-dom: 12.23.12
vue: 3.5.25([email protected])
@@ -14633,7 +14640,9 @@ snapshots:
+
@@ -14643,7 +14652,7 @@ snapshots:
dependencies:
- '@netlify/open-api': 2.52.0
+ '@netlify/open-api': 2.49.0
lodash-es: 4.17.23
micro-api-client: 3.3.0
node-fetch: 3.3.2
@@ -14804,29 +14813,16 @@ snapshots:
- dependencies:
- '@nuxt/kit': 3.17.7([email protected])
- '@posva/lru-cache': 10.0.1
- firebase: 12.6.0
- lodash-es: 4.17.23
- strip-json-comments: 5.0.2
- optionalDependencies:
- '@firebase/app-types': 0.9.3
- transitivePeerDependencies:
- - magicast
-
dependencies:
'@dxup/nuxt': 0.2.2([email protected])
'@nuxt/cli': 3.30.0([email protected])
'@nuxt/kit': 4.2.1([email protected])
'@nuxt/schema': 4.2.1
'@nuxt/telemetry': 2.6.6([email protected])
'@unhead/vue': 2.0.19([email protected]([email protected]))
'@vue/shared': 3.5.24
c12: 3.3.2([email protected])
@@ -14878,7 +14874,7 @@ snapshots:
optionalDependencies:
'@parcel/watcher': 2.5.1
- '@types/node': 24.1.0
+ '@types/node': 25.2.3
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -15449,25 +15445,16 @@ snapshots:
kleur: 3.0.3
sisteransi: 1.0.5
- dependencies:
- '@protobufjs/aspromise': 1.1.2
- '@protobufjs/base64': 1.1.2
- '@protobufjs/codegen': 2.0.4
- '@protobufjs/eventemitter': 1.1.0
- '@protobufjs/fetch': 1.1.0
- '@protobufjs/float': 1.0.2
- '@protobufjs/inquire': 1.1.0
- '@protobufjs/path': 1.1.2
- '@protobufjs/pool': 1.1.0
- '@protobufjs/utf8': 1.1.0
- '@types/node': 24.1.0
- long: 5.3.2
-
+ dependencies:
+ tslib: 2.8.1
+
+
dependencies:
side-channel: 1.1.0
@@ -15492,6 +15479,13 @@ snapshots:
defu: 6.1.4
destr: 2.0.5
+ dependencies:
+ react: 19.2.4
+ scheduler: 0.27.0
+
+
dependencies:
core-util-is: 1.0.3
@@ -15528,6 +15522,8 @@ snapshots:
dependencies:
'@eslint-community/regexpp': 4.12.1
+
dependencies:
call-bind: 1.0.8
@@ -15593,6 +15589,8 @@ snapshots:
- '@vue/composition-api'
- typescript
+
@@ -15664,6 +15662,8 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.53.2
fsevents: 2.3.3
+
@@ -15697,6 +15697,8 @@ snapshots:
+
dependencies:
'@eslint-community/regexpp': 4.12.1
@@ -15746,6 +15748,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
dependencies:
define-data-property: 1.1.4
@@ -15967,12 +15971,6 @@ snapshots:
-
- dependencies:
- js-tokens: 9.0.1
-
dependencies:
js-tokens: 9.0.1
@@ -16080,11 +16078,6 @@ snapshots:
- dependencies:
- fdir: 6.4.6([email protected])
- picomatch: 4.0.3
-
dependencies:
fdir: 6.5.0([email protected])
@@ -16126,18 +16119,23 @@ snapshots:
picomatch: 4.0.3
typescript: 5.9.3
+
+ dependencies:
+ tslib: 1.14.1
+
dependencies:
prelude-ls: 1.2.1
- optional: true
dependencies:
@@ -16202,7 +16200,7 @@ snapshots:
magic-string: 0.30.17
unplugin: 2.3.5
dependencies:
@@ -16244,23 +16242,6 @@ snapshots:
ofetch: 1.5.1
ohash: 2.0.11
- dependencies:
- acorn: 8.15.0
- escape-string-regexp: 5.0.0
- estree-walker: 3.0.3
- local-pkg: 1.1.1
- magic-string: 0.30.17
- mlly: 1.7.4
- pathe: 2.0.3
- picomatch: 4.0.3
- pkg-types: 2.2.0
- scule: 1.3.0
- strip-literal: 3.0.0
- tinyglobby: 0.2.14
- unplugin: 2.3.5
- unplugin-utils: 0.2.4
-
dependencies:
acorn: 8.15.0
@@ -16347,7 +16328,7 @@ snapshots:
pathe: 2.0.3
picomatch: 4.0.3
dependencies:
chokidar: 4.0.3
debug: 4.4.3
@@ -16359,7 +16340,7 @@ snapshots:
unplugin-utils: 0.3.1
vue: 3.5.25([email protected])
optionalDependencies:
- '@babel/parser': 7.29.2
+ '@babel/parser': 7.29.0
'@nuxt/kit': 4.2.1([email protected])
transitivePeerDependencies:
- supports-color
@@ -16548,23 +16529,23 @@ snapshots:
transitivePeerDependencies:
- '@vue/composition-api'
dependencies:
birpc: 2.8.0
dependencies:
dependencies:
cac: 6.7.14
es-module-lexer: 1.7.0
obug: 2.0.0([email protected])
pathe: 2.0.3
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -16579,7 +16560,7 @@ snapshots:
- tsx
- yaml
dependencies:
'@babel/code-frame': 7.27.1
chokidar: 4.0.3
@@ -16588,14 +16569,14 @@ snapshots:
picomatch: 4.0.3
tiny-invariant: 1.3.3
tinyglobby: 0.2.15
vscode-uri: 3.1.0
optionalDependencies:
eslint: 9.39.1([email protected])
optionator: 0.9.4
typescript: 5.9.3
dependencies:
ansis: 4.1.0
debug: 4.4.3
@@ -16605,35 +16586,35 @@ snapshots:
perfect-debounce: 2.0.0
sirv: 3.0.2
unplugin-utils: 0.3.0
optionalDependencies:
'@nuxt/kit': 4.2.1([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
debug: 4.4.3
pretty-bytes: 6.1.1
tinyglobby: 0.2.15
workbox-build: 7.3.0
workbox-window: 7.3.0
transitivePeerDependencies:
- supports-color
dependencies:
estree-walker: 3.0.3
exsolve: 1.0.7
magic-string: 0.30.21
pathe: 2.0.3
source-map-js: 1.2.1
vue: 3.5.25([email protected])
dependencies:
esbuild: 0.25.12
fdir: 6.5.0([email protected])
@@ -16642,17 +16623,17 @@ snapshots:
rollup: 4.53.2
tinyglobby: 0.2.15
optionalDependencies:
- '@types/node': 24.1.0
+ '@types/node': 25.2.3
fsevents: 2.3.3
jiti: 2.6.1
lightningcss: 1.30.2
terser: 5.43.1
yaml: 2.8.2
dependencies:
'@vitest/expect': 4.0.15
'@vitest/pretty-format': 4.0.15
'@vitest/runner': 4.0.15
'@vitest/snapshot': 4.0.15
@@ -16669,11 +16650,11 @@ snapshots:
tinyexec: 1.0.2
tinyglobby: 0.2.15
tinyrainbow: 3.0.3
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
- '@types/node': 24.1.0
+ '@types/node': 25.2.3
transitivePeerDependencies:
- jiti
- less
@@ -16746,33 +16727,15 @@ snapshots:
optionalDependencies:
typescript: 5.9.3
- dependencies:
- vue: 3.5.25([email protected])
- optionalDependencies:
- consola: 3.4.2
- firebase: 12.6.0
-
optional: true
-
- dependencies:
- http-parser-js: 0.5.10
- safe-buffer: 5.2.1
- websocket-extensions: 0.1.4
-
-
dependencies:
tr46: 0.0.3
@@ -16855,12 +16818,12 @@ snapshots:
dependencies:
'@apideck/better-ajv-errors': 0.3.6([email protected])
'@babel/core': 7.29.0
- '@babel/preset-env': 7.29.2(@babel/[email protected])
- '@babel/runtime': 7.29.2
- '@rollup/plugin-babel': 5.3.1(@babel/[email protected])([email protected])
- '@rollup/plugin-node-resolve': 15.3.1([email protected])
- '@rollup/plugin-replace': 2.4.2([email protected])
- '@rollup/plugin-terser': 0.4.4([email protected])
+ '@babel/preset-env': 7.29.0(@babel/[email protected])
+ '@babel/runtime': 7.28.6
+ '@rollup/plugin-babel': 5.3.1(@babel/[email protected])([email protected])
+ '@rollup/plugin-node-resolve': 15.3.1([email protected])
+ '@rollup/plugin-replace': 2.4.2([email protected])
+ '@rollup/plugin-terser': 0.4.4([email protected])
'@surma/rollup-plugin-off-main-thread': 2.2.3
ajv: 8.18.0
common-tags: 1.8.2
@@ -17048,6 +17011,8 @@ snapshots:
+
dependencies:
tslib: 2.3.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
deleted file mode 100644
index efc037aa..00000000
--- a/pnpm-workspace.yaml
+++ /dev/null
@@ -1,2 +0,0 @@
-onlyBuiltDependencies:
- - esbuild
diff --git a/services/convex/api.ts b/services/convex/api.ts
new file mode 100644
index 00000000..a3704a38
--- /dev/null
+++ b/services/convex/api.ts
@@ -0,0 +1,31 @@
+import type { Categories, CategoryItem } from '~/components/categories/types'
+import type { TrnItem, Trns } from '~/components/trns/types'
+import type { WalletItem, Wallets } from '~/components/wallets/types'
+
+type ConvexDoc = {
+ [key: string]: unknown
+ _creationTime: number
+ _id: string
+ userId: string
+}
+
+function arrayToMap<T>(docs: ConvexDoc[]): Record<string, T> {
+ const map: Record<string, T> = {}
+ for (const doc of docs) {
+ const { _creationTime, _id, userId, ...rest } = doc
+ map[_id] = rest as T
+ }
+ return map
+}
+
+export function convexWalletsToMap(wallets: ConvexDoc[]): Wallets {
+ return arrayToMap<WalletItem>(wallets)
+}
+
+export function convexCategoriesToMap(categories: ConvexDoc[]): Categories {
+ return arrayToMap<CategoryItem>(categories)
+}
+
+export function convexTrnsToMap(trns: ConvexDoc[]): Trns {
+ return arrayToMap<TrnItem>(trns)
+}
diff --git a/services/convex/client.ts b/services/convex/client.ts
new file mode 100644
index 00000000..52ffc057
--- /dev/null
+++ b/services/convex/client.ts
@@ -0,0 +1,16 @@
+import { ConvexClient, ConvexHttpClient } from 'convex/browser'
+
+let clientInstance: ConvexClient | null = null
+let httpClientInstance: ConvexHttpClient | null = null
+
+export function createConvexClient(url: string): ConvexClient {
+ if (!clientInstance)
+ clientInstance = new ConvexClient(url)
+ return clientInstance
+}
+
+export function createConvexHttpClient(url: string): ConvexHttpClient {
+ if (!httpClientInstance)
+ httpClientInstance = new ConvexHttpClient(url)
+ return httpClientInstance
+}
diff --git a/services/firebase/api.js b/services/firebase/api.js
deleted file mode 100644
index 9b70090e..00000000
--- a/services/firebase/api.js
+++ /dev/null
@@ -1,44 +0,0 @@
-import { initializeApp } from 'firebase/app'
-import { child, get, getDatabase, off, onValue, ref, remove, set, update } from 'firebase/database'
-import { config } from '~~/services/firebase/config'
-
-export const app = initializeApp(config)
-export const db = getDatabase(app)
-
-export function getDataOnce(path) {
- return new Promise((resolve) => {
- get(child(ref(db), path))
- .then((snapshot) => {
- if (snapshot)
- return resolve(snapshot.val())
- resolve(false)
- })
- .catch((error) => {
- console.log(error.message)
- resolve()
- })
- })
-}
-
-export function getDataAndWatch(path, callback) {
- onValue(ref(db, path), (snapshot) => {
- const data = snapshot.val()
- return callback(data)
- })
-}
-
-export function updateData(path, updates) {
- return update(ref(db, path), updates)
-}
-
-export function removeData(path) {
- return remove(ref(db, path))
-}
-
-export async function saveData(path, value) {
- return await set(ref(db, path), value)
-}
-
-export function unsubscribeData(path) {
- return off(ref(db, path))
-}
diff --git a/services/firebase/config.js b/services/firebase/config.js
deleted file mode 100755
index 57baffa6..00000000
--- a/services/firebase/config.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export const config = {
- apiKey: 'AIzaSyAjJG6UrfA1FEzV8qbjmuk8wiUic0uWv-8',
- appId: '1:1057184379213:web:8c728d0b7099f194',
- authDomain: 'finapp-17474.firebaseapp.com',
- databaseURL: 'https://finapp-17474.firebaseio.com',
- messagingSenderId: '1057184379213',
- projectId: 'finapp-17474',
- storageBucket: 'finapp-17474.appspot.com',
-}
diff --git a/utils/fnv1a.ts b/utils/fnv1a.ts
new file mode 100644
index 00000000..de0d4384
--- /dev/null
+++ b/utils/fnv1a.ts
@@ -0,0 +1,15 @@
+export function fnv1aNum(str: string): number {
+ let hash = 0x811C9DC5
+ for (let i = 0; i < str.length; i++) {
+ hash ^= str.charCodeAt(i)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return hash >>> 0
+}
+
+export function xorIdsHash(ids: string[]): string {
+ let hash = 0
+ for (const id of ids)
+ hash = (hash ^ fnv1aNum(id)) >>> 0
+ return hash.toString(36)
+}
diff --git a/utils/generateId.ts b/utils/generateId.ts
index 8565ac9c..fb2be19c 100644
--- a/utils/generateId.ts
+++ b/utils/generateId.ts
@@ -1,6 +1,4 @@
-import { format } from 'date-fns'
-
export function generateId() {
- const st = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
- return `${format(new Date(), 'yyMMdd')}_${st.slice(0, 6)}`
+ const random = Math.random().toString(36).substring(2, 8)
+ return `local_${random}`
}
diff --git a/utils/migrate/firebase.js b/utils/migrate/firebase.js
new file mode 100644
index 00000000..695f0c2c
--- /dev/null
+++ b/utils/migrate/firebase.js
@@ -0,0 +1,231 @@
+#!/usr/bin/env node
+
+/**
+ * Import Firebase JSON export into Convex.
+ *
+ * Usage:
+ * node utils/migrate/firebase.js <userId> # import to dev
+ * node utils/migrate/firebase.js <userId> --prod # import to prod
+ *
+ * Reads utils/migrate/data.json.
+ * Deletes existing user data before importing.
+ */
+
+import { execSync } from 'node:child_process'
+import { readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import process from 'node:process'
+
+const args = process.argv.slice(2)
+const isProd = args.includes('--prod')
+const USER_ID = args.find(a => !a.startsWith('--'))
+
+if (!USER_ID) {
+ console.error('Usage: node utils/migrate/firebase.js <userId> [--prod]')
+ process.exit(1)
+}
+
+const BATCH_SIZE = 200
+const ENV = isProd ? 'PROD' : 'DEV'
+const JSON_FILE = './utils/migrate/data.json'
+
+console.log(`\n=== Import to ${ENV} (userId: ${USER_ID}) ===\n`)
+
+const data = JSON.parse(readFileSync(JSON_FILE, 'utf8'))
+console.log(`Accounts: ${Object.keys(data.accounts).length}`)
+console.log(`Categories: ${Object.keys(data.categories).length}`)
+console.log(`Trns: ${Object.keys(data.trns).length}`)
+
+const TMP = join(tmpdir(), 'finapp-import')
+execSync(`mkdir -p ${TMP}`)
+
+function runConvex(fnPath, fnArgs) {
+ const flag = isProd ? ' --prod' : ''
+ const argsFile = join(TMP, 'args.json')
+ const outFile = join(TMP, 'out.json')
+ writeFileSync(argsFile, JSON.stringify(fnArgs))
+ const argsStr = readFileSync(argsFile, 'utf-8')
+ const cmd = `npx convex run ${fnPath} '${argsStr}'${flag} > ${outFile} 2>&1`
+ console.log(` convex run ${fnPath}${flag}`)
+
+ try {
+ execSync(cmd, { maxBuffer: 100 * 1024 * 1024, shell: true })
+ }
+ catch (e) {
+ const out = readFileSync(outFile, 'utf-8')
+ console.error('Error output:', out)
+ throw e
+ }
+
+ const stdout = readFileSync(outFile, 'utf-8').trim()
+
+ try {
+ return JSON.parse(stdout)
+ }
+ catch {}
+
+ const jsonStart = stdout.indexOf('{')
+ if (jsonStart !== -1) {
+ try {
+ return JSON.parse(stdout.slice(jsonStart))
+ }
+ catch {}
+ }
+
+ const lines = stdout.split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ try {
+ return JSON.parse(lines[i])
+ }
+ catch {}
+ }
+
+ console.log('stdout:', stdout)
+ return null
+}
+
+function fixIcon(icon) {
+ if (!icon || icon.trim() === '')
+ return 'mdi:category-outline'
+ const match = icon.match(/mdi[- ]mdi-(.+)/)
+ if (match)
+ return `mdi:${match[1]}`
+ return icon
+}
+
+// 0. Delete existing data
+console.log(`\n=== Deleting existing data on ${ENV} ===`)
+const deleted = runConvex('migrate:deleteUserData', { userId: USER_ID })
+console.log('Deleted:', deleted)
+
+// 1. Import wallets
+console.log(`\n=== Importing ${Object.keys(data.accounts).length} wallets ===`)
+const wallets = Object.entries(data.accounts).map(([oldId, w]) => ({
+ color: w.color,
+ currency: w.currency,
+ desc: w.desc || undefined,
+ isArchived: w.isArchived ?? false,
+ isExcludeInTotal: w.isExcludeInTotal ?? false,
+ isWithdrawal: w.isWithdrawal ?? false,
+ name: w.name,
+ oldId,
+ order: w.order ?? 0,
+ type: w.type,
+ updatedAt: w.editedAt ?? Date.now(),
+ ...(w.creditLimit !== undefined ? { creditLimit: w.creditLimit } : {}),
+}))
+
+const walletIdMap = runConvex('migrate:insertWallets', { userId: USER_ID, wallets })
+console.log(`Wallet ID map: ${Object.keys(walletIdMap).length} entries`)
+
+// 2. Import categories
+console.log(`\n=== Importing ${Object.keys(data.categories).length} categories ===`)
+
+const childIdsMap = {}
+for (const [id, cat] of Object.entries(data.categories)) {
+ if (cat.parentId && cat.parentId !== 0) {
+ if (!childIdsMap[cat.parentId])
+ childIdsMap[cat.parentId] = []
+ childIdsMap[cat.parentId].push(id)
+ }
+}
+
+const categories = Object.entries(data.categories).map(([oldId, c]) => ({
+ color: c.color,
+ icon: fixIcon(c.icon),
+ name: c.name,
+ oldChildIds: childIdsMap[oldId] || [],
+ oldId,
+ oldParentId: c.parentId === 0 ? undefined : c.parentId ? String(c.parentId) : undefined,
+ parentId: 0,
+ showInLastUsed: c.showInLastUsed ?? false,
+ showInQuickSelector: c.showInQuickSelector ?? false,
+ updatedAt: c.edited,
+}))
+
+const categoryIdMap = runConvex('migrate:insertCategories', { categories, userId: USER_ID })
+console.log(`Category ID map: ${Object.keys(categoryIdMap).length} entries`)
+
+// 3. Import trns
+const allTrns = Object.entries(data.trns).map(([_oldId, t]) => {
+ const trn = {
+ date: t.date,
+ type: t.type,
+ updatedAt: t.edited,
+ }
+
+ if (t.desc)
+ trn.desc = t.desc
+ if (t.amount !== undefined)
+ trn.amount = t.amount
+
+ // Map wallet IDs (handle old walletFromId/walletToId format)
+ const expenseWalletId = t.expenseWalletId || t.walletFromId
+ const incomeWalletId = t.incomeWalletId || t.walletToId
+
+ if (expenseWalletId)
+ trn.expenseWalletId = walletIdMap[expenseWalletId] || expenseWalletId
+ if (incomeWalletId)
+ trn.incomeWalletId = walletIdMap[incomeWalletId] || incomeWalletId
+ if (t.walletId && !expenseWalletId && !incomeWalletId)
+ trn.walletId = walletIdMap[t.walletId] || t.walletId
+ else if (t.walletId && t.type !== 2)
+ trn.walletId = walletIdMap[t.walletId] || t.walletId
+
+ if (t.categoryId === 'transfer')
+ trn.categoryId = 'transfer'
+ else if (t.categoryId === 'adjustment')
+ trn.categoryId = 'adjustment'
+ else if (t.categoryId)
+ trn.categoryId = categoryIdMap[t.categoryId] || t.categoryId
+
+ // Map amounts (handle old amountFrom/amountTo format)
+ if (t.expenseAmount !== undefined)
+ trn.expenseAmount = t.expenseAmount
+ else if (t.amountFrom !== undefined)
+ trn.expenseAmount = t.amountFrom
+ if (t.incomeAmount !== undefined)
+ trn.incomeAmount = t.incomeAmount
+ else if (t.amountTo !== undefined)
+ trn.incomeAmount = t.amountTo
+
+ return trn
+})
+
+let missingWallets = 0
+let missingCategories = 0
+for (const t of allTrns) {
+ if (t.walletId && !t.walletId.startsWith('j') && !t.walletId.startsWith('k'))
+ missingWallets++
+ if (t.categoryId && t.categoryId !== 'transfer' && t.categoryId !== 'adjustment' && !t.categoryId.startsWith('j') && !t.categoryId.startsWith('k'))
+ missingCategories++
+}
+if (missingWallets)
+ console.warn(`Warning: ${missingWallets} trns with unmapped walletId`)
+if (missingCategories)
+ console.warn(`Warning: ${missingCategories} trns with unmapped categoryId`)
+
+console.log(`\n=== Importing ${allTrns.length} trns in batches of ${BATCH_SIZE} ===`)
+let totalImported = 0
+for (let i = 0; i < allTrns.length; i += BATCH_SIZE) {
+ const batch = allTrns.slice(i, i + BATCH_SIZE)
+ const count = runConvex('migrate:insertTrnsBatch', { trns: batch, userId: USER_ID })
+ totalImported += count
+ console.log(` Batch ${Math.floor(i / BATCH_SIZE) + 1}: ${totalImported}/${allTrns.length}`)
+}
+
+// 4. Import user settings
+if (data.settings) {
+ console.log('\n=== Importing user settings ===')
+ runConvex('migrate:insertUserSettings', {
+ baseCurrency: data.settings.baseCurrency,
+ locale: data.settings.lang,
+ userId: USER_ID,
+ })
+}
+
+console.log(`\n=== Import to ${ENV} complete! ===`)
+console.log(` Wallets: ${wallets.length}`)
+console.log(` Categories: ${categories.length}`)
+console.log(` Trns: ${totalImported}`)
diff --git a/vite.config.ts b/vite.config.ts
index 1f4677aa..e685abfe 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,6 +1,9 @@
import { defineConfig } from 'vite'
export default defineConfig({
+ define: {
+ 'import.meta.client': true,
+ },
resolve: {
alias: {
'~/': '/app/',