Compare commits
12 Commits
v0.4.0
..
a00c953dc0
| Author | SHA1 | Date | |
|---|---|---|---|
| a00c953dc0 | |||
| 904a969b18 | |||
| 0558d92203 | |||
| d2aa9d8ae2 | |||
| 8dd5fd42e3 | |||
| 380ddaf303 | |||
| eaf80c6bb4 | |||
| 7fda139199 | |||
| be9f2a5c3a | |||
| b79951601c | |||
| 3644e081b1 | |||
| de91f2505a |
+44
-1
@@ -6,6 +6,48 @@ Biçim [Keep a Changelog](https://keepachangelog.com/tr-TR/1.1.0/) esas alınır
|
|||||||
|
|
||||||
## [Yayınlanmamış]
|
## [Yayınlanmamış]
|
||||||
|
|
||||||
|
Faz 6 (alt fazlar halinde; `v0.6.0` Faz 6c sonunda).
|
||||||
|
|
||||||
|
### Eklendi — Faz 6a: para, hesaplar ve kategoriler
|
||||||
|
|
||||||
|
- `shared/money.ts`: Türkçe tutar ayrıştırma (`"1.250,50"` → 125050 kuruş; binlik/ondalık kuralları belgeli), `formatMoneyInput`, `sumMoney`, kuruş kaybı olmadan oransal bölme (`allocate`, `splitEvenly`).
|
||||||
|
- `shared/quantity.ts`: miktarlar birimin binde biri tamsayı (`1,5 kg` → 1500); ayrıştırma, biçimlendirme, kg↔g / lt↔ml dönüşümü.
|
||||||
|
- `shared/dates.ts`: İstanbul günü yardımcıları (gün başlangıcı, UTC → yerel gün).
|
||||||
|
- Hesaplar (`/hesaplar`): nakit, vadesiz banka (KMH limiti, aylık faiz, kesim günü), birikim, kredi kartı (limit, kesim günü, son ödeme kuralı, ödeme hesabı), yemek kartı (sağlayıcı); hesap sahibi kişi ve "yalnızca ben" (bakiyeyi yalnızca hesap sahibi görür, toplamlar hane ayarına uyar); renk/ikon, sıralama, arşiv. Varlık / kart borcu / net özet.
|
||||||
|
- Kategoriler (`/kategoriler`): gelir ve gider ağaçları (5 seviyeye kadar), ekleme, düzenleme, taşıma (alt ağaçla, transaction), sıralama, arşivleme (alt ağaçla); kardeşler arasında ad tekrarı engeli (Türkçe normalize).
|
||||||
|
- Varsayılan Türkçe kategori seti (44 kategori): yeni hanede aynı transaction'da, mevcut hanelere `002` migration'ıyla, idempotent (`defaultKey`).
|
||||||
|
- Kategori ağacı saf fonksiyonları (`buildTree`, `toOptions`, `checkMove`, `rollupTotals` …) ve birim testleri.
|
||||||
|
- Renk paleti (13 renk, açık/koyu tema değişkenleri) ve ikon kayıt tablosu; ikon/renk seçiciler, `MoneyInput`.
|
||||||
|
- Seed: varsayılan kategoriler ve 7 örnek hesap (KMH'li banka, kredi kartı, birikim, "yalnızca ben" yemek kartı).
|
||||||
|
- Denetim kaydı: hesap oluşturma/düzenleme/arşiv, kategori taşıma/arşiv.
|
||||||
|
- Entegrasyon testleri: kategori ve hesap izolasyonu, roller, gizli bakiye, kart kuralları, ağaç kuralları.
|
||||||
|
|
||||||
|
## [0.5.0] - 2026-11-05
|
||||||
|
|
||||||
|
Faz 5: Haneler, hane içi roller ve veri izolasyonu.
|
||||||
|
|
||||||
|
### Eklendi
|
||||||
|
|
||||||
|
- Hane içi roller (`viewer < member < owner`) ve kuralları: son sahip düşürülemez veya çıkarılamaz.
|
||||||
|
- DAL: `getHouseholdContext` (istek başına tek okuma), `requireActiveHousehold(minRole)`, `getHouseholdActionContext(minRole)`, `requireHouseholdMember(householdId, minRole)`. Sistem admini için hane verisinde ayrıcalık yok.
|
||||||
|
- Hane servisi (`features/households/service.ts`, framework'ten bağımsız): her hane kapsamlı fonksiyon üyeliği kendisi de doğrular; hane oluşturma + ilk sahip + denetim kaydı tek MongoDB transaction'ında.
|
||||||
|
- Aktif hane seçici (üst bar): seçim sunucuda doğrulanır, `butcem.hh` cookie'sine yazılır; geçersiz/uydurma cookie yok sayılır. Tercih yoksa en yüksek rolün olduğu hane açılır.
|
||||||
|
- `/ayarlar`: hane adı, bütçe ayı başlangıç günü, taksit modu, günlük plan dağıtımı, "yalnızca ben" hesaplarının toplamlara dahil edilmesi, ek mağaza tasarruf eşiği; üye rolleri ve üye çıkarma (yalnızca sahip; diğer roller salt okunur).
|
||||||
|
- `/admin/haneler`: hane oluşturma (ilk sahip seçerek), kullanıcıyı haneye ekleme, hane içi rol değiştirme, üye çıkarma.
|
||||||
|
- `/hane-yok`: hiçbir haneye üye olmayan kullanıcılar için yönlendirme sayfası.
|
||||||
|
- Denetim kaydı (`auditLogs`): hane ayarları, üye ekleme/rol/çıkarma, hane oluşturma ve tüm admin kullanıcı işlemleri (oluşturma, düzenleme, rol, şifre sıfırlama, askı, silme).
|
||||||
|
- Migration mekanizması: `npm run migrate`, `scripts/migrations/NNN-*.ts`, uygulananlar `migrations` koleksiyonunda; `001-initial-indexes`. Seed önce migration'ları çalıştırır.
|
||||||
|
- Veri izolasyonu entegrasyon testleri (başka hanenin üyeliği/ayrıntısı/ayarları, rol yetersizliği, uydurma ve enjeksiyon denemesi kimlikler, hanesi olmayan admin, çapraz hane üyelik değişikliği, son sahip, transaction).
|
||||||
|
|
||||||
|
### Değişti
|
||||||
|
|
||||||
|
- İzleyici (viewer) rolünde Hızlı ekle gizlenir/pasifleşir.
|
||||||
|
- Kullanıcı silindiğinde tüm hane üyelikleri de temizlenir.
|
||||||
|
|
||||||
|
### Kaldırıldı
|
||||||
|
|
||||||
|
- Hane mock verisi.
|
||||||
|
|
||||||
## [0.4.0] - 2026-11-05
|
## [0.4.0] - 2026-11-05
|
||||||
|
|
||||||
Faz 4: Örnek test verisi.
|
Faz 4: Örnek test verisi.
|
||||||
@@ -94,7 +136,8 @@ Faz 1: Framework, klasör yapısı ve altyapı.
|
|||||||
- `.nvmrc` (Node 26), `engines.node`, `typecheck`, `test`, `format`, `db:up`, `seed` scriptleri.
|
- `.nvmrc` (Node 26), `engines.node`, `typecheck`, `test`, `format`, `db:up`, `seed` scriptleri.
|
||||||
- `docs/PROMPT.md` (ana prompt ve Faz 0 kararları), `README.md`, `CHANGELOG.md`.
|
- `docs/PROMPT.md` (ana prompt ve Faz 0 kararları), `README.md`, `CHANGELOG.md`.
|
||||||
|
|
||||||
[Yayınlanmamış]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.4.0...HEAD
|
[Yayınlanmamış]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.5.0...HEAD
|
||||||
|
[0.5.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.4.0...v0.5.0
|
||||||
[0.4.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.3.0...v0.4.0
|
[0.4.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.3.0...v0.4.0
|
||||||
[0.3.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.2.0...v0.3.0
|
[0.3.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.2.0...v0.3.0
|
||||||
[0.2.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.1.0...v0.2.0
|
[0.2.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.1.0...v0.2.0
|
||||||
|
|||||||
@@ -63,6 +63,12 @@ Giriş kullanıcı adı **veya** e-posta ile yapılır. Kayıt kapalıdır; kull
|
|||||||
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
|
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
|
||||||
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
|
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
|
||||||
|
|
||||||
|
## Haneler ve yetki
|
||||||
|
|
||||||
|
- Tüm alan verisi bir **haneye** (`householdId`) aittir; kullanıcı yalnızca üyesi olduğu hanelerin verisini görür. Sistem admini de bu kurala tabidir.
|
||||||
|
- Hane içi roller: **sahip** (ayarlar, üyeler), **üye** (veri girer), **izleyici** (yalnızca görüntüler).
|
||||||
|
- Her sayfa, Server Action ve API, hane yetkisini `src/lib/dal.ts` üzerinden sunucuda doğrular; servisler de üyeliği ayrıca kontrol eder.
|
||||||
|
|
||||||
## Marka dosyaları
|
## Marka dosyaları
|
||||||
|
|
||||||
`public/brand/`: `logo.svg` (açık tema), `logo-dark.svg` (koyu tema), `icon.svg` (uygulama ikonu), `icon-maskable.svg` (Android/iOS, köşesiz). Yazı Noto Sans Bold (OFL) harf yollarıdır. İkonları değiştirdikten sonra `npm run icons` çalıştırın; favicon ve PWA ikonları bu kaynaklardan üretilir.
|
`public/brand/`: `logo.svg` (açık tema), `logo-dark.svg` (koyu tema), `icon.svg` (uygulama ikonu), `icon-maskable.svg` (Android/iOS, köşesiz). Yazı Noto Sans Bold (OFL) harf yollarıdır. İkonları değiştirdikten sonra `npm run icons` çalıştırın; favicon ve PWA ikonları bu kaynaklardan üretilir.
|
||||||
|
|||||||
@@ -317,6 +317,7 @@ Aşağıdakileri varsayılan olarak kabul ettim. Faz 0'da yalnızca bunlardan em
|
|||||||
- **Değerleme:** varlıklar ve aynî alacaklar **alış** fiyatıyla, aynî borçlar **satış** fiyatıyla değerlenir. Tek fiyat girilirse ikisine de yazılır.
|
- **Değerleme:** varlıklar ve aynî alacaklar **alış** fiyatıyla, aynî borçlar **satış** fiyatıyla değerlenir. Tek fiyat girilirse ikisine de yazılır.
|
||||||
- **URL'ler:** ekran yolları Türkçe ASCII (`/islemler`, `/butce`); kod, koleksiyon adları ve `/api/v1` İngilizce.
|
- **URL'ler:** ekran yolları Türkçe ASCII (`/islemler`, `/butce`); kod, koleksiyon adları ve `/api/v1` İngilizce.
|
||||||
- **Canlı domain:** `butcem.ta1sph.website` (Gitea `gitea.ta1sph.info` üzerinde; fark kasıtlı).
|
- **Canlı domain:** `butcem.ta1sph.website` (Gitea `gitea.ta1sph.info` üzerinde; fark kasıtlı).
|
||||||
|
- **Aktif hane varsayılanı:** tercih (cookie) yoksa kullanıcının en yüksek rolde olduğu hane açılır.
|
||||||
- **Lokal MongoDB portu:** host'ta `27019` (27017 ve 27018 geliştirme makinesinde dolu). `BUTCEM_MONGO_PORT` ile değiştirilebilir.
|
- **Lokal MongoDB portu:** host'ta `27019` (27017 ve 27018 geliştirme makinesinde dolu). `BUTCEM_MONGO_PORT` ile değiştirilebilir.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+3
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "butcem",
|
"name": "butcem",
|
||||||
"version": "0.4.0",
|
"version": "0.5.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
|
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -21,7 +21,8 @@
|
|||||||
"seed": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts",
|
"seed": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts",
|
||||||
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
|
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
|
||||||
"icons": "tsx scripts/generate-icons.ts",
|
"icons": "tsx scripts/generate-icons.ts",
|
||||||
"test:integration": "vitest run --config vitest.integration.config.mts"
|
"test:integration": "vitest run --config vitest.integration.config.mts",
|
||||||
|
"migrate": "tsx --conditions=react-server --env-file=.env.local scripts/migrate.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "^7.0.2",
|
"@hookform/resolvers": "^7.0.2",
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* Migration'ları uygular: npm run migrate (canlıda deploy sonrası; bkz. docs/DEPLOY.md, Faz 15).
|
||||||
|
* `server-only` modülleri Next dışında yükleyebilmek için --conditions=react-server ile çalışır.
|
||||||
|
*/
|
||||||
|
import mongoose from "mongoose";
|
||||||
|
import { getMongoClient } from "@/lib/db/mongo";
|
||||||
|
import { runMigrations } from "./migrations";
|
||||||
|
|
||||||
|
runMigrations()
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
console.error(err instanceof Error ? err.message : err);
|
||||||
|
process.exitCode = 1;
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await mongoose.disconnect();
|
||||||
|
await getMongoClient().close();
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { AuditLogModel } from "@/models/audit-log";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { HouseholdMemberModel } from "@/models/household-member";
|
||||||
|
import type { Migration } from "./types";
|
||||||
|
|
||||||
|
/** Hane, üyelik ve denetim kaydı index'leri (Mongoose şemalarındaki tanımlarla). */
|
||||||
|
export const migration: Migration = {
|
||||||
|
name: "001-initial-indexes",
|
||||||
|
description: "households, householdMembers ve auditLogs index'leri",
|
||||||
|
async up() {
|
||||||
|
await HouseholdModel.createIndexes();
|
||||||
|
await HouseholdMemberModel.createIndexes();
|
||||||
|
await AuditLogModel.createIndexes();
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { Types } from "mongoose";
|
||||||
|
import { installDefaultCategories } from "@/features/categories/service";
|
||||||
|
import { AccountModel } from "@/models/account";
|
||||||
|
import { CategoryModel } from "@/models/category";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import type { Migration } from "./types";
|
||||||
|
|
||||||
|
/** Hesap ve kategori index'leri + mevcut hanelere varsayılan kategori seti (idempotent). */
|
||||||
|
export const migration: Migration = {
|
||||||
|
name: "002-accounts-categories",
|
||||||
|
description: "accounts/categories index'leri ve mevcut hanelere varsayılan kategoriler",
|
||||||
|
async up() {
|
||||||
|
await AccountModel.createIndexes();
|
||||||
|
await CategoryModel.createIndexes();
|
||||||
|
for (const h of await HouseholdModel.find().select({ _id: 1, createdBy: 1 }).lean()) {
|
||||||
|
await installDefaultCategories(h._id as Types.ObjectId, h.createdBy as Types.ObjectId);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { getDb } from "@/lib/db/mongo";
|
||||||
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
|
import { migration as m001 } from "./001-initial-indexes";
|
||||||
|
import { migration as m002 } from "./002-accounts-categories";
|
||||||
|
import type { Migration } from "./types";
|
||||||
|
|
||||||
|
/** Sıralı migration listesi. Yeni migration: dosyayı ekle ve buraya sırayla ekle. */
|
||||||
|
export const MIGRATIONS: Migration[] = [m001, m002];
|
||||||
|
|
||||||
|
const COLLECTION = "migrations";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uygulanmamış migration'ları sırayla çalıştırır; her biri bir kez (`migrations` koleksiyonu).
|
||||||
|
* Aynı anda iki çalıştırma olursa benzersiz `name` index'i ikinci kaydı reddeder.
|
||||||
|
*/
|
||||||
|
export async function runMigrations(log: (line: string) => void = console.log): Promise<string[]> {
|
||||||
|
const db = getDb();
|
||||||
|
await connectMongoose();
|
||||||
|
const col = db.collection<{ name: string; appliedAt: Date; durationMs: number }>(COLLECTION);
|
||||||
|
await col.createIndex({ name: 1 }, { unique: true });
|
||||||
|
const applied = new Set(
|
||||||
|
(await col.find({}, { projection: { name: 1 } }).toArray()).map((d) => d.name),
|
||||||
|
);
|
||||||
|
|
||||||
|
const ran: string[] = [];
|
||||||
|
for (const m of MIGRATIONS) {
|
||||||
|
if (applied.has(m.name)) continue;
|
||||||
|
const started = Date.now();
|
||||||
|
await m.up(db);
|
||||||
|
await col.insertOne({ name: m.name, appliedAt: new Date(), durationMs: Date.now() - started });
|
||||||
|
ran.push(m.name);
|
||||||
|
log(`✓ Migration: ${m.name} — ${m.description}`);
|
||||||
|
}
|
||||||
|
if (!ran.length) log("• Bekleyen migration yok.");
|
||||||
|
return ran;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import type { Db } from "mongodb";
|
||||||
|
|
||||||
|
/** Bir migration: adı dosya adıyla aynı olmalı (ör. "001-initial-indexes"). Geri alma yok; ileri yönlü. */
|
||||||
|
export type Migration = {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
up: (db: Db) => Promise<void>;
|
||||||
|
};
|
||||||
+4
-2
@@ -11,8 +11,10 @@ import { closeSeedConnections, runSeed } from "./seed/run";
|
|||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const summary = await runSeed({ reset: process.argv.includes("--reset") });
|
const summary = await runSeed({ reset: process.argv.includes("--reset") });
|
||||||
const { users, households, memberships } = summary.created;
|
const { users, households, memberships, categories, accounts } = summary.created;
|
||||||
console.log(`\nOluşturulan: ${users} kullanıcı, ${households} hane, ${memberships} üyelik.`);
|
console.log(
|
||||||
|
`\nOluşturulan: ${users} kullanıcı, ${households} hane, ${memberships} üyelik, ${categories} kategori, ${accounts} hesap.`,
|
||||||
|
);
|
||||||
|
|
||||||
// Hesap tablosu yalnızca geliştirme ortamında gösterilir.
|
// Hesap tablosu yalnızca geliştirme ortamında gösterilir.
|
||||||
if (env().NODE_ENV !== "production" && summary.accounts.length) {
|
if (env().NODE_ENV !== "production" && summary.accounts.length) {
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import type { HouseholdRole } from "@/features/households/types";
|
import type { HouseholdRole } from "@/features/households/types";
|
||||||
|
import type { AccountType, MealCardProvider } from "@/shared/accounts";
|
||||||
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
import type { SystemRole } from "@/shared/schemas/common";
|
import type { SystemRole } from "@/shared/schemas/common";
|
||||||
|
|
||||||
/** Örnek (geliştirme) kullanıcıları. E-postası olmayanlar kullanıcı adıyla giriş yapar. */
|
/** Örnek (geliştirme) kullanıcıları. E-postası olmayanlar kullanıcı adıyla giriş yapar. */
|
||||||
@@ -56,3 +58,97 @@ export const SEED_HOUSEHOLDS: SeedHousehold[] = [
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Örnek hesaplar (tutarlar kuruş; kart borcu negatif). Açılış: 6 ay önce. */
|
||||||
|
export type SeedAccount = {
|
||||||
|
household: string;
|
||||||
|
name: string;
|
||||||
|
type: AccountType;
|
||||||
|
institution?: string;
|
||||||
|
openingBalanceMinor: number;
|
||||||
|
color: Swatch;
|
||||||
|
icon: IconKey;
|
||||||
|
owner?: string;
|
||||||
|
isPrivate?: boolean;
|
||||||
|
mealCardProvider?: MealCardProvider;
|
||||||
|
overdraft?: { limitMinor: number; monthlyRateBp: number; statementDay: number };
|
||||||
|
creditCard?: {
|
||||||
|
limitMinor: number;
|
||||||
|
statementDay: number;
|
||||||
|
dueDays: number;
|
||||||
|
paymentAccount: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SEED_ACCOUNTS: SeedAccount[] = [
|
||||||
|
{
|
||||||
|
household: "Çakır Ailesi",
|
||||||
|
name: "Cüzdan",
|
||||||
|
type: "cash",
|
||||||
|
openingBalanceMinor: 2_350_00,
|
||||||
|
color: "green",
|
||||||
|
icon: "wallet",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Çakır Ailesi",
|
||||||
|
name: "Ziraat Maaş",
|
||||||
|
type: "bank",
|
||||||
|
institution: "Ziraat Bankası",
|
||||||
|
openingBalanceMinor: 18_420_50,
|
||||||
|
color: "red",
|
||||||
|
icon: "landmark",
|
||||||
|
overdraft: { limitMinor: 10_000_00, monthlyRateBp: 425, statementDay: 1 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Çakır Ailesi",
|
||||||
|
name: "Garanti Bonus",
|
||||||
|
type: "credit_card",
|
||||||
|
institution: "Garanti BBVA",
|
||||||
|
openingBalanceMinor: -6_480_75,
|
||||||
|
color: "teal",
|
||||||
|
icon: "credit-card",
|
||||||
|
creditCard: {
|
||||||
|
limitMinor: 60_000_00,
|
||||||
|
statementDay: 29,
|
||||||
|
dueDays: 10,
|
||||||
|
paymentAccount: "Ziraat Maaş",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Çakır Ailesi",
|
||||||
|
name: "Birikim (Vadeli)",
|
||||||
|
type: "savings",
|
||||||
|
institution: "Ziraat Bankası",
|
||||||
|
openingBalanceMinor: 45_000_00,
|
||||||
|
color: "indigo",
|
||||||
|
icon: "piggy-bank",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Çakır Ailesi",
|
||||||
|
name: "Ayşe — Pluxee",
|
||||||
|
type: "meal_card",
|
||||||
|
mealCardProvider: "pluxee",
|
||||||
|
openingBalanceMinor: 3_120_00,
|
||||||
|
color: "lime",
|
||||||
|
icon: "utensils",
|
||||||
|
owner: "ayse",
|
||||||
|
isPrivate: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Annemler",
|
||||||
|
name: "Nakit",
|
||||||
|
type: "cash",
|
||||||
|
openingBalanceMinor: 1_500_00,
|
||||||
|
color: "green",
|
||||||
|
icon: "wallet",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
household: "Annemler",
|
||||||
|
name: "Vakıfbank Emekli",
|
||||||
|
type: "bank",
|
||||||
|
institution: "VakıfBank",
|
||||||
|
openingBalanceMinor: 27_800_00,
|
||||||
|
color: "amber",
|
||||||
|
icon: "landmark",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|||||||
@@ -24,18 +24,26 @@ describe("seed", () => {
|
|||||||
it("ilk çalıştırmada admin, örnek kullanıcılar, haneler ve üyelikleri oluşturur", async () => {
|
it("ilk çalıştırmada admin, örnek kullanıcılar, haneler ve üyelikleri oluşturur", async () => {
|
||||||
const summary = await runSeed({ log: silent });
|
const summary = await runSeed({ log: silent });
|
||||||
const memberCount = SEED_HOUSEHOLDS.reduce((n, h) => n + h.members.length, 0);
|
const memberCount = SEED_HOUSEHOLDS.reduce((n, h) => n + h.members.length, 0);
|
||||||
expect(summary.created).toEqual({
|
expect(summary.created).toMatchObject({
|
||||||
users: SEED_USERS.length + 1,
|
users: SEED_USERS.length + 1,
|
||||||
households: SEED_HOUSEHOLDS.length,
|
households: SEED_HOUSEHOLDS.length,
|
||||||
memberships: memberCount,
|
memberships: memberCount,
|
||||||
});
|
});
|
||||||
|
expect(summary.created.categories).toBeGreaterThan(40);
|
||||||
|
expect(summary.created.accounts).toBe(7);
|
||||||
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
|
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
|
||||||
expect(await HouseholdMemberModel.countDocuments()).toBe(memberCount);
|
expect(await HouseholdMemberModel.countDocuments()).toBe(memberCount);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("idempotenttir: ikinci çalıştırma kopya oluşturmaz", async () => {
|
it("idempotenttir: ikinci çalıştırma kopya oluşturmaz", async () => {
|
||||||
const summary = await runSeed({ log: silent });
|
const summary = await runSeed({ log: silent });
|
||||||
expect(summary.created).toEqual({ users: 0, households: 0, memberships: 0 });
|
expect(summary.created).toEqual({
|
||||||
|
users: 0,
|
||||||
|
households: 0,
|
||||||
|
memberships: 0,
|
||||||
|
categories: 0,
|
||||||
|
accounts: 0,
|
||||||
|
});
|
||||||
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
|
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
|
||||||
expect(await HouseholdModel.countDocuments()).toBe(SEED_HOUSEHOLDS.length);
|
expect(await HouseholdModel.countDocuments()).toBe(SEED_HOUSEHOLDS.length);
|
||||||
});
|
});
|
||||||
|
|||||||
+74
-8
@@ -3,10 +3,19 @@ import { getAuth } from "@/lib/auth";
|
|||||||
import { getDb } from "@/lib/db/mongo";
|
import { getDb } from "@/lib/db/mongo";
|
||||||
import { connectMongoose } from "@/lib/db/mongoose";
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
import { env } from "@/lib/env";
|
import { env } from "@/lib/env";
|
||||||
|
import { installDefaultCategories } from "@/features/categories/service";
|
||||||
|
import { AccountModel } from "@/models/account";
|
||||||
import { HouseholdModel } from "@/models/household";
|
import { HouseholdModel } from "@/models/household";
|
||||||
import { HouseholdMemberModel } from "@/models/household-member";
|
import { HouseholdMemberModel } from "@/models/household-member";
|
||||||
import { storedEmail } from "@/shared/account-email";
|
import { storedEmail } from "@/shared/account-email";
|
||||||
import { ADMIN_USERNAME, SEED_HOUSEHOLDS, SEED_USERS, type SeedUser } from "./fixtures";
|
import { runMigrations } from "../migrations";
|
||||||
|
import {
|
||||||
|
ADMIN_USERNAME,
|
||||||
|
SEED_ACCOUNTS,
|
||||||
|
SEED_HOUSEHOLDS,
|
||||||
|
SEED_USERS,
|
||||||
|
type SeedUser,
|
||||||
|
} from "./fixtures";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* İdempotent seed. Kullanıcılar Better Auth API'siyle oluşturulur (şifreler doğru hashlenir);
|
* İdempotent seed. Kullanıcılar Better Auth API'siyle oluşturulur (şifreler doğru hashlenir);
|
||||||
@@ -25,12 +34,24 @@ export type SeedAccountRow = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type SeedSummary = {
|
export type SeedSummary = {
|
||||||
created: { users: number; households: number; memberships: number };
|
created: {
|
||||||
|
users: number;
|
||||||
|
households: number;
|
||||||
|
memberships: number;
|
||||||
|
categories: number;
|
||||||
|
accounts: number;
|
||||||
|
};
|
||||||
accounts: SeedAccountRow[];
|
accounts: SeedAccountRow[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const AUTH_COLLECTIONS = ["user", "account", "session", "verification", "rateLimit"];
|
const AUTH_COLLECTIONS = ["user", "account", "session", "verification", "rateLimit"];
|
||||||
const DOMAIN_COLLECTIONS = ["households", "householdMembers"];
|
const DOMAIN_COLLECTIONS = [
|
||||||
|
"households",
|
||||||
|
"householdMembers",
|
||||||
|
"auditLogs",
|
||||||
|
"categories",
|
||||||
|
"accounts",
|
||||||
|
];
|
||||||
|
|
||||||
type AuthApi = ReturnType<typeof getAuth>["api"];
|
type AuthApi = ReturnType<typeof getAuth>["api"];
|
||||||
|
|
||||||
@@ -72,7 +93,7 @@ export async function runSeed({
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
await connectMongoose();
|
await connectMongoose();
|
||||||
const summary: SeedSummary = {
|
const summary: SeedSummary = {
|
||||||
created: { users: 0, households: 0, memberships: 0 },
|
created: { users: 0, households: 0, memberships: 0, categories: 0, accounts: 0 },
|
||||||
accounts: [],
|
accounts: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,9 +104,8 @@ export async function runSeed({
|
|||||||
log("• Kimlik doğrulama ve hane koleksiyonları temizlendi.");
|
log("• Kimlik doğrulama ve hane koleksiyonları temizlendi.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Index'ler (production'da Mongoose autoIndex kapalı olduğu için açıkça oluşturulur).
|
// Index'ler ve şema değişiklikleri (production'da Mongoose autoIndex kapalı).
|
||||||
await HouseholdModel.createIndexes();
|
await runMigrations(log);
|
||||||
await HouseholdMemberModel.createIndexes();
|
|
||||||
|
|
||||||
// 1) Admin
|
// 1) Admin
|
||||||
const adminEmail = e.SEED_ADMIN_EMAIL.toLowerCase();
|
const adminEmail = e.SEED_ADMIN_EMAIL.toLowerCase();
|
||||||
@@ -180,7 +200,53 @@ export async function runSeed({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5) Geliştirme hesapları tablosu
|
// 5) Varsayılan kategoriler ve örnek hesaplar
|
||||||
|
const householdIds = new Map<string, Types.ObjectId>();
|
||||||
|
for (const h of SEED_HOUSEHOLDS) {
|
||||||
|
const doc = await HouseholdModel.findOne({ name: h.name }).select({ _id: 1 }).lean();
|
||||||
|
householdIds.set(h.name, doc!._id);
|
||||||
|
summary.created.categories += await installDefaultCategories(doc!._id, actor);
|
||||||
|
}
|
||||||
|
const openingDate = new Date(Date.now() - 183 * 24 * 60 * 60 * 1000);
|
||||||
|
for (const [order, a] of SEED_ACCOUNTS.entries()) {
|
||||||
|
const householdId = householdIds.get(a.household)!;
|
||||||
|
if (await AccountModel.exists({ householdId, name: a.name })) continue;
|
||||||
|
const payer = a.creditCard
|
||||||
|
? await AccountModel.findOne({ householdId, name: a.creditCard.paymentAccount })
|
||||||
|
.select({ _id: 1 })
|
||||||
|
.lean()
|
||||||
|
: null;
|
||||||
|
await AccountModel.create({
|
||||||
|
householdId,
|
||||||
|
name: a.name,
|
||||||
|
type: a.type,
|
||||||
|
institution: a.institution ?? "",
|
||||||
|
mealCardProvider: a.mealCardProvider ?? null,
|
||||||
|
openingBalanceMinor: a.openingBalanceMinor,
|
||||||
|
openingDate,
|
||||||
|
color: a.color,
|
||||||
|
icon: a.icon,
|
||||||
|
order,
|
||||||
|
ownerUserId: a.owner ? new Types.ObjectId(ids.get(a.owner)!) : null,
|
||||||
|
isPrivate: a.isPrivate ?? false,
|
||||||
|
overdraft: a.overdraft ? { enabled: true, ...a.overdraft } : null,
|
||||||
|
creditCard: a.creditCard
|
||||||
|
? {
|
||||||
|
limitMinor: a.creditCard.limitMinor,
|
||||||
|
statementDay: a.creditCard.statementDay,
|
||||||
|
dueRule: { kind: "daysAfter", value: a.creditCard.dueDays },
|
||||||
|
paymentAccountId: payer?._id ?? null,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
});
|
||||||
|
summary.created.accounts++;
|
||||||
|
}
|
||||||
|
if (summary.created.categories) log(`✓ Varsayılan kategoriler: ${summary.created.categories}`);
|
||||||
|
if (summary.created.accounts) log(`✓ Örnek hesaplar: ${summary.created.accounts}`);
|
||||||
|
|
||||||
|
// 6) Geliştirme hesapları tablosu
|
||||||
const all = [
|
const all = [
|
||||||
{ username: ADMIN_USERNAME, name: "Yönetici", email: adminEmail, role: "admin" as const },
|
{ username: ADMIN_USERNAME, name: "Yönetici", email: adminEmail, role: "admin" as const },
|
||||||
...SEED_USERS,
|
...SEED_USERS,
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { HouseholdsAdmin } from "@/features/admin-households/components/households-admin";
|
||||||
|
import { getAdminHouseholdsData } from "@/features/admin-households/queries";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { requireRole } from "@/lib/dal";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: tr.adminHouseholds.title };
|
||||||
|
|
||||||
|
export default async function AdminHouseholdsPage() {
|
||||||
|
const [admin, data] = await Promise.all([requireRole("admin"), getAdminHouseholdsData()]);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={tr.adminHouseholds.title} description={tr.adminHouseholds.description} />
|
||||||
|
<HouseholdsAdmin households={data.households} users={data.users} currentUserId={admin.id} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { HouseholdSettingsForm } from "@/features/households/components/household-settings-form";
|
||||||
|
import { SettingsMembers } from "@/features/households/components/settings-members";
|
||||||
|
import { getHouseholdDetail } from "@/features/households/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { requireActiveHousehold } from "@/lib/dal";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: tr.settings.title };
|
||||||
|
|
||||||
|
export default async function SettingsPage() {
|
||||||
|
const { user, household } = await requireActiveHousehold("viewer");
|
||||||
|
const detail = await getHouseholdDetail(user.id, household.id);
|
||||||
|
if (!detail) notFound();
|
||||||
|
const isOwner = household.role === "owner";
|
||||||
|
const t = tr.settings;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t.title} description={t.description} />
|
||||||
|
<div className="grid gap-4 lg:grid-cols-2 lg:items-start">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t.household}</CardTitle>
|
||||||
|
<CardDescription>{isOwner ? t.householdDescription : t.ownerOnly}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<HouseholdSettingsForm settings={detail.settings} canEdit={isOwner} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t.members}</CardTitle>
|
||||||
|
<CardDescription>{t.membersDescription}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<SettingsMembers
|
||||||
|
members={detail.members}
|
||||||
|
householdName={detail.name}
|
||||||
|
currentUserId={user.id}
|
||||||
|
canManage={isOwner}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { PageHeader } from "@/components/page-header";
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { SummaryCardsSkeleton } from "@/features/dashboard/components/summary-cards-skeleton";
|
import { SummaryCardsSkeleton } from "@/features/dashboard/components/summary-cards-skeleton";
|
||||||
import { tr } from "@/i18n/tr";
|
import { tr } from "@/i18n/tr";
|
||||||
import { requireSession } from "@/lib/dal";
|
import { requireActiveHousehold } from "@/lib/dal";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { formatMoney } from "@/shared/format";
|
import { formatMoney } from "@/shared/format";
|
||||||
|
|
||||||
@@ -52,12 +52,12 @@ async function SummaryCards() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const user = await requireSession();
|
const { user, household } = await requireActiveHousehold("viewer");
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={tr.dashboard.welcome(user.name.split(" ")[0] ?? user.name)}
|
title={tr.dashboard.welcome(user.name.split(" ")[0] ?? user.name)}
|
||||||
description={tr.dashboard.welcomeDescription}
|
description={`${household.name} · ${tr.dashboard.welcomeDescription}`}
|
||||||
/>
|
/>
|
||||||
<Suspense fallback={<SummaryCardsSkeleton />}>
|
<Suspense fallback={<SummaryCardsSkeleton />}>
|
||||||
<SummaryCards />
|
<SummaryCards />
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { House } from "lucide-react";
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { getHouseholdContext } from "@/lib/dal";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: tr.households.noHousehold.title };
|
||||||
|
|
||||||
|
/** Hiçbir haneye üye olmayan kullanıcılar (ör. hanesi olmayan admin) buraya yönlenir. */
|
||||||
|
export default async function NoHouseholdPage() {
|
||||||
|
const ctx = await getHouseholdContext();
|
||||||
|
if (!ctx) redirect("/login");
|
||||||
|
if (ctx.household) redirect("/dashboard");
|
||||||
|
const t = tr.households.noHousehold;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center">
|
||||||
|
<Card className="max-w-md">
|
||||||
|
<CardHeader>
|
||||||
|
<span className="mb-2 flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary">
|
||||||
|
<House className="size-6" />
|
||||||
|
</span>
|
||||||
|
<CardTitle className="text-xl">{t.title}</CardTitle>
|
||||||
|
<CardDescription>{t.description}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
{ctx.user.role === "admin" ? (
|
||||||
|
<CardContent className="flex flex-col items-start gap-3">
|
||||||
|
<p className="text-sm text-muted-foreground">{t.adminHint}</p>
|
||||||
|
<Button asChild>
|
||||||
|
<Link href="/admin/haneler">{t.adminLink}</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
) : null}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { AccountsView } from "@/features/accounts/components/accounts-view";
|
||||||
|
import { listAccounts, listMemberOptions } from "@/features/accounts/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { requireActiveHousehold } from "@/lib/dal";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: tr.accounts.title };
|
||||||
|
|
||||||
|
export default async function AccountsPage() {
|
||||||
|
const { user, household } = await requireActiveHousehold("viewer");
|
||||||
|
const [data, members] = await Promise.all([
|
||||||
|
listAccounts(user.id, household.id, { includeArchived: true }),
|
||||||
|
listMemberOptions(user.id, household.id),
|
||||||
|
]);
|
||||||
|
if (!data || !members) notFound();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={tr.accounts.title} description={tr.accounts.description} />
|
||||||
|
<AccountsView
|
||||||
|
accounts={data.accounts}
|
||||||
|
totals={data.totals}
|
||||||
|
members={members}
|
||||||
|
canEdit={household.role === "owner"}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { CategoriesManager } from "@/features/categories/components/categories-manager";
|
||||||
|
import { listCategories } from "@/features/categories/service";
|
||||||
|
import { hasHouseholdRole } from "@/features/households/roles";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { requireActiveHousehold } from "@/lib/dal";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: tr.categories.title };
|
||||||
|
|
||||||
|
export default async function CategoriesPage() {
|
||||||
|
const { user, household } = await requireActiveHousehold("viewer");
|
||||||
|
const categories = await listCategories(user.id, household.id, { includeArchived: true });
|
||||||
|
if (!categories) notFound();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={tr.categories.title} description={tr.categories.description} />
|
||||||
|
<CategoriesManager
|
||||||
|
categories={categories}
|
||||||
|
canEdit={hasHouseholdRole(household.role, "member")}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
import { AppHeader } from "@/components/layout/app-header";
|
import { AppHeader } from "@/components/layout/app-header";
|
||||||
import { AppShellFallback } from "@/components/layout/app-shell-fallback";
|
import { AppShellFallback } from "@/components/layout/app-shell-fallback";
|
||||||
@@ -5,8 +6,8 @@ import { AppSidebar } from "@/components/layout/app-sidebar";
|
|||||||
import { BottomNav } from "@/components/layout/bottom-nav";
|
import { BottomNav } from "@/components/layout/bottom-nav";
|
||||||
import { QuickAddProvider } from "@/components/layout/quick-add";
|
import { QuickAddProvider } from "@/components/layout/quick-add";
|
||||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
|
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
|
||||||
import { MOCK_HOUSEHOLDS } from "@/features/households/mock";
|
import { hasHouseholdRole } from "@/features/households/roles";
|
||||||
import { requireSession } from "@/lib/dal";
|
import { getHouseholdContext } from "@/lib/dal";
|
||||||
import { APP_VERSION } from "@/lib/version";
|
import { APP_VERSION } from "@/lib/version";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,18 +24,26 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function AuthenticatedShell({ children }: { children: React.ReactNode }) {
|
async function AuthenticatedShell({ children }: { children: React.ReactNode }) {
|
||||||
const user = await requireSession();
|
const ctx = await getHouseholdContext();
|
||||||
|
if (!ctx) redirect("/login");
|
||||||
|
const { user, household, memberships } = ctx;
|
||||||
|
const canWrite = household ? hasHouseholdRole(household.role, "member") : false;
|
||||||
return (
|
return (
|
||||||
<SidebarProvider>
|
<SidebarProvider>
|
||||||
<QuickAddProvider>
|
<QuickAddProvider>
|
||||||
<AppSidebar isAdmin={user.role === "admin"} version={APP_VERSION} />
|
<AppSidebar isAdmin={user.role === "admin"} version={APP_VERSION} />
|
||||||
<SidebarInset>
|
<SidebarInset>
|
||||||
{/* FAZ 5: kullanıcının üye olduğu haneler */}
|
<AppHeader
|
||||||
<AppHeader user={user} households={MOCK_HOUSEHOLDS} version={APP_VERSION} />
|
user={user}
|
||||||
|
households={memberships}
|
||||||
|
activeHouseholdId={household?.id}
|
||||||
|
canWrite={canWrite}
|
||||||
|
version={APP_VERSION}
|
||||||
|
/>
|
||||||
{/* Mobilde alt menü yüksekliği kadar boşluk */}
|
{/* Mobilde alt menü yüksekliği kadar boşluk */}
|
||||||
<div className="flex flex-1 flex-col gap-4 p-4 pb-24 md:p-6 md:pb-6">{children}</div>
|
<div className="flex flex-1 flex-col gap-4 p-4 pb-24 md:p-6 md:pb-6">{children}</div>
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
<BottomNav />
|
<BottomNav canWrite={canWrite} />
|
||||||
</QuickAddProvider>
|
</QuickAddProvider>
|
||||||
</SidebarProvider>
|
</SidebarProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -96,6 +96,21 @@
|
|||||||
--chart-4: var(--warning);
|
--chart-4: var(--warning);
|
||||||
--chart-5: oklch(0.65 0.08 230);
|
--chart-5: oklch(0.65 0.08 230);
|
||||||
--radius: 0.625rem;
|
--radius: 0.625rem;
|
||||||
|
|
||||||
|
/* Kullanıcı verisi renkleri (kategori/hesap): anahtar → değişken (shared/appearance.ts) */
|
||||||
|
--swatch-blue: oklch(0.6 0.15 258);
|
||||||
|
--swatch-sky: oklch(0.6 0.15 230);
|
||||||
|
--swatch-teal: oklch(0.6 0.15 185);
|
||||||
|
--swatch-green: oklch(0.6 0.15 150);
|
||||||
|
--swatch-lime: oklch(0.6 0.15 125);
|
||||||
|
--swatch-amber: oklch(0.6 0.15 80);
|
||||||
|
--swatch-orange: oklch(0.6 0.15 55);
|
||||||
|
--swatch-red: oklch(0.6 0.15 25);
|
||||||
|
--swatch-rose: oklch(0.6 0.15 10);
|
||||||
|
--swatch-pink: oklch(0.6 0.15 350);
|
||||||
|
--swatch-purple: oklch(0.6 0.15 305);
|
||||||
|
--swatch-indigo: oklch(0.6 0.15 275);
|
||||||
|
--swatch-slate: oklch(0.55 0.03 255);
|
||||||
--sidebar: oklch(0.975 0.008 250);
|
--sidebar: oklch(0.975 0.008 250);
|
||||||
--sidebar-foreground: oklch(0.22 0.04 262);
|
--sidebar-foreground: oklch(0.22 0.04 262);
|
||||||
--sidebar-primary: oklch(0.49 0.17 258);
|
--sidebar-primary: oklch(0.49 0.17 258);
|
||||||
@@ -140,6 +155,20 @@
|
|||||||
--chart-3: var(--expense);
|
--chart-3: var(--expense);
|
||||||
--chart-4: var(--warning);
|
--chart-4: var(--warning);
|
||||||
--chart-5: oklch(0.7 0.07 230);
|
--chart-5: oklch(0.7 0.07 230);
|
||||||
|
|
||||||
|
--swatch-blue: oklch(0.74 0.13 258);
|
||||||
|
--swatch-sky: oklch(0.74 0.13 230);
|
||||||
|
--swatch-teal: oklch(0.74 0.13 185);
|
||||||
|
--swatch-green: oklch(0.74 0.13 150);
|
||||||
|
--swatch-lime: oklch(0.74 0.13 125);
|
||||||
|
--swatch-amber: oklch(0.74 0.13 80);
|
||||||
|
--swatch-orange: oklch(0.74 0.13 55);
|
||||||
|
--swatch-red: oklch(0.74 0.13 25);
|
||||||
|
--swatch-rose: oklch(0.74 0.13 10);
|
||||||
|
--swatch-pink: oklch(0.74 0.13 350);
|
||||||
|
--swatch-purple: oklch(0.74 0.13 305);
|
||||||
|
--swatch-indigo: oklch(0.74 0.13 275);
|
||||||
|
--swatch-slate: oklch(0.72 0.03 255);
|
||||||
--sidebar: oklch(0.2 0.045 264);
|
--sidebar: oklch(0.2 0.045 264);
|
||||||
--sidebar-foreground: oklch(0.96 0.01 250);
|
--sidebar-foreground: oklch(0.96 0.01 250);
|
||||||
--sidebar-primary: oklch(0.76 0.12 245);
|
--sidebar-primary: oklch(0.76 0.12 245);
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import {
|
||||||
|
Baby,
|
||||||
|
Banknote,
|
||||||
|
Book,
|
||||||
|
Briefcase,
|
||||||
|
Building,
|
||||||
|
Bus,
|
||||||
|
Car,
|
||||||
|
CircleEllipsis,
|
||||||
|
Coffee,
|
||||||
|
Coins,
|
||||||
|
CreditCard,
|
||||||
|
Droplet,
|
||||||
|
Dumbbell,
|
||||||
|
Film,
|
||||||
|
Flame,
|
||||||
|
Fuel,
|
||||||
|
Gamepad2,
|
||||||
|
Gift,
|
||||||
|
GraduationCap,
|
||||||
|
HeartPulse,
|
||||||
|
House,
|
||||||
|
Landmark,
|
||||||
|
Music,
|
||||||
|
PawPrint,
|
||||||
|
Percent,
|
||||||
|
PiggyBank,
|
||||||
|
Pill,
|
||||||
|
Plane,
|
||||||
|
Receipt,
|
||||||
|
Repeat,
|
||||||
|
Scissors,
|
||||||
|
Shirt,
|
||||||
|
ShoppingBasket,
|
||||||
|
ShoppingCart,
|
||||||
|
Smartphone,
|
||||||
|
Sofa,
|
||||||
|
Sparkles,
|
||||||
|
SprayCan,
|
||||||
|
Tag,
|
||||||
|
Train,
|
||||||
|
TrendingUp,
|
||||||
|
Undo2,
|
||||||
|
Utensils,
|
||||||
|
Wallet,
|
||||||
|
Wifi,
|
||||||
|
Wrench,
|
||||||
|
Zap,
|
||||||
|
type LucideIcon,
|
||||||
|
type LucideProps,
|
||||||
|
} from "lucide-react";
|
||||||
|
import type { IconKey } from "@/shared/appearance";
|
||||||
|
|
||||||
|
/** Saklanan ikon anahtarı → lucide bileşeni (shared/appearance.ts ICON_KEYS ile birebir). */
|
||||||
|
export const ICONS: Record<IconKey, LucideIcon> = {
|
||||||
|
wallet: Wallet,
|
||||||
|
banknote: Banknote,
|
||||||
|
landmark: Landmark,
|
||||||
|
"piggy-bank": PiggyBank,
|
||||||
|
"credit-card": CreditCard,
|
||||||
|
utensils: Utensils,
|
||||||
|
"shopping-cart": ShoppingCart,
|
||||||
|
"shopping-basket": ShoppingBasket,
|
||||||
|
receipt: Receipt,
|
||||||
|
zap: Zap,
|
||||||
|
droplet: Droplet,
|
||||||
|
flame: Flame,
|
||||||
|
wifi: Wifi,
|
||||||
|
smartphone: Smartphone,
|
||||||
|
house: House,
|
||||||
|
building: Building,
|
||||||
|
car: Car,
|
||||||
|
fuel: Fuel,
|
||||||
|
bus: Bus,
|
||||||
|
train: Train,
|
||||||
|
"heart-pulse": HeartPulse,
|
||||||
|
pill: Pill,
|
||||||
|
"graduation-cap": GraduationCap,
|
||||||
|
book: Book,
|
||||||
|
shirt: Shirt,
|
||||||
|
gamepad: Gamepad2,
|
||||||
|
film: Film,
|
||||||
|
music: Music,
|
||||||
|
coffee: Coffee,
|
||||||
|
plane: Plane,
|
||||||
|
gift: Gift,
|
||||||
|
baby: Baby,
|
||||||
|
"paw-print": PawPrint,
|
||||||
|
wrench: Wrench,
|
||||||
|
sofa: Sofa,
|
||||||
|
repeat: Repeat,
|
||||||
|
briefcase: Briefcase,
|
||||||
|
"trending-up": TrendingUp,
|
||||||
|
coins: Coins,
|
||||||
|
percent: Percent,
|
||||||
|
undo: Undo2,
|
||||||
|
sparkles: Sparkles,
|
||||||
|
"spray-can": SprayCan,
|
||||||
|
scissors: Scissors,
|
||||||
|
dumbbell: Dumbbell,
|
||||||
|
tag: Tag,
|
||||||
|
"circle-ellipsis": CircleEllipsis,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AppIcon({ name, ...props }: { name: IconKey } & LucideProps) {
|
||||||
|
const Icon = ICONS[name] ?? Tag;
|
||||||
|
return <Icon aria-hidden {...props} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Check } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ICON_KEYS, SWATCHES, type IconKey, type Swatch } from "@/shared/appearance";
|
||||||
|
import { AppIcon } from "./app-icon";
|
||||||
|
import { swatchStyle } from "./swatch";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
|
||||||
|
/** Renk seçici (radio grubu, klavye ile gezilebilir). */
|
||||||
|
export function SwatchPicker({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
labelledBy,
|
||||||
|
}: {
|
||||||
|
value: Swatch;
|
||||||
|
onChange: (v: Swatch) => void;
|
||||||
|
labelledBy: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div role="radiogroup" aria-labelledby={labelledBy} className="flex flex-wrap gap-2">
|
||||||
|
{SWATCHES.map((s) => (
|
||||||
|
<button
|
||||||
|
key={s}
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={value === s}
|
||||||
|
aria-label={tr.swatches[s]}
|
||||||
|
title={tr.swatches[s]}
|
||||||
|
onClick={() => onChange(s)}
|
||||||
|
style={swatchStyle(s)}
|
||||||
|
className="flex size-8 items-center justify-center rounded-full bg-(--swatch) text-background ring-offset-2 ring-offset-background outline-none focus-visible:ring-3 focus-visible:ring-ring/50 aria-checked:ring-2 aria-checked:ring-(--swatch)"
|
||||||
|
>
|
||||||
|
{value === s ? <Check className="size-4" /> : null}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** İkon seçici; seçili renkle önizler. */
|
||||||
|
export function IconPicker({
|
||||||
|
value,
|
||||||
|
color,
|
||||||
|
onChange,
|
||||||
|
labelledBy,
|
||||||
|
}: {
|
||||||
|
value: IconKey;
|
||||||
|
color: Swatch;
|
||||||
|
onChange: (v: IconKey) => void;
|
||||||
|
labelledBy: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="radiogroup"
|
||||||
|
aria-labelledby={labelledBy}
|
||||||
|
style={swatchStyle(color)}
|
||||||
|
className="grid max-h-44 grid-cols-8 gap-1 overflow-y-auto rounded-lg border p-1.5 sm:grid-cols-10"
|
||||||
|
>
|
||||||
|
{ICON_KEYS.map((key) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={value === key}
|
||||||
|
aria-label={key}
|
||||||
|
onClick={() => onChange(key)}
|
||||||
|
className={cn(
|
||||||
|
"flex aspect-square items-center justify-center rounded-md outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50",
|
||||||
|
"aria-checked:bg-(--swatch)/15 aria-checked:text-(--swatch) aria-checked:ring-1 aria-checked:ring-(--swatch)",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<AppIcon name={key} className="size-4.5" />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
|
import { AppIcon } from "./app-icon";
|
||||||
|
|
||||||
|
/** Renk anahtarını CSS değişkenine bağlar: --swatch-blue → --swatch (sınıflar bunu kullanır). */
|
||||||
|
export const swatchStyle = (color: Swatch) =>
|
||||||
|
({ "--swatch": `var(--swatch-${color})` }) as React.CSSProperties;
|
||||||
|
|
||||||
|
/** Renkli yuvarlak ikon rozeti (kategori/hesap). */
|
||||||
|
export function IconBadge({
|
||||||
|
icon,
|
||||||
|
color,
|
||||||
|
className,
|
||||||
|
size = "md",
|
||||||
|
}: {
|
||||||
|
icon: IconKey;
|
||||||
|
color: Swatch;
|
||||||
|
className?: string;
|
||||||
|
size?: "sm" | "md";
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
style={swatchStyle(color)}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex shrink-0 items-center justify-center rounded-full bg-(--swatch)/15 text-(--swatch)",
|
||||||
|
size === "sm" ? "size-7 [&_svg]:size-3.5" : "size-9 [&_svg]:size-4.5",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<AppIcon name={icon} />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,18 +11,23 @@ import { UserMenu } from "./user-menu";
|
|||||||
export function AppHeader({
|
export function AppHeader({
|
||||||
user,
|
user,
|
||||||
households,
|
households,
|
||||||
|
activeHouseholdId,
|
||||||
|
canWrite,
|
||||||
version,
|
version,
|
||||||
}: {
|
}: {
|
||||||
user: SessionUser;
|
user: SessionUser;
|
||||||
households: HouseholdSummary[];
|
households: HouseholdSummary[];
|
||||||
|
activeHouseholdId: string | undefined;
|
||||||
|
/** Aktif hanede en az "member" mi? (İzleyici veri giremez.) */
|
||||||
|
canWrite: boolean;
|
||||||
version: string;
|
version: string;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-background/95 px-3 backdrop-blur supports-backdrop-filter:bg-background/80 md:px-4">
|
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-background/95 px-3 backdrop-blur supports-backdrop-filter:bg-background/80 md:px-4">
|
||||||
<SidebarTrigger className="hidden md:inline-flex" aria-label={tr.nav.toggleSidebar} />
|
<SidebarTrigger className="hidden md:inline-flex" aria-label={tr.nav.toggleSidebar} />
|
||||||
<HouseholdSwitcher households={households} />
|
<HouseholdSwitcher households={households} activeId={activeHouseholdId} />
|
||||||
<div className="ml-auto flex items-center gap-1">
|
<div className="ml-auto flex items-center gap-1">
|
||||||
<QuickAddButton className="hidden md:inline-flex" />
|
{canWrite ? <QuickAddButton className="hidden md:inline-flex" /> : null}
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<UserMenu user={user} version={version} />
|
<UserMenu user={user} version={version} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ function BottomNavLink({ item, pathname }: { item: NavItem; pathname: string })
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Mobil alt gezinme çubuğu (md altı). */
|
/** Mobil alt gezinme çubuğu (md altı). */
|
||||||
export function BottomNav() {
|
export function BottomNav({ canWrite }: { canWrite: boolean }) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { openQuickAdd } = useQuickAdd();
|
const { openQuickAdd } = useQuickAdd();
|
||||||
const { setOpenMobile } = useSidebar();
|
const { setOpenMobile } = useSidebar();
|
||||||
@@ -57,8 +57,10 @@ export function BottomNav() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={openQuickAdd}
|
onClick={openQuickAdd}
|
||||||
|
disabled={!canWrite}
|
||||||
|
title={canWrite ? undefined : tr.households.viewerReadOnly}
|
||||||
aria-label={tr.quickAdd.button}
|
aria-label={tr.quickAdd.button}
|
||||||
className="-mt-5 flex size-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg outline-none focus-visible:ring-4 focus-visible:ring-ring/50"
|
className="-mt-5 flex size-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg outline-none focus-visible:ring-4 focus-visible:ring-ring/50 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
<Plus className="size-6" />
|
<Plus className="size-6" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { House } from "lucide-react";
|
import { House } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useTransition } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -9,17 +10,38 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
|
import { switchHouseholdAction } from "@/features/households/actions";
|
||||||
import type { HouseholdSummary } from "@/features/households/types";
|
import type { HouseholdSummary } from "@/features/households/types";
|
||||||
import { tr } from "@/i18n/tr";
|
import { tr } from "@/i18n/tr";
|
||||||
|
|
||||||
/** Üst bar aktif hane seçici. FAZ 5: seçim sunucuda (cookie) saklanacak. */
|
/** Üst bar aktif hane seçici. Seçim sunucuda doğrulanır ve cookie'ye yazılır. */
|
||||||
export function HouseholdSwitcher({ households }: { households: HouseholdSummary[] }) {
|
export function HouseholdSwitcher({
|
||||||
const [value, setValue] = useState(households[0]?.id);
|
households,
|
||||||
const current = households.find((h) => h.id === value);
|
activeId,
|
||||||
|
}: {
|
||||||
|
households: HouseholdSummary[];
|
||||||
|
activeId: string | undefined;
|
||||||
|
}) {
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
const current = households.find((h) => h.id === activeId);
|
||||||
if (households.length === 0) return null;
|
if (households.length === 0) return null;
|
||||||
|
|
||||||
|
function onChange(id: string) {
|
||||||
|
if (id === activeId) return;
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await switchHouseholdAction(id);
|
||||||
|
if (result.ok) toast.success(tr.household.switched(result.data.name));
|
||||||
|
else toast.error(result.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Select value={value} onValueChange={setValue}>
|
<Select value={activeId} onValueChange={onChange} disabled={pending || households.length < 2}>
|
||||||
<SelectTrigger aria-label={tr.household.label} className="w-[min(46vw,13rem)]">
|
<SelectTrigger
|
||||||
|
aria-label={tr.household.label}
|
||||||
|
className="w-[min(46vw,13rem)]"
|
||||||
|
aria-busy={pending}
|
||||||
|
>
|
||||||
<House className="text-muted-foreground" />
|
<House className="text-muted-foreground" />
|
||||||
{/* Etiket children ile verilir: Radix aksi halde hydration'a kadar boş gösterir. */}
|
{/* Etiket children ile verilir: Radix aksi halde hydration'a kadar boş gösterir. */}
|
||||||
<SelectValue placeholder={tr.household.select}>{current?.name}</SelectValue>
|
<SelectValue placeholder={tr.household.select}>{current?.name}</SelectValue>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Package,
|
Package,
|
||||||
Settings,
|
Settings,
|
||||||
ShoppingCart,
|
ShoppingCart,
|
||||||
|
Tags,
|
||||||
Target,
|
Target,
|
||||||
UserCog,
|
UserCog,
|
||||||
Users,
|
Users,
|
||||||
@@ -25,14 +26,16 @@ export type NavItem = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
|
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
|
||||||
export const CURRENT_PHASE = 2;
|
/** Alt fazlar ondalıkla: 6.1 = Faz 6a. */
|
||||||
|
export const CURRENT_PHASE = 6.1;
|
||||||
|
|
||||||
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
|
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
|
||||||
|
|
||||||
export const MAIN_NAV: NavItem[] = [
|
export const MAIN_NAV: NavItem[] = [
|
||||||
{ href: "/dashboard", label: tr.nav.dashboard, icon: LayoutDashboard, phase: 2 },
|
{ href: "/dashboard", label: tr.nav.dashboard, icon: LayoutDashboard, phase: 2 },
|
||||||
{ href: "/islemler", label: tr.nav.transactions, icon: ArrowLeftRight, phase: 6 },
|
{ href: "/islemler", label: tr.nav.transactions, icon: ArrowLeftRight, phase: 6.2 },
|
||||||
{ href: "/hesaplar", label: tr.nav.accounts, icon: Wallet, phase: 6 },
|
{ href: "/hesaplar", label: tr.nav.accounts, icon: Wallet, phase: 6.1 },
|
||||||
|
{ href: "/kategoriler", label: tr.nav.categories, icon: Tags, phase: 6.1 },
|
||||||
{ href: "/planli", label: tr.nav.planned, icon: CalendarClock, phase: 7 },
|
{ href: "/planli", label: tr.nav.planned, icon: CalendarClock, phase: 7 },
|
||||||
{ href: "/cari", label: tr.nav.contacts, icon: Users, phase: 8 },
|
{ href: "/cari", label: tr.nav.contacts, icon: Users, phase: 8 },
|
||||||
{ href: "/birikim", label: tr.nav.savings, icon: Coins, phase: 9 },
|
{ href: "/birikim", label: tr.nav.savings, icon: Coins, phase: 9 },
|
||||||
@@ -49,9 +52,11 @@ export const ADMIN_NAV: NavItem[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
/** Mobil alt menü: ortada Hızlı ekle, sağda "Daha fazla" (yan menüyü açar). */
|
/** Mobil alt menü: ortada Hızlı ekle, sağda "Daha fazla" (yan menüyü açar). */
|
||||||
|
const navByHref = (href: string) => MAIN_NAV.find((i) => i.href === href)!;
|
||||||
|
|
||||||
export const BOTTOM_NAV = {
|
export const BOTTOM_NAV = {
|
||||||
left: [MAIN_NAV[0]!, MAIN_NAV[1]!],
|
left: [navByHref("/dashboard"), navByHref("/islemler")],
|
||||||
right: [MAIN_NAV[6]!],
|
right: [navByHref("/butce")],
|
||||||
};
|
};
|
||||||
|
|
||||||
export function isActivePath(pathname: string, href: string) {
|
export function isActivePath(pathname: string, href: string) {
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
InputGroup,
|
||||||
|
InputGroupAddon,
|
||||||
|
InputGroupInput,
|
||||||
|
InputGroupText,
|
||||||
|
} from "@/components/ui/input-group";
|
||||||
|
import { formatMoneyInput, parseMoney } from "@/shared/money";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Türkçe tutar girişi ("1.250,50"). Değer string olarak tutulur (zod sunucuda/istemcide ayrıştırır);
|
||||||
|
* alandan çıkınca geçerliyse Türkçe biçime getirilir.
|
||||||
|
*/
|
||||||
|
export function MoneyInput({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
onBlur,
|
||||||
|
allowNegative = false,
|
||||||
|
...props
|
||||||
|
}: Omit<React.ComponentProps<typeof InputGroupInput>, "value" | "onChange" | "type"> & {
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
allowNegative?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<InputGroup>
|
||||||
|
<InputGroupInput
|
||||||
|
{...props}
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
autoComplete="off"
|
||||||
|
className="text-right tabular-nums"
|
||||||
|
value={value}
|
||||||
|
onChange={(e) =>
|
||||||
|
onChange(e.target.value.replace(allowNegative ? /[^\d.,\s-−]/g : /[^\d.,\s]/g, ""))
|
||||||
|
}
|
||||||
|
onBlur={(e) => {
|
||||||
|
const minor = parseMoney(value);
|
||||||
|
if (minor !== null && value.trim() !== "") onChange(formatMoneyInput(minor));
|
||||||
|
onBlur?.(e);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<InputGroupAddon align="inline-end">
|
||||||
|
<InputGroupText>₺</InputGroupText>
|
||||||
|
</InputGroupAddon>
|
||||||
|
</InputGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { getHouseholdActionContext } from "@/lib/dal";
|
||||||
|
import { accountFormSchema } from "@/shared/schemas/account";
|
||||||
|
import { createAccount, reorderAccount, setAccountArchived, updateAccount } from "./service";
|
||||||
|
|
||||||
|
const PATH = "/hesaplar";
|
||||||
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
||||||
|
|
||||||
|
/** zod hatalarını alan bazlı mesajlara çevirir (formda gösterilir). */
|
||||||
|
function fieldErrors(error: z.ZodError) {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const issue of error.issues) {
|
||||||
|
const key = String(issue.path[0] ?? "");
|
||||||
|
if (key && !out[key]) out[key] = issue.message;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAccountAction(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const parsed = accountFormSchema.safeParse(input);
|
||||||
|
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
|
||||||
|
const result = await createAccount(ctx.user.id, ctx.household.id, parsed.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAccountAction(
|
||||||
|
accountId: unknown,
|
||||||
|
input: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(accountId);
|
||||||
|
const parsed = accountFormSchema.safeParse(input);
|
||||||
|
if (!id.success) return fail(tr.common.notFound);
|
||||||
|
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
|
||||||
|
const result = await updateAccount(ctx.user.id, ctx.household.id, id.data, parsed.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setAccountArchivedAction(
|
||||||
|
accountId: unknown,
|
||||||
|
archived: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(accountId);
|
||||||
|
const a = z.boolean().safeParse(archived);
|
||||||
|
if (!id.success || !a.success) return fail(tr.common.genericError);
|
||||||
|
const result = await setAccountArchived(ctx.user.id, ctx.household.id, id.data, a.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reorderAccountAction(
|
||||||
|
accountId: unknown,
|
||||||
|
direction: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(accountId);
|
||||||
|
const dir = z.enum(["up", "down"]).safeParse(direction);
|
||||||
|
if (!id.success || !dir.success) return fail(tr.common.genericError);
|
||||||
|
const result = await reorderAccount(ctx.user.id, ctx.household.id, id.data, dir.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,678 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { ChevronDown, Loader2 } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Controller, useForm, useWatch, type Control, type Resolver } from "react-hook-form";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { IconPicker, SwatchPicker } from "@/components/appearance/pickers";
|
||||||
|
import { MoneyInput } from "@/components/money-input";
|
||||||
|
import { ResponsiveDialog } from "@/components/responsive-dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||||
|
import {
|
||||||
|
Field,
|
||||||
|
FieldDescription,
|
||||||
|
FieldError,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLabel,
|
||||||
|
FieldLegend,
|
||||||
|
FieldSet,
|
||||||
|
} from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import {
|
||||||
|
ACCOUNT_TYPES,
|
||||||
|
DUE_RULE_KINDS,
|
||||||
|
MEAL_CARD_PROVIDERS,
|
||||||
|
type AccountType,
|
||||||
|
} from "@/shared/accounts";
|
||||||
|
import type { IconKey } from "@/shared/appearance";
|
||||||
|
import { todayIstanbul } from "@/shared/dates";
|
||||||
|
import { formatMoneyInput } from "@/shared/money";
|
||||||
|
import {
|
||||||
|
accountFormSchema,
|
||||||
|
type AccountForm,
|
||||||
|
type AccountFormInput,
|
||||||
|
} from "@/shared/schemas/account";
|
||||||
|
import { createAccountAction, updateAccountAction } from "../actions";
|
||||||
|
import type { AccountView } from "../service";
|
||||||
|
|
||||||
|
const t = tr.accounts;
|
||||||
|
const f = t.fields;
|
||||||
|
const NONE = "__none__";
|
||||||
|
const DAYS = Array.from({ length: 31 }, (_, i) => i + 1);
|
||||||
|
|
||||||
|
const DEFAULT_ICON: Record<AccountType, IconKey> = {
|
||||||
|
cash: "wallet",
|
||||||
|
bank: "landmark",
|
||||||
|
savings: "piggy-bank",
|
||||||
|
credit_card: "credit-card",
|
||||||
|
meal_card: "utensils",
|
||||||
|
};
|
||||||
|
|
||||||
|
type FormValues = {
|
||||||
|
name: string;
|
||||||
|
type: AccountType;
|
||||||
|
institution: string;
|
||||||
|
mealCardProvider: AccountFormInput["mealCardProvider"];
|
||||||
|
openingBalance: string;
|
||||||
|
openingDate: string;
|
||||||
|
color: AccountFormInput["color"];
|
||||||
|
icon: AccountFormInput["icon"];
|
||||||
|
ownerUserId: string;
|
||||||
|
isPrivate: boolean;
|
||||||
|
overdraftEnabled: boolean;
|
||||||
|
overdraftLimit: string;
|
||||||
|
overdraftMonthlyRate: string;
|
||||||
|
overdraftStatementDay: string;
|
||||||
|
cardLimit: string;
|
||||||
|
cardStatementDay: string;
|
||||||
|
cardDueKind: AccountFormInput["cardDueKind"];
|
||||||
|
cardDueValue: string;
|
||||||
|
cardPaymentAccountId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const money = (minor: number | null | undefined) => (minor ? formatMoneyInput(minor) : "");
|
||||||
|
|
||||||
|
function toValues(a?: AccountView): FormValues {
|
||||||
|
if (!a) {
|
||||||
|
return {
|
||||||
|
name: "",
|
||||||
|
type: "bank",
|
||||||
|
institution: "",
|
||||||
|
mealCardProvider: null,
|
||||||
|
openingBalance: "",
|
||||||
|
openingDate: todayIstanbul(),
|
||||||
|
color: "blue",
|
||||||
|
icon: "landmark",
|
||||||
|
ownerUserId: "",
|
||||||
|
isPrivate: false,
|
||||||
|
overdraftEnabled: false,
|
||||||
|
overdraftLimit: "",
|
||||||
|
overdraftMonthlyRate: "",
|
||||||
|
overdraftStatementDay: "",
|
||||||
|
cardLimit: "",
|
||||||
|
cardStatementDay: "1",
|
||||||
|
cardDueKind: "daysAfter",
|
||||||
|
cardDueValue: "10",
|
||||||
|
cardPaymentAccountId: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const isCard = a.type === "credit_card";
|
||||||
|
return {
|
||||||
|
name: a.name,
|
||||||
|
type: a.type,
|
||||||
|
institution: a.institution,
|
||||||
|
mealCardProvider: a.mealCardProvider,
|
||||||
|
openingBalance:
|
||||||
|
a.openingBalanceMinor === null
|
||||||
|
? ""
|
||||||
|
: money(isCard ? Math.abs(a.openingBalanceMinor) : a.openingBalanceMinor),
|
||||||
|
openingDate: a.openingDate,
|
||||||
|
color: a.color,
|
||||||
|
icon: a.icon,
|
||||||
|
ownerUserId: a.ownerUserId ?? "",
|
||||||
|
isPrivate: a.isPrivate,
|
||||||
|
overdraftEnabled: Boolean(a.overdraft),
|
||||||
|
overdraftLimit: money(a.overdraft?.limitMinor),
|
||||||
|
overdraftMonthlyRate: a.overdraft?.monthlyRateBp
|
||||||
|
? formatMoneyInput(a.overdraft.monthlyRateBp)
|
||||||
|
: "",
|
||||||
|
overdraftStatementDay: a.overdraft?.statementDay ? String(a.overdraft.statementDay) : "",
|
||||||
|
cardLimit: money(a.creditCard?.limitMinor),
|
||||||
|
cardStatementDay: String(a.creditCard?.statementDay ?? 1),
|
||||||
|
cardDueKind: a.creditCard?.dueRule.kind ?? "daysAfter",
|
||||||
|
cardDueValue: String(a.creditCard?.dueRule.value ?? 10),
|
||||||
|
cardPaymentAccountId: a.creditCard?.paymentAccountId ?? "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function DaySelect({
|
||||||
|
id,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
max = 31,
|
||||||
|
allowEmpty,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (v: string) => void;
|
||||||
|
max?: number;
|
||||||
|
allowEmpty?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Select value={value || NONE} onValueChange={(v) => onChange(v === NONE ? "" : v)}>
|
||||||
|
<SelectTrigger id={id} className="w-28">
|
||||||
|
<SelectValue>{value || "—"}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="max-h-64">
|
||||||
|
{allowEmpty ? <SelectItem value={NONE}>—</SelectItem> : null}
|
||||||
|
{DAYS.slice(0, max).map((d) => (
|
||||||
|
<SelectItem key={d} value={String(d)}>
|
||||||
|
{d}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MoneyField({
|
||||||
|
control,
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
hint,
|
||||||
|
allowNegative,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
control: Control<FormValues, unknown, AccountForm>;
|
||||||
|
name: "openingBalance" | "overdraftLimit" | "cardLimit";
|
||||||
|
label: string;
|
||||||
|
hint?: string;
|
||||||
|
allowNegative?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Controller
|
||||||
|
name={name}
|
||||||
|
control={control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor={`acc-${name}`}>{label}</FieldLabel>
|
||||||
|
<MoneyInput
|
||||||
|
id={`acc-${name}`}
|
||||||
|
name={field.name}
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
allowNegative={allowNegative}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={disabled ? t.hidden : "0,00"}
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
aria-describedby={hint ? `acc-${name}-hint` : undefined}
|
||||||
|
/>
|
||||||
|
{hint ? <FieldDescription id={`acc-${name}-hint`}>{hint}</FieldDescription> : null}
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AccountFormDialog({
|
||||||
|
open,
|
||||||
|
account,
|
||||||
|
members,
|
||||||
|
paymentAccounts,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
account?: AccountView;
|
||||||
|
members: { id: string; name: string }[];
|
||||||
|
paymentAccounts: { id: string; name: string }[];
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const isEdit = Boolean(account);
|
||||||
|
const balanceHidden = isEdit && account!.openingBalanceMinor === null;
|
||||||
|
const form = useForm<FormValues, unknown, AccountForm>({
|
||||||
|
// FormValues, şemanın giriş şekliyle birebir (sayısal alanlar string olarak girilir, zod çevirir).
|
||||||
|
resolver: zodResolver(accountFormSchema) as unknown as Resolver<
|
||||||
|
FormValues,
|
||||||
|
unknown,
|
||||||
|
AccountForm
|
||||||
|
>,
|
||||||
|
defaultValues: toValues(),
|
||||||
|
});
|
||||||
|
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) form.reset(toValues(account));
|
||||||
|
}, [open, account, form]);
|
||||||
|
|
||||||
|
function handleOpenChange(next: boolean) {
|
||||||
|
if (!next) setAdvancedOpen(false);
|
||||||
|
onOpenChange(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = useWatch({ control: form.control, name: "type" });
|
||||||
|
const color = useWatch({ control: form.control, name: "color" });
|
||||||
|
const overdraftEnabled = useWatch({ control: form.control, name: "overdraftEnabled" });
|
||||||
|
const dueKind = useWatch({ control: form.control, name: "cardDueKind" });
|
||||||
|
const isCard = type === "credit_card";
|
||||||
|
|
||||||
|
/** Ham form değerleri gönderilir; sunucu aynı şemayla ayrıştırır. */
|
||||||
|
async function onSubmit() {
|
||||||
|
const values = form.getValues();
|
||||||
|
// Gizli bakiyede sunucu mevcut değeri korur; doğrulamadan geçmesi için 0 gönderilir.
|
||||||
|
const payload = balanceHidden ? { ...values, openingBalance: "0" } : values;
|
||||||
|
const result = account
|
||||||
|
? await updateAccountAction(account.id, payload)
|
||||||
|
: await createAccountAction(payload);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(account ? t.updated(values.name) : t.created(values.name));
|
||||||
|
handleOpenChange(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let advancedError = false;
|
||||||
|
for (const [name, message] of Object.entries(result.fieldErrors ?? {})) {
|
||||||
|
if (!message) continue;
|
||||||
|
form.setError(name as keyof FormValues, { message });
|
||||||
|
if (/^(overdraft|ownerUserId|isPrivate)/.test(name)) advancedError = true;
|
||||||
|
}
|
||||||
|
if (advancedError) setAdvancedOpen(true);
|
||||||
|
if (!result.fieldErrors) form.setError("root", { message: result.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveDialog
|
||||||
|
open={open}
|
||||||
|
onOpenChange={handleOpenChange}
|
||||||
|
title={isEdit ? t.editTitle : t.createTitle}
|
||||||
|
description={t.formDescription}
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button variant="outline" type="button" onClick={() => handleOpenChange(false)}>
|
||||||
|
{tr.common.cancel}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" form="account-form" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
|
{isEdit ? tr.common.save : tr.common.create}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<form id="account-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="type"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="acc-type">{f.type}</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={field.value}
|
||||||
|
disabled={isEdit}
|
||||||
|
onValueChange={(v) => {
|
||||||
|
field.onChange(v);
|
||||||
|
if (!isEdit) form.setValue("icon", DEFAULT_ICON[v as AccountType]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="acc-type" className="w-full">
|
||||||
|
<SelectValue>{t.types[field.value]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{ACCOUNT_TYPES.map((x) => (
|
||||||
|
<SelectItem key={x} value={x}>
|
||||||
|
{t.types[x]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{isEdit ? <FieldDescription>{f.typeLockedHint}</FieldDescription> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="name"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-name">{f.name}</FieldLabel>
|
||||||
|
<Input {...field} id="acc-name" aria-invalid={fieldState.invalid} />
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{type === "meal_card" ? (
|
||||||
|
<Controller
|
||||||
|
name="mealCardProvider"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-provider">{f.provider}</FieldLabel>
|
||||||
|
<Select value={field.value ?? undefined} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger
|
||||||
|
id="acc-provider"
|
||||||
|
className="w-full"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
>
|
||||||
|
<SelectValue placeholder={f.provider}>
|
||||||
|
{field.value ? t.providers[field.value] : null}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{MEAL_CARD_PROVIDERS.map((p) => (
|
||||||
|
<SelectItem key={p} value={p}>
|
||||||
|
{t.providers[p]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
) : type !== "cash" ? (
|
||||||
|
<Controller
|
||||||
|
name="institution"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="acc-institution">{f.institution}</FieldLabel>
|
||||||
|
<Input {...field} id="acc-institution" placeholder={f.institutionPlaceholder} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<MoneyField
|
||||||
|
control={form.control}
|
||||||
|
name="openingBalance"
|
||||||
|
label={isCard ? f.openingDebt : f.openingBalance}
|
||||||
|
hint={
|
||||||
|
balanceHidden
|
||||||
|
? t.hiddenHint
|
||||||
|
: isCard
|
||||||
|
? f.openingDebtHint
|
||||||
|
: type === "bank"
|
||||||
|
? f.openingBalanceHint
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
allowNegative={type === "bank"}
|
||||||
|
disabled={balanceHidden}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="openingDate"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-date">{f.openingDate}</FieldLabel>
|
||||||
|
<Input {...field} id="acc-date" type="date" aria-invalid={fieldState.invalid} />
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isCard ? (
|
||||||
|
<FieldSet>
|
||||||
|
<FieldLegend>{f.card}</FieldLegend>
|
||||||
|
<FieldGroup>
|
||||||
|
<MoneyField control={form.control} name="cardLimit" label={f.cardLimit} />
|
||||||
|
<Controller
|
||||||
|
name="cardStatementDay"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="acc-card-statement">{f.cardStatementDay}</FieldLabel>
|
||||||
|
<DaySelect
|
||||||
|
id="acc-card-statement"
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
/>
|
||||||
|
<FieldDescription>{f.cardStatementDayHint}</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Controller
|
||||||
|
name="cardDueKind"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="acc-card-due-kind">{f.cardDueKind}</FieldLabel>
|
||||||
|
<Select value={field.value} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger id="acc-card-due-kind" className="w-full">
|
||||||
|
<SelectValue>{f.dueKinds[field.value]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{DUE_RULE_KINDS.map((k) => (
|
||||||
|
<SelectItem key={k} value={k}>
|
||||||
|
{f.dueKinds[k]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="cardDueValue"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-card-due-value">
|
||||||
|
{dueKind === "daysAfter" ? f.cardDueValueDays : f.cardDueValueDay}
|
||||||
|
</FieldLabel>
|
||||||
|
<DaySelect
|
||||||
|
id="acc-card-due-value"
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
max={dueKind === "daysAfter" ? 30 : 31}
|
||||||
|
/>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Controller
|
||||||
|
name="cardPaymentAccountId"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-card-payer">{f.cardPaymentAccount}</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={field.value || NONE}
|
||||||
|
onValueChange={(v) => field.onChange(v === NONE ? "" : v)}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id="acc-card-payer"
|
||||||
|
className="w-full"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
>
|
||||||
|
<SelectValue>
|
||||||
|
{paymentAccounts.find((p) => p.id === field.value)?.name ??
|
||||||
|
f.cardPaymentAccountNone}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={NONE}>{f.cardPaymentAccountNone}</SelectItem>
|
||||||
|
{paymentAccounts
|
||||||
|
.filter((p) => p.id !== account?.id)
|
||||||
|
.map((p) => (
|
||||||
|
<SelectItem key={p.id} value={p.id}>
|
||||||
|
{p.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</FieldGroup>
|
||||||
|
</FieldSet>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<Button type="button" variant="ghost" className="-ml-2 w-fit">
|
||||||
|
<ChevronDown
|
||||||
|
className={
|
||||||
|
advancedOpen ? "rotate-180 transition-transform" : "transition-transform"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{f.advanced}
|
||||||
|
</Button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent className="pt-3">
|
||||||
|
<FieldGroup>
|
||||||
|
{type === "bank" ? (
|
||||||
|
<FieldSet>
|
||||||
|
<FieldLegend>{f.overdraft}</FieldLegend>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="overdraftEnabled"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<Checkbox
|
||||||
|
id="acc-od"
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={(v) => field.onChange(v === true)}
|
||||||
|
/>
|
||||||
|
<FieldLabel htmlFor="acc-od" className="font-normal">
|
||||||
|
{f.overdraftEnabled}
|
||||||
|
</FieldLabel>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{overdraftEnabled ? (
|
||||||
|
<>
|
||||||
|
<MoneyField
|
||||||
|
control={form.control}
|
||||||
|
name="overdraftLimit"
|
||||||
|
label={f.overdraftLimit}
|
||||||
|
/>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Controller
|
||||||
|
name="overdraftMonthlyRate"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-od-rate">{f.overdraftRate}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
id="acc-od-rate"
|
||||||
|
inputMode="decimal"
|
||||||
|
placeholder="4,25"
|
||||||
|
className="w-28 tabular-nums"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
/>
|
||||||
|
{fieldState.invalid ? (
|
||||||
|
<FieldError errors={[fieldState.error]} />
|
||||||
|
) : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="overdraftStatementDay"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="acc-od-day">
|
||||||
|
{f.overdraftStatementDay}
|
||||||
|
</FieldLabel>
|
||||||
|
<DaySelect
|
||||||
|
id="acc-od-day"
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
allowEmpty
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</FieldSet>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Controller
|
||||||
|
name="ownerUserId"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="acc-owner">{f.owner}</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={field.value || NONE}
|
||||||
|
onValueChange={(v) => field.onChange(v === NONE ? "" : v)}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id="acc-owner"
|
||||||
|
className="w-full"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
>
|
||||||
|
<SelectValue>
|
||||||
|
{members.find((m) => m.id === field.value)?.name ?? f.ownerNone}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={NONE}>{f.ownerNone}</SelectItem>
|
||||||
|
{members.map((m) => (
|
||||||
|
<SelectItem key={m.id} value={m.id}>
|
||||||
|
{m.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="isPrivate"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<Checkbox
|
||||||
|
id="acc-private"
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={(v) => field.onChange(v === true)}
|
||||||
|
/>
|
||||||
|
<FieldLabel htmlFor="acc-private" className="font-normal">
|
||||||
|
{f.isPrivate}
|
||||||
|
</FieldLabel>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="color"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel id="acc-color-label">{tr.categories.color}</FieldLabel>
|
||||||
|
<SwatchPicker
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
labelledBy="acc-color-label"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="icon"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel id="acc-icon-label">{tr.categories.icon}</FieldLabel>
|
||||||
|
<IconPicker
|
||||||
|
value={field.value}
|
||||||
|
color={color}
|
||||||
|
onChange={field.onChange}
|
||||||
|
labelledBy="acc-icon-label"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</FieldGroup>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
{form.formState.errors.root ? (
|
||||||
|
<FieldError>{form.formState.errors.root.message}</FieldError>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</ResponsiveDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Archive,
|
||||||
|
ArchiveRestore,
|
||||||
|
ArrowDown,
|
||||||
|
ArrowUp,
|
||||||
|
ChevronDown,
|
||||||
|
EyeOff,
|
||||||
|
MoreHorizontal,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { IconBadge } from "@/components/appearance/swatch";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ACCOUNT_TYPES, isLiabilityType } from "@/shared/accounts";
|
||||||
|
import { formatMoney } from "@/shared/format";
|
||||||
|
import { reorderAccountAction, setAccountArchivedAction } from "../actions";
|
||||||
|
import type { AccountTotals, AccountView } from "../service";
|
||||||
|
import { AccountFormDialog } from "./account-form-dialog";
|
||||||
|
|
||||||
|
const t = tr.accounts;
|
||||||
|
|
||||||
|
function BalanceText({ account }: { account: AccountView }) {
|
||||||
|
if (account.balanceMinor === null) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-1 text-sm text-muted-foreground"
|
||||||
|
title={t.hiddenHint}
|
||||||
|
>
|
||||||
|
<EyeOff className="size-3.5" />
|
||||||
|
{t.hidden}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const liability = isLiabilityType(account.type);
|
||||||
|
const value = account.balanceMinor;
|
||||||
|
return (
|
||||||
|
<span className="flex flex-col items-end">
|
||||||
|
{liability ? <span className="text-xs text-muted-foreground">{t.debt}</span> : null}
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-semibold tabular-nums",
|
||||||
|
(liability ? value < 0 : value < 0) && "text-expense",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{formatMoney(liability ? Math.abs(value) : value)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AccountsView({
|
||||||
|
accounts,
|
||||||
|
totals,
|
||||||
|
members,
|
||||||
|
canEdit,
|
||||||
|
}: {
|
||||||
|
accounts: AccountView[];
|
||||||
|
totals: AccountTotals;
|
||||||
|
members: { id: string; name: string }[];
|
||||||
|
canEdit: boolean;
|
||||||
|
}) {
|
||||||
|
const [dialog, setDialog] = useState<{ account?: AccountView } | null>(null);
|
||||||
|
const [archiving, setArchiving] = useState<AccountView | null>(null);
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
const active = accounts.filter((a) => !a.archived);
|
||||||
|
const archived = accounts.filter((a) => a.archived);
|
||||||
|
const memberName = (id: string | null) => members.find((m) => m.id === id)?.name;
|
||||||
|
const paymentAccounts = active
|
||||||
|
.filter((a) => ["bank", "cash", "savings"].includes(a.type))
|
||||||
|
.map((a) => ({ id: a.id, name: a.name }));
|
||||||
|
|
||||||
|
function run(promise: Promise<{ ok: boolean; error?: string }>, success?: string) {
|
||||||
|
startTransition(async () => {
|
||||||
|
const r = await promise;
|
||||||
|
if (r.ok) {
|
||||||
|
if (success) toast.success(success);
|
||||||
|
} else toast.error(r.error ?? tr.common.genericError);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({ a, index }: { a: AccountView; index: number }) {
|
||||||
|
const owner = memberName(a.ownerUserId);
|
||||||
|
return (
|
||||||
|
<li className={cn("flex items-center gap-3 p-3", a.archived && "opacity-60")}>
|
||||||
|
<IconBadge icon={a.icon} color={a.color} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium">{a.name}</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||||
|
{a.type === "meal_card" && a.mealCardProvider ? (
|
||||||
|
<span>{t.providers[a.mealCardProvider]}</span>
|
||||||
|
) : null}
|
||||||
|
{a.institution ? <span>{a.institution}</span> : null}
|
||||||
|
{owner ? <span>· {owner}</span> : null}
|
||||||
|
{a.isPrivate ? <Badge variant="outline">{t.privateBadge}</Badge> : null}
|
||||||
|
{a.overdraft ? (
|
||||||
|
<Badge variant="secondary">
|
||||||
|
{t.overdraftBadge(formatMoney(a.overdraft.limitMinor))}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
{a.creditCard ? (
|
||||||
|
<>
|
||||||
|
<Badge variant="secondary">
|
||||||
|
{t.limitLabel(formatMoney(a.creditCard.limitMinor))}
|
||||||
|
</Badge>
|
||||||
|
<span>{t.statementLabel(a.creditCard.statementDay)}</span>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<BalanceText account={a} />
|
||||||
|
{canEdit ? (
|
||||||
|
<DropdownMenu modal={false}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
aria-label={`${a.name} — ${tr.common.actions}`}
|
||||||
|
disabled={pending}
|
||||||
|
>
|
||||||
|
<MoreHorizontal />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-48">
|
||||||
|
{a.archived ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() =>
|
||||||
|
run(setAccountArchivedAction(a.id, false), t.unarchivedToast(a.name))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ArchiveRestore />
|
||||||
|
{t.unarchive}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<DropdownMenuItem onSelect={() => setDialog({ account: a })}>
|
||||||
|
<Pencil />
|
||||||
|
{tr.common.edit}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
disabled={index === 0}
|
||||||
|
onSelect={() => run(reorderAccountAction(a.id, "up"))}
|
||||||
|
>
|
||||||
|
<ArrowUp />
|
||||||
|
{tr.categories.moveUp}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
disabled={index === active.length - 1}
|
||||||
|
onSelect={() => run(reorderAccountAction(a.id, "down"))}
|
||||||
|
>
|
||||||
|
<ArrowDown />
|
||||||
|
{tr.categories.moveDown}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem variant="destructive" onSelect={() => setArchiving(a)}>
|
||||||
|
<Archive />
|
||||||
|
{t.archive}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = [
|
||||||
|
{ label: t.summary.assets, value: totals.assetsMinor, tone: "text-income" },
|
||||||
|
{
|
||||||
|
label: t.summary.cardDebt,
|
||||||
|
value: Math.abs(totals.cardDebtMinor),
|
||||||
|
tone: totals.cardDebtMinor ? "text-expense" : "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t.summary.net,
|
||||||
|
value: totals.netMinor,
|
||||||
|
tone: totals.netMinor < 0 ? "text-expense" : "",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
{summary.map((s) => (
|
||||||
|
<Card key={s.label} size="sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardDescription>{s.label}</CardDescription>
|
||||||
|
<CardTitle className={cn("text-base tabular-nums sm:text-lg", s.tone)}>
|
||||||
|
{formatMoney(s.value)}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{totals.includesHidden || totals.excludesHidden ? (
|
||||||
|
<p className="-mt-2 text-xs text-muted-foreground">
|
||||||
|
{totals.excludesHidden ? t.summary.excludesHidden : t.summary.includesHidden}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{!canEdit ? <p className="text-sm text-muted-foreground">{t.ownerOnly}</p> : null}
|
||||||
|
{canEdit ? (
|
||||||
|
<Button className="ml-auto" onClick={() => setDialog({})}>
|
||||||
|
<Plus />
|
||||||
|
{t.newAccount}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{active.length === 0 ? (
|
||||||
|
<div className="rounded-xl border border-dashed p-8 text-center text-muted-foreground">
|
||||||
|
<p>{t.empty}</p>
|
||||||
|
{canEdit ? <p className="mt-1 text-sm">{t.emptyOwnerHint}</p> : null}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
ACCOUNT_TYPES.map((type) => {
|
||||||
|
const group = active.filter((a) => a.type === type);
|
||||||
|
if (!group.length) return null;
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
key={type}
|
||||||
|
aria-labelledby={`acc-group-${type}`}
|
||||||
|
className="flex flex-col gap-2"
|
||||||
|
>
|
||||||
|
<h2 id={`acc-group-${type}`} className="text-sm font-medium text-muted-foreground">
|
||||||
|
{t.typeGroups[type]}
|
||||||
|
</h2>
|
||||||
|
<ul className="divide-y rounded-xl border bg-card" aria-busy={pending}>
|
||||||
|
{group.map((a) => (
|
||||||
|
<Row key={a.id} a={a} index={active.indexOf(a)} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
|
||||||
|
{archived.length ? (
|
||||||
|
<Collapsible>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<Button variant="ghost" className="-ml-2 w-fit">
|
||||||
|
<ChevronDown />
|
||||||
|
{t.archivedSection(archived.length)}
|
||||||
|
</Button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<ul className="mt-2 divide-y rounded-xl border bg-card">
|
||||||
|
{archived.map((a) => (
|
||||||
|
<Row key={a.id} a={a} index={-1} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<AccountFormDialog
|
||||||
|
open={Boolean(dialog)}
|
||||||
|
account={dialog?.account}
|
||||||
|
members={members}
|
||||||
|
paymentAccounts={paymentAccounts}
|
||||||
|
onOpenChange={(o) => !o && setDialog(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<AlertDialog open={Boolean(archiving)} onOpenChange={(o) => !o && setArchiving(null)}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{t.archiveTitle}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{archiving ? t.archiveDescription(archiving.name) : null}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>{tr.common.cancel}</AlertDialogCancel>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => {
|
||||||
|
const a = archiving!;
|
||||||
|
setArchiving(null);
|
||||||
|
run(setAccountArchivedAction(a.id, true), t.archivedToast(a.name));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t.archive}
|
||||||
|
</Button>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
import { AccountModel } from "@/models/account";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { setupSeededDb, teardownDb } from "@/test/seeded-db";
|
||||||
|
import { createAccount, listAccounts, setAccountArchived, updateAccount } from "./service";
|
||||||
|
|
||||||
|
let ids: Awaited<ReturnType<typeof setupSeededDb>>;
|
||||||
|
let cakir = "";
|
||||||
|
let annemler = "";
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ids = await setupSeededDb();
|
||||||
|
cakir = ids.household("Çakır Ailesi");
|
||||||
|
annemler = ids.household("Annemler");
|
||||||
|
});
|
||||||
|
afterAll(teardownDb);
|
||||||
|
|
||||||
|
const base = {
|
||||||
|
name: "Test Hesap",
|
||||||
|
type: "bank" as const,
|
||||||
|
institution: "",
|
||||||
|
mealCardProvider: null,
|
||||||
|
openingBalance: 100_00,
|
||||||
|
openingDate: "2026-05-01",
|
||||||
|
color: "blue" as const,
|
||||||
|
icon: "landmark" as const,
|
||||||
|
ownerUserId: null,
|
||||||
|
isPrivate: false,
|
||||||
|
overdraftEnabled: false,
|
||||||
|
overdraftLimit: 0,
|
||||||
|
overdraftMonthlyRate: null,
|
||||||
|
overdraftStatementDay: null,
|
||||||
|
cardLimit: 0,
|
||||||
|
cardStatementDay: 1,
|
||||||
|
cardDueKind: "daysAfter" as const,
|
||||||
|
cardDueValue: 10,
|
||||||
|
cardPaymentAccountId: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const accountId = (name: string, householdId = cakir) =>
|
||||||
|
AccountModel.findOne({ householdId, name })
|
||||||
|
.lean()
|
||||||
|
.then((a) => String(a!._id));
|
||||||
|
|
||||||
|
describe("roller ve izolasyon", () => {
|
||||||
|
it("yalnızca sahip hesap oluşturur", async () => {
|
||||||
|
expect((await createAccount(ids.user("emre"), cakir, base)).ok).toBe(false);
|
||||||
|
expect((await createAccount(ids.user("zeynep"), cakir, base)).ok).toBe(false);
|
||||||
|
expect((await createAccount(ids.user("fatma"), cakir, base)).ok).toBe(false);
|
||||||
|
expect((await createAccount(ids.user("ayse"), cakir, base)).ok).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("başka hanenin hesaplarını göremez ve değiştiremez", async () => {
|
||||||
|
expect(await listAccounts(ids.user("fatma"), cakir)).toBeNull();
|
||||||
|
const cuzdan = await accountId("Cüzdan");
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await updateAccount(ids.user("fatma"), annemler, cuzdan, {
|
||||||
|
...base,
|
||||||
|
type: "cash",
|
||||||
|
name: "X",
|
||||||
|
})
|
||||||
|
).ok,
|
||||||
|
).toBe(false);
|
||||||
|
expect((await setAccountArchived(ids.user("fatma"), annemler, cuzdan, true)).ok).toBe(false);
|
||||||
|
const own = (await listAccounts(ids.user("fatma"), annemler))!.accounts.map((a) => a.name);
|
||||||
|
expect(own.sort()).toEqual(["Nakit", "Vakıfbank Emekli"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("başka hanenin hesabı kart ödeme hesabı veya hesap sahibi başka hanenin üyesi olamaz", async () => {
|
||||||
|
const vakif = await accountId("Vakıfbank Emekli", annemler);
|
||||||
|
const card = {
|
||||||
|
...base,
|
||||||
|
type: "credit_card" as const,
|
||||||
|
name: "Sızma Kart",
|
||||||
|
cardPaymentAccountId: vakif,
|
||||||
|
};
|
||||||
|
expect((await createAccount(ids.user("ayse"), cakir, card)).ok).toBe(false);
|
||||||
|
expect(
|
||||||
|
(await createAccount(ids.user("ayse"), cakir, { ...base, ownerUserId: ids.user("fatma") }))
|
||||||
|
.ok,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("“yalnızca ben” hesabı", () => {
|
||||||
|
it("bakiyeyi yalnızca hesap sahibi görür (hane sahibi dahil diğerleri göremez)", async () => {
|
||||||
|
const find = async (user: string) =>
|
||||||
|
(await listAccounts(ids.user(user), cakir))!.accounts.find(
|
||||||
|
(a) => a.name === "Ayşe — Pluxee",
|
||||||
|
)!;
|
||||||
|
expect((await find("ayse")).balanceMinor).toBe(3_120_00);
|
||||||
|
expect((await find("admin")).balanceMinor).toBeNull();
|
||||||
|
expect((await find("emre")).balanceMinor).toBeNull();
|
||||||
|
expect((await find("emre")).openingBalanceMinor).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("toplamlar hane ayarına uyar", async () => {
|
||||||
|
const withHidden = (await listAccounts(ids.user("emre"), cakir))!.totals;
|
||||||
|
expect(withHidden.includesHidden).toBe(true);
|
||||||
|
await HouseholdModel.updateOne(
|
||||||
|
{ _id: cakir },
|
||||||
|
{ $set: { "settings.includePrivateAccountsInTotals": false } },
|
||||||
|
);
|
||||||
|
const without = (await listAccounts(ids.user("emre"), cakir))!.totals;
|
||||||
|
expect(without.excludesHidden).toBe(true);
|
||||||
|
expect(withHidden.assetsMinor - without.assetsMinor).toBe(3_120_00);
|
||||||
|
// Hesap sahibi kendi hesabını her zaman toplamda görür.
|
||||||
|
const ayse = (await listAccounts(ids.user("ayse"), cakir))!.totals;
|
||||||
|
expect(ayse.assetsMinor).toBe(withHidden.assetsMinor);
|
||||||
|
await HouseholdModel.updateOne(
|
||||||
|
{ _id: cakir },
|
||||||
|
{ $set: { "settings.includePrivateAccountsInTotals": true } },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bakiyeyi göremeyen sahip düzenlediğinde gizli bakiye korunur", async () => {
|
||||||
|
const id = await accountId("Ayşe — Pluxee");
|
||||||
|
const r = await updateAccount(ids.user("admin"), cakir, id, {
|
||||||
|
...base,
|
||||||
|
type: "meal_card",
|
||||||
|
mealCardProvider: "pluxee",
|
||||||
|
name: "Ayşe — Pluxee",
|
||||||
|
openingBalance: 0,
|
||||||
|
ownerUserId: ids.user("ayse"),
|
||||||
|
isPrivate: true,
|
||||||
|
});
|
||||||
|
expect(r.ok).toBe(true);
|
||||||
|
expect((await AccountModel.findById(id).lean())?.openingBalanceMinor).toBe(3_120_00);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("kart ve tür kuralları", () => {
|
||||||
|
it("kart açılış borcu negatif saklanır; tür değiştirilemez", async () => {
|
||||||
|
const payer = await accountId("Ziraat Maaş");
|
||||||
|
const r = await createAccount(ids.user("ayse"), cakir, {
|
||||||
|
...base,
|
||||||
|
type: "credit_card",
|
||||||
|
name: "Yeni Kart",
|
||||||
|
openingBalance: 1_500_00,
|
||||||
|
cardLimit: 20_000_00,
|
||||||
|
cardStatementDay: 31,
|
||||||
|
cardPaymentAccountId: payer,
|
||||||
|
});
|
||||||
|
expect(r.ok).toBe(true);
|
||||||
|
const card = await AccountModel.findById(r.ok ? r.data.id : "").lean();
|
||||||
|
expect(card?.openingBalanceMinor).toBe(-1_500_00);
|
||||||
|
expect(card?.creditCard?.statementDay).toBe(31);
|
||||||
|
expect(card?.creditCard?.paymentAccountId?.toString()).toBe(payer);
|
||||||
|
const change = await updateAccount(ids.user("ayse"), cakir, String(card!._id), {
|
||||||
|
...base,
|
||||||
|
name: "Yeni Kart",
|
||||||
|
});
|
||||||
|
expect(change.ok).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
import { getHouseholdDetail, resolveMembership } from "@/features/households/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { diffFields, writeAudit } from "@/lib/audit";
|
||||||
|
import { toObjectId } from "@/lib/object-id";
|
||||||
|
import { AccountModel } from "@/models/account";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { HouseholdMemberModel } from "@/models/household-member";
|
||||||
|
import {
|
||||||
|
isLiabilityType,
|
||||||
|
type AccountType,
|
||||||
|
type DueRuleKind,
|
||||||
|
type MealCardProvider,
|
||||||
|
} from "@/shared/accounts";
|
||||||
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
|
import { istanbulDayStart, toIstanbulYmd } from "@/shared/dates";
|
||||||
|
import type { AccountForm } from "@/shared/schemas/account";
|
||||||
|
import { compareTr } from "@/shared/search";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hesap servisi. Okuma: viewer; oluşturma/düzenleme/arşiv/sıralama: owner (Bölüm 5).
|
||||||
|
* "Yalnızca ben" hesaplarında bakiye yalnızca hesap sahibi kişiye görünür.
|
||||||
|
* Bakiye işareti: varlık pozitif, kredi kartı borcu negatif.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const t = tr.accounts;
|
||||||
|
|
||||||
|
export type AccountView = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: AccountType;
|
||||||
|
institution: string;
|
||||||
|
mealCardProvider: MealCardProvider | null;
|
||||||
|
color: Swatch;
|
||||||
|
icon: IconKey;
|
||||||
|
order: number;
|
||||||
|
archived: boolean;
|
||||||
|
isPrivate: boolean;
|
||||||
|
ownerUserId: string | null;
|
||||||
|
/** Bu kullanıcıya gizliyse null. */
|
||||||
|
balanceMinor: number | null;
|
||||||
|
openingBalanceMinor: number | null;
|
||||||
|
openingDate: string;
|
||||||
|
overdraft: {
|
||||||
|
enabled: boolean;
|
||||||
|
limitMinor: number;
|
||||||
|
monthlyRateBp: number | null;
|
||||||
|
statementDay: number | null;
|
||||||
|
} | null;
|
||||||
|
creditCard: {
|
||||||
|
limitMinor: number;
|
||||||
|
statementDay: number;
|
||||||
|
dueRule: { kind: DueRuleKind; value: number };
|
||||||
|
paymentAccountId: string | null;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AccountTotals = {
|
||||||
|
/** Nakit + banka + birikim + yemek kartı (pozitif bakiyeler). */
|
||||||
|
assetsMinor: number;
|
||||||
|
/** Kredi kartı borçları (negatif). */
|
||||||
|
cardDebtMinor: number;
|
||||||
|
netMinor: number;
|
||||||
|
/** Toplamlarda bu kullanıcının bakiyesini göremediği hesap var mı? */
|
||||||
|
includesHidden: boolean;
|
||||||
|
/** Gizli hesaplar hane ayarı gereği toplamlardan çıkarıldı mı? */
|
||||||
|
excludesHidden: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Lean = {
|
||||||
|
_id: Types.ObjectId;
|
||||||
|
name: string;
|
||||||
|
type: AccountType;
|
||||||
|
institution: string;
|
||||||
|
mealCardProvider: MealCardProvider | null;
|
||||||
|
color: Swatch;
|
||||||
|
icon: IconKey;
|
||||||
|
order: number;
|
||||||
|
archivedAt: Date | null;
|
||||||
|
isPrivate: boolean;
|
||||||
|
ownerUserId: Types.ObjectId | null;
|
||||||
|
openingBalanceMinor: number;
|
||||||
|
openingDate: Date;
|
||||||
|
overdraft: AccountView["overdraft"];
|
||||||
|
creditCard:
|
||||||
|
| (Omit<NonNullable<AccountView["creditCard"]>, "paymentAccountId"> & {
|
||||||
|
paymentAccountId: Types.ObjectId | null;
|
||||||
|
})
|
||||||
|
| null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const canSeeBalance = (a: Lean, viewerId: string) =>
|
||||||
|
!a.isPrivate || String(a.ownerUserId) === viewerId;
|
||||||
|
|
||||||
|
/** FAZ 6b: açılış bakiyesi + işlemler. Şimdilik açılış bakiyesi. */
|
||||||
|
function computeBalance(a: Lean): number {
|
||||||
|
return a.openingBalanceMinor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toView(a: Lean, viewerId: string): AccountView {
|
||||||
|
const visible = canSeeBalance(a, viewerId);
|
||||||
|
return {
|
||||||
|
id: String(a._id),
|
||||||
|
name: a.name,
|
||||||
|
type: a.type,
|
||||||
|
institution: a.institution ?? "",
|
||||||
|
mealCardProvider: a.mealCardProvider ?? null,
|
||||||
|
color: a.color,
|
||||||
|
icon: a.icon,
|
||||||
|
order: a.order,
|
||||||
|
archived: Boolean(a.archivedAt),
|
||||||
|
isPrivate: a.isPrivate,
|
||||||
|
ownerUserId: a.ownerUserId ? String(a.ownerUserId) : null,
|
||||||
|
balanceMinor: visible ? computeBalance(a) : null,
|
||||||
|
openingBalanceMinor: visible ? a.openingBalanceMinor : null,
|
||||||
|
openingDate: toIstanbulYmd(a.openingDate),
|
||||||
|
overdraft: a.overdraft?.enabled ? a.overdraft : null,
|
||||||
|
creditCard: a.creditCard
|
||||||
|
? {
|
||||||
|
...a.creditCard,
|
||||||
|
paymentAccountId: a.creditCard.paymentAccountId
|
||||||
|
? String(a.creditCard.paymentAccountId)
|
||||||
|
: null,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAccounts(
|
||||||
|
userId: string,
|
||||||
|
householdId: string,
|
||||||
|
opts: { includeArchived?: boolean } = {},
|
||||||
|
): Promise<{ accounts: AccountView[]; totals: AccountTotals } | null> {
|
||||||
|
const m = await resolveMembership(userId, householdId, "viewer");
|
||||||
|
if (!m) return null;
|
||||||
|
const filter: Record<string, unknown> = { householdId: m.householdId };
|
||||||
|
if (!opts.includeArchived) filter.archivedAt = null;
|
||||||
|
const rows = (await AccountModel.find(filter).lean<Lean[]>()).sort(
|
||||||
|
(a, b) => a.order - b.order || compareTr(a.name, b.name),
|
||||||
|
);
|
||||||
|
const household = await HouseholdModel.findById(m.householdId).select({ settings: 1 }).lean();
|
||||||
|
const includePrivate = household?.settings?.includePrivateAccountsInTotals ?? true;
|
||||||
|
|
||||||
|
const totals: AccountTotals = {
|
||||||
|
assetsMinor: 0,
|
||||||
|
cardDebtMinor: 0,
|
||||||
|
netMinor: 0,
|
||||||
|
includesHidden: false,
|
||||||
|
excludesHidden: false,
|
||||||
|
};
|
||||||
|
for (const a of rows) {
|
||||||
|
if (a.archivedAt) continue;
|
||||||
|
const visible = canSeeBalance(a, userId);
|
||||||
|
if (!visible && !includePrivate) {
|
||||||
|
totals.excludesHidden = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!visible) totals.includesHidden = true;
|
||||||
|
const balance = computeBalance(a);
|
||||||
|
if (isLiabilityType(a.type)) totals.cardDebtMinor += balance;
|
||||||
|
else totals.assetsMinor += balance;
|
||||||
|
}
|
||||||
|
totals.netMinor = totals.assetsMinor + totals.cardDebtMinor;
|
||||||
|
return { accounts: rows.map((a) => toView(a, userId)), totals };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Form → belge alanları. Kart için açılış borcu negatif saklanır. */
|
||||||
|
async function toDocFields(
|
||||||
|
householdId: Types.ObjectId,
|
||||||
|
input: AccountForm,
|
||||||
|
selfId?: Types.ObjectId,
|
||||||
|
): Promise<ActionResult<Record<string, unknown>>> {
|
||||||
|
const openingDate = istanbulDayStart(input.openingDate);
|
||||||
|
if (!openingDate) return fail(tr.validation.date, { openingDate: tr.validation.date });
|
||||||
|
|
||||||
|
let ownerUserId: Types.ObjectId | null = null;
|
||||||
|
if (input.ownerUserId) {
|
||||||
|
ownerUserId = toObjectId(input.ownerUserId);
|
||||||
|
const isMember =
|
||||||
|
ownerUserId && (await HouseholdMemberModel.exists({ householdId, userId: ownerUserId }));
|
||||||
|
if (!isMember) return fail(t.ownerNotMember, { ownerUserId: t.ownerNotMember });
|
||||||
|
}
|
||||||
|
|
||||||
|
let paymentAccountId: Types.ObjectId | null = null;
|
||||||
|
if (input.type === "credit_card" && input.cardPaymentAccountId) {
|
||||||
|
paymentAccountId = toObjectId(input.cardPaymentAccountId);
|
||||||
|
const payer =
|
||||||
|
paymentAccountId &&
|
||||||
|
!paymentAccountId.equals(selfId ?? new Types.ObjectId()) &&
|
||||||
|
(await AccountModel.exists({
|
||||||
|
_id: paymentAccountId,
|
||||||
|
householdId,
|
||||||
|
archivedAt: null,
|
||||||
|
type: { $in: ["bank", "cash", "savings"] },
|
||||||
|
}));
|
||||||
|
if (!payer)
|
||||||
|
return fail(t.invalidPaymentAccount, { cardPaymentAccountId: t.invalidPaymentAccount });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCard = input.type === "credit_card";
|
||||||
|
return ok({
|
||||||
|
name: input.name,
|
||||||
|
institution: input.institution,
|
||||||
|
mealCardProvider: input.type === "meal_card" ? input.mealCardProvider : null,
|
||||||
|
openingBalanceMinor: isCard ? -Math.abs(input.openingBalance) : input.openingBalance,
|
||||||
|
openingDate,
|
||||||
|
color: input.color,
|
||||||
|
icon: input.icon,
|
||||||
|
ownerUserId,
|
||||||
|
isPrivate: input.isPrivate,
|
||||||
|
overdraft:
|
||||||
|
input.type === "bank" && input.overdraftEnabled
|
||||||
|
? {
|
||||||
|
enabled: true,
|
||||||
|
limitMinor: input.overdraftLimit,
|
||||||
|
monthlyRateBp: input.overdraftMonthlyRate,
|
||||||
|
statementDay: input.overdraftStatementDay,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
creditCard: isCard
|
||||||
|
? {
|
||||||
|
limitMinor: input.cardLimit,
|
||||||
|
statementDay: input.cardStatementDay,
|
||||||
|
dueRule: { kind: input.cardDueKind, value: input.cardDueValue },
|
||||||
|
paymentAccountId,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAccount(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
input: AccountForm,
|
||||||
|
): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const fields = await toDocFields(m.householdId, input);
|
||||||
|
if (!fields.ok) return fields;
|
||||||
|
const last = await AccountModel.findOne({ householdId: m.householdId })
|
||||||
|
.sort({ order: -1 })
|
||||||
|
.select({ order: 1 })
|
||||||
|
.lean();
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
const doc = await AccountModel.create({
|
||||||
|
...fields.data,
|
||||||
|
householdId: m.householdId,
|
||||||
|
type: input.type,
|
||||||
|
order: (last?.order ?? -1) + 1,
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
});
|
||||||
|
await writeAudit({
|
||||||
|
action: "account.create",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: m.householdId,
|
||||||
|
targetType: "account",
|
||||||
|
targetId: String(doc._id),
|
||||||
|
diff: { name: input.name, type: input.type },
|
||||||
|
});
|
||||||
|
return ok({ id: String(doc._id) });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAccount(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
accountId: string,
|
||||||
|
input: AccountForm,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const id = toObjectId(accountId);
|
||||||
|
const current = id
|
||||||
|
? await AccountModel.findOne({ _id: id, householdId: m.householdId }).lean<Lean>()
|
||||||
|
: null;
|
||||||
|
if (!current) return fail(tr.common.notFound);
|
||||||
|
// Tür değişikliği desteklenmez (işlemler ve kart dönemleri türe bağlıdır).
|
||||||
|
if (current.type !== input.type) return fail(t.typeLocked, { type: t.typeLocked });
|
||||||
|
const fields = await toDocFields(m.householdId, input, current._id);
|
||||||
|
if (!fields.ok) return fields;
|
||||||
|
// Bakiyesini göremediği gizli hesapta açılış bakiyesi korunur (ne görünür ne değişir).
|
||||||
|
if (!canSeeBalance(current, actorId)) delete fields.data.openingBalanceMinor;
|
||||||
|
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
await AccountModel.updateOne(
|
||||||
|
{ _id: current._id, householdId: m.householdId },
|
||||||
|
{ $set: { ...fields.data, updatedBy: actor } },
|
||||||
|
);
|
||||||
|
await writeAudit({
|
||||||
|
action: "account.update",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: m.householdId,
|
||||||
|
targetType: "account",
|
||||||
|
targetId: accountId,
|
||||||
|
// Gizli hesabın bakiyesi denetim kaydına yazılmaz.
|
||||||
|
diff: diffFields(
|
||||||
|
{
|
||||||
|
name: current.name,
|
||||||
|
institution: current.institution,
|
||||||
|
isPrivate: current.isPrivate,
|
||||||
|
ownerUserId: String(current.ownerUserId ?? ""),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: input.name,
|
||||||
|
institution: input.institution,
|
||||||
|
isPrivate: input.isPrivate,
|
||||||
|
ownerUserId: input.ownerUserId ?? "",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setAccountArchived(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
accountId: string,
|
||||||
|
archived: boolean,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const id = toObjectId(accountId);
|
||||||
|
const current = id
|
||||||
|
? await AccountModel.findOne({ _id: id, householdId: m.householdId }).lean<Lean>()
|
||||||
|
: null;
|
||||||
|
if (!current) return fail(tr.common.notFound);
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
await AccountModel.updateOne(
|
||||||
|
{ _id: current._id, householdId: m.householdId },
|
||||||
|
{ $set: { archivedAt: archived ? new Date() : null, updatedBy: actor } },
|
||||||
|
);
|
||||||
|
await writeAudit({
|
||||||
|
action: archived ? "account.archive" : "account.unarchive",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: m.householdId,
|
||||||
|
targetType: "account",
|
||||||
|
targetId: accountId,
|
||||||
|
diff: { name: current.name },
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reorderAccount(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
accountId: string,
|
||||||
|
direction: "up" | "down",
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const list = (
|
||||||
|
await AccountModel.find({ householdId: m.householdId, archivedAt: null }).lean<Lean[]>()
|
||||||
|
).sort((a, b) => a.order - b.order || compareTr(a.name, b.name));
|
||||||
|
const i = list.findIndex((a) => String(a._id) === accountId);
|
||||||
|
const j = direction === "up" ? i - 1 : i + 1;
|
||||||
|
if (i < 0 || j < 0 || j >= list.length) return ok(undefined);
|
||||||
|
[list[i], list[j]] = [list[j]!, list[i]!];
|
||||||
|
await AccountModel.bulkWrite(
|
||||||
|
list.map((a, order) => ({
|
||||||
|
updateOne: {
|
||||||
|
filter: { _id: a._id, householdId: m.householdId },
|
||||||
|
update: { $set: { order } },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hane üyeleri (hesap sahibi seçimi için). */
|
||||||
|
export async function listMemberOptions(userId: string, householdId: string) {
|
||||||
|
const detail = await getHouseholdDetail(userId, householdId);
|
||||||
|
if (!detail) return null;
|
||||||
|
return detail.members.map((x) => ({ id: x.userId, name: x.name }));
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
adminAddMember,
|
||||||
|
adminCreateHousehold,
|
||||||
|
adminRemoveMember,
|
||||||
|
adminSetMemberRole,
|
||||||
|
} from "@/features/households/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { getActionUser } from "@/lib/dal";
|
||||||
|
import {
|
||||||
|
addMemberSchema,
|
||||||
|
householdCreateSchema,
|
||||||
|
householdRoleSchema,
|
||||||
|
} from "@/shared/schemas/household";
|
||||||
|
|
||||||
|
/** Sistem admini: hane ve üyelik yönetimi. Hanenin finansal verisine dokunmaz. */
|
||||||
|
|
||||||
|
const PATH = "/admin/haneler";
|
||||||
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
||||||
|
|
||||||
|
export async function createHouseholdAction(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const admin = await getActionUser("admin");
|
||||||
|
if (!admin) return fail(tr.common.unauthorized);
|
||||||
|
const parsed = householdCreateSchema.safeParse(input);
|
||||||
|
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields);
|
||||||
|
const result = await adminCreateHousehold(admin.id, parsed.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addMemberAction(householdId: unknown, input: unknown): Promise<ActionResult> {
|
||||||
|
const admin = await getActionUser("admin");
|
||||||
|
if (!admin) return fail(tr.common.unauthorized);
|
||||||
|
const hid = idSchema.safeParse(householdId);
|
||||||
|
const parsed = addMemberSchema.safeParse(input);
|
||||||
|
if (!hid.success || !parsed.success) return fail(tr.adminUsers.errors.checkFields);
|
||||||
|
const result = await adminAddMember(admin.id, hid.data, parsed.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminSetMemberRoleAction(
|
||||||
|
householdId: unknown,
|
||||||
|
userId: unknown,
|
||||||
|
role: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const admin = await getActionUser("admin");
|
||||||
|
if (!admin) return fail(tr.common.unauthorized);
|
||||||
|
const hid = idSchema.safeParse(householdId);
|
||||||
|
const uid = idSchema.safeParse(userId);
|
||||||
|
const r = householdRoleSchema.safeParse(role);
|
||||||
|
if (!hid.success || !uid.success || !r.success) return fail(tr.common.genericError);
|
||||||
|
const result = await adminSetMemberRole(admin.id, hid.data, uid.data, r.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminRemoveMemberAction(
|
||||||
|
householdId: unknown,
|
||||||
|
userId: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const admin = await getActionUser("admin");
|
||||||
|
if (!admin) return fail(tr.common.unauthorized);
|
||||||
|
const hid = idSchema.safeParse(householdId);
|
||||||
|
const uid = idSchema.safeParse(userId);
|
||||||
|
if (!hid.success || !uid.success) return fail(tr.common.genericError);
|
||||||
|
const result = await adminRemoveMember(admin.id, hid.data, uid.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { Loader2, Plus, UserPlus } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Controller, useForm } from "react-hook-form";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { ResponsiveDialog } from "@/components/responsive-dialog";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardAction,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { MembersList } from "@/features/households/components/members-list";
|
||||||
|
import type { AdminHouseholdRow, UserOption } from "@/features/households/service";
|
||||||
|
import { HOUSEHOLD_ROLES } from "@/features/households/types";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import {
|
||||||
|
addMemberSchema,
|
||||||
|
householdCreateSchema,
|
||||||
|
type AddMemberInput,
|
||||||
|
type HouseholdCreateInput,
|
||||||
|
} from "@/shared/schemas/household";
|
||||||
|
import {
|
||||||
|
addMemberAction,
|
||||||
|
adminRemoveMemberAction,
|
||||||
|
adminSetMemberRoleAction,
|
||||||
|
createHouseholdAction,
|
||||||
|
} from "../actions";
|
||||||
|
import { UserSelect } from "./user-select";
|
||||||
|
|
||||||
|
const t = tr.adminHouseholds;
|
||||||
|
|
||||||
|
function CreateHouseholdDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
users,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (o: boolean) => void;
|
||||||
|
users: UserOption[];
|
||||||
|
}) {
|
||||||
|
const form = useForm<HouseholdCreateInput>({
|
||||||
|
resolver: zodResolver(householdCreateSchema),
|
||||||
|
defaultValues: { name: "", ownerUserId: "" },
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) form.reset({ name: "", ownerUserId: "" });
|
||||||
|
}, [open, form]);
|
||||||
|
|
||||||
|
async function onSubmit(values: HouseholdCreateInput) {
|
||||||
|
const result = await createHouseholdAction(values);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(t.created(values.name));
|
||||||
|
onOpenChange(false);
|
||||||
|
} else {
|
||||||
|
form.setError("root", { message: result.error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveDialog
|
||||||
|
open={open}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
title={t.createTitle}
|
||||||
|
description={t.createDescription}
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
|
||||||
|
{tr.common.cancel}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" form="household-create" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
|
{tr.common.create}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<form id="household-create" onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="name"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="hh-create-name">{t.name}</FieldLabel>
|
||||||
|
<Input {...field} id="hh-create-name" aria-invalid={fieldState.invalid} />
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="ownerUserId"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="hh-create-owner">{t.owner}</FieldLabel>
|
||||||
|
<UserSelect
|
||||||
|
id="hh-create-owner"
|
||||||
|
users={users}
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
invalid={fieldState.invalid}
|
||||||
|
/>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{form.formState.errors.root ? (
|
||||||
|
<FieldError>{form.formState.errors.root.message}</FieldError>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</ResponsiveDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AddMemberDialog({
|
||||||
|
household,
|
||||||
|
users,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
household: AdminHouseholdRow | null;
|
||||||
|
users: UserOption[];
|
||||||
|
onOpenChange: (o: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const form = useForm<AddMemberInput>({
|
||||||
|
resolver: zodResolver(addMemberSchema),
|
||||||
|
defaultValues: { userId: "", role: "member" },
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
if (household) form.reset({ userId: "", role: "member" });
|
||||||
|
}, [household, form]);
|
||||||
|
|
||||||
|
async function onSubmit(values: AddMemberInput) {
|
||||||
|
if (!household) return;
|
||||||
|
const result = await addMemberAction(household.id, values);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(t.memberAdded(users.find((u) => u.id === values.userId)?.name ?? ""));
|
||||||
|
onOpenChange(false);
|
||||||
|
} else {
|
||||||
|
form.setError("root", { message: result.error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveDialog
|
||||||
|
open={Boolean(household)}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
title={household ? t.addMemberTitle(household.name) : t.addMember}
|
||||||
|
description={t.addMemberDescription}
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
|
||||||
|
{tr.common.cancel}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" form="household-add-member" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
|
{t.addMember}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<form id="household-add-member" onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="userId"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="hh-member-user">{t.user}</FieldLabel>
|
||||||
|
<UserSelect
|
||||||
|
id="hh-member-user"
|
||||||
|
users={users}
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
invalid={fieldState.invalid}
|
||||||
|
/>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="role"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="hh-member-role">{t.role}</FieldLabel>
|
||||||
|
<Select value={field.value} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger
|
||||||
|
id="hh-member-role"
|
||||||
|
className="w-full"
|
||||||
|
aria-describedby="hh-member-role-hint"
|
||||||
|
>
|
||||||
|
<SelectValue>{tr.household.roles[field.value]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{HOUSEHOLD_ROLES.map((r) => (
|
||||||
|
<SelectItem key={r} value={r}>
|
||||||
|
{tr.household.roles[r]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<FieldDescription id="hh-member-role-hint">
|
||||||
|
{tr.household.roleHints[field.value]}
|
||||||
|
</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{form.formState.errors.root ? (
|
||||||
|
<FieldError>{form.formState.errors.root.message}</FieldError>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</ResponsiveDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HouseholdsAdmin({
|
||||||
|
households,
|
||||||
|
users,
|
||||||
|
currentUserId,
|
||||||
|
}: {
|
||||||
|
households: AdminHouseholdRow[];
|
||||||
|
users: UserOption[];
|
||||||
|
currentUserId: string;
|
||||||
|
}) {
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [addingTo, setAddingTo] = useState<AdminHouseholdRow | null>(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<p className="max-w-2xl text-sm text-muted-foreground">{t.privacyNote}</p>
|
||||||
|
<Button className="ml-auto" onClick={() => setCreating(true)}>
|
||||||
|
<Plus />
|
||||||
|
{t.newHousehold}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{households.length === 0 ? (
|
||||||
|
<p className="rounded-xl border border-dashed p-8 text-center text-muted-foreground">
|
||||||
|
{t.empty}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-4 xl:grid-cols-2">
|
||||||
|
{households.map((h) => (
|
||||||
|
<Card key={h.id}>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{h.name}</CardTitle>
|
||||||
|
<CardDescription className="flex flex-wrap items-center gap-2">
|
||||||
|
<span>{t.members(h.memberCount)}</span>
|
||||||
|
{h.owners.length ? (
|
||||||
|
<span>
|
||||||
|
· {t.owners}: {h.owners.join(", ")}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<Badge variant="destructive">{t.noOwner}</Badge>
|
||||||
|
)}
|
||||||
|
</CardDescription>
|
||||||
|
<CardAction>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setAddingTo(h)}>
|
||||||
|
<UserPlus />
|
||||||
|
{t.addMember}
|
||||||
|
</Button>
|
||||||
|
</CardAction>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<MembersList
|
||||||
|
members={h.members}
|
||||||
|
householdName={h.name}
|
||||||
|
currentUserId={currentUserId}
|
||||||
|
canManage
|
||||||
|
onSetRole={(userId, role) => adminSetMemberRoleAction(h.id, userId, role)}
|
||||||
|
onRemove={(userId) => adminRemoveMemberAction(h.id, userId)}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<CreateHouseholdDialog open={creating} onOpenChange={setCreating} users={users} />
|
||||||
|
<AddMemberDialog
|
||||||
|
household={addingTo}
|
||||||
|
users={users}
|
||||||
|
onOpenChange={(o) => !o && setAddingTo(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import type { UserOption } from "@/features/households/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
|
||||||
|
/** Kullanıcı seçici (askıdakiler işaretli). */
|
||||||
|
export function UserSelect({
|
||||||
|
id,
|
||||||
|
users,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
invalid,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
users: UserOption[];
|
||||||
|
value: string;
|
||||||
|
onChange: (id: string) => void;
|
||||||
|
invalid?: boolean;
|
||||||
|
}) {
|
||||||
|
const selected = users.find((u) => u.id === value);
|
||||||
|
return (
|
||||||
|
<Select value={value || undefined} onValueChange={onChange}>
|
||||||
|
<SelectTrigger id={id} className="w-full" aria-invalid={invalid}>
|
||||||
|
<SelectValue placeholder={tr.adminHouseholds.selectUser}>
|
||||||
|
{selected ? `${selected.name} (@${selected.username})` : null}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="max-h-72">
|
||||||
|
{users.map((u) => (
|
||||||
|
<SelectItem key={u.id} value={u.id}>
|
||||||
|
{u.name}
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
@{u.username}
|
||||||
|
{u.banned ? ` · ${tr.settings.banned}` : ""}
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { adminListHouseholds, adminListUserOptions } from "@/features/households/service";
|
||||||
|
import { requireRole } from "@/lib/dal";
|
||||||
|
|
||||||
|
/** Admin: haneler (üyeleriyle) ve hane atamaları için kullanıcı listesi. */
|
||||||
|
export async function getAdminHouseholdsData() {
|
||||||
|
await requireRole("admin");
|
||||||
|
const [households, users] = await Promise.all([adminListHouseholds(), adminListUserOptions()]);
|
||||||
|
return { households, users };
|
||||||
|
}
|
||||||
@@ -7,7 +7,9 @@ import { tr } from "@/i18n/tr";
|
|||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
import { getAuth } from "@/lib/auth";
|
import { getAuth } from "@/lib/auth";
|
||||||
import { authErrorCode } from "@/lib/auth-errors";
|
import { authErrorCode } from "@/lib/auth-errors";
|
||||||
|
import { writeAudit } from "@/lib/audit";
|
||||||
import { getActionUser } from "@/lib/dal";
|
import { getActionUser } from "@/lib/dal";
|
||||||
|
import { removeAllMembershipsOfUser } from "@/features/households/service";
|
||||||
import { storedEmail } from "@/shared/account-email";
|
import { storedEmail } from "@/shared/account-email";
|
||||||
import { systemRoleSchema, type SystemRole } from "@/shared/schemas/common";
|
import { systemRoleSchema, type SystemRole } from "@/shared/schemas/common";
|
||||||
import {
|
import {
|
||||||
@@ -102,8 +104,9 @@ export async function createUserAction(input: unknown): Promise<ActionResult> {
|
|||||||
const parsed = userCreateSchema.safeParse(input);
|
const parsed = userCreateSchema.safeParse(input);
|
||||||
if (!parsed.success) return fail(t.errors.checkFields);
|
if (!parsed.success) return fail(t.errors.checkFields);
|
||||||
const v = parsed.data;
|
const v = parsed.data;
|
||||||
|
let createdId = "";
|
||||||
try {
|
try {
|
||||||
await ctx.api.createUser({
|
const created = await ctx.api.createUser({
|
||||||
headers: ctx.headers,
|
headers: ctx.headers,
|
||||||
body: {
|
body: {
|
||||||
name: v.name,
|
name: v.name,
|
||||||
@@ -113,9 +116,17 @@ export async function createUserAction(input: unknown): Promise<ActionResult> {
|
|||||||
data: { username: v.username },
|
data: { username: v.username },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
createdId = created.user.id;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.create",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: createdId,
|
||||||
|
diff: { username: v.username, role: v.role },
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
@@ -148,6 +159,13 @@ export async function updateUserAction(userId: unknown, input: unknown): Promise
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.update",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: target.id,
|
||||||
|
diff: { name: v.name, username: v.username, role: v.role },
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
@@ -167,6 +185,13 @@ export async function setRoleAction(userId: unknown, role: unknown): Promise<Act
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.role",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: target.id,
|
||||||
|
diff: { role: { from: target.role, to: r.data } },
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
@@ -191,6 +216,12 @@ export async function setPasswordAction(userId: unknown, input: unknown): Promis
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.password.reset",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: target.id,
|
||||||
|
});
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,6 +244,13 @@ export async function banUserAction(userId: unknown, input: unknown): Promise<Ac
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.ban",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: target.id,
|
||||||
|
diff: { reason: parsed.data.reason ?? null },
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
@@ -227,6 +265,12 @@ export async function unbanUserAction(userId: unknown): Promise<ActionResult> {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.unban",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: id.data,
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
@@ -245,6 +289,14 @@ export async function removeUserAction(userId: unknown): Promise<ActionResult> {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mapAuthError(error);
|
return mapAuthError(error);
|
||||||
}
|
}
|
||||||
|
const removedMemberships = await removeAllMembershipsOfUser(target.id);
|
||||||
|
await writeAudit({
|
||||||
|
action: "user.remove",
|
||||||
|
actorId: ctx.actor.id,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: target.id,
|
||||||
|
diff: { name: target.name, removedMemberships },
|
||||||
|
});
|
||||||
revalidatePath(PATH);
|
revalidatePath(PATH);
|
||||||
return ok(undefined);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { getHouseholdActionContext } from "@/lib/dal";
|
||||||
|
import { categoryFormSchema } from "@/shared/schemas/category";
|
||||||
|
import { createCategory, reorderCategory, setCategoryArchived, updateCategory } from "./service";
|
||||||
|
|
||||||
|
const PATH = "/kategoriler";
|
||||||
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
||||||
|
const checkFields = tr.adminUsers.errors.checkFields;
|
||||||
|
|
||||||
|
export async function createCategoryAction(input: unknown): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const ctx = await getHouseholdActionContext("member");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const parsed = categoryFormSchema.safeParse(input);
|
||||||
|
if (!parsed.success) return fail(checkFields);
|
||||||
|
const result = await createCategory(ctx.user.id, ctx.household.id, parsed.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateCategoryAction(
|
||||||
|
categoryId: unknown,
|
||||||
|
input: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("member");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(categoryId);
|
||||||
|
const parsed = categoryFormSchema.safeParse(input);
|
||||||
|
if (!id.success || !parsed.success) return fail(checkFields);
|
||||||
|
const result = await updateCategory(ctx.user.id, ctx.household.id, id.data, parsed.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reorderCategoryAction(
|
||||||
|
categoryId: unknown,
|
||||||
|
direction: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("member");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(categoryId);
|
||||||
|
const dir = z.enum(["up", "down"]).safeParse(direction);
|
||||||
|
if (!id.success || !dir.success) return fail(tr.common.genericError);
|
||||||
|
const result = await reorderCategory(ctx.user.id, ctx.household.id, id.data, dir.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setCategoryArchivedAction(
|
||||||
|
categoryId: unknown,
|
||||||
|
archived: unknown,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("member");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const id = idSchema.safeParse(categoryId);
|
||||||
|
const a = z.boolean().safeParse(archived);
|
||||||
|
if (!id.success || !a.success) return fail(tr.common.genericError);
|
||||||
|
const result = await setCategoryArchived(ctx.user.id, ctx.household.id, id.data, a.data);
|
||||||
|
if (result.ok) revalidatePath(PATH);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Archive,
|
||||||
|
ArchiveRestore,
|
||||||
|
ArrowDown,
|
||||||
|
ArrowUp,
|
||||||
|
MoreHorizontal,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useMemo, useState, useTransition } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { IconBadge } from "@/components/appearance/swatch";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type { CategoryKind } from "@/shared/schemas/category";
|
||||||
|
import { reorderCategoryAction, setCategoryArchivedAction } from "../actions";
|
||||||
|
import type { CategoryView } from "../service";
|
||||||
|
import { buildTree, MAX_DEPTH, type CategoryNode } from "../tree";
|
||||||
|
import { CategoryFormDialog, type CategoryDialogState } from "./category-form-dialog";
|
||||||
|
|
||||||
|
const t = tr.categories;
|
||||||
|
|
||||||
|
export function CategoriesManager({
|
||||||
|
categories,
|
||||||
|
canEdit,
|
||||||
|
}: {
|
||||||
|
categories: CategoryView[];
|
||||||
|
canEdit: boolean;
|
||||||
|
}) {
|
||||||
|
const [kind, setKind] = useState<CategoryKind>("expense");
|
||||||
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
|
const [dialog, setDialog] = useState<CategoryDialogState>(null);
|
||||||
|
const [archiving, setArchiving] = useState<CategoryView | null>(null);
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const tree = useMemo(
|
||||||
|
() => buildTree(categories.filter((c) => c.kind === kind && (showArchived || !c.archived))),
|
||||||
|
[categories, kind, showArchived],
|
||||||
|
);
|
||||||
|
const archivedCount = categories.filter((c) => c.kind === kind && c.archived).length;
|
||||||
|
|
||||||
|
function run(promise: Promise<{ ok: boolean; error?: string }>, success?: string) {
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await promise;
|
||||||
|
if (result.ok) {
|
||||||
|
if (success) toast.success(success);
|
||||||
|
} else toast.error(result.error ?? tr.common.genericError);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({
|
||||||
|
node,
|
||||||
|
index,
|
||||||
|
siblings,
|
||||||
|
}: {
|
||||||
|
node: CategoryNode<CategoryView>;
|
||||||
|
index: number;
|
||||||
|
siblings: number;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<li
|
||||||
|
className={cn("flex items-center gap-3 py-2 pr-2", node.archived && "opacity-60")}
|
||||||
|
style={{ paddingInlineStart: `${0.75 + node.depth * 1.5}rem` }}
|
||||||
|
>
|
||||||
|
<IconBadge icon={node.icon} color={node.color} size={node.depth ? "sm" : "md"} />
|
||||||
|
<span className={cn("min-w-0 flex-1 truncate", node.depth === 0 && "font-medium")}>
|
||||||
|
{node.name}
|
||||||
|
</span>
|
||||||
|
{node.archived ? <Badge variant="outline">{t.archived}</Badge> : null}
|
||||||
|
{canEdit ? (
|
||||||
|
<DropdownMenu modal={false}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
aria-label={`${node.name} — ${tr.common.actions}`}
|
||||||
|
disabled={pending}
|
||||||
|
>
|
||||||
|
<MoreHorizontal />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-52">
|
||||||
|
{!node.archived ? (
|
||||||
|
<>
|
||||||
|
{node.depth < MAX_DEPTH - 1 ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() => setDialog({ mode: "create", kind, parentId: node.id })}
|
||||||
|
>
|
||||||
|
<Plus />
|
||||||
|
{t.addChild}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
<DropdownMenuItem onSelect={() => setDialog({ mode: "edit", category: node })}>
|
||||||
|
<Pencil />
|
||||||
|
{t.edit}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
disabled={index === 0}
|
||||||
|
onSelect={() => run(reorderCategoryAction(node.id, "up"))}
|
||||||
|
>
|
||||||
|
<ArrowUp />
|
||||||
|
{t.moveUp}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
disabled={index === siblings - 1}
|
||||||
|
onSelect={() => run(reorderCategoryAction(node.id, "down"))}
|
||||||
|
>
|
||||||
|
<ArrowDown />
|
||||||
|
{t.moveDown}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem variant="destructive" onSelect={() => setArchiving(node)}>
|
||||||
|
<Archive />
|
||||||
|
{t.archive}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() =>
|
||||||
|
run(setCategoryArchivedAction(node.id, false), t.unarchivedToast(node.name))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ArchiveRestore />
|
||||||
|
{t.unarchive}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
{node.children.map((child, i) => (
|
||||||
|
<Row key={child.id} node={child} index={i} siblings={node.children.length} />
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<Tabs value={kind} onValueChange={(v) => setKind(v as CategoryKind)}>
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="expense">{t.expense}</TabsTrigger>
|
||||||
|
<TabsTrigger value="income">{t.income}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
</Tabs>
|
||||||
|
{archivedCount ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Checkbox
|
||||||
|
id="cat-show-archived"
|
||||||
|
checked={showArchived}
|
||||||
|
onCheckedChange={(v) => setShowArchived(v === true)}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="cat-show-archived" className="font-normal">
|
||||||
|
{t.showArchived} ({archivedCount})
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{canEdit ? (
|
||||||
|
<Button
|
||||||
|
className="ml-auto"
|
||||||
|
onClick={() => setDialog({ mode: "create", kind, parentId: null })}
|
||||||
|
>
|
||||||
|
<Plus />
|
||||||
|
{t.newCategory}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{!canEdit ? <p className="text-sm text-muted-foreground">{t.readOnly}</p> : null}
|
||||||
|
|
||||||
|
{tree.length ? (
|
||||||
|
<ul className="divide-y rounded-xl border bg-card" aria-busy={pending}>
|
||||||
|
{tree.map((node, i) => (
|
||||||
|
<Row key={node.id} node={node} index={i} siblings={tree.length} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="rounded-xl border border-dashed p-8 text-center text-muted-foreground">
|
||||||
|
{t.empty}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<CategoryFormDialog
|
||||||
|
state={dialog}
|
||||||
|
categories={categories}
|
||||||
|
onOpenChange={(o) => !o && setDialog(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<AlertDialog open={Boolean(archiving)} onOpenChange={(o) => !o && setArchiving(null)}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{t.archiveTitle}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{archiving ? t.archiveDescription(archiving.name) : null}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>{tr.common.cancel}</AlertDialogCancel>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => {
|
||||||
|
const c = archiving!;
|
||||||
|
setArchiving(null);
|
||||||
|
run(setCategoryArchivedAction(c.id, true), t.archivedToast(c.name));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t.archive}
|
||||||
|
</Button>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { useEffect, useMemo } from "react";
|
||||||
|
import { Controller, useForm, useWatch } from "react-hook-form";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { IconPicker, SwatchPicker } from "@/components/appearance/pickers";
|
||||||
|
import { ResponsiveDialog } from "@/components/responsive-dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import {
|
||||||
|
categoryFormSchema,
|
||||||
|
type CategoryForm,
|
||||||
|
type CategoryFormInput,
|
||||||
|
type CategoryKind,
|
||||||
|
} from "@/shared/schemas/category";
|
||||||
|
import { createCategoryAction, updateCategoryAction } from "../actions";
|
||||||
|
import type { CategoryView } from "../service";
|
||||||
|
import { buildTree, descendantIds, MAX_DEPTH, toOptions } from "../tree";
|
||||||
|
|
||||||
|
const t = tr.categories;
|
||||||
|
const ROOT = "__root__";
|
||||||
|
|
||||||
|
export type CategoryDialogState =
|
||||||
|
| { mode: "create"; kind: CategoryKind; parentId: string | null }
|
||||||
|
| { mode: "edit"; category: CategoryView }
|
||||||
|
| null;
|
||||||
|
|
||||||
|
export function CategoryFormDialog({
|
||||||
|
state,
|
||||||
|
categories,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
state: CategoryDialogState;
|
||||||
|
categories: CategoryView[];
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const form = useForm<CategoryFormInput, unknown, CategoryForm>({
|
||||||
|
resolver: zodResolver(categoryFormSchema),
|
||||||
|
});
|
||||||
|
const kind = state?.mode === "edit" ? state.category.kind : (state?.kind ?? "expense");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!state) return;
|
||||||
|
if (state.mode === "edit") {
|
||||||
|
const c = state.category;
|
||||||
|
form.reset({
|
||||||
|
kind: c.kind,
|
||||||
|
name: c.name,
|
||||||
|
parentId: c.parentId ?? "",
|
||||||
|
icon: c.icon,
|
||||||
|
color: c.color,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const parent = categories.find((c) => c.id === state.parentId);
|
||||||
|
form.reset({
|
||||||
|
kind: state.kind,
|
||||||
|
name: "",
|
||||||
|
parentId: state.parentId ?? "",
|
||||||
|
icon: parent?.icon ?? "tag",
|
||||||
|
color: parent?.color ?? "blue",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [state, categories, form]);
|
||||||
|
|
||||||
|
/** Üst kategori seçenekleri: aynı tür, aktif; düzenlemede kendisi ve alt kategorileri hariç. */
|
||||||
|
const parentOptions = useMemo(() => {
|
||||||
|
const sameKind = categories.filter((c) => c.kind === kind);
|
||||||
|
const excluded = new Set(
|
||||||
|
state?.mode === "edit"
|
||||||
|
? [state.category.id, ...descendantIds(sameKind, state.category.id)]
|
||||||
|
: [],
|
||||||
|
);
|
||||||
|
return toOptions(buildTree(sameKind)).filter(
|
||||||
|
(o) => !excluded.has(o.id) && o.depth < MAX_DEPTH - 1,
|
||||||
|
);
|
||||||
|
}, [categories, kind, state]);
|
||||||
|
|
||||||
|
/** Ham form değerleri gönderilir; sunucu aynı şemayla yeniden ayrıştırır (tek doğruluk kaynağı). */
|
||||||
|
async function onSubmit() {
|
||||||
|
const values = form.getValues();
|
||||||
|
const result =
|
||||||
|
state?.mode === "edit"
|
||||||
|
? await updateCategoryAction(state.category.id, values)
|
||||||
|
: await createCategoryAction(values);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(state?.mode === "edit" ? t.updated(values.name) : t.created(values.name));
|
||||||
|
onOpenChange(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const [name, message] of Object.entries(result.fieldErrors ?? {})) {
|
||||||
|
if (message) form.setError(name as keyof CategoryFormInput, { message });
|
||||||
|
}
|
||||||
|
if (!result.fieldErrors) form.setError("root", { message: result.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const color = useWatch({ control: form.control, name: "color" }) ?? "blue";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveDialog
|
||||||
|
open={Boolean(state)}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
title={state?.mode === "edit" ? t.editTitle : t.createTitle}
|
||||||
|
description={t.formDescription}
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
|
||||||
|
{tr.common.cancel}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" form="category-form" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
|
{state?.mode === "edit" ? tr.common.save : tr.common.create}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<form id="category-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="name"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="cat-name">{t.name}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
value={field.value ?? ""}
|
||||||
|
id="cat-name"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
/>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="parentId"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => {
|
||||||
|
const current = parentOptions.find((o) => o.id === field.value);
|
||||||
|
return (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="cat-parent">{t.parent}</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={field.value || ROOT}
|
||||||
|
onValueChange={(v) => field.onChange(v === ROOT ? "" : v)}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id="cat-parent"
|
||||||
|
className="w-full"
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
>
|
||||||
|
<SelectValue>{current?.path ?? t.noParent}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="max-h-72">
|
||||||
|
<SelectItem value={ROOT}>{t.noParent}</SelectItem>
|
||||||
|
{parentOptions.map((o) => (
|
||||||
|
<SelectItem key={o.id} value={o.id}>
|
||||||
|
<span style={{ paddingInlineStart: `${o.depth * 0.75}rem` }}>
|
||||||
|
{o.label}
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="color"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel id="cat-color-label">{t.color}</FieldLabel>
|
||||||
|
<SwatchPicker
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
labelledBy="cat-color-label"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="icon"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel id="cat-icon-label">{t.icon}</FieldLabel>
|
||||||
|
<IconPicker
|
||||||
|
value={field.value}
|
||||||
|
color={color}
|
||||||
|
onChange={field.onChange}
|
||||||
|
labelledBy="cat-icon-label"
|
||||||
|
/>
|
||||||
|
<FieldDescription className="sr-only">{t.icon}</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{form.formState.errors.root ? (
|
||||||
|
<FieldError>{form.formState.errors.root.message}</FieldError>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</ResponsiveDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
|
import type { CategoryKind } from "@/shared/schemas/category";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hane oluşturulunca yüklenen varsayılan Türkçe kategori seti (Bölüm 6.2).
|
||||||
|
* `key` sabittir: set tekrar yüklendiğinde kopya oluşmaz, kullanıcı adı değiştirse bile tanınır.
|
||||||
|
*/
|
||||||
|
export type DefaultCategory = {
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
icon: IconKey;
|
||||||
|
color: Swatch;
|
||||||
|
children?: Omit<DefaultCategory, "children">[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_CATEGORIES: Record<CategoryKind, DefaultCategory[]> = {
|
||||||
|
expense: [
|
||||||
|
{
|
||||||
|
key: "market",
|
||||||
|
name: "Market",
|
||||||
|
icon: "shopping-cart",
|
||||||
|
color: "green",
|
||||||
|
children: [
|
||||||
|
{ key: "market.gida", name: "Gıda", icon: "shopping-basket", color: "green" },
|
||||||
|
{ key: "market.temizlik", name: "Temizlik", icon: "spray-can", color: "teal" },
|
||||||
|
{ key: "market.kisisel-bakim", name: "Kişisel bakım", icon: "sparkles", color: "pink" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "faturalar",
|
||||||
|
name: "Faturalar",
|
||||||
|
icon: "receipt",
|
||||||
|
color: "amber",
|
||||||
|
children: [
|
||||||
|
{ key: "faturalar.elektrik", name: "Elektrik", icon: "zap", color: "amber" },
|
||||||
|
{ key: "faturalar.su", name: "Su", icon: "droplet", color: "sky" },
|
||||||
|
{ key: "faturalar.dogalgaz", name: "Doğalgaz", icon: "flame", color: "orange" },
|
||||||
|
{ key: "faturalar.internet", name: "İnternet", icon: "wifi", color: "indigo" },
|
||||||
|
{ key: "faturalar.telefon", name: "Telefon", icon: "smartphone", color: "purple" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ key: "kira", name: "Kira", icon: "house", color: "blue" },
|
||||||
|
{ key: "aidat", name: "Aidat", icon: "building", color: "slate" },
|
||||||
|
{
|
||||||
|
key: "ulasim",
|
||||||
|
name: "Ulaşım",
|
||||||
|
icon: "car",
|
||||||
|
color: "sky",
|
||||||
|
children: [
|
||||||
|
{ key: "ulasim.yakit", name: "Yakıt", icon: "fuel", color: "orange" },
|
||||||
|
{ key: "ulasim.toplu-tasima", name: "Toplu taşıma", icon: "bus", color: "sky" },
|
||||||
|
{ key: "ulasim.arac-bakim", name: "Araç bakım ve sigorta", icon: "wrench", color: "slate" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "saglik",
|
||||||
|
name: "Sağlık",
|
||||||
|
icon: "heart-pulse",
|
||||||
|
color: "red",
|
||||||
|
children: [
|
||||||
|
{ key: "saglik.ilac", name: "İlaç", icon: "pill", color: "red" },
|
||||||
|
{ key: "saglik.muayene", name: "Muayene ve tahlil", icon: "heart-pulse", color: "rose" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ key: "egitim", name: "Eğitim", icon: "graduation-cap", color: "indigo" },
|
||||||
|
{ key: "giyim", name: "Giyim", icon: "shirt", color: "purple" },
|
||||||
|
{
|
||||||
|
key: "eglence",
|
||||||
|
name: "Eğlence",
|
||||||
|
icon: "film",
|
||||||
|
color: "pink",
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
key: "eglence.disarida-yemek",
|
||||||
|
name: "Dışarıda yemek",
|
||||||
|
icon: "utensils",
|
||||||
|
color: "orange",
|
||||||
|
},
|
||||||
|
{ key: "eglence.kafe", name: "Kafe", icon: "coffee", color: "amber" },
|
||||||
|
{ key: "eglence.tatil", name: "Tatil", icon: "plane", color: "sky" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ key: "abonelikler", name: "Abonelikler", icon: "repeat", color: "purple" },
|
||||||
|
{ key: "ev", name: "Ev ve mobilya", icon: "sofa", color: "teal" },
|
||||||
|
{ key: "cocuk", name: "Çocuk", icon: "baby", color: "rose" },
|
||||||
|
{ key: "evcil-hayvan", name: "Evcil hayvan", icon: "paw-print", color: "lime" },
|
||||||
|
{ key: "hediye", name: "Hediye ve bağış", icon: "gift", color: "pink" },
|
||||||
|
{
|
||||||
|
key: "banka",
|
||||||
|
name: "Banka ve kart giderleri",
|
||||||
|
icon: "percent",
|
||||||
|
color: "slate",
|
||||||
|
children: [
|
||||||
|
{ key: "banka.faiz", name: "Faiz", icon: "percent", color: "red" },
|
||||||
|
{ key: "banka.vergi", name: "KKDF / BSMV", icon: "receipt", color: "slate" },
|
||||||
|
{
|
||||||
|
key: "banka.ucret",
|
||||||
|
name: "Kart ve hesap ücretleri",
|
||||||
|
icon: "credit-card",
|
||||||
|
color: "slate",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ key: "vergi", name: "Vergi ve harçlar", icon: "landmark", color: "slate" },
|
||||||
|
{ key: "diger-gider", name: "Diğer", icon: "circle-ellipsis", color: "slate" },
|
||||||
|
],
|
||||||
|
income: [
|
||||||
|
{ key: "maas", name: "Maaş", icon: "briefcase", color: "green" },
|
||||||
|
{ key: "ek-gelir", name: "Ek gelir", icon: "coins", color: "teal" },
|
||||||
|
{ key: "yemek-karti", name: "Yemek kartı yüklemesi", icon: "utensils", color: "lime" },
|
||||||
|
{ key: "kira-geliri", name: "Kira geliri", icon: "house", color: "blue" },
|
||||||
|
{ key: "getiri", name: "Faiz ve getiri", icon: "trending-up", color: "indigo" },
|
||||||
|
{ key: "iade", name: "İade", icon: "undo", color: "sky" },
|
||||||
|
{ key: "hediye-gelir", name: "Hediye", icon: "gift", color: "pink" },
|
||||||
|
{ key: "diger-gelir", name: "Diğer", icon: "circle-ellipsis", color: "slate" },
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { Types } from "mongoose";
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
import { CategoryModel } from "@/models/category";
|
||||||
|
import { setupSeededDb, teardownDb } from "@/test/seeded-db";
|
||||||
|
import {
|
||||||
|
createCategory,
|
||||||
|
installDefaultCategories,
|
||||||
|
listCategories,
|
||||||
|
setCategoryArchived,
|
||||||
|
updateCategory,
|
||||||
|
} from "./service";
|
||||||
|
|
||||||
|
let ids: Awaited<ReturnType<typeof setupSeededDb>>;
|
||||||
|
let cakir = "";
|
||||||
|
let annemler = "";
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ids = await setupSeededDb();
|
||||||
|
cakir = ids.household("Çakır Ailesi");
|
||||||
|
annemler = ids.household("Annemler");
|
||||||
|
});
|
||||||
|
afterAll(teardownDb);
|
||||||
|
|
||||||
|
const byKey = (key: string, householdId = cakir) =>
|
||||||
|
CategoryModel.findOne({ householdId, defaultKey: key })
|
||||||
|
.lean()
|
||||||
|
.then((c) => String(c!._id));
|
||||||
|
const form = (over: Partial<Parameters<typeof createCategory>[2]> = {}) => ({
|
||||||
|
kind: "expense" as const,
|
||||||
|
name: "Test",
|
||||||
|
parentId: null,
|
||||||
|
icon: "tag" as const,
|
||||||
|
color: "blue" as const,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("varsayılan kategoriler", () => {
|
||||||
|
it("tekrar yüklemede kopya oluşmaz", async () => {
|
||||||
|
const before = await CategoryModel.countDocuments({ householdId: cakir });
|
||||||
|
const added = await installDefaultCategories(
|
||||||
|
new Types.ObjectId(cakir),
|
||||||
|
new Types.ObjectId(ids.user("admin")),
|
||||||
|
);
|
||||||
|
expect(added).toBe(0);
|
||||||
|
expect(await CategoryModel.countDocuments({ householdId: cakir })).toBe(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("alt kategoriler doğru ancestors zinciriyle yüklenir", async () => {
|
||||||
|
const elektrik = await CategoryModel.findOne({
|
||||||
|
householdId: cakir,
|
||||||
|
defaultKey: "faturalar.elektrik",
|
||||||
|
}).lean();
|
||||||
|
const faturalar = await byKey("faturalar");
|
||||||
|
expect(elektrik?.ancestors.map(String)).toEqual([faturalar]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("izolasyon ve roller", () => {
|
||||||
|
it("başka hanenin kategorilerini okuyamaz ve değiştiremez", async () => {
|
||||||
|
expect(await listCategories(ids.user("fatma"), cakir)).toBeNull();
|
||||||
|
const kira = await byKey("kira");
|
||||||
|
// fatma kendi hanesinin kimliğiyle, Çakır'ın kategorisini hedefler → bulunamaz.
|
||||||
|
const r = await updateCategory(
|
||||||
|
ids.user("fatma"),
|
||||||
|
annemler,
|
||||||
|
kira,
|
||||||
|
form({ name: "Ele geçirildi" }),
|
||||||
|
);
|
||||||
|
expect(r.ok).toBe(false);
|
||||||
|
expect((await CategoryModel.findById(kira).lean())?.name).toBe("Kira");
|
||||||
|
const r2 = await setCategoryArchived(ids.user("fatma"), annemler, kira, true);
|
||||||
|
expect(r2.ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("izleyici ekleyemez, üye ekler", async () => {
|
||||||
|
expect((await createCategory(ids.user("zeynep"), cakir, form({ name: "Harçlık" }))).ok).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect((await createCategory(ids.user("emre"), cakir, form({ name: "Harçlık" }))).ok).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("başka hanenin kategorisini üst kategori yapamaz", async () => {
|
||||||
|
const annemlerMarket = await byKey("market", annemler);
|
||||||
|
const r = await createCategory(
|
||||||
|
ids.user("ayse"),
|
||||||
|
cakir,
|
||||||
|
form({ name: "Sızma", parentId: annemlerMarket }),
|
||||||
|
);
|
||||||
|
expect(r.ok).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ağaç kuralları", () => {
|
||||||
|
it("aynı düzeyde aynı ad (Türkçe normalize) reddedilir", async () => {
|
||||||
|
const r = await createCategory(ids.user("ayse"), cakir, form({ name: " KİRA " }));
|
||||||
|
expect(r.ok).toBe(false);
|
||||||
|
// farklı düzeyde aynı ad serbest
|
||||||
|
const market = await byKey("market");
|
||||||
|
expect(
|
||||||
|
(await createCategory(ids.user("ayse"), cakir, form({ name: "Kira", parentId: market }))).ok,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("taşıma alt ağacın ancestors alanlarını günceller", async () => {
|
||||||
|
const ulasim = await byKey("ulasim");
|
||||||
|
const yakit = await byKey("ulasim.yakit");
|
||||||
|
const created = await createCategory(
|
||||||
|
ids.user("ayse"),
|
||||||
|
cakir,
|
||||||
|
form({ name: "LPG", parentId: yakit }),
|
||||||
|
);
|
||||||
|
const lpg = created.ok ? created.data.id : "";
|
||||||
|
const ev = await byKey("ev");
|
||||||
|
// Yakıt'ı (alt kategorisi LPG ile) "Ev ve mobilya" altına taşı.
|
||||||
|
const r = await updateCategory(
|
||||||
|
ids.user("ayse"),
|
||||||
|
cakir,
|
||||||
|
yakit,
|
||||||
|
form({ name: "Yakıt", parentId: ev, icon: "fuel" }),
|
||||||
|
);
|
||||||
|
expect(r.ok).toBe(true);
|
||||||
|
expect((await CategoryModel.findById(yakit).lean())?.ancestors.map(String)).toEqual([ev]);
|
||||||
|
expect((await CategoryModel.findById(lpg).lean())?.ancestors.map(String)).toEqual([ev, yakit]);
|
||||||
|
expect((await CategoryModel.findById(yakit).lean())?.parentId?.toString()).not.toBe(ulasim);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("döngü ve tür uyuşmazlığı reddedilir", async () => {
|
||||||
|
const market = await byKey("market");
|
||||||
|
const gida = await byKey("market.gida");
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await updateCategory(
|
||||||
|
ids.user("ayse"),
|
||||||
|
cakir,
|
||||||
|
market,
|
||||||
|
form({ name: "Market", parentId: gida }),
|
||||||
|
)
|
||||||
|
).ok,
|
||||||
|
).toBe(false);
|
||||||
|
const maas = await byKey("maas");
|
||||||
|
expect(
|
||||||
|
(await updateCategory(ids.user("ayse"), cakir, gida, form({ name: "Gıda", parentId: maas })))
|
||||||
|
.ok,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("arşivleme alt ağaçla birlikte yapılır; üstü arşivliyken alt kategori geri alınamaz", async () => {
|
||||||
|
const saglik = await byKey("saglik");
|
||||||
|
const ilac = await byKey("saglik.ilac");
|
||||||
|
expect((await setCategoryArchived(ids.user("emre"), cakir, saglik, true)).ok).toBe(true);
|
||||||
|
const active = (await listCategories(ids.user("emre"), cakir))!.map((c) => c.id);
|
||||||
|
expect(active).not.toContain(saglik);
|
||||||
|
expect(active).not.toContain(ilac);
|
||||||
|
expect((await setCategoryArchived(ids.user("emre"), cakir, ilac, false)).ok).toBe(false);
|
||||||
|
expect((await setCategoryArchived(ids.user("emre"), cakir, saglik, false)).ok).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { Types, type ClientSession } from "mongoose";
|
||||||
|
import { resolveMembership } from "@/features/households/service";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { writeAudit } from "@/lib/audit";
|
||||||
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
|
import { toObjectId } from "@/lib/object-id";
|
||||||
|
import { CategoryModel } from "@/models/category";
|
||||||
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
|
import type { CategoryForm, CategoryKind } from "@/shared/schemas/category";
|
||||||
|
import { foldTr } from "@/shared/search";
|
||||||
|
import { DEFAULT_CATEGORIES } from "./defaults";
|
||||||
|
import {
|
||||||
|
checkCreate,
|
||||||
|
checkMove,
|
||||||
|
descendantIds,
|
||||||
|
type FlatCategory,
|
||||||
|
type MoveViolation,
|
||||||
|
} from "./tree";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kategori servisi. Okuma: viewer; yazma: member. Hane kapsamı her fonksiyonda doğrulanır.
|
||||||
|
* Silme yoktur: arşivleme (alt ağaçla birlikte). İşlemler arşivli kategoriyi göstermeye devam eder.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const t = tr.categories;
|
||||||
|
|
||||||
|
export type CategoryView = FlatCategory & { icon: IconKey; color: Swatch; isDefault: boolean };
|
||||||
|
|
||||||
|
type Lean = {
|
||||||
|
_id: Types.ObjectId;
|
||||||
|
kind: CategoryKind;
|
||||||
|
name: string;
|
||||||
|
parentId: Types.ObjectId | null;
|
||||||
|
order: number;
|
||||||
|
archivedAt: Date | null;
|
||||||
|
icon: string;
|
||||||
|
color: string;
|
||||||
|
defaultKey: string | null;
|
||||||
|
ancestors: Types.ObjectId[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const toView = (c: Lean): CategoryView => ({
|
||||||
|
id: String(c._id),
|
||||||
|
kind: c.kind,
|
||||||
|
name: c.name,
|
||||||
|
parentId: c.parentId ? String(c.parentId) : null,
|
||||||
|
order: c.order,
|
||||||
|
archived: Boolean(c.archivedAt),
|
||||||
|
icon: c.icon as IconKey,
|
||||||
|
color: c.color as Swatch,
|
||||||
|
isDefault: Boolean(c.defaultKey),
|
||||||
|
});
|
||||||
|
|
||||||
|
const violationMessage = (v: MoveViolation) => t.violations[v];
|
||||||
|
|
||||||
|
export async function listCategories(
|
||||||
|
userId: string,
|
||||||
|
householdId: string,
|
||||||
|
opts: { kind?: CategoryKind; includeArchived?: boolean } = {},
|
||||||
|
): Promise<CategoryView[] | null> {
|
||||||
|
const m = await resolveMembership(userId, householdId, "viewer");
|
||||||
|
if (!m) return null;
|
||||||
|
const filter: Record<string, unknown> = { householdId: m.householdId };
|
||||||
|
if (opts.kind) filter.kind = opts.kind;
|
||||||
|
if (!opts.includeArchived) filter.archivedAt = null;
|
||||||
|
const rows = await CategoryModel.find(filter).lean<Lean[]>();
|
||||||
|
return rows.map(toView);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadKind(householdId: Types.ObjectId, kind: CategoryKind, session?: ClientSession) {
|
||||||
|
return CategoryModel.find({ householdId, kind })
|
||||||
|
.session(session ?? null)
|
||||||
|
.lean<Lean[]>();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasSiblingNamed(all: Lean[], parentId: string | null, name: string, exceptId?: string) {
|
||||||
|
const key = foldTr(name);
|
||||||
|
return all.some(
|
||||||
|
(c) =>
|
||||||
|
!c.archivedAt &&
|
||||||
|
String(c._id) !== exceptId &&
|
||||||
|
(c.parentId ? String(c.parentId) : null) === parentId &&
|
||||||
|
foldTr(c.name) === key,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Varsayılan seti yükler (idempotent: defaultKey'e göre). Yeni hane oluşturulurken aynı
|
||||||
|
* transaction içinde (session) ya da migration/seed'den çağrılır. Eklenen kategori sayısını döner.
|
||||||
|
*/
|
||||||
|
export async function installDefaultCategories(
|
||||||
|
householdId: Types.ObjectId,
|
||||||
|
actor: Types.ObjectId,
|
||||||
|
session?: ClientSession,
|
||||||
|
): Promise<number> {
|
||||||
|
await connectMongoose();
|
||||||
|
let inserted = 0;
|
||||||
|
const upsert = async (
|
||||||
|
kind: CategoryKind,
|
||||||
|
def: { key: string; name: string; icon: string; color: string },
|
||||||
|
order: number,
|
||||||
|
parent: { _id: Types.ObjectId; ancestors: Types.ObjectId[] } | null,
|
||||||
|
) => {
|
||||||
|
const res = await CategoryModel.findOneAndUpdate(
|
||||||
|
{ householdId, defaultKey: def.key },
|
||||||
|
{
|
||||||
|
$setOnInsert: {
|
||||||
|
householdId,
|
||||||
|
kind,
|
||||||
|
name: def.name,
|
||||||
|
nameKey: foldTr(def.name),
|
||||||
|
parentId: parent?._id ?? null,
|
||||||
|
ancestors: parent ? [...parent.ancestors, parent._id] : [],
|
||||||
|
icon: def.icon,
|
||||||
|
color: def.color,
|
||||||
|
order,
|
||||||
|
defaultKey: def.key,
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true, returnDocument: "after", includeResultMetadata: true, session },
|
||||||
|
);
|
||||||
|
if (!res.lastErrorObject?.updatedExisting) inserted++;
|
||||||
|
return res.value!;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const kind of ["expense", "income"] as const) {
|
||||||
|
for (const [i, def] of DEFAULT_CATEGORIES[kind].entries()) {
|
||||||
|
const parent = await upsert(kind, def, i, null);
|
||||||
|
for (const [j, child] of (def.children ?? []).entries()) {
|
||||||
|
await upsert(kind, child, j, { _id: parent._id, ancestors: parent.ancestors });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inserted;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createCategory(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
input: CategoryForm,
|
||||||
|
): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "member");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const all = await loadKind(m.householdId, input.kind);
|
||||||
|
const violation = checkCreate(all.map(toView), input.kind, input.parentId);
|
||||||
|
if (violation)
|
||||||
|
return fail(violationMessage(violation), { parentId: violationMessage(violation) });
|
||||||
|
if (hasSiblingNamed(all, input.parentId, input.name))
|
||||||
|
return fail(t.duplicate, { name: t.duplicate });
|
||||||
|
|
||||||
|
const parent = input.parentId ? all.find((c) => String(c._id) === input.parentId) : null;
|
||||||
|
const siblings = all.filter((c) => (c.parentId ? String(c.parentId) : null) === input.parentId);
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
const doc = await CategoryModel.create({
|
||||||
|
householdId: m.householdId,
|
||||||
|
kind: input.kind,
|
||||||
|
name: input.name,
|
||||||
|
nameKey: foldTr(input.name),
|
||||||
|
parentId: parent?._id ?? null,
|
||||||
|
ancestors: parent ? [...parent.ancestors, parent._id] : [],
|
||||||
|
icon: input.icon,
|
||||||
|
color: input.color,
|
||||||
|
order: siblings.length ? Math.max(...siblings.map((s) => s.order)) + 1 : 0,
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
});
|
||||||
|
return ok({ id: String(doc._id) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOne(householdId: Types.ObjectId, categoryId: string) {
|
||||||
|
const id = toObjectId(categoryId);
|
||||||
|
if (!id) return null;
|
||||||
|
// householdId filtresi: başka hanenin kategorisi asla bulunmaz.
|
||||||
|
return CategoryModel.findOne({ _id: id, householdId }).lean<Lean>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ad, ikon, renk ve (değiştiyse) üst kategori. Taşıma alt ağaçla birlikte transaction'da. */
|
||||||
|
export async function updateCategory(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
categoryId: string,
|
||||||
|
input: CategoryForm,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "member");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const current = await loadOne(m.householdId, categoryId);
|
||||||
|
if (!current || current.kind !== input.kind) return fail(tr.common.notFound);
|
||||||
|
const all = await loadKind(m.householdId, current.kind);
|
||||||
|
const currentParent = current.parentId ? String(current.parentId) : null;
|
||||||
|
const moving = currentParent !== input.parentId;
|
||||||
|
|
||||||
|
if (moving) {
|
||||||
|
const violation = checkMove(all.map(toView), categoryId, input.parentId);
|
||||||
|
if (violation)
|
||||||
|
return fail(violationMessage(violation), { parentId: violationMessage(violation) });
|
||||||
|
}
|
||||||
|
if (hasSiblingNamed(all, input.parentId, input.name, categoryId))
|
||||||
|
return fail(t.duplicate, { name: t.duplicate });
|
||||||
|
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
const mongoose = await connectMongoose();
|
||||||
|
await mongoose.connection.transaction(async (session) => {
|
||||||
|
const set: Record<string, unknown> = {
|
||||||
|
name: input.name,
|
||||||
|
nameKey: foldTr(input.name),
|
||||||
|
icon: input.icon,
|
||||||
|
color: input.color,
|
||||||
|
updatedBy: actor,
|
||||||
|
};
|
||||||
|
if (moving) {
|
||||||
|
const parent = input.parentId ? all.find((c) => String(c._id) === input.parentId)! : null;
|
||||||
|
const newAncestors = parent ? [...parent.ancestors, parent._id] : [];
|
||||||
|
const siblings = all.filter(
|
||||||
|
(c) => (c.parentId ? String(c.parentId) : null) === input.parentId,
|
||||||
|
);
|
||||||
|
Object.assign(set, {
|
||||||
|
parentId: parent?._id ?? null,
|
||||||
|
ancestors: newAncestors,
|
||||||
|
order: siblings.length ? Math.max(...siblings.map((s) => s.order)) + 1 : 0,
|
||||||
|
});
|
||||||
|
// Alt ağaç: yeni üst zincir + (taşınan düğüm) + düğümün altındaki eski yol.
|
||||||
|
for (const d of all.filter((c) => c.ancestors.some((a) => a.equals(current._id)))) {
|
||||||
|
const idx = d.ancestors.findIndex((a) => a.equals(current._id));
|
||||||
|
await CategoryModel.updateOne(
|
||||||
|
{ _id: d._id, householdId: m.householdId },
|
||||||
|
{ $set: { ancestors: [...newAncestors, current._id, ...d.ancestors.slice(idx + 1)] } },
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await writeAudit(
|
||||||
|
{
|
||||||
|
action: "category.move",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: m.householdId,
|
||||||
|
targetType: "category",
|
||||||
|
targetId: categoryId,
|
||||||
|
diff: { parentId: { from: currentParent, to: input.parentId } },
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await CategoryModel.updateOne(
|
||||||
|
{ _id: current._id, householdId: m.householdId },
|
||||||
|
{ $set: set },
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kardeşler arasında bir yukarı/aşağı taşır. */
|
||||||
|
export async function reorderCategory(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
categoryId: string,
|
||||||
|
direction: "up" | "down",
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "member");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const current = await loadOne(m.householdId, categoryId);
|
||||||
|
if (!current) return fail(tr.common.notFound);
|
||||||
|
const siblings = (await loadKind(m.householdId, current.kind))
|
||||||
|
.filter((c) => !c.archivedAt && String(c.parentId ?? "") === String(current.parentId ?? ""))
|
||||||
|
.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name, "tr"));
|
||||||
|
const i = siblings.findIndex((c) => c._id.equals(current._id));
|
||||||
|
const j = direction === "up" ? i - 1 : i + 1;
|
||||||
|
if (i < 0 || j < 0 || j >= siblings.length) return ok(undefined);
|
||||||
|
[siblings[i], siblings[j]] = [siblings[j]!, siblings[i]!];
|
||||||
|
await CategoryModel.bulkWrite(
|
||||||
|
siblings.map((c, order) => ({
|
||||||
|
updateOne: {
|
||||||
|
filter: { _id: c._id, householdId: m.householdId },
|
||||||
|
update: { $set: { order } },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arşivler (alt kategorilerle birlikte) veya arşivden çıkarır (üstü aktif olmalı). */
|
||||||
|
export async function setCategoryArchived(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
categoryId: string,
|
||||||
|
archived: boolean,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const m = await resolveMembership(actorId, householdId, "member");
|
||||||
|
if (!m) return fail(tr.common.unauthorized);
|
||||||
|
const current = await loadOne(m.householdId, categoryId);
|
||||||
|
if (!current) return fail(tr.common.notFound);
|
||||||
|
const all = await loadKind(m.householdId, current.kind);
|
||||||
|
|
||||||
|
if (!archived && current.parentId) {
|
||||||
|
const parent = all.find((c) => c._id.equals(current.parentId!));
|
||||||
|
if (parent?.archivedAt) return fail(t.violations.parentArchived);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!archived &&
|
||||||
|
hasSiblingNamed(
|
||||||
|
all,
|
||||||
|
current.parentId ? String(current.parentId) : null,
|
||||||
|
current.name,
|
||||||
|
categoryId,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return fail(t.duplicate);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ids = [
|
||||||
|
current._id,
|
||||||
|
...descendantIds(all.map(toView), categoryId).map((id) => new Types.ObjectId(id)),
|
||||||
|
];
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
await CategoryModel.updateMany(
|
||||||
|
{ _id: { $in: ids }, householdId: m.householdId },
|
||||||
|
{ $set: { archivedAt: archived ? new Date() : null, updatedBy: actor } },
|
||||||
|
);
|
||||||
|
await writeAudit({
|
||||||
|
action: archived ? "category.archive" : "category.unarchive",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: m.householdId,
|
||||||
|
targetType: "category",
|
||||||
|
targetId: categoryId,
|
||||||
|
diff: { name: current.name, affected: ids.length },
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
ancestorIds,
|
||||||
|
buildTree,
|
||||||
|
checkCreate,
|
||||||
|
checkMove,
|
||||||
|
descendantIds,
|
||||||
|
rollupTotals,
|
||||||
|
toOptions,
|
||||||
|
type FlatCategory,
|
||||||
|
} from "./tree";
|
||||||
|
|
||||||
|
const c = (
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
parentId: string | null,
|
||||||
|
order = 0,
|
||||||
|
kind: "expense" | "income" = "expense",
|
||||||
|
): FlatCategory => ({
|
||||||
|
id,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
parentId,
|
||||||
|
order,
|
||||||
|
archived: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const items: FlatCategory[] = [
|
||||||
|
c("fat", "Faturalar", null, 1),
|
||||||
|
c("elk", "Elektrik", "fat", 0),
|
||||||
|
c("su", "Su", "fat", 1),
|
||||||
|
c("mar", "Market", null, 0),
|
||||||
|
c("gida", "Gıda", "mar", 0),
|
||||||
|
c("meyve", "Meyve", "gida", 0),
|
||||||
|
c("maas", "Maaş", null, 0, "income"),
|
||||||
|
];
|
||||||
|
|
||||||
|
describe("buildTree / toOptions", () => {
|
||||||
|
it("sıra ve derinlikle ağaç kurar, yol etiketleri üretir", () => {
|
||||||
|
const tree = buildTree(items.filter((i) => i.kind === "expense"));
|
||||||
|
expect(tree.map((n) => n.name)).toEqual(["Market", "Faturalar"]);
|
||||||
|
expect(toOptions(tree).map((o) => [o.path, o.depth])).toEqual([
|
||||||
|
["Market", 0],
|
||||||
|
["Market › Gıda", 1],
|
||||||
|
["Market › Gıda › Meyve", 2],
|
||||||
|
["Faturalar", 0],
|
||||||
|
["Faturalar › Elektrik", 1],
|
||||||
|
["Faturalar › Su", 1],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("arşivlenenleri varsayılan olarak seçeneklere koymaz", () => {
|
||||||
|
const tree = buildTree([c("a", "A", null), { ...c("b", "B", "a"), archived: true }]);
|
||||||
|
expect(toOptions(tree).map((o) => o.id)).toEqual(["a"]);
|
||||||
|
expect(toOptions(tree, { includeArchived: true }).map((o) => o.id)).toEqual(["a", "b"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("üstü olmayan düğümü köke alır, döngüde takılmaz", () => {
|
||||||
|
const loop = [c("x", "X", "y"), c("y", "Y", "x"), c("z", "Z", "yok")];
|
||||||
|
expect(() => buildTree(loop)).not.toThrow();
|
||||||
|
expect(buildTree(loop).map((n) => n.id)).toContain("z");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ancestorIds / descendantIds", () => {
|
||||||
|
it("üst ve alt kategorileri bulur", () => {
|
||||||
|
expect(ancestorIds(items, "meyve")).toEqual(["mar", "gida"]);
|
||||||
|
expect(descendantIds(items, "mar").sort()).toEqual(["gida", "meyve"]);
|
||||||
|
expect(descendantIds(items, "elk")).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("checkMove", () => {
|
||||||
|
it("kendine, alt kategorisine ve farklı türe taşımayı reddeder", () => {
|
||||||
|
expect(checkMove(items, "mar", "mar")).toBe("self");
|
||||||
|
expect(checkMove(items, "mar", "meyve")).toBe("descendant");
|
||||||
|
expect(checkMove(items, "elk", "maas")).toBe("kind");
|
||||||
|
expect(checkMove(items, "elk", "yok")).toBe("parentNotFound");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("geçerli taşımaya ve köke taşımaya izin verir", () => {
|
||||||
|
expect(checkMove(items, "su", "mar")).toBeNull();
|
||||||
|
expect(checkMove(items, "gida", null)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("derinlik sınırını uygular (en fazla 5 seviye: derinlik 0–4)", () => {
|
||||||
|
const deep = [
|
||||||
|
c("1", "1", null),
|
||||||
|
c("2", "2", "1"),
|
||||||
|
c("3", "3", "2"),
|
||||||
|
c("4", "4", "3"),
|
||||||
|
c("5", "5", "4"),
|
||||||
|
c("x", "X", null),
|
||||||
|
c("y", "Y", "x"),
|
||||||
|
];
|
||||||
|
expect(checkCreate(deep, "expense", "4")).toBeNull(); // yeni düğüm derinlik 4
|
||||||
|
expect(checkCreate(deep, "expense", "5")).toBe("depth"); // derinlik 5
|
||||||
|
expect(checkMove(deep, "y", "4")).toBeNull();
|
||||||
|
expect(checkMove(deep, "y", "5")).toBe("depth");
|
||||||
|
expect(checkMove(deep, "x", "4")).toBe("depth"); // x derinlik 4, alt kategorisi y derinlik 5
|
||||||
|
expect(checkCreate(deep, "income", "3")).toBe("kind");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rollupTotals", () => {
|
||||||
|
it("alt kategori tutarlarını üst kategorilere toplar", () => {
|
||||||
|
const totals = rollupTotals(
|
||||||
|
items,
|
||||||
|
new Map([
|
||||||
|
["meyve", 300],
|
||||||
|
["gida", 500],
|
||||||
|
["elk", 1000],
|
||||||
|
["su", 250],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(totals.get("mar")).toBe(800);
|
||||||
|
expect(totals.get("gida")).toBe(800);
|
||||||
|
expect(totals.get("fat")).toBe(1250);
|
||||||
|
expect(totals.get("maas") ?? 0).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import type { CategoryKind } from "@/shared/schemas/category";
|
||||||
|
import { compareTr } from "@/shared/search";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kategori ağacı saf fonksiyonları (framework'ten bağımsız, birim testli).
|
||||||
|
* Derinlik pratikte 3 seviye; güvenlik için en fazla MAX_DEPTH seviye.
|
||||||
|
*/
|
||||||
|
export const MAX_DEPTH = 5;
|
||||||
|
|
||||||
|
export type FlatCategory = {
|
||||||
|
id: string;
|
||||||
|
kind: CategoryKind;
|
||||||
|
name: string;
|
||||||
|
parentId: string | null;
|
||||||
|
order: number;
|
||||||
|
archived: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CategoryNode<T extends FlatCategory = FlatCategory> = T & {
|
||||||
|
depth: number;
|
||||||
|
children: CategoryNode<T>[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const bySortOrder = (a: FlatCategory, b: FlatCategory) =>
|
||||||
|
a.order - b.order || compareTr(a.name, b.name);
|
||||||
|
|
||||||
|
/** Düz listeden ağaç kurar. Üstü bulunamayan (veya döngülü) düğümler köke alınır. */
|
||||||
|
export function buildTree<T extends FlatCategory>(items: readonly T[]): CategoryNode<T>[] {
|
||||||
|
const nodes = new Map(
|
||||||
|
items.map((c) => [c.id, { ...c, depth: 0, children: [] as CategoryNode<T>[] }]),
|
||||||
|
);
|
||||||
|
const roots: CategoryNode<T>[] = [];
|
||||||
|
for (const node of nodes.values()) {
|
||||||
|
const parent = node.parentId ? nodes.get(node.parentId) : undefined;
|
||||||
|
if (parent && parent !== node) parent.children.push(node);
|
||||||
|
else roots.push(node);
|
||||||
|
}
|
||||||
|
const visit = (list: CategoryNode<T>[], depth: number, seen: Set<string>) => {
|
||||||
|
list.sort(bySortOrder);
|
||||||
|
for (const n of list) {
|
||||||
|
if (seen.has(n.id)) continue;
|
||||||
|
seen.add(n.id);
|
||||||
|
n.depth = depth;
|
||||||
|
visit(n.children, depth + 1, seen);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
visit(roots, 0, new Set());
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CategoryOption = {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
path: string;
|
||||||
|
depth: number;
|
||||||
|
kind: CategoryKind;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Seçim listesi (işlem formları): derinlik sırasıyla, "Faturalar › Elektrik" yoluyla. */
|
||||||
|
export function toOptions<T extends FlatCategory>(
|
||||||
|
tree: CategoryNode<T>[],
|
||||||
|
{ includeArchived = false } = {},
|
||||||
|
): CategoryOption[] {
|
||||||
|
const out: CategoryOption[] = [];
|
||||||
|
const walk = (list: CategoryNode<T>[], prefix: string[]) => {
|
||||||
|
for (const n of list) {
|
||||||
|
if (n.archived && !includeArchived) continue;
|
||||||
|
const path = [...prefix, n.name];
|
||||||
|
out.push({ id: n.id, label: n.name, path: path.join(" › "), depth: n.depth, kind: n.kind });
|
||||||
|
walk(n.children, path);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(tree, []);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `id`'nin tüm alt kategorileri (kendisi hariç). */
|
||||||
|
export function descendantIds(items: readonly FlatCategory[], id: string): string[] {
|
||||||
|
const children = new Map<string, string[]>();
|
||||||
|
for (const c of items)
|
||||||
|
if (c.parentId) children.set(c.parentId, [...(children.get(c.parentId) ?? []), c.id]);
|
||||||
|
const out: string[] = [];
|
||||||
|
const stack = [...(children.get(id) ?? [])];
|
||||||
|
while (stack.length) {
|
||||||
|
const next = stack.pop()!;
|
||||||
|
if (out.includes(next)) continue;
|
||||||
|
out.push(next);
|
||||||
|
stack.push(...(children.get(next) ?? []));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kökten `id`'ye kadar üst kategori kimlikleri (id hariç). */
|
||||||
|
export function ancestorIds(items: readonly FlatCategory[], id: string): string[] {
|
||||||
|
const byId = new Map(items.map((c) => [c.id, c]));
|
||||||
|
const out: string[] = [];
|
||||||
|
let cur = byId.get(id)?.parentId ?? null;
|
||||||
|
while (cur && !out.includes(cur)) {
|
||||||
|
out.unshift(cur);
|
||||||
|
cur = byId.get(cur)?.parentId ?? null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alt ağacın yüksekliği (yaprak = 0). */
|
||||||
|
function subtreeHeight(items: readonly FlatCategory[], id: string): number {
|
||||||
|
const kids = items.filter((c) => c.parentId === id);
|
||||||
|
return kids.length ? 1 + Math.max(...kids.map((k) => subtreeHeight(items, k.id))) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MoveViolation =
|
||||||
|
"self" | "descendant" | "kind" | "depth" | "parentNotFound" | "parentArchived";
|
||||||
|
|
||||||
|
/** `id` kategorisi `newParentId` altına (null = kök) taşınabilir mi? */
|
||||||
|
export function checkMove(
|
||||||
|
items: readonly FlatCategory[],
|
||||||
|
id: string,
|
||||||
|
newParentId: string | null,
|
||||||
|
): MoveViolation | null {
|
||||||
|
if (newParentId === null) return null;
|
||||||
|
if (newParentId === id) return "self";
|
||||||
|
const parent = items.find((c) => c.id === newParentId);
|
||||||
|
const self = items.find((c) => c.id === id);
|
||||||
|
if (!parent || !self) return "parentNotFound";
|
||||||
|
if (parent.kind !== self.kind) return "kind";
|
||||||
|
if (parent.archived) return "parentArchived";
|
||||||
|
if (descendantIds(items, id).includes(newParentId)) return "descendant";
|
||||||
|
const newDepth = ancestorIds(items, newParentId).length + 1;
|
||||||
|
if (newDepth + subtreeHeight(items, id) >= MAX_DEPTH) return "depth";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Yeni kategori `parentId` altına eklenebilir mi? */
|
||||||
|
export function checkCreate(
|
||||||
|
items: readonly FlatCategory[],
|
||||||
|
kind: CategoryKind,
|
||||||
|
parentId: string | null,
|
||||||
|
): MoveViolation | null {
|
||||||
|
if (!parentId) return null;
|
||||||
|
const parent = items.find((c) => c.id === parentId);
|
||||||
|
if (!parent) return "parentNotFound";
|
||||||
|
if (parent.kind !== kind) return "kind";
|
||||||
|
if (parent.archived) return "parentArchived";
|
||||||
|
if (ancestorIds(items, parentId).length + 1 >= MAX_DEPTH) return "depth";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kategori bazlı tutarları üst kategorilere toplar (raporlar ve bütçe için):
|
||||||
|
* her kategori kendi tutarı + tüm alt kategorilerinin tutarı.
|
||||||
|
*/
|
||||||
|
export function rollupTotals(
|
||||||
|
items: readonly FlatCategory[],
|
||||||
|
totals: ReadonlyMap<string, number>,
|
||||||
|
): Map<string, number> {
|
||||||
|
const out = new Map<string, number>();
|
||||||
|
for (const c of items) {
|
||||||
|
const own = totals.get(c.id) ?? 0;
|
||||||
|
for (const target of [c.id, ...ancestorIds(items, c.id)])
|
||||||
|
out.set(target, (out.get(target) ?? 0) + own);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { writeActiveHouseholdId } from "@/lib/active-household";
|
||||||
|
import { getCurrentUser, getHouseholdActionContext } from "@/lib/dal";
|
||||||
|
import { householdRoleSchema, householdSettingsSchema } from "@/shared/schemas/household";
|
||||||
|
import { removeMember, resolveMembership, setMemberRole, updateHouseholdSettings } from "./service";
|
||||||
|
|
||||||
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
||||||
|
|
||||||
|
/** Aktif haneyi değiştirir: önce üyelik doğrulanır, sonra cookie yazılır. */
|
||||||
|
export async function switchHouseholdAction(
|
||||||
|
householdId: unknown,
|
||||||
|
): Promise<ActionResult<{ name: string }>> {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
const id = idSchema.safeParse(householdId);
|
||||||
|
if (!user || !id.success) return fail(tr.common.unauthorized);
|
||||||
|
const membership = await resolveMembership(user.id, id.data, "viewer");
|
||||||
|
if (!membership) return fail(tr.common.unauthorized);
|
||||||
|
await writeActiveHouseholdId(id.data);
|
||||||
|
revalidatePath("/", "layout");
|
||||||
|
return ok({ name: membership.name });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: hane adı ve ayarları (aktif hane). */
|
||||||
|
export async function updateHouseholdSettingsAction(input: unknown): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const parsed = householdSettingsSchema.safeParse(input);
|
||||||
|
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields);
|
||||||
|
const result = await updateHouseholdSettings(ctx.user.id, ctx.household.id, parsed.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: aktif hanedeki üyenin rolü. */
|
||||||
|
export async function setMemberRoleAction(userId: unknown, role: unknown): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const uid = idSchema.safeParse(userId);
|
||||||
|
const r = householdRoleSchema.safeParse(role);
|
||||||
|
if (!uid.success || !r.success) return fail(tr.common.genericError);
|
||||||
|
const result = await setMemberRole(ctx.user.id, ctx.household.id, uid.data, r.data);
|
||||||
|
if (result.ok) revalidatePath("/ayarlar");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: üyeyi aktif haneden çıkarır. */
|
||||||
|
export async function removeMemberAction(userId: unknown): Promise<ActionResult> {
|
||||||
|
const ctx = await getHouseholdActionContext("owner");
|
||||||
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
|
const uid = idSchema.safeParse(userId);
|
||||||
|
if (!uid.success) return fail(tr.common.genericError);
|
||||||
|
const result = await removeMember(ctx.user.id, ctx.household.id, uid.data);
|
||||||
|
if (result.ok) revalidatePath("/", "layout");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { Controller, useForm } from "react-hook-form";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
|
import {
|
||||||
|
Field,
|
||||||
|
FieldDescription,
|
||||||
|
FieldError,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLabel,
|
||||||
|
FieldSet,
|
||||||
|
} from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { householdSettingsSchema, type HouseholdSettings } from "@/shared/schemas/household";
|
||||||
|
import { updateHouseholdSettingsAction } from "../actions";
|
||||||
|
|
||||||
|
const t = tr.settings.fields;
|
||||||
|
|
||||||
|
/** Form şeması: eşik TL (tam sayı) olarak girilir, kuruşa sunucuya giderken çevrilir. */
|
||||||
|
const formSchema = householdSettingsSchema
|
||||||
|
.omit({ extraStoreSavingThresholdMinor: true, budgetMonthStartDay: true })
|
||||||
|
.extend({
|
||||||
|
budgetMonthStartDay: z.number().int().min(1).max(28),
|
||||||
|
extraStoreSavingThresholdTl: z
|
||||||
|
.number({ error: tr.validation.wholeNumber })
|
||||||
|
.int(tr.validation.wholeNumber)
|
||||||
|
.min(0)
|
||||||
|
.max(100_000),
|
||||||
|
});
|
||||||
|
type FormValues = z.infer<typeof formSchema>;
|
||||||
|
|
||||||
|
const DAYS = Array.from({ length: 28 }, (_, i) => i + 1);
|
||||||
|
|
||||||
|
export function HouseholdSettingsForm({
|
||||||
|
settings,
|
||||||
|
canEdit,
|
||||||
|
}: {
|
||||||
|
settings: HouseholdSettings;
|
||||||
|
canEdit: boolean;
|
||||||
|
}) {
|
||||||
|
const form = useForm<FormValues>({
|
||||||
|
resolver: zodResolver(formSchema),
|
||||||
|
defaultValues: {
|
||||||
|
name: settings.name,
|
||||||
|
budgetMonthStartDay: settings.budgetMonthStartDay,
|
||||||
|
installmentBudgetMode: settings.installmentBudgetMode,
|
||||||
|
dailyPlanMode: settings.dailyPlanMode,
|
||||||
|
includePrivateAccountsInTotals: settings.includePrivateAccountsInTotals,
|
||||||
|
extraStoreSavingThresholdTl: Math.round(settings.extraStoreSavingThresholdMinor / 100),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function onSubmit({ extraStoreSavingThresholdTl, ...rest }: FormValues) {
|
||||||
|
const result = await updateHouseholdSettingsAction({
|
||||||
|
...rest,
|
||||||
|
extraStoreSavingThresholdMinor: extraStoreSavingThresholdTl * 100,
|
||||||
|
});
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(tr.settings.saved);
|
||||||
|
form.reset({ ...rest, extraStoreSavingThresholdTl });
|
||||||
|
} else {
|
||||||
|
toast.error(result.error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitting = form.formState.isSubmitting;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} noValidate>
|
||||||
|
{/* Sahip olmayanlar için tüm alanlar salt okunur. */}
|
||||||
|
<FieldSet disabled={!canEdit || submitting}>
|
||||||
|
<FieldGroup>
|
||||||
|
<Controller
|
||||||
|
name="name"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="hh-name">{t.name}</FieldLabel>
|
||||||
|
<Input {...field} id="hh-name" aria-invalid={fieldState.invalid} />
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="budgetMonthStartDay"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="hh-start-day">{t.budgetMonthStartDay}</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={String(field.value)}
|
||||||
|
onValueChange={(v) => field.onChange(Number(v))}
|
||||||
|
disabled={!canEdit}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id="hh-start-day"
|
||||||
|
className="w-28"
|
||||||
|
aria-describedby="hh-start-day-hint"
|
||||||
|
>
|
||||||
|
<SelectValue>{field.value}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="max-h-64">
|
||||||
|
{DAYS.map((d) => (
|
||||||
|
<SelectItem key={d} value={String(d)}>
|
||||||
|
{d}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<FieldDescription id="hh-start-day-hint">
|
||||||
|
{t.budgetMonthStartDayHint}
|
||||||
|
</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="installmentBudgetMode"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="hh-installment">{t.installmentBudgetMode}</FieldLabel>
|
||||||
|
<Select value={field.value} onValueChange={field.onChange} disabled={!canEdit}>
|
||||||
|
<SelectTrigger id="hh-installment" className="w-full sm:w-80">
|
||||||
|
<SelectValue>{t.installmentModes[field.value]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{(["per_installment", "purchase_month"] as const).map((m) => (
|
||||||
|
<SelectItem key={m} value={m}>
|
||||||
|
{t.installmentModes[m]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="dailyPlanMode"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="hh-daily">{t.dailyPlanMode}</FieldLabel>
|
||||||
|
<Select value={field.value} onValueChange={field.onChange} disabled={!canEdit}>
|
||||||
|
<SelectTrigger id="hh-daily" className="w-full sm:w-80">
|
||||||
|
<SelectValue>{t.dailyPlanModes[field.value]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{(["even", "previous_month_pattern"] as const).map((m) => (
|
||||||
|
<SelectItem key={m} value={m}>
|
||||||
|
{t.dailyPlanModes[m]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="extraStoreSavingThresholdTl"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field, fieldState }) => (
|
||||||
|
<Field data-invalid={fieldState.invalid}>
|
||||||
|
<FieldLabel htmlFor="hh-threshold">{t.extraStoreSavingThreshold}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="hh-threshold"
|
||||||
|
type="number"
|
||||||
|
inputMode="numeric"
|
||||||
|
min={0}
|
||||||
|
step={1}
|
||||||
|
className="w-36 tabular-nums"
|
||||||
|
name={field.name}
|
||||||
|
ref={field.ref}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
value={Number.isNaN(field.value) ? "" : field.value}
|
||||||
|
onChange={(e) => field.onChange(e.target.valueAsNumber)}
|
||||||
|
aria-invalid={fieldState.invalid}
|
||||||
|
aria-describedby="hh-threshold-hint"
|
||||||
|
/>
|
||||||
|
<FieldDescription id="hh-threshold-hint">
|
||||||
|
{t.extraStoreSavingThresholdHint}
|
||||||
|
</FieldDescription>
|
||||||
|
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name="includePrivateAccountsInTotals"
|
||||||
|
control={form.control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<Checkbox
|
||||||
|
id="hh-private"
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={(v) => field.onChange(v === true)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
/>
|
||||||
|
<FieldLabel htmlFor="hh-private" className="font-normal">
|
||||||
|
{t.includePrivateAccountsInTotals}
|
||||||
|
</FieldLabel>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{canEdit ? (
|
||||||
|
<div>
|
||||||
|
<Button type="submit" disabled={submitting || !form.formState.isDirty}>
|
||||||
|
{submitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
|
{tr.common.save}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</FieldGroup>
|
||||||
|
</FieldSet>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { UserMinus } from "lucide-react";
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { initials } from "@/components/layout/user-menu";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import type { ActionResult } from "@/lib/action-result";
|
||||||
|
import { HOUSEHOLD_ROLES, type HouseholdRole } from "../types";
|
||||||
|
|
||||||
|
export type MemberRow = {
|
||||||
|
userId: string;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
role: HouseholdRole;
|
||||||
|
banned: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
members: MemberRow[];
|
||||||
|
householdName: string;
|
||||||
|
currentUserId: string;
|
||||||
|
canManage: boolean;
|
||||||
|
onSetRole: (userId: string, role: HouseholdRole) => Promise<ActionResult>;
|
||||||
|
onRemove: (userId: string) => Promise<ActionResult>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Hane üyeleri: owner (veya admin) rol değiştirir / haneden çıkarır. Kurallar sunucuda. */
|
||||||
|
export function MembersList({
|
||||||
|
members,
|
||||||
|
householdName,
|
||||||
|
currentUserId,
|
||||||
|
canManage,
|
||||||
|
onSetRole,
|
||||||
|
onRemove,
|
||||||
|
}: Props) {
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
const [removing, setRemoving] = useState<MemberRow | null>(null);
|
||||||
|
const t = tr.settings;
|
||||||
|
|
||||||
|
function changeRole(member: MemberRow, role: HouseholdRole) {
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await onSetRole(member.userId, role);
|
||||||
|
if (result.ok) toast.success(t.roleChanged(member.name));
|
||||||
|
else toast.error(result.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmRemove() {
|
||||||
|
const member = removing;
|
||||||
|
if (!member) return;
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await onRemove(member.userId);
|
||||||
|
if (result.ok) {
|
||||||
|
toast.success(t.memberRemoved(member.name));
|
||||||
|
setRemoving(null);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ul className="divide-y rounded-xl border" aria-busy={pending}>
|
||||||
|
{members.map((m) => (
|
||||||
|
<li key={m.userId} className="flex flex-wrap items-center gap-3 p-3">
|
||||||
|
<Avatar>
|
||||||
|
<AvatarFallback className="bg-primary/10 text-xs font-medium text-primary">
|
||||||
|
{initials(m.name)}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium">
|
||||||
|
{m.name}
|
||||||
|
{m.userId === currentUserId ? (
|
||||||
|
<span className="ml-1.5 text-xs font-normal text-muted-foreground">
|
||||||
|
({tr.adminUsers.you})
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-xs text-muted-foreground">@{m.username}</p>
|
||||||
|
</div>
|
||||||
|
{m.banned ? <Badge variant="destructive">{t.banned}</Badge> : null}
|
||||||
|
{canManage ? (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Select
|
||||||
|
value={m.role}
|
||||||
|
onValueChange={(v) => changeRole(m, v as HouseholdRole)}
|
||||||
|
disabled={pending}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
size="sm"
|
||||||
|
className="w-32"
|
||||||
|
aria-label={`${m.name} — ${t.changeRole}`}
|
||||||
|
>
|
||||||
|
<SelectValue>{tr.household.roles[m.role]}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent align="end">
|
||||||
|
{HOUSEHOLD_ROLES.map((r) => (
|
||||||
|
<SelectItem key={r} value={r}>
|
||||||
|
<span className="flex flex-col">
|
||||||
|
<span>{tr.household.roles[r]}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{tr.household.roleHints[r]}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
onClick={() => setRemoving(m)}
|
||||||
|
disabled={pending}
|
||||||
|
aria-label={`${m.name} — ${t.removeMember}`}
|
||||||
|
title={t.removeMember}
|
||||||
|
>
|
||||||
|
<UserMinus />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Badge variant={m.role === "owner" ? "default" : "secondary"}>
|
||||||
|
{tr.household.roles[m.role]}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<AlertDialog open={Boolean(removing)} onOpenChange={(open) => !open && setRemoving(null)}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{t.removeTitle}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{removing ? t.removeDescription(removing.name, householdName) : null}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel disabled={pending}>{tr.common.cancel}</AlertDialogCancel>
|
||||||
|
<Button variant="destructive" onClick={confirmRemove} disabled={pending}>
|
||||||
|
{t.removeConfirm}
|
||||||
|
</Button>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { removeMemberAction, setMemberRoleAction } from "../actions";
|
||||||
|
import type { HouseholdRole } from "../types";
|
||||||
|
import { MembersList, type MemberRow } from "./members-list";
|
||||||
|
|
||||||
|
/** /ayarlar: aktif hanenin üyeleri (owner action'larına bağlı). */
|
||||||
|
export function SettingsMembers(props: {
|
||||||
|
members: MemberRow[];
|
||||||
|
householdName: string;
|
||||||
|
currentUserId: string;
|
||||||
|
canManage: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MembersList
|
||||||
|
{...props}
|
||||||
|
onSetRole={(userId, role: HouseholdRole) => setMemberRoleAction(userId, role)}
|
||||||
|
onRemove={(userId) => removeMemberAction(userId)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import type { HouseholdSummary } from "./types";
|
|
||||||
|
|
||||||
/** FAZ 2 GEÇİCİ: Faz 5'te kullanıcının üye olduğu hanelerle değiştirilecek. */
|
|
||||||
export const MOCK_HOUSEHOLDS: HouseholdSummary[] = [
|
|
||||||
{ id: "h_cakir", name: "Çakır Ailesi", role: "owner" },
|
|
||||||
{ id: "h_anne", name: "Annemler", role: "viewer" },
|
|
||||||
];
|
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { checkMemberChange, hasHouseholdRole, pickActiveHousehold } from "./roles";
|
||||||
|
|
||||||
|
describe("hasHouseholdRole", () => {
|
||||||
|
it("viewer < member < owner sırasını uygular", () => {
|
||||||
|
expect(hasHouseholdRole("owner", "member")).toBe(true);
|
||||||
|
expect(hasHouseholdRole("member", "member")).toBe(true);
|
||||||
|
expect(hasHouseholdRole("viewer", "member")).toBe(false);
|
||||||
|
expect(hasHouseholdRole("member", "owner")).toBe(false);
|
||||||
|
expect(hasHouseholdRole("viewer", "viewer")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("checkMemberChange", () => {
|
||||||
|
it("son sahip düşürülemez veya çıkarılamaz", () => {
|
||||||
|
const ctx = { targetRole: "owner" as const, ownerCount: 1 };
|
||||||
|
expect(checkMemberChange({ type: "remove" }, ctx)).toBe("lastOwner");
|
||||||
|
expect(checkMemberChange({ type: "setRole", role: "member" }, ctx)).toBe("lastOwner");
|
||||||
|
expect(checkMemberChange({ type: "setRole", role: "owner" }, ctx)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("birden çok sahip varken biri düşürülebilir; sahip olmayanlar serbest", () => {
|
||||||
|
expect(
|
||||||
|
checkMemberChange({ type: "remove" }, { targetRole: "owner", ownerCount: 2 }),
|
||||||
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
checkMemberChange({ type: "remove" }, { targetRole: "viewer", ownerCount: 1 }),
|
||||||
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
checkMemberChange(
|
||||||
|
{ type: "setRole", role: "owner" },
|
||||||
|
{ targetRole: "member", ownerCount: 1 },
|
||||||
|
),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pickActiveHousehold", () => {
|
||||||
|
const list = [
|
||||||
|
{ id: "a", role: "viewer" as const },
|
||||||
|
{ id: "b", role: "owner" as const },
|
||||||
|
{ id: "c", role: "owner" as const },
|
||||||
|
];
|
||||||
|
it("üyesi olunan tercih edilen haneyi seçer", () => {
|
||||||
|
expect(pickActiveHousehold(list, "a")?.id).toBe("a");
|
||||||
|
});
|
||||||
|
it("tercih yoksa veya uydurmaysa en yüksek rolün olduğu ilk haneye düşer", () => {
|
||||||
|
expect(pickActiveHousehold(list, "x")?.id).toBe("b");
|
||||||
|
expect(pickActiveHousehold(list, undefined)?.id).toBe("b");
|
||||||
|
});
|
||||||
|
it("hiç üyelik yoksa null", () => {
|
||||||
|
expect(pickActiveHousehold([], "a")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import type { HouseholdRole } from "./types";
|
||||||
|
|
||||||
|
/** Hane içi yetki sırası: viewer < member < owner. */
|
||||||
|
const RANK: Record<HouseholdRole, number> = { viewer: 0, member: 1, owner: 2 };
|
||||||
|
|
||||||
|
/** `role`, en az `min` yetkisine sahip mi? */
|
||||||
|
export function hasHouseholdRole(role: HouseholdRole, min: HouseholdRole): boolean {
|
||||||
|
return RANK[role] >= RANK[min];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MemberChange = { type: "setRole"; role: HouseholdRole } | { type: "remove" };
|
||||||
|
|
||||||
|
export type MemberChangeViolation = "lastOwner";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Üyelik değişikliği kuralı: hanenin son sahibi (owner) düşürülemez veya çıkarılamaz.
|
||||||
|
* Böylece her hanenin ayarlarını ve üyelerini yönetebilecek en az bir kişi kalır.
|
||||||
|
*/
|
||||||
|
export function checkMemberChange(
|
||||||
|
change: MemberChange,
|
||||||
|
ctx: { targetRole: HouseholdRole; ownerCount: number },
|
||||||
|
): MemberChangeViolation | null {
|
||||||
|
const removesOwner =
|
||||||
|
ctx.targetRole === "owner" &&
|
||||||
|
(change.type === "remove" || (change.type === "setRole" && change.role !== "owner"));
|
||||||
|
return removesOwner && ctx.ownerCount <= 1 ? "lastOwner" : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aktif hane seçimi: tercih edilen (cookie) hane kullanıcının üyelikleri arasındaysa o;
|
||||||
|
* değilse en yüksek rolün olduğu hane (eşitlikte listedeki ilk). Uydurma veya artık üye
|
||||||
|
* olunmayan bir hane kimliği asla seçilmez.
|
||||||
|
*/
|
||||||
|
export function pickActiveHousehold<T extends { id: string; role: HouseholdRole }>(
|
||||||
|
memberships: T[],
|
||||||
|
preferredId: string | undefined,
|
||||||
|
): T | null {
|
||||||
|
const preferred = memberships.find((m) => m.id === preferredId);
|
||||||
|
if (preferred) return preferred;
|
||||||
|
let best: T | null = null;
|
||||||
|
for (const m of memberships) if (!best || RANK[m.role] > RANK[best.role]) best = m;
|
||||||
|
return best;
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
import mongoose, { Types } from "mongoose";
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
import { getDb, getMongoClient } from "@/lib/db/mongo";
|
||||||
|
import { AuditLogModel } from "@/models/audit-log";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { HouseholdMemberModel } from "@/models/household-member";
|
||||||
|
import { runSeed } from "../../../scripts/seed/run";
|
||||||
|
import {
|
||||||
|
adminCreateHousehold,
|
||||||
|
adminSetMemberRole,
|
||||||
|
getHouseholdDetail,
|
||||||
|
listMemberships,
|
||||||
|
removeAllMembershipsOfUser,
|
||||||
|
removeMember,
|
||||||
|
resolveMembership,
|
||||||
|
setMemberRole,
|
||||||
|
updateHouseholdSettings,
|
||||||
|
} from "./service";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VERİ İZOLASYONU (Bölüm 5): başka hanenin verisine erişim imkânsız olmalı.
|
||||||
|
* Seed verisi: Çakır Ailesi (admin+ayse owner, emre member, zeynep viewer, ozan member),
|
||||||
|
* Annemler (fatma owner, mehmet member, ayse viewer), burak = hanesi olmayan admin.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ids = new Map<string, string>();
|
||||||
|
let cakir = "";
|
||||||
|
let annemler = "";
|
||||||
|
|
||||||
|
const settings = {
|
||||||
|
name: "Çakır Ailesi",
|
||||||
|
budgetMonthStartDay: 15,
|
||||||
|
installmentBudgetMode: "purchase_month" as const,
|
||||||
|
dailyPlanMode: "even" as const,
|
||||||
|
includePrivateAccountsInTotals: false,
|
||||||
|
extraStoreSavingThresholdMinor: 25_000,
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
expect(getDb().databaseName).toBe("butcem_test");
|
||||||
|
await getDb().dropDatabase();
|
||||||
|
await runSeed({ log: () => {} });
|
||||||
|
for (const u of await getDb().collection("user").find().toArray())
|
||||||
|
ids.set(String(u.username), String(u._id));
|
||||||
|
cakir = String((await HouseholdModel.findOne({ name: "Çakır Ailesi" }))!._id);
|
||||||
|
annemler = String((await HouseholdModel.findOne({ name: "Annemler" }))!._id);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await getDb().dropDatabase();
|
||||||
|
await mongoose.disconnect();
|
||||||
|
await getMongoClient().close();
|
||||||
|
});
|
||||||
|
|
||||||
|
const id = (username: string) => ids.get(username)!;
|
||||||
|
|
||||||
|
describe("üyelik çözümleme (izolasyon çekirdeği)", () => {
|
||||||
|
it("üye olmayan kullanıcı başka hanenin üyeliğini çözemez", async () => {
|
||||||
|
expect(await resolveMembership(id("fatma"), cakir)).toBeNull();
|
||||||
|
expect(await resolveMembership(id("emre"), annemler)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rol yetmezse null döner", async () => {
|
||||||
|
expect((await resolveMembership(id("ayse"), annemler, "viewer"))?.role).toBe("viewer");
|
||||||
|
expect(await resolveMembership(id("ayse"), annemler, "member")).toBeNull();
|
||||||
|
expect(await resolveMembership(id("zeynep"), cakir, "member")).toBeNull();
|
||||||
|
expect((await resolveMembership(id("emre"), cakir, "member"))?.role).toBe("member");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hanesi olmayan admin hiçbir haneyi göremez (admin ayrıcalığı yok)", async () => {
|
||||||
|
expect(await listMemberships(id("burak"))).toEqual([]);
|
||||||
|
expect(await resolveMembership(id("burak"), cakir)).toBeNull();
|
||||||
|
expect(await getHouseholdDetail(id("burak"), cakir)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("geçersiz ve uydurma kimlikler reddedilir", async () => {
|
||||||
|
const forged = new Types.ObjectId().toHexString();
|
||||||
|
expect(await resolveMembership(id("ayse"), forged)).toBeNull();
|
||||||
|
expect(await resolveMembership(id("ayse"), "not-an-id")).toBeNull();
|
||||||
|
expect(await resolveMembership(id("ayse"), { $ne: null } as unknown as string)).toBeNull();
|
||||||
|
expect(await resolveMembership("", cakir)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kullanıcı yalnızca kendi hanelerini listeler", async () => {
|
||||||
|
expect((await listMemberships(id("ayse"))).map((m) => [m.name, m.role])).toEqual([
|
||||||
|
["Annemler", "viewer"],
|
||||||
|
["Çakır Ailesi", "owner"],
|
||||||
|
]);
|
||||||
|
expect((await listMemberships(id("fatma"))).map((m) => m.name)).toEqual(["Annemler"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("hane ayrıntısı ve ayarlar", () => {
|
||||||
|
it("başka hanenin ayrıntısı okunamaz", async () => {
|
||||||
|
expect(await getHouseholdDetail(id("fatma"), cakir)).toBeNull();
|
||||||
|
const own = await getHouseholdDetail(id("emre"), cakir);
|
||||||
|
expect(own?.members.map((m) => m.username).sort()).toEqual([
|
||||||
|
"admin",
|
||||||
|
"ayse",
|
||||||
|
"emre",
|
||||||
|
"ozan",
|
||||||
|
"zeynep",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("başka hanenin sahibi, üye ve izleyici ayarları değiştiremez", async () => {
|
||||||
|
for (const u of ["fatma", "emre", "zeynep", "burak"]) {
|
||||||
|
const res = await updateHouseholdSettings(id(u), cakir, settings);
|
||||||
|
expect(res.ok, u).toBe(false);
|
||||||
|
}
|
||||||
|
const h = await HouseholdModel.findById(cakir).lean();
|
||||||
|
expect(h?.settings?.budgetMonthStartDay).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sahip ayarları değiştirir ve denetim kaydı yazılır", async () => {
|
||||||
|
const res = await updateHouseholdSettings(id("ayse"), cakir, settings);
|
||||||
|
expect(res.ok).toBe(true);
|
||||||
|
const h = await HouseholdModel.findById(cakir).lean();
|
||||||
|
expect(h?.settings?.budgetMonthStartDay).toBe(15);
|
||||||
|
const audit = await AuditLogModel.findOne({
|
||||||
|
action: "household.settings.update",
|
||||||
|
householdId: cakir,
|
||||||
|
}).lean();
|
||||||
|
expect(audit?.actorId.toString()).toBe(id("ayse"));
|
||||||
|
expect((audit?.diff as Record<string, unknown>).budgetMonthStartDay).toEqual({
|
||||||
|
from: 1,
|
||||||
|
to: 15,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("üyelik değişiklikleri", () => {
|
||||||
|
it("üye ve izleyici rol değiştiremez, üye çıkaramaz", async () => {
|
||||||
|
expect((await setMemberRole(id("emre"), cakir, id("zeynep"), "owner")).ok).toBe(false);
|
||||||
|
expect((await removeMember(id("zeynep"), cakir, id("emre"))).ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bir hanenin sahibi başka hanedeki üyeliği etkileyemez", async () => {
|
||||||
|
// ayse Çakır'ın sahibi; fatma Çakır üyesi değil → işlem bulunamaz, Annemler'deki rolü değişmez.
|
||||||
|
expect((await setMemberRole(id("ayse"), cakir, id("fatma"), "viewer")).ok).toBe(false);
|
||||||
|
expect((await removeMember(id("ayse"), cakir, id("mehmet"))).ok).toBe(false);
|
||||||
|
// fatma Annemler'in sahibi; Çakır üzerinde yetkisi yok.
|
||||||
|
expect((await setMemberRole(id("fatma"), cakir, id("emre"), "viewer")).ok).toBe(false);
|
||||||
|
const fatma = await HouseholdMemberModel.findOne({
|
||||||
|
householdId: annemler,
|
||||||
|
userId: id("fatma"),
|
||||||
|
}).lean();
|
||||||
|
const mehmet = await HouseholdMemberModel.findOne({
|
||||||
|
householdId: annemler,
|
||||||
|
userId: id("mehmet"),
|
||||||
|
}).lean();
|
||||||
|
const emre = await HouseholdMemberModel.findOne({
|
||||||
|
householdId: cakir,
|
||||||
|
userId: id("emre"),
|
||||||
|
}).lean();
|
||||||
|
expect([fatma?.role, mehmet?.role, emre?.role]).toEqual(["owner", "member", "member"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("son sahip düşürülemez; birden çok sahip varken düşürülebilir", async () => {
|
||||||
|
expect((await adminSetMemberRole(id("admin"), annemler, id("fatma"), "member")).ok).toBe(false);
|
||||||
|
expect((await setMemberRole(id("fatma"), annemler, id("fatma"), "member")).ok).toBe(false);
|
||||||
|
// Çakır'da iki sahip var (admin + ayse).
|
||||||
|
expect((await setMemberRole(id("ayse"), cakir, id("admin"), "member")).ok).toBe(true);
|
||||||
|
// Artık ayse son sahip.
|
||||||
|
expect((await setMemberRole(id("ayse"), cakir, id("ayse"), "member")).ok).toBe(false);
|
||||||
|
expect((await setMemberRole(id("ayse"), cakir, id("admin"), "owner")).ok).toBe(true);
|
||||||
|
expect(
|
||||||
|
await AuditLogModel.countDocuments({ action: "household.member.role", householdId: cakir }),
|
||||||
|
).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sahip üyeyi haneden çıkarır; kullanıcı artık haneyi göremez", async () => {
|
||||||
|
expect((await removeMember(id("ayse"), cakir, id("ozan"))).ok).toBe(true);
|
||||||
|
expect(await resolveMembership(id("ozan"), cakir)).toBeNull();
|
||||||
|
expect(await listMemberships(id("ozan"))).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("admin işlemleri", () => {
|
||||||
|
it("hane + ilk sahip + denetim kaydı tek transaction'da oluşur", async () => {
|
||||||
|
const res = await adminCreateHousehold(id("admin"), {
|
||||||
|
name: "Yazlık",
|
||||||
|
ownerUserId: id("burak"),
|
||||||
|
});
|
||||||
|
expect(res.ok).toBe(true);
|
||||||
|
const hid = res.ok ? res.data.id : "";
|
||||||
|
expect((await resolveMembership(id("burak"), hid, "owner"))?.name).toBe("Yazlık");
|
||||||
|
expect(
|
||||||
|
await AuditLogModel.countDocuments({ action: "household.create", householdId: hid }),
|
||||||
|
).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("var olmayan kullanıcıyla hane oluşturulmaz", async () => {
|
||||||
|
const before = await HouseholdModel.countDocuments();
|
||||||
|
const res = await adminCreateHousehold(id("admin"), {
|
||||||
|
name: "Hayalet",
|
||||||
|
ownerUserId: new Types.ObjectId().toHexString(),
|
||||||
|
});
|
||||||
|
expect(res.ok).toBe(false);
|
||||||
|
expect(await HouseholdModel.countDocuments()).toBe(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("kullanıcı silinince tüm üyelikleri temizlenir", async () => {
|
||||||
|
expect(await removeAllMembershipsOfUser(id("mehmet"))).toBe(1);
|
||||||
|
expect(await listMemberships(id("mehmet"))).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
import { tr } from "@/i18n/tr";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { diffFields, writeAudit } from "@/lib/audit";
|
||||||
|
import { getDb } from "@/lib/db/mongo";
|
||||||
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
|
import { toObjectId } from "@/lib/object-id";
|
||||||
|
import { installDefaultCategories } from "@/features/categories/service";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { HouseholdMemberModel } from "@/models/household-member";
|
||||||
|
import type { HouseholdSettings } from "@/shared/schemas/household";
|
||||||
|
import { compareTr } from "@/shared/search";
|
||||||
|
import { checkMemberChange, hasHouseholdRole, type MemberChange } from "./roles";
|
||||||
|
import type { HouseholdRole, HouseholdSummary } from "./types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hane servisi — framework'ten bağımsız (web Server Action'ları ve ileride /api/v1 aynı
|
||||||
|
* fonksiyonları çağırır). Hane kapsamlı her fonksiyon üyeliği KENDİSİ de doğrular:
|
||||||
|
* çağıran taraf DAL kontrolünü atlasa bile başka hanenin verisine erişilemez.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const t = tr.households;
|
||||||
|
|
||||||
|
export type Membership = { householdId: Types.ObjectId; role: HouseholdRole; name: string };
|
||||||
|
|
||||||
|
export type HouseholdMemberView = {
|
||||||
|
userId: string;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
role: HouseholdRole;
|
||||||
|
banned: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type HouseholdDetail = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
settings: HouseholdSettings;
|
||||||
|
members: HouseholdMemberView[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Kullanıcının üye olduğu (arşivlenmemiş) haneler, ada göre sıralı. */
|
||||||
|
export async function listMemberships(userId: string): Promise<HouseholdSummary[]> {
|
||||||
|
const uid = toObjectId(userId);
|
||||||
|
if (!uid) return [];
|
||||||
|
await connectMongoose();
|
||||||
|
const memberships = await HouseholdMemberModel.find({ userId: uid }).lean();
|
||||||
|
if (!memberships.length) return [];
|
||||||
|
const households = await HouseholdModel.find({
|
||||||
|
_id: { $in: memberships.map((m) => m.householdId) },
|
||||||
|
archivedAt: null,
|
||||||
|
})
|
||||||
|
.select({ name: 1 })
|
||||||
|
.lean();
|
||||||
|
const roleOf = new Map(memberships.map((m) => [String(m.householdId), m.role]));
|
||||||
|
return households
|
||||||
|
.map((h) => ({ id: String(h._id), name: h.name, role: roleOf.get(String(h._id))! }))
|
||||||
|
.sort((a, b) => compareTr(a.name, b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VERİ İZOLASYONUNUN ÇEKİRDEĞİ: kullanıcı bu hanenin en az `minRole` yetkili üyesi mi?
|
||||||
|
* Değilse null. Geçersiz/uydurma kimlikler de null döner.
|
||||||
|
*/
|
||||||
|
export async function resolveMembership(
|
||||||
|
userId: string,
|
||||||
|
householdId: string,
|
||||||
|
minRole: HouseholdRole = "viewer",
|
||||||
|
): Promise<Membership | null> {
|
||||||
|
const uid = toObjectId(userId);
|
||||||
|
const hid = toObjectId(householdId);
|
||||||
|
if (!uid || !hid) return null;
|
||||||
|
await connectMongoose();
|
||||||
|
const member = await HouseholdMemberModel.findOne({ userId: uid, householdId: hid }).lean();
|
||||||
|
if (!member || !hasHouseholdRole(member.role, minRole)) return null;
|
||||||
|
const household = await HouseholdModel.findOne({ _id: hid, archivedAt: null })
|
||||||
|
.select({ name: 1 })
|
||||||
|
.lean();
|
||||||
|
if (!household) return null;
|
||||||
|
return { householdId: hid, role: member.role, name: household.name };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function memberViews(householdId: Types.ObjectId): Promise<HouseholdMemberView[]> {
|
||||||
|
const members = await HouseholdMemberModel.find({ householdId }).lean();
|
||||||
|
const users = await getDb()
|
||||||
|
.collection("user")
|
||||||
|
.find(
|
||||||
|
{ _id: { $in: members.map((m) => m.userId) } },
|
||||||
|
{ projection: { name: 1, username: 1, banned: 1 } },
|
||||||
|
)
|
||||||
|
.toArray();
|
||||||
|
const byId = new Map(users.map((u) => [String(u._id), u]));
|
||||||
|
return members
|
||||||
|
.map((m) => {
|
||||||
|
const u = byId.get(String(m.userId));
|
||||||
|
return {
|
||||||
|
userId: String(m.userId),
|
||||||
|
name: (u?.name as string | undefined) ?? "—",
|
||||||
|
username: (u?.username as string | undefined) ?? "",
|
||||||
|
role: m.role,
|
||||||
|
banned: Boolean(u?.banned),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => compareTr(a.name, b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSettings(h: {
|
||||||
|
name: string;
|
||||||
|
settings?: Partial<HouseholdSettings> | null;
|
||||||
|
}): HouseholdSettings {
|
||||||
|
const s = h.settings ?? {};
|
||||||
|
return {
|
||||||
|
name: h.name,
|
||||||
|
budgetMonthStartDay: s.budgetMonthStartDay ?? 1,
|
||||||
|
installmentBudgetMode: s.installmentBudgetMode ?? "per_installment",
|
||||||
|
dailyPlanMode: s.dailyPlanMode ?? "even",
|
||||||
|
includePrivateAccountsInTotals: s.includePrivateAccountsInTotals ?? true,
|
||||||
|
extraStoreSavingThresholdMinor: s.extraStoreSavingThresholdMinor ?? 10_000,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Üye için hane ayrıntısı (ayarlar + üyeler). Üye değilse null. */
|
||||||
|
export async function getHouseholdDetail(
|
||||||
|
userId: string,
|
||||||
|
householdId: string,
|
||||||
|
): Promise<HouseholdDetail | null> {
|
||||||
|
const membership = await resolveMembership(userId, householdId, "viewer");
|
||||||
|
if (!membership) return null;
|
||||||
|
const household = await HouseholdModel.findById(membership.householdId).lean();
|
||||||
|
if (!household) return null;
|
||||||
|
return {
|
||||||
|
id: String(household._id),
|
||||||
|
name: household.name,
|
||||||
|
settings: toSettings(household),
|
||||||
|
members: await memberViews(membership.householdId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: hane adı ve ayarları. */
|
||||||
|
export async function updateHouseholdSettings(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
input: HouseholdSettings,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const membership = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!membership) return fail(tr.common.unauthorized);
|
||||||
|
const before = await HouseholdModel.findById(membership.householdId).lean();
|
||||||
|
if (!before) return fail(tr.common.notFound);
|
||||||
|
|
||||||
|
const { name, ...settings } = input;
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
await HouseholdModel.updateOne(
|
||||||
|
{ _id: membership.householdId },
|
||||||
|
{ $set: { name, settings, updatedBy: actor } },
|
||||||
|
);
|
||||||
|
await writeAudit({
|
||||||
|
action: "household.settings.update",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: membership.householdId,
|
||||||
|
targetType: "household",
|
||||||
|
targetId: String(membership.householdId),
|
||||||
|
diff: diffFields(toSettings(before), input),
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ortak üyelik değişikliği (owner yolu ve admin yolu aynı kuralı uygular). */
|
||||||
|
async function applyMemberChange(
|
||||||
|
actor: Types.ObjectId,
|
||||||
|
householdId: Types.ObjectId,
|
||||||
|
targetUserId: string,
|
||||||
|
change: MemberChange,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const target = toObjectId(targetUserId);
|
||||||
|
if (!target) return fail(tr.common.notFound);
|
||||||
|
const member = await HouseholdMemberModel.findOne({ householdId, userId: target }).lean();
|
||||||
|
if (!member) return fail(tr.common.notFound);
|
||||||
|
if (change.type === "setRole" && change.role === member.role) return ok(undefined);
|
||||||
|
|
||||||
|
const ownerCount = await HouseholdMemberModel.countDocuments({ householdId, role: "owner" });
|
||||||
|
if (checkMemberChange(change, { targetRole: member.role, ownerCount })) return fail(t.lastOwner);
|
||||||
|
|
||||||
|
if (change.type === "remove") {
|
||||||
|
await HouseholdMemberModel.deleteOne({ _id: member._id });
|
||||||
|
} else {
|
||||||
|
await HouseholdMemberModel.updateOne(
|
||||||
|
{ _id: member._id },
|
||||||
|
{ $set: { role: change.role, updatedBy: actor } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await writeAudit({
|
||||||
|
action: change.type === "remove" ? "household.member.remove" : "household.member.role",
|
||||||
|
actorId: actor,
|
||||||
|
householdId,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: targetUserId,
|
||||||
|
diff:
|
||||||
|
change.type === "remove"
|
||||||
|
? { role: { from: member.role, to: null } }
|
||||||
|
: { role: { from: member.role, to: change.role } },
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: üyenin hane içi rolünü değiştirir. */
|
||||||
|
export async function setMemberRole(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
targetUserId: string,
|
||||||
|
role: HouseholdRole,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const membership = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!membership) return fail(tr.common.unauthorized);
|
||||||
|
return applyMemberChange(new Types.ObjectId(actorId), membership.householdId, targetUserId, {
|
||||||
|
type: "setRole",
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Owner: üyeyi haneden çıkarır. */
|
||||||
|
export async function removeMember(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
targetUserId: string,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const membership = await resolveMembership(actorId, householdId, "owner");
|
||||||
|
if (!membership) return fail(tr.common.unauthorized);
|
||||||
|
return applyMemberChange(new Types.ObjectId(actorId), membership.householdId, targetUserId, {
|
||||||
|
type: "remove",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Sistem admini (yönetim) — çağıran Server Action admin rolünü doğrular. ---
|
||||||
|
// Admin haneleri ve üyelikleri yönetir; hanenin finansal verisini GÖRMEZ (Faz 0 kararı).
|
||||||
|
|
||||||
|
export type AdminHouseholdRow = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
memberCount: number;
|
||||||
|
owners: string[];
|
||||||
|
members: HouseholdMemberView[];
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function adminListHouseholds(): Promise<AdminHouseholdRow[]> {
|
||||||
|
await connectMongoose();
|
||||||
|
const households = await HouseholdModel.find({ archivedAt: null }).sort({ name: 1 }).lean();
|
||||||
|
const rows = await Promise.all(
|
||||||
|
households.map(async (h) => {
|
||||||
|
const members = await memberViews(h._id);
|
||||||
|
return {
|
||||||
|
id: String(h._id),
|
||||||
|
name: h.name,
|
||||||
|
memberCount: members.length,
|
||||||
|
owners: members.filter((m) => m.role === "owner").map((m) => m.name),
|
||||||
|
members,
|
||||||
|
createdAt: new Date(h.createdAt).toISOString(),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return rows.sort((a, b) => compareTr(a.name, b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserOption = { id: string; name: string; username: string; banned: boolean };
|
||||||
|
|
||||||
|
export async function adminListUserOptions(): Promise<UserOption[]> {
|
||||||
|
const users = await getDb()
|
||||||
|
.collection("user")
|
||||||
|
.find({}, { projection: { name: 1, username: 1, banned: 1 } })
|
||||||
|
.toArray();
|
||||||
|
return users
|
||||||
|
.map((u) => ({
|
||||||
|
id: String(u._id),
|
||||||
|
name: String(u.name ?? ""),
|
||||||
|
username: String(u.username ?? ""),
|
||||||
|
banned: Boolean(u.banned),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => compareTr(a.name, b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Admin: hane + ilk sahip üyeliği tek transaction'da. */
|
||||||
|
export async function adminCreateHousehold(
|
||||||
|
actorId: string,
|
||||||
|
input: { name: string; ownerUserId: string },
|
||||||
|
): Promise<ActionResult<{ id: string }>> {
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
const owner = toObjectId(input.ownerUserId);
|
||||||
|
if (!owner) return fail(tr.validation.selectUser);
|
||||||
|
const ownerExists = await getDb().collection("user").countDocuments({ _id: owner }, { limit: 1 });
|
||||||
|
if (!ownerExists) return fail(tr.validation.selectUser);
|
||||||
|
|
||||||
|
const mongoose = await connectMongoose();
|
||||||
|
let createdId = "";
|
||||||
|
await mongoose.connection.transaction(async (session) => {
|
||||||
|
const [household] = await HouseholdModel.create(
|
||||||
|
[{ name: input.name, createdBy: actor, updatedBy: actor }],
|
||||||
|
{
|
||||||
|
session,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
createdId = String(household!._id);
|
||||||
|
await HouseholdMemberModel.create(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
householdId: household!._id,
|
||||||
|
userId: owner,
|
||||||
|
role: "owner",
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
await writeAudit(
|
||||||
|
{
|
||||||
|
action: "household.create",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: household!._id,
|
||||||
|
targetType: "household",
|
||||||
|
targetId: createdId,
|
||||||
|
diff: { name: input.name, ownerUserId: input.ownerUserId },
|
||||||
|
},
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
// Varsayılan Türkçe kategori seti aynı transaction'da (Bölüm 6.2).
|
||||||
|
await installDefaultCategories(household!._id, actor, session);
|
||||||
|
});
|
||||||
|
return ok({ id: createdId });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Admin: kullanıcıyı haneye ekler (zaten üyeyse rolünü günceller). */
|
||||||
|
export async function adminAddMember(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
input: { userId: string; role: HouseholdRole },
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const actor = new Types.ObjectId(actorId);
|
||||||
|
const hid = toObjectId(householdId);
|
||||||
|
const uid = toObjectId(input.userId);
|
||||||
|
if (!hid || !uid) return fail(tr.common.notFound);
|
||||||
|
await connectMongoose();
|
||||||
|
const household = await HouseholdModel.exists({ _id: hid, archivedAt: null });
|
||||||
|
const user = await getDb().collection("user").countDocuments({ _id: uid }, { limit: 1 });
|
||||||
|
if (!household || !user) return fail(tr.common.notFound);
|
||||||
|
|
||||||
|
const existing = await HouseholdMemberModel.findOne({ householdId: hid, userId: uid }).lean();
|
||||||
|
if (existing)
|
||||||
|
return applyMemberChange(actor, hid, input.userId, { type: "setRole", role: input.role });
|
||||||
|
|
||||||
|
await HouseholdMemberModel.create({
|
||||||
|
householdId: hid,
|
||||||
|
userId: uid,
|
||||||
|
role: input.role,
|
||||||
|
createdBy: actor,
|
||||||
|
updatedBy: actor,
|
||||||
|
});
|
||||||
|
await writeAudit({
|
||||||
|
action: "household.member.add",
|
||||||
|
actorId: actor,
|
||||||
|
householdId: hid,
|
||||||
|
targetType: "user",
|
||||||
|
targetId: input.userId,
|
||||||
|
diff: { role: { from: null, to: input.role } },
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminSetMemberRole(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
targetUserId: string,
|
||||||
|
role: HouseholdRole,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const hid = toObjectId(householdId);
|
||||||
|
if (!hid) return fail(tr.common.notFound);
|
||||||
|
await connectMongoose();
|
||||||
|
return applyMemberChange(new Types.ObjectId(actorId), hid, targetUserId, {
|
||||||
|
type: "setRole",
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminRemoveMember(
|
||||||
|
actorId: string,
|
||||||
|
householdId: string,
|
||||||
|
targetUserId: string,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
const hid = toObjectId(householdId);
|
||||||
|
if (!hid) return fail(tr.common.notFound);
|
||||||
|
await connectMongoose();
|
||||||
|
return applyMemberChange(new Types.ObjectId(actorId), hid, targetUserId, { type: "remove" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kullanıcı silindiğinde tüm üyeliklerini temizler (admin kullanıcı silme akışı). */
|
||||||
|
export async function removeAllMembershipsOfUser(userId: string): Promise<number> {
|
||||||
|
const uid = toObjectId(userId);
|
||||||
|
if (!uid) return 0;
|
||||||
|
await connectMongoose();
|
||||||
|
const res = await HouseholdMemberModel.deleteMany({ userId: uid });
|
||||||
|
return res.deletedCount;
|
||||||
|
}
|
||||||
+245
@@ -34,6 +34,21 @@ export const tr = {
|
|||||||
unauthorized: "Bu işlem için yetkiniz yok.",
|
unauthorized: "Bu işlem için yetkiniz yok.",
|
||||||
notFound: "Kayıt bulunamadı.",
|
notFound: "Kayıt bulunamadı.",
|
||||||
},
|
},
|
||||||
|
swatches: {
|
||||||
|
blue: "Mavi",
|
||||||
|
sky: "Gök mavisi",
|
||||||
|
teal: "Turkuaz",
|
||||||
|
green: "Yeşil",
|
||||||
|
lime: "Fıstık yeşili",
|
||||||
|
amber: "Kehribar",
|
||||||
|
orange: "Turuncu",
|
||||||
|
red: "Kırmızı",
|
||||||
|
rose: "Gül",
|
||||||
|
pink: "Pembe",
|
||||||
|
purple: "Mor",
|
||||||
|
indigo: "Çivit",
|
||||||
|
slate: "Gri",
|
||||||
|
},
|
||||||
theme: {
|
theme: {
|
||||||
label: "Tema",
|
label: "Tema",
|
||||||
light: "Açık",
|
light: "Açık",
|
||||||
@@ -45,6 +60,7 @@ export const tr = {
|
|||||||
dashboard: "Ana sayfa",
|
dashboard: "Ana sayfa",
|
||||||
transactions: "İşlemler",
|
transactions: "İşlemler",
|
||||||
accounts: "Hesaplar",
|
accounts: "Hesaplar",
|
||||||
|
categories: "Kategoriler",
|
||||||
budget: "Bütçe",
|
budget: "Bütçe",
|
||||||
planned: "Planlı işlemler",
|
planned: "Planlı işlemler",
|
||||||
contacts: "Cari hesaplar",
|
contacts: "Cari hesaplar",
|
||||||
@@ -63,6 +79,224 @@ export const tr = {
|
|||||||
label: "Aktif hane",
|
label: "Aktif hane",
|
||||||
select: "Hane seçin",
|
select: "Hane seçin",
|
||||||
roles: { owner: "Sahip", member: "Üye", viewer: "İzleyici" },
|
roles: { owner: "Sahip", member: "Üye", viewer: "İzleyici" },
|
||||||
|
roleHints: {
|
||||||
|
owner: "Hane ayarları, üyeler ve hesaplar",
|
||||||
|
member: "İşlem girer, liste ve stok günceller",
|
||||||
|
viewer: "Yalnızca görüntüler",
|
||||||
|
},
|
||||||
|
switched: (name: string) => `Aktif hane: ${name}`,
|
||||||
|
},
|
||||||
|
households: {
|
||||||
|
lastOwner: "Hanenin son sahibi düşürülemez veya çıkarılamaz.",
|
||||||
|
noHousehold: {
|
||||||
|
title: "Henüz bir haneye üye değilsiniz",
|
||||||
|
description:
|
||||||
|
"Bütçe ve diğer verileri görmek için bir haneye üye olmanız gerekir. Yöneticiden sizi bir haneye eklemesini isteyin.",
|
||||||
|
adminHint:
|
||||||
|
"Yönetici olarak Yönetim › Haneler sayfasından hane oluşturabilir ve üye ekleyebilirsiniz.",
|
||||||
|
adminLink: "Hanelere git",
|
||||||
|
},
|
||||||
|
viewerReadOnly: "İzleyici rolündesiniz; bu hanede değişiklik yapamazsınız.",
|
||||||
|
},
|
||||||
|
settings: {
|
||||||
|
title: "Ayarlar",
|
||||||
|
description: "Aktif hanenin ayarları ve üyeleri.",
|
||||||
|
household: "Hane",
|
||||||
|
householdDescription: "Bütçe ve planlama tercihleri tüm hane için geçerlidir.",
|
||||||
|
ownerOnly: "Bu ayarları yalnızca hane sahipleri değiştirebilir.",
|
||||||
|
fields: {
|
||||||
|
name: "Hane adı",
|
||||||
|
budgetMonthStartDay: "Bütçe ayı başlangıç günü",
|
||||||
|
budgetMonthStartDayHint:
|
||||||
|
"1 = takvim ayı. Örneğin 15 seçilirse bütçe ayı her ayın 15. günü başlar.",
|
||||||
|
installmentBudgetMode: "Taksitlerin bütçeye etkisi",
|
||||||
|
installmentModes: {
|
||||||
|
per_installment: "Her taksit kendi ayına",
|
||||||
|
purchase_month: "Tamamı harcama ayına",
|
||||||
|
},
|
||||||
|
dailyPlanMode: "Günlük plan dağıtımı",
|
||||||
|
dailyPlanModes: {
|
||||||
|
even: "Değişken bütçe günlere eşit",
|
||||||
|
previous_month_pattern: "Önceki ayın harcama örüntüsüne göre",
|
||||||
|
},
|
||||||
|
includePrivateAccountsInTotals: "“Yalnızca ben” hesapları hane toplamlarına dahil edilsin",
|
||||||
|
extraStoreSavingThreshold: "Ek mağaza tasarruf eşiği (TL)",
|
||||||
|
extraStoreSavingThresholdHint:
|
||||||
|
"Alışveriş planlayıcı, ek bir mağazayı yalnızca tasarruf bu tutarı aşarsa önerir.",
|
||||||
|
},
|
||||||
|
saved: "Hane ayarları kaydedildi.",
|
||||||
|
members: "Üyeler",
|
||||||
|
membersDescription: "Hane içi roller. Yeni üyeyi yönetici ekler.",
|
||||||
|
memberActions: (name: string) => `${name} — işlemler`,
|
||||||
|
changeRole: "Rolü değiştir",
|
||||||
|
removeMember: "Haneden çıkar",
|
||||||
|
removeTitle: "Üye haneden çıkarılsın mı?",
|
||||||
|
removeDescription: (name: string, household: string) =>
|
||||||
|
`${name}, “${household}” hanesine artık erişemeyecek. Kullanıcı hesabı silinmez.`,
|
||||||
|
removeConfirm: "Haneden çıkar",
|
||||||
|
roleChanged: (name: string) => `${name} için rol güncellendi.`,
|
||||||
|
memberRemoved: (name: string) => `${name} haneden çıkarıldı.`,
|
||||||
|
banned: "Askıda",
|
||||||
|
},
|
||||||
|
accounts: {
|
||||||
|
title: "Hesaplar",
|
||||||
|
description: "Nakit, banka, birikim, kredi kartı ve yemek kartı hesapları.",
|
||||||
|
newAccount: "Yeni hesap",
|
||||||
|
createTitle: "Yeni hesap",
|
||||||
|
editTitle: "Hesabı düzenle",
|
||||||
|
formDescription: "Güncel bakiye işlemlerden hesaplanır; açılış bakiyesi başlangıç noktasıdır.",
|
||||||
|
types: {
|
||||||
|
cash: "Nakit",
|
||||||
|
bank: "Vadesiz banka",
|
||||||
|
savings: "Birikim / vadeli",
|
||||||
|
credit_card: "Kredi kartı",
|
||||||
|
meal_card: "Yemek kartı",
|
||||||
|
},
|
||||||
|
typeGroups: {
|
||||||
|
cash: "Nakit",
|
||||||
|
bank: "Banka hesapları",
|
||||||
|
savings: "Birikim hesapları",
|
||||||
|
credit_card: "Kredi kartları",
|
||||||
|
meal_card: "Yemek kartları",
|
||||||
|
},
|
||||||
|
providers: {
|
||||||
|
pluxee: "Pluxee (Sodexo)",
|
||||||
|
multinet: "Multinet",
|
||||||
|
edenred: "Edenred (Ticket)",
|
||||||
|
setcard: "Setcard",
|
||||||
|
metropol: "Metropol",
|
||||||
|
other: "Diğer",
|
||||||
|
},
|
||||||
|
fields: {
|
||||||
|
name: "Hesap adı",
|
||||||
|
type: "Tür",
|
||||||
|
typeLockedHint: "Hesap türü oluşturulduktan sonra değiştirilemez.",
|
||||||
|
institution: "Banka / kurum",
|
||||||
|
institutionPlaceholder: "ör. Ziraat Bankası",
|
||||||
|
provider: "Kart sağlayıcısı",
|
||||||
|
openingBalance: "Açılış bakiyesi (TL)",
|
||||||
|
openingDebt: "Açılış borcu (TL)",
|
||||||
|
openingBalanceHint: "Banka hesabı KMH kullanıyorsa eksi girilebilir (ör. -2.500,00).",
|
||||||
|
openingDebtHint: "Karttaki mevcut toplam borç; pozitif girin.",
|
||||||
|
openingDate: "Açılış tarihi",
|
||||||
|
owner: "Hesap sahibi",
|
||||||
|
ownerNone: "— Ortak hesap —",
|
||||||
|
isPrivate: "Yalnızca ben (bakiyeyi yalnızca hesap sahibi görür)",
|
||||||
|
appearance: "Görünüm",
|
||||||
|
advanced: "Gelişmiş ayarlar",
|
||||||
|
overdraft: "Esnek hesap (KMH)",
|
||||||
|
overdraftEnabled: "Bu hesapta KMH var",
|
||||||
|
overdraftLimit: "KMH limiti (TL)",
|
||||||
|
overdraftRate: "Aylık faiz oranı (%)",
|
||||||
|
overdraftStatementDay: "Hesap kesim günü",
|
||||||
|
card: "Kart bilgileri",
|
||||||
|
cardLimit: "Kart limiti (TL)",
|
||||||
|
cardStatementDay: "Hesap kesim günü",
|
||||||
|
cardStatementDayHint: "Ayda o gün yoksa (ör. 31) ayın son günü kullanılır.",
|
||||||
|
cardDueKind: "Son ödeme günü",
|
||||||
|
dueKinds: { daysAfter: "Kesimden N gün sonra", fixedDay: "Ayın sabit günü" },
|
||||||
|
cardDueValueDays: "Gün sayısı",
|
||||||
|
cardDueValueDay: "Ayın günü",
|
||||||
|
cardPaymentAccount: "Ödeme hesabı",
|
||||||
|
cardPaymentAccountNone: "— Seçilmedi —",
|
||||||
|
},
|
||||||
|
summary: {
|
||||||
|
assets: "Varlıklar",
|
||||||
|
cardDebt: "Kart borçları",
|
||||||
|
net: "Net",
|
||||||
|
includesHidden: "Toplamlara gizli hesaplar dahil.",
|
||||||
|
excludesHidden: "Gizli hesaplar toplamlara dahil değil (hane ayarı).",
|
||||||
|
},
|
||||||
|
balance: "Bakiye",
|
||||||
|
debt: "Borç",
|
||||||
|
hidden: "Gizli",
|
||||||
|
hiddenHint: "Bu hesap “yalnızca ben” olarak işaretli; bakiyeyi yalnızca hesap sahibi görür.",
|
||||||
|
privateBadge: "Yalnızca ben",
|
||||||
|
overdraftBadge: (limit: string) => `KMH ${limit}`,
|
||||||
|
limitLabel: (limit: string) => `Limit ${limit}`,
|
||||||
|
statementLabel: (day: number) => `Kesim: ${day}`,
|
||||||
|
empty: "Henüz hesap yok.",
|
||||||
|
emptyOwnerHint: "Başlamak için ilk hesabınızı ekleyin (ör. nakit cüzdan, maaş hesabı).",
|
||||||
|
archivedSection: (n: number) => `Arşivlenmiş hesaplar (${n})`,
|
||||||
|
archive: "Arşivle",
|
||||||
|
unarchive: "Arşivden çıkar",
|
||||||
|
archiveTitle: "Hesap arşivlensin mi?",
|
||||||
|
archiveDescription: (name: string) =>
|
||||||
|
`“${name}” yeni işlemlerde seçilemez; geçmiş işlemler ve raporlar korunur. İstediğiniz zaman arşivden çıkarabilirsiniz.`,
|
||||||
|
created: (name: string) => `${name} oluşturuldu.`,
|
||||||
|
updated: (name: string) => `${name} güncellendi.`,
|
||||||
|
archivedToast: (name: string) => `${name} arşivlendi.`,
|
||||||
|
unarchivedToast: (name: string) => `${name} arşivden çıkarıldı.`,
|
||||||
|
ownerNotMember: "Hesap sahibi bu hanenin üyesi olmalı.",
|
||||||
|
invalidPaymentAccount:
|
||||||
|
"Ödeme hesabı bu hanedeki aktif bir banka, nakit veya birikim hesabı olmalı.",
|
||||||
|
typeLocked: "Hesap türü değiştirilemez.",
|
||||||
|
ownerOnly: "Hesapları yalnızca hane sahipleri yönetebilir.",
|
||||||
|
},
|
||||||
|
categories: {
|
||||||
|
title: "Kategoriler",
|
||||||
|
description: "Gelir ve gider kategorileri. Alt kategoriler raporlarda üst kategoriye toplanır.",
|
||||||
|
expense: "Gider",
|
||||||
|
income: "Gelir",
|
||||||
|
newCategory: "Yeni kategori",
|
||||||
|
addChild: "Alt kategori ekle",
|
||||||
|
edit: "Düzenle",
|
||||||
|
moveUp: "Yukarı taşı",
|
||||||
|
moveDown: "Aşağı taşı",
|
||||||
|
archive: "Arşivle",
|
||||||
|
unarchive: "Arşivden çıkar",
|
||||||
|
showArchived: "Arşivi göster",
|
||||||
|
archived: "Arşivli",
|
||||||
|
defaultBadge: "Varsayılan",
|
||||||
|
empty: "Bu türde kategori yok.",
|
||||||
|
createTitle: "Yeni kategori",
|
||||||
|
editTitle: "Kategoriyi düzenle",
|
||||||
|
formDescription: "Alt kategori için bir üst kategori seçin; boş bırakılırsa ana kategori olur.",
|
||||||
|
name: "Ad",
|
||||||
|
parent: "Üst kategori",
|
||||||
|
noParent: "— Ana kategori —",
|
||||||
|
icon: "İkon",
|
||||||
|
color: "Renk",
|
||||||
|
created: (name: string) => `${name} oluşturuldu.`,
|
||||||
|
updated: (name: string) => `${name} güncellendi.`,
|
||||||
|
archivedToast: (name: string) => `${name} arşivlendi.`,
|
||||||
|
unarchivedToast: (name: string) => `${name} arşivden çıkarıldı.`,
|
||||||
|
archiveTitle: "Kategori arşivlensin mi?",
|
||||||
|
archiveDescription: (name: string) =>
|
||||||
|
`“${name}” ve alt kategorileri yeni işlemlerde seçilemez. Geçmiş işlemler ve raporlar etkilenmez.`,
|
||||||
|
duplicate: "Bu düzeyde aynı adlı bir kategori zaten var.",
|
||||||
|
violations: {
|
||||||
|
self: "Kategori kendi altına taşınamaz.",
|
||||||
|
descendant: "Kategori kendi alt kategorisinin altına taşınamaz.",
|
||||||
|
kind: "Gelir ve gider kategorileri birbirinin altına konamaz.",
|
||||||
|
depth: "En fazla 5 seviye derinliğe izin verilir.",
|
||||||
|
parentNotFound: "Üst kategori bulunamadı.",
|
||||||
|
parentArchived: "Üst kategori arşivli; önce onu arşivden çıkarın.",
|
||||||
|
},
|
||||||
|
readOnly: "İzleyici rolündesiniz; kategorileri değiştiremezsiniz.",
|
||||||
|
},
|
||||||
|
adminHouseholds: {
|
||||||
|
title: "Haneler",
|
||||||
|
description: "Hane oluşturma, kullanıcıları haneye atama ve hane içi roller.",
|
||||||
|
newHousehold: "Yeni hane",
|
||||||
|
createTitle: "Yeni hane",
|
||||||
|
createDescription: "Hane oluşturulur ve seçilen kullanıcı ilk sahibi olur.",
|
||||||
|
name: "Hane adı",
|
||||||
|
owner: "İlk sahip",
|
||||||
|
selectUser: "Kullanıcı seçin",
|
||||||
|
created: (name: string) => `${name} hanesi oluşturuldu.`,
|
||||||
|
members: (n: number) => `${n} üye`,
|
||||||
|
owners: "Sahipler",
|
||||||
|
noOwner: "Sahibi yok",
|
||||||
|
addMember: "Üye ekle",
|
||||||
|
addMemberTitle: (household: string) => `${household} — üye ekle`,
|
||||||
|
addMemberDescription: "Kullanıcı zaten üyeyse rolü güncellenir.",
|
||||||
|
user: "Kullanıcı",
|
||||||
|
role: "Hane içi rol",
|
||||||
|
memberAdded: (name: string) => `${name} haneye eklendi.`,
|
||||||
|
empty: "Henüz hane yok.",
|
||||||
|
privacyNote:
|
||||||
|
"Yöneticiler haneleri ve üyelikleri yönetir; üyesi olmadıkları hanenin finansal verisini göremez.",
|
||||||
},
|
},
|
||||||
userMenu: {
|
userMenu: {
|
||||||
open: "Kullanıcı menüsü",
|
open: "Kullanıcı menüsü",
|
||||||
@@ -196,6 +430,17 @@ export const tr = {
|
|||||||
passwordMin: "Şifre en az 8 karakter olmalı",
|
passwordMin: "Şifre en az 8 karakter olmalı",
|
||||||
passwordMax: "Şifre en fazla 128 karakter olabilir",
|
passwordMax: "Şifre en fazla 128 karakter olabilir",
|
||||||
banReasonMax: "Neden en fazla 200 karakter olabilir",
|
banReasonMax: "Neden en fazla 200 karakter olabilir",
|
||||||
|
householdNameMin: "Hane adı en az 2 karakter olmalı",
|
||||||
|
householdNameMax: "Hane adı en fazla 80 karakter olabilir",
|
||||||
|
selectUser: "Bir kullanıcı seçin",
|
||||||
|
wholeNumber: "Tam sayı girin",
|
||||||
|
money: "Geçerli bir tutar girin (ör. 1.250,50)",
|
||||||
|
moneyNonNegative: "Tutar negatif olamaz",
|
||||||
|
percent: "0 ile 100 arasında bir oran girin (ör. 4,25)",
|
||||||
|
date: "Geçerli bir tarih seçin",
|
||||||
|
selectProvider: "Kart sağlayıcısını seçin",
|
||||||
|
privateNeedsOwner: "“Yalnızca ben” hesabı için hesap sahibini seçin",
|
||||||
|
dueDays: "Kesimden sonra en fazla 30 gün olabilir",
|
||||||
},
|
},
|
||||||
errors: {
|
errors: {
|
||||||
notFoundTitle: "Sayfa bulunamadı",
|
notFoundTitle: "Sayfa bulunamadı",
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { env } from "@/lib/env";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aktif hane seçimi cookie'de tutulur. Cookie yalnızca bir TERCİHtir: DAL her istekte
|
||||||
|
* kullanıcının gerçekten o hanenin üyesi olduğunu doğrular; değilse ilk haneye düşer.
|
||||||
|
*/
|
||||||
|
export const ACTIVE_HOUSEHOLD_COOKIE = "butcem.hh";
|
||||||
|
|
||||||
|
export async function readActiveHouseholdId(): Promise<string | undefined> {
|
||||||
|
return (await cookies()).get(ACTIVE_HOUSEHOLD_COOKIE)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Yalnızca Server Action / Route Handler içinde çağrılabilir. */
|
||||||
|
export async function writeActiveHouseholdId(householdId: string): Promise<void> {
|
||||||
|
(await cookies()).set(ACTIVE_HOUSEHOLD_COOKIE, householdId, {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: "lax",
|
||||||
|
secure: env().NODE_ENV === "production",
|
||||||
|
path: "/",
|
||||||
|
maxAge: 60 * 60 * 24 * 365,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { diffFields } from "./audit";
|
||||||
|
|
||||||
|
describe("diffFields", () => {
|
||||||
|
it("yalnızca değişen alanları döner", () => {
|
||||||
|
expect(diffFields({ a: 1, b: "x", c: true }, { a: 2, b: "x" })).toEqual({
|
||||||
|
a: { from: 1, to: 2 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("iç içe değerleri içerik olarak karşılaştırır", () => {
|
||||||
|
expect(diffFields({ s: { d: 1 } }, { s: { d: 1 } })).toEqual({});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import "server-only";
|
||||||
|
import type { ClientSession, Types } from "mongoose";
|
||||||
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
|
import { AuditLogModel, type AuditAction } from "@/models/audit-log";
|
||||||
|
|
||||||
|
export type AuditEntry = {
|
||||||
|
action: AuditAction;
|
||||||
|
actorId: Types.ObjectId | string;
|
||||||
|
householdId?: Types.ObjectId | null;
|
||||||
|
targetType: string;
|
||||||
|
targetId: string;
|
||||||
|
diff?: Record<string, unknown> | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Önce/sonra nesnelerinden yalnızca değişen alanları çıkarır: { alan: { from, to } }. */
|
||||||
|
export function diffFields<T extends Record<string, unknown>>(before: T, after: Partial<T>) {
|
||||||
|
const out: Record<string, { from: unknown; to: unknown }> = {};
|
||||||
|
for (const [key, to] of Object.entries(after)) {
|
||||||
|
const from = before[key];
|
||||||
|
if (JSON.stringify(from) !== JSON.stringify(to)) out[key] = { from, to };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Denetim kaydı yazar. `session` verilirse transaction'ın parçası olur (işlem geri alınırsa
|
||||||
|
* kayıt da geri alınır). Session yoksa hata asıl işlemi bozmaz; sunucuda loglanır.
|
||||||
|
*/
|
||||||
|
export async function writeAudit(entry: AuditEntry, session?: ClientSession): Promise<void> {
|
||||||
|
const doc = { ...entry, householdId: entry.householdId ?? null, diff: entry.diff ?? null };
|
||||||
|
if (session) {
|
||||||
|
await AuditLogModel.create([doc], { session });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await connectMongoose();
|
||||||
|
await AuditLogModel.create(doc);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[audit] kayıt yazılamadı", entry.action, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,10 @@ import { headers } from "next/headers";
|
|||||||
import { notFound, redirect } from "next/navigation";
|
import { notFound, redirect } from "next/navigation";
|
||||||
import { cache } from "react";
|
import { cache } from "react";
|
||||||
import type { SessionUser } from "@/features/auth/types";
|
import type { SessionUser } from "@/features/auth/types";
|
||||||
|
import { hasHouseholdRole, pickActiveHousehold } from "@/features/households/roles";
|
||||||
|
import { listMemberships, resolveMembership, type Membership } from "@/features/households/service";
|
||||||
|
import type { HouseholdRole, HouseholdSummary } from "@/features/households/types";
|
||||||
|
import { readActiveHouseholdId } from "@/lib/active-household";
|
||||||
import { getAuth } from "@/lib/auth";
|
import { getAuth } from "@/lib/auth";
|
||||||
import { visibleEmail } from "@/shared/account-email";
|
import { visibleEmail } from "@/shared/account-email";
|
||||||
import type { SystemRole } from "@/shared/schemas/common";
|
import type { SystemRole } from "@/shared/schemas/common";
|
||||||
@@ -66,3 +70,67 @@ export async function getActionUser(role?: SystemRole): Promise<SessionUser | nu
|
|||||||
if (role && user.role !== role) return null;
|
if (role && user.role !== role) return null;
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Hane kapsamı (veri izolasyonu) ---
|
||||||
|
|
||||||
|
export type HouseholdContext = {
|
||||||
|
user: SessionUser;
|
||||||
|
/** Aktif hane; kullanıcı hiçbir haneye üye değilse null. */
|
||||||
|
household: HouseholdSummary | null;
|
||||||
|
memberships: HouseholdSummary[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Oturum + kullanıcının haneleri + aktif hane (istek başına bir kez). Cookie'deki hane
|
||||||
|
* kullanıcının üyesi olduğu bir hane değilse yok sayılır ve ilk haneye düşülür.
|
||||||
|
* Sistem admini için ayrıcalık YOKTUR: yalnızca üyesi olduğu haneler görünür.
|
||||||
|
*/
|
||||||
|
export const getHouseholdContext = cache(async (): Promise<HouseholdContext | null> => {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (!user) return null;
|
||||||
|
const [memberships, preferred] = await Promise.all([
|
||||||
|
listMemberships(user.id),
|
||||||
|
readActiveHouseholdId(),
|
||||||
|
]);
|
||||||
|
const household = pickActiveHousehold(memberships, preferred);
|
||||||
|
return { user, household, memberships };
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ActiveHousehold = HouseholdContext & { household: HouseholdSummary };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sayfa: aktif hanede en az `minRole` yetkisi. Oturum yoksa /login, hanesi yoksa /hane-yok,
|
||||||
|
* yetkisi yetmiyorsa 404.
|
||||||
|
*/
|
||||||
|
export async function requireActiveHousehold(
|
||||||
|
minRole: HouseholdRole = "viewer",
|
||||||
|
): Promise<ActiveHousehold> {
|
||||||
|
const ctx = await getHouseholdContext();
|
||||||
|
if (!ctx) redirect("/login");
|
||||||
|
if (!ctx.household) redirect("/hane-yok");
|
||||||
|
if (!hasHouseholdRole(ctx.household.role, minRole)) notFound();
|
||||||
|
return ctx as ActiveHousehold;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Server Action: aktif hanede en az `minRole` yetkisi; yoksa null (yönlendirme yapmaz). */
|
||||||
|
export async function getHouseholdActionContext(
|
||||||
|
minRole: HouseholdRole = "viewer",
|
||||||
|
): Promise<ActiveHousehold | null> {
|
||||||
|
const ctx = await getHouseholdContext();
|
||||||
|
if (!ctx?.household || !hasHouseholdRole(ctx.household.role, minRole)) return null;
|
||||||
|
return ctx as ActiveHousehold;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Belirli bir hane için üyelik kontrolü (ör. URL'den veya istek gövdesinden gelen householdId).
|
||||||
|
* Üye değilse veya yetkisi yetmiyorsa null — çağıran 404/403 döner.
|
||||||
|
*/
|
||||||
|
export async function requireHouseholdMember(
|
||||||
|
householdId: string,
|
||||||
|
minRole: HouseholdRole = "viewer",
|
||||||
|
): Promise<{ user: SessionUser; membership: Membership } | null> {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (!user) return null;
|
||||||
|
const membership = await resolveMembership(user.id, householdId, minRole);
|
||||||
|
return membership ? { user, membership } : null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Types } from "mongoose";
|
||||||
|
|
||||||
|
/** Geçerli 24 haneli hex ise ObjectId, değilse null (kullanıcı girdisi asla doğrudan sorguya girmez). */
|
||||||
|
export function toObjectId(value: unknown): Types.ObjectId | null {
|
||||||
|
return typeof value === "string" && /^[a-f0-9]{24}$/i.test(value)
|
||||||
|
? new Types.ObjectId(value)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
|
||||||
|
import { ACCOUNT_TYPES, DUE_RULE_KINDS, MEAL_CARD_PROVIDERS } from "@/shared/accounts";
|
||||||
|
import { ICON_KEYS, SWATCHES } from "@/shared/appearance";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hesap (Bölüm 6.1). Tutarlar kuruş. Bakiye işareti: varlık pozitif, kart borcu negatif.
|
||||||
|
* Güncel bakiyenin tek doğruluk kaynağı işlemlerdir (Faz 6b); `balanceCacheMinor` yalnızca önbellek.
|
||||||
|
*/
|
||||||
|
const overdraftSchema = new Schema(
|
||||||
|
{
|
||||||
|
enabled: { type: Boolean, default: false },
|
||||||
|
limitMinor: { type: Number, min: 0, default: 0 },
|
||||||
|
/** Aylık faiz oranı, baz puan (4,25% → 425). */
|
||||||
|
monthlyRateBp: { type: Number, min: 0, max: 10_000, default: null },
|
||||||
|
statementDay: { type: Number, min: 1, max: 31, default: null },
|
||||||
|
},
|
||||||
|
{ _id: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const creditCardSchema = new Schema(
|
||||||
|
{
|
||||||
|
limitMinor: { type: Number, min: 0, default: 0 },
|
||||||
|
/** Hesap kesim günü; ayda yoksa (31) ayın son günü kullanılır (Faz 7). */
|
||||||
|
statementDay: { type: Number, min: 1, max: 31, default: 1 },
|
||||||
|
dueRule: {
|
||||||
|
kind: { type: String, enum: DUE_RULE_KINDS, default: "daysAfter" },
|
||||||
|
value: { type: Number, min: 1, max: 31, default: 10 },
|
||||||
|
},
|
||||||
|
/** Kart borcunun ödeneceği varsayılan hesap. */
|
||||||
|
paymentAccountId: { type: Schema.Types.ObjectId, default: null },
|
||||||
|
},
|
||||||
|
{ _id: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const accountSchema = new Schema(
|
||||||
|
{
|
||||||
|
householdId: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
name: { type: String, required: true, trim: true, maxlength: 80 },
|
||||||
|
type: { type: String, enum: ACCOUNT_TYPES, required: true },
|
||||||
|
institution: { type: String, trim: true, maxlength: 80, default: "" },
|
||||||
|
mealCardProvider: { type: String, enum: [...MEAL_CARD_PROVIDERS, null], default: null },
|
||||||
|
/** İleride döviz hesabı için; şimdilik yalnızca TRY. */
|
||||||
|
currency: { type: String, enum: ["TRY"], default: "TRY" },
|
||||||
|
openingBalanceMinor: { type: Number, required: true, default: 0 },
|
||||||
|
openingDate: { type: Date, required: true },
|
||||||
|
color: { type: String, enum: SWATCHES, default: "blue" },
|
||||||
|
icon: { type: String, enum: ICON_KEYS, default: "wallet" },
|
||||||
|
order: { type: Number, default: 0 },
|
||||||
|
archivedAt: { type: Date, default: null },
|
||||||
|
/** Hesabın sahibi kişi (hane üyesi). "Yalnızca ben" hesaplarında bakiyeyi yalnızca o görür. */
|
||||||
|
ownerUserId: { type: Schema.Types.ObjectId, default: null },
|
||||||
|
isPrivate: { type: Boolean, default: false },
|
||||||
|
overdraft: { type: overdraftSchema, default: null },
|
||||||
|
creditCard: { type: creditCardSchema, default: null },
|
||||||
|
balanceCacheMinor: { type: Number, default: null },
|
||||||
|
createdBy: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
updatedBy: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
},
|
||||||
|
{ timestamps: true, collection: "accounts" },
|
||||||
|
);
|
||||||
|
|
||||||
|
accountSchema.index({ householdId: 1, archivedAt: 1, order: 1 });
|
||||||
|
|
||||||
|
export type Account = InferSchemaType<typeof accountSchema>;
|
||||||
|
|
||||||
|
export const AccountModel: Model<Account> =
|
||||||
|
(models.Account as Model<Account> | undefined) ?? model<Account>("Account", accountSchema);
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Denetim kaydı (yalnızca eklenir, güncellenmez). Bölüm 7.2: hane ayarları, üye değişiklikleri,
|
||||||
|
* silmeler, aynî borç kapatma ve mutabakat düzeltmeleri; ayrıca admin kullanıcı işlemleri.
|
||||||
|
*/
|
||||||
|
export const AUDIT_ACTIONS = [
|
||||||
|
"household.create",
|
||||||
|
"household.settings.update",
|
||||||
|
"household.member.add",
|
||||||
|
"household.member.role",
|
||||||
|
"household.member.remove",
|
||||||
|
"user.create",
|
||||||
|
"user.update",
|
||||||
|
"user.role",
|
||||||
|
"user.password.reset",
|
||||||
|
"user.ban",
|
||||||
|
"user.unban",
|
||||||
|
"user.remove",
|
||||||
|
"account.create",
|
||||||
|
"account.update",
|
||||||
|
"account.archive",
|
||||||
|
"account.unarchive",
|
||||||
|
"category.archive",
|
||||||
|
"category.unarchive",
|
||||||
|
"category.move",
|
||||||
|
] as const;
|
||||||
|
export type AuditAction = (typeof AUDIT_ACTIONS)[number];
|
||||||
|
|
||||||
|
const auditLogSchema = new Schema(
|
||||||
|
{
|
||||||
|
/** Hane kapsamındaki işlemlerde dolu; sistem (admin) işlemlerinde null. */
|
||||||
|
householdId: { type: Schema.Types.ObjectId, default: null },
|
||||||
|
actorId: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
action: { type: String, enum: AUDIT_ACTIONS, required: true },
|
||||||
|
targetType: { type: String, required: true },
|
||||||
|
targetId: { type: String, required: true },
|
||||||
|
/** Değişen alanlar: { alan: { from, to } } veya özet bilgi. Şifre vb. sır asla yazılmaz. */
|
||||||
|
diff: { type: Schema.Types.Mixed, default: null },
|
||||||
|
at: { type: Date, default: () => new Date() },
|
||||||
|
},
|
||||||
|
{ collection: "auditLogs", versionKey: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
auditLogSchema.index({ householdId: 1, at: -1 });
|
||||||
|
auditLogSchema.index({ actorId: 1, at: -1 });
|
||||||
|
|
||||||
|
export type AuditLog = InferSchemaType<typeof auditLogSchema>;
|
||||||
|
|
||||||
|
export const AuditLogModel: Model<AuditLog> =
|
||||||
|
(models.AuditLog as Model<AuditLog> | undefined) ?? model<AuditLog>("AuditLog", auditLogSchema);
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
|
||||||
|
import { ICON_KEYS, SWATCHES } from "@/shared/appearance";
|
||||||
|
import { CATEGORY_KINDS } from "@/shared/schemas/category";
|
||||||
|
|
||||||
|
/** Gelir/gider kategori ağacı (Bölüm 6.2). Silme yok; arşivleme (alt ağaçla birlikte). */
|
||||||
|
const categorySchema = new Schema(
|
||||||
|
{
|
||||||
|
householdId: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
kind: { type: String, enum: CATEGORY_KINDS, required: true },
|
||||||
|
name: { type: String, required: true, trim: true, maxlength: 80 },
|
||||||
|
/** Kardeşler arasında ad tekrarını önlemek için normalize ad (foldTr). */
|
||||||
|
nameKey: { type: String, required: true },
|
||||||
|
parentId: { type: Schema.Types.ObjectId, default: null },
|
||||||
|
/** Kökten üst kategoriye kadar kimlikler (alt ağaç sorguları ve toplama için). */
|
||||||
|
ancestors: { type: [Schema.Types.ObjectId], default: [] },
|
||||||
|
icon: { type: String, enum: ICON_KEYS, default: "tag" },
|
||||||
|
color: { type: String, enum: SWATCHES, default: "slate" },
|
||||||
|
order: { type: Number, default: 0 },
|
||||||
|
archivedAt: { type: Date, default: null },
|
||||||
|
/** Varsayılan setten geldiyse sabit anahtar (tekrar yüklemede kopya olmaz). */
|
||||||
|
defaultKey: { type: String, default: null },
|
||||||
|
createdBy: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
updatedBy: { type: Schema.Types.ObjectId, required: true },
|
||||||
|
},
|
||||||
|
{ timestamps: true, collection: "categories" },
|
||||||
|
);
|
||||||
|
|
||||||
|
categorySchema.index({ householdId: 1, kind: 1, parentId: 1, order: 1 });
|
||||||
|
categorySchema.index({ householdId: 1, ancestors: 1 });
|
||||||
|
categorySchema.index(
|
||||||
|
{ householdId: 1, defaultKey: 1 },
|
||||||
|
{ unique: true, partialFilterExpression: { defaultKey: { $type: "string" } } },
|
||||||
|
);
|
||||||
|
|
||||||
|
export type Category = InferSchemaType<typeof categorySchema>;
|
||||||
|
|
||||||
|
export const CategoryModel: Model<Category> =
|
||||||
|
(models.Category as Model<Category> | undefined) ?? model<Category>("Category", categorySchema);
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/** Hesap türleri ve yemek kartı sağlayıcıları (Bölüm 6.1). */
|
||||||
|
export const ACCOUNT_TYPES = ["cash", "bank", "savings", "credit_card", "meal_card"] as const;
|
||||||
|
export type AccountType = (typeof ACCOUNT_TYPES)[number];
|
||||||
|
|
||||||
|
export const MEAL_CARD_PROVIDERS = [
|
||||||
|
"pluxee",
|
||||||
|
"multinet",
|
||||||
|
"edenred",
|
||||||
|
"setcard",
|
||||||
|
"metropol",
|
||||||
|
"other",
|
||||||
|
] as const;
|
||||||
|
export type MealCardProvider = (typeof MEAL_CARD_PROVIDERS)[number];
|
||||||
|
|
||||||
|
/** Kredi kartı son ödeme kuralı: kesimden N gün sonra | ayın sabit günü. */
|
||||||
|
export const DUE_RULE_KINDS = ["daysAfter", "fixedDay"] as const;
|
||||||
|
export type DueRuleKind = (typeof DUE_RULE_KINDS)[number];
|
||||||
|
|
||||||
|
/** Borç (negatif bakiye) taşıyan hesap türleri. */
|
||||||
|
export const isLiabilityType = (type: AccountType) => type === "credit_card";
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* Kullanıcı verisindeki renk ve ikonlar anahtar olarak saklanır (sabit renk kodu yok).
|
||||||
|
* Renkler globals.css'teki --swatch-* değişkenlerine, ikonlar lucide bileşenlerine eşlenir.
|
||||||
|
*/
|
||||||
|
export const SWATCHES = [
|
||||||
|
"blue",
|
||||||
|
"sky",
|
||||||
|
"teal",
|
||||||
|
"green",
|
||||||
|
"lime",
|
||||||
|
"amber",
|
||||||
|
"orange",
|
||||||
|
"red",
|
||||||
|
"rose",
|
||||||
|
"pink",
|
||||||
|
"purple",
|
||||||
|
"indigo",
|
||||||
|
"slate",
|
||||||
|
] as const;
|
||||||
|
export type Swatch = (typeof SWATCHES)[number];
|
||||||
|
|
||||||
|
export const ICON_KEYS = [
|
||||||
|
"wallet",
|
||||||
|
"banknote",
|
||||||
|
"landmark",
|
||||||
|
"piggy-bank",
|
||||||
|
"credit-card",
|
||||||
|
"utensils",
|
||||||
|
"shopping-cart",
|
||||||
|
"shopping-basket",
|
||||||
|
"receipt",
|
||||||
|
"zap",
|
||||||
|
"droplet",
|
||||||
|
"flame",
|
||||||
|
"wifi",
|
||||||
|
"smartphone",
|
||||||
|
"house",
|
||||||
|
"building",
|
||||||
|
"car",
|
||||||
|
"fuel",
|
||||||
|
"bus",
|
||||||
|
"train",
|
||||||
|
"heart-pulse",
|
||||||
|
"pill",
|
||||||
|
"graduation-cap",
|
||||||
|
"book",
|
||||||
|
"shirt",
|
||||||
|
"gamepad",
|
||||||
|
"film",
|
||||||
|
"music",
|
||||||
|
"coffee",
|
||||||
|
"plane",
|
||||||
|
"gift",
|
||||||
|
"baby",
|
||||||
|
"paw-print",
|
||||||
|
"wrench",
|
||||||
|
"sofa",
|
||||||
|
"repeat",
|
||||||
|
"briefcase",
|
||||||
|
"trending-up",
|
||||||
|
"coins",
|
||||||
|
"percent",
|
||||||
|
"undo",
|
||||||
|
"sparkles",
|
||||||
|
"spray-can",
|
||||||
|
"scissors",
|
||||||
|
"dumbbell",
|
||||||
|
"tag",
|
||||||
|
"circle-ellipsis",
|
||||||
|
] as const;
|
||||||
|
export type IconKey = (typeof ICON_KEYS)[number];
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { istanbulDayStart, toIstanbulYmd, todayIstanbul } from "./dates";
|
||||||
|
|
||||||
|
describe("İstanbul günü", () => {
|
||||||
|
it("gün başlangıcı UTC+3'e göre hesaplanır", () => {
|
||||||
|
expect(istanbulDayStart("2026-11-05")?.toISOString()).toBe("2026-11-04T21:00:00.000Z");
|
||||||
|
expect(istanbulDayStart("2027-01-01")?.toISOString()).toBe("2026-12-31T21:00:00.000Z");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("geçersiz tarihleri reddeder", () => {
|
||||||
|
expect(istanbulDayStart("2026-02-30")).toBeNull();
|
||||||
|
expect(istanbulDayStart("05.11.2026")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("anı İstanbul gününe çevirir (gece yarısı sınırı)", () => {
|
||||||
|
expect(toIstanbulYmd("2026-12-31T20:59:59Z")).toBe("2026-12-31");
|
||||||
|
expect(toIstanbulYmd("2026-12-31T21:00:00Z")).toBe("2027-01-01");
|
||||||
|
expect(todayIstanbul(new Date("2026-11-04T22:30:00Z"))).toBe("2026-11-05");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gidiş-dönüş tutarlıdır", () => {
|
||||||
|
for (const ymd of ["2026-03-31", "2026-10-25", "2028-02-29"]) {
|
||||||
|
expect(toIstanbulYmd(istanbulDayStart(ymd)!)).toBe(ymd);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { TIME_ZONE } from "./format";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* İstanbul günü yardımcıları. Veritabanında UTC saklanır; gün sınırları İstanbul'a göredir.
|
||||||
|
* Türkiye 2016'dan beri sabit UTC+3 kullanır; yine de dönüşüm Intl ile yapılır (kural değişirse
|
||||||
|
* yalnızca ofset hesabı güncellenir).
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ymdFmt = new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: TIME_ZONE,
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Bir anın İstanbul'daki takvim günü: "2026-11-05". */
|
||||||
|
export function toIstanbulYmd(date: Date | string | number): string {
|
||||||
|
return ymdFmt.format(new Date(date));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bugünün İstanbul günü. */
|
||||||
|
export function todayIstanbul(now: Date = new Date()): string {
|
||||||
|
return toIstanbulYmd(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** İstanbul'un verilen andaki UTC ofseti (dakika; +180). */
|
||||||
|
function istanbulOffsetMinutes(at: Date): number {
|
||||||
|
const parts = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone: TIME_ZONE,
|
||||||
|
hourCycle: "h23",
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
}).formatToParts(at);
|
||||||
|
const get = (t: string) => Number(parts.find((p) => p.type === t)?.value);
|
||||||
|
const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"));
|
||||||
|
return Math.round((asUtc - at.getTime()) / 60_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-11-05" → o günün İstanbul'daki başlangıç anı (UTC Date). Geçersizse null. */
|
||||||
|
export function istanbulDayStart(ymd: string): Date | null {
|
||||||
|
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(ymd);
|
||||||
|
if (!m) return null;
|
||||||
|
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
||||||
|
const guess = new Date(Date.UTC(y, mo - 1, d));
|
||||||
|
if (guess.getUTCFullYear() !== y || guess.getUTCMonth() !== mo - 1 || guess.getUTCDate() !== d)
|
||||||
|
return null;
|
||||||
|
return new Date(guess.getTime() - istanbulOffsetMinutes(guess) * 60_000);
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { allocate, formatMoneyInput, parseMoney, splitEvenly, sumMoney } from "./money";
|
||||||
|
|
||||||
|
describe("parseMoney", () => {
|
||||||
|
it.each([
|
||||||
|
["1.250,50", 125050],
|
||||||
|
["1250,50", 125050],
|
||||||
|
["1250,5", 125050],
|
||||||
|
["1250", 125000],
|
||||||
|
["0,01", 1],
|
||||||
|
[",5", 50],
|
||||||
|
["1.250", 125000],
|
||||||
|
["12.345.678,90", 1234567890],
|
||||||
|
["12.5", 1250],
|
||||||
|
["12.50", 1250],
|
||||||
|
["₺1.250,50", 125050],
|
||||||
|
["1.250,50 TL", 125050],
|
||||||
|
[" 1 250,50 ", 125050],
|
||||||
|
["-12,30", -1230],
|
||||||
|
["−12,30", -1230],
|
||||||
|
["+7", 700],
|
||||||
|
["0", 0],
|
||||||
|
["-0", 0],
|
||||||
|
])("%s → %i", (input, expected) => {
|
||||||
|
expect(parseMoney(input)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
"",
|
||||||
|
"abc",
|
||||||
|
"1,2,3",
|
||||||
|
"12,345",
|
||||||
|
"1.25,00",
|
||||||
|
"1.2345",
|
||||||
|
"12.345.6",
|
||||||
|
"1,5e3",
|
||||||
|
"--5",
|
||||||
|
"100000000000,01",
|
||||||
|
])("geçersiz: %s", (input) => {
|
||||||
|
expect(parseMoney(input)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatMoneyInput", () => {
|
||||||
|
it("Türkçe biçimde simgesiz yazar ve parseMoney ile geri döner", () => {
|
||||||
|
for (const v of [0, 1, 99, 100, 125050, 1234567890, -1230]) {
|
||||||
|
expect(parseMoney(formatMoneyInput(v))).toBe(v);
|
||||||
|
}
|
||||||
|
expect(formatMoneyInput(125050)).toBe("1.250,50");
|
||||||
|
expect(formatMoneyInput(-5)).toBe("-0,05");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("allocate", () => {
|
||||||
|
it("toplam her zaman korunur (kuruş kaybı yok)", () => {
|
||||||
|
for (const total of [1, 100, 10000, 99999, 120000, -10001]) {
|
||||||
|
for (const weights of [[1], [1, 1, 1], [800, 250, 150], [1, 2, 3, 4, 5, 6, 7], [0, 1]]) {
|
||||||
|
const parts = allocate(total, weights);
|
||||||
|
expect(parts.reduce((a, b) => a + b, 0)).toBe(total);
|
||||||
|
expect(parts).toHaveLength(weights.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ağırlıklara orantılıdır ve deterministiktir", () => {
|
||||||
|
expect(allocate(120000, [800, 250, 150])).toEqual([80000, 25000, 15000]);
|
||||||
|
expect(allocate(100, [1, 1, 1])).toEqual([34, 33, 33]);
|
||||||
|
expect(allocate(-100, [1, 1, 1])).toEqual([-34, -33, -33]);
|
||||||
|
expect(allocate(5, [0, 1])).toEqual([0, 5]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("geçersiz girdiyi reddeder", () => {
|
||||||
|
expect(() => allocate(100, [])).toThrow(RangeError);
|
||||||
|
expect(() => allocate(100, [0, 0])).toThrow(RangeError);
|
||||||
|
expect(() => allocate(100, [-1, 2])).toThrow(RangeError);
|
||||||
|
expect(() => allocate(1.5, [1])).toThrow(TypeError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("splitEvenly", () => {
|
||||||
|
it("9 taksit: 1.000,00 TL", () => {
|
||||||
|
const parts = splitEvenly(100000, 9);
|
||||||
|
expect(sumMoney(parts)).toBe(100000);
|
||||||
|
expect(parts[0]).toBe(11112);
|
||||||
|
expect(parts.slice(1).every((p) => p === 11111)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
/**
|
||||||
|
* Para birimi yardımcıları — tutarlar HER ZAMAN tamsayı kuruştur (`amountMinor`).
|
||||||
|
* 125,50 TL → 12550. Float ile hesap yapılmaz; yuvarlama yalnızca gösterimde.
|
||||||
|
*
|
||||||
|
* Ayrıştırma kuralları (tr-TR):
|
||||||
|
* - Virgül varsa ondalık ayırıcıdır; noktalar ve boşluklar binlik ayırıcıdır: "1.250,50" → 125050.
|
||||||
|
* - Virgül yoksa ve noktalar geçerli binlik gruplarıysa (1.250 / 12.345.678) binlik ayırıcıdır.
|
||||||
|
* - Virgül yoksa ve tek nokta 1–2 ondalık içeriyorsa ondalıktır: "12.5" → 1250 (telefon klavyeleri).
|
||||||
|
* - En fazla 2 ondalık; "₺", "TL", boşluklar ve baştaki +/− kabul edilir. Belirsiz girdi → null.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const MAX_AMOUNT_MINOR = 100_000_000_000_00; // 100 milyar TL üst sınırı (güvenli tamsayı içinde)
|
||||||
|
|
||||||
|
const THOUSANDS_GROUPED = /^\d{1,3}(\.\d{3})+$/;
|
||||||
|
|
||||||
|
export function parseMoney(input: string): number | null {
|
||||||
|
let s = input
|
||||||
|
.trim()
|
||||||
|
.replace(/\s| | /g, "")
|
||||||
|
.replace(/₺|TL$/i, "");
|
||||||
|
if (!s) return null;
|
||||||
|
let sign = 1;
|
||||||
|
if (s.startsWith("-") || s.startsWith("−")) {
|
||||||
|
sign = -1;
|
||||||
|
s = s.slice(1);
|
||||||
|
} else if (s.startsWith("+")) {
|
||||||
|
s = s.slice(1);
|
||||||
|
}
|
||||||
|
s = s.replace(/₺/g, "");
|
||||||
|
|
||||||
|
let intPart: string;
|
||||||
|
let fracPart = "";
|
||||||
|
if (s.includes(",")) {
|
||||||
|
const parts = s.split(",");
|
||||||
|
if (parts.length !== 2) return null;
|
||||||
|
[intPart, fracPart] = parts as [string, string];
|
||||||
|
if (intPart.includes(".")) {
|
||||||
|
if (!THOUSANDS_GROUPED.test(intPart)) return null;
|
||||||
|
intPart = intPart.replace(/\./g, "");
|
||||||
|
}
|
||||||
|
} else if (s.includes(".")) {
|
||||||
|
if (THOUSANDS_GROUPED.test(s)) {
|
||||||
|
intPart = s.replace(/\./g, "");
|
||||||
|
} else {
|
||||||
|
const parts = s.split(".");
|
||||||
|
if (parts.length !== 2 || parts[1]!.length > 2) return null;
|
||||||
|
[intPart, fracPart] = parts as [string, string];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
intPart = s;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intPart === "") intPart = "0";
|
||||||
|
if (!/^\d+$/.test(intPart) || !/^\d{0,2}$/.test(fracPart)) return null;
|
||||||
|
const minor = Number(intPart) * 100 + Number(fracPart.padEnd(2, "0"));
|
||||||
|
if (!Number.isSafeInteger(minor) || minor > MAX_AMOUNT_MINOR) return null;
|
||||||
|
return sign * minor === 0 ? 0 : sign * minor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Form alanı için: 125050 → "1.250,50" (simgesiz). */
|
||||||
|
export function formatMoneyInput(amountMinor: number): string {
|
||||||
|
assertMinor(amountMinor);
|
||||||
|
const sign = amountMinor < 0 ? "-" : "";
|
||||||
|
const abs = Math.abs(amountMinor);
|
||||||
|
const int = Math.trunc(abs / 100)
|
||||||
|
.toString()
|
||||||
|
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
|
||||||
|
const frac = (abs % 100).toString().padStart(2, "0");
|
||||||
|
return `${sign}${int},${frac}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertMinor(value: number): void {
|
||||||
|
if (!Number.isSafeInteger(value)) throw new TypeError(`Kuruş tutarı tamsayı olmalı: ${value}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kuruş tutarlarını toplar (tamsayı garantili). */
|
||||||
|
export function sumMoney(values: readonly number[]): number {
|
||||||
|
let total = 0;
|
||||||
|
for (const v of values) {
|
||||||
|
assertMinor(v);
|
||||||
|
total += v;
|
||||||
|
}
|
||||||
|
assertMinor(total);
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Oransal bölme (en büyük kalan yöntemi): kuruş kaybı olmadan `totalMinor`'u ağırlıklara böler.
|
||||||
|
* Parçaların toplamı her zaman tam olarak `totalMinor`'dur. Taksit ve bölünmüş işlem için.
|
||||||
|
* Eşit kalanlarda önceki parça önceliklidir (deterministik).
|
||||||
|
*/
|
||||||
|
export function allocate(totalMinor: number, weights: readonly number[]): number[] {
|
||||||
|
assertMinor(totalMinor);
|
||||||
|
if (weights.length === 0) throw new RangeError("En az bir ağırlık gerekli");
|
||||||
|
if (weights.some((w) => !Number.isFinite(w) || w < 0))
|
||||||
|
throw new RangeError("Ağırlıklar negatif olamaz");
|
||||||
|
const weightSum = weights.reduce((a, b) => a + b, 0);
|
||||||
|
if (weightSum <= 0) throw new RangeError("Ağırlıkların toplamı sıfırdan büyük olmalı");
|
||||||
|
|
||||||
|
const sign = totalMinor < 0 ? -1 : 1;
|
||||||
|
const abs = Math.abs(totalMinor);
|
||||||
|
const raw = weights.map((w) => (abs * w) / weightSum);
|
||||||
|
const parts = raw.map((r) => Math.floor(r));
|
||||||
|
let remainder = abs - parts.reduce((a, b) => a + b, 0);
|
||||||
|
const order = raw
|
||||||
|
.map((r, i) => ({ i, frac: r - Math.floor(r) }))
|
||||||
|
.sort((a, b) => b.frac - a.frac || a.i - b.i);
|
||||||
|
for (let k = 0; remainder > 0; k = (k + 1) % order.length, remainder--) parts[order[k]!.i]! += 1;
|
||||||
|
return parts.map((p) => (p === 0 ? 0 : sign * p));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Eşit bölme: 100,00 TL / 3 → [3334, 3333, 3333]. */
|
||||||
|
export function splitEvenly(totalMinor: number, count: number): number[] {
|
||||||
|
if (!Number.isInteger(count) || count < 1) throw new RangeError("Parça sayısı en az 1 olmalı");
|
||||||
|
return allocate(
|
||||||
|
totalMinor,
|
||||||
|
Array.from({ length: count }, () => 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { convertQuantity, formatQuantity, parseQuantity } from "./quantity";
|
||||||
|
|
||||||
|
describe("parseQuantity", () => {
|
||||||
|
it.each([
|
||||||
|
["1,5", 1500],
|
||||||
|
["1.5", 1500],
|
||||||
|
["2", 2000],
|
||||||
|
["0,125", 125],
|
||||||
|
["5", 5000],
|
||||||
|
[" 10,25 ", 10250],
|
||||||
|
])("%s → %i", (input, expected) => {
|
||||||
|
expect(parseQuantity(input)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["", "-1", "1,2345", "1,2,3", "abc", "1e3"])("geçersiz: %s", (input) => {
|
||||||
|
expect(parseQuantity(input)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatQuantity", () => {
|
||||||
|
it("gereksiz sıfırları atar, birim ekler", () => {
|
||||||
|
expect(formatQuantity(1500, "kg")).toBe("1,5 kg");
|
||||||
|
expect(formatQuantity(5000, "gr")).toBe("5 gr");
|
||||||
|
expect(formatQuantity(125)).toBe("0,125");
|
||||||
|
expect(formatQuantity(1234500)).toBe("1.234,5");
|
||||||
|
expect(formatQuantity(-250)).toBe("-0,25");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("convertQuantity", () => {
|
||||||
|
it("aynı boyutta dönüştürür", () => {
|
||||||
|
expect(convertQuantity(1500, "kg", "g")).toBe(1500000); // 1,5 kg = 1500 g
|
||||||
|
expect(convertQuantity(500000, "g", "kg")).toBe(500); // 500 g = 0,5 kg
|
||||||
|
expect(convertQuantity(2000, "lt", "ml")).toBe(2000000);
|
||||||
|
});
|
||||||
|
it("uyumsuz birimde hata verir", () => {
|
||||||
|
expect(() => convertQuantity(1000, "kg", "lt")).toThrow(RangeError);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* Miktar yardımcıları (stok, gram altın, döviz, adet).
|
||||||
|
*
|
||||||
|
* KURAL: Tüm miktarlar birimin BİNDE BİRİ cinsinden tamsayı saklanır (QUANTITY_SCALE = 1000):
|
||||||
|
* 1,5 kg → 1500 · 5 gr altın → 5000 · 2 adet çeyrek → 2000 · 0,125 lt → 125 · 100 USD → 100000
|
||||||
|
* Böylece 3 ondalık hassasiyet sağlanır, toplama/çıkarma tamsayıdır. Birimler arası dönüşüm
|
||||||
|
* (kg↔g, lt↔ml) aynı boyuttaki birimler için tanımlıdır; özel birimler ("yıkama", "tablet")
|
||||||
|
* ürün bazında dönüşüm oranıyla (Faz 12) çevrilir.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const QUANTITY_SCALE = 1000;
|
||||||
|
|
||||||
|
export const UNITS = {
|
||||||
|
g: { label: "g", dimension: "mass", factor: 1 },
|
||||||
|
kg: { label: "kg", dimension: "mass", factor: 1000 },
|
||||||
|
ml: { label: "ml", dimension: "volume", factor: 1 },
|
||||||
|
lt: { label: "lt", dimension: "volume", factor: 1000 },
|
||||||
|
adet: { label: "adet", dimension: "count", factor: 1 },
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type Unit = keyof typeof UNITS;
|
||||||
|
|
||||||
|
/** "1,5" / "1.5" / "2" / "0,125" → binde bir tamsayı. En fazla 3 ondalık; geçersizse null. */
|
||||||
|
export function parseQuantity(input: string): number | null {
|
||||||
|
const s = input.trim().replace(/\s/g, "");
|
||||||
|
const m = /^(\d+)(?:[.,](\d{1,3}))?$/.exec(s);
|
||||||
|
if (!m) return null;
|
||||||
|
const value = Number(m[1]) * QUANTITY_SCALE + Number((m[2] ?? "").padEnd(3, "0"));
|
||||||
|
return Number.isSafeInteger(value) ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 1500 → "1,5"; 5000 → "5"; 125 → "0,125" (gereksiz sıfırlar atılır). */
|
||||||
|
export function formatQuantity(quantity: number, unit?: string): string {
|
||||||
|
if (!Number.isSafeInteger(quantity)) throw new TypeError(`Miktar tamsayı olmalı: ${quantity}`);
|
||||||
|
const sign = quantity < 0 ? "-" : "";
|
||||||
|
const abs = Math.abs(quantity);
|
||||||
|
const int = Math.trunc(abs / QUANTITY_SCALE).toLocaleString("tr-TR");
|
||||||
|
const frac = (abs % QUANTITY_SCALE).toString().padStart(3, "0").replace(/0+$/, "");
|
||||||
|
const text = `${sign}${int}${frac ? `,${frac}` : ""}`;
|
||||||
|
return unit ? `${text} ${unit}` : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aynı boyuttaki birimler arasında dönüşüm (kg → g vb.). Uyumsuz birimde hata. */
|
||||||
|
export function convertQuantity(quantity: number, from: Unit, to: Unit): number {
|
||||||
|
const a = UNITS[from];
|
||||||
|
const b = UNITS[to];
|
||||||
|
if (a.dimension !== b.dimension) throw new RangeError(`${from} → ${to} dönüştürülemez`);
|
||||||
|
const result = (quantity * a.factor) / b.factor;
|
||||||
|
// Hassasiyet kaybı olursa (ör. 1 ml → lt = 0,001 lt = 1) yuvarlanır; 3 ondalık sınırı.
|
||||||
|
return Math.round(result);
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { tr } from "../../i18n/tr";
|
||||||
|
import { ACCOUNT_TYPES, DUE_RULE_KINDS, MEAL_CARD_PROVIDERS } from "../accounts";
|
||||||
|
import { ICON_KEYS, SWATCHES } from "../appearance";
|
||||||
|
import { parseMoney } from "../money";
|
||||||
|
|
||||||
|
const v = tr.validation;
|
||||||
|
|
||||||
|
/** Türkçe para girişi ("1.250,50") → kuruş. Boş → 0 (opsiyonel alanlarda). */
|
||||||
|
export const moneyInputSchema = z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.transform((s, ctx) => {
|
||||||
|
if (s === "") return 0;
|
||||||
|
const minor = parseMoney(s);
|
||||||
|
if (minor === null) {
|
||||||
|
ctx.addIssue({ code: "custom", message: v.money });
|
||||||
|
return z.NEVER;
|
||||||
|
}
|
||||||
|
return minor;
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Pozitif (≥ 0) para girişi. */
|
||||||
|
export const nonNegativeMoneySchema = moneyInputSchema.refine((n) => n >= 0, v.moneyNonNegative);
|
||||||
|
|
||||||
|
const day = (max: number) => z.coerce.number().int().min(1).max(max);
|
||||||
|
const objectIdOrEmpty = z
|
||||||
|
.string()
|
||||||
|
.regex(/^([a-f0-9]{24})?$/i)
|
||||||
|
.transform((s) => (s === "" ? null : s));
|
||||||
|
|
||||||
|
/** Yüzde girişi ("4,25") → baz puan (425). Boş → null. */
|
||||||
|
const percentToBp = z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.transform((s, ctx) => {
|
||||||
|
if (s === "") return null;
|
||||||
|
const minor = parseMoney(s); // aynı ondalık kuralları: 2 hane
|
||||||
|
if (minor === null || minor < 0 || minor > 100_00) {
|
||||||
|
ctx.addIssue({ code: "custom", message: v.percent });
|
||||||
|
return z.NEVER;
|
||||||
|
}
|
||||||
|
return minor;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const accountFormSchema = z
|
||||||
|
.object({
|
||||||
|
name: z.string().trim().min(1, tr.common.required).max(80, v.nameMax),
|
||||||
|
type: z.enum(ACCOUNT_TYPES),
|
||||||
|
institution: z.string().trim().max(80, v.nameMax),
|
||||||
|
mealCardProvider: z.enum(MEAL_CARD_PROVIDERS).nullable(),
|
||||||
|
/** Kart için "açılış borcu" pozitif girilir; sunucu negatife çevirir. */
|
||||||
|
openingBalance: moneyInputSchema,
|
||||||
|
/** yyyy-MM-dd (İstanbul günü) */
|
||||||
|
openingDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, v.date),
|
||||||
|
color: z.enum(SWATCHES),
|
||||||
|
icon: z.enum(ICON_KEYS),
|
||||||
|
ownerUserId: objectIdOrEmpty,
|
||||||
|
isPrivate: z.boolean(),
|
||||||
|
overdraftEnabled: z.boolean(),
|
||||||
|
overdraftLimit: nonNegativeMoneySchema,
|
||||||
|
overdraftMonthlyRate: percentToBp,
|
||||||
|
overdraftStatementDay: z
|
||||||
|
.union([z.literal(""), day(31)])
|
||||||
|
.transform((d) => (d === "" ? null : d)),
|
||||||
|
cardLimit: nonNegativeMoneySchema,
|
||||||
|
cardStatementDay: day(31),
|
||||||
|
cardDueKind: z.enum(DUE_RULE_KINDS),
|
||||||
|
cardDueValue: day(31),
|
||||||
|
cardPaymentAccountId: objectIdOrEmpty,
|
||||||
|
})
|
||||||
|
.superRefine((a, ctx) => {
|
||||||
|
if (a.type === "meal_card" && !a.mealCardProvider) {
|
||||||
|
ctx.addIssue({ code: "custom", path: ["mealCardProvider"], message: v.selectProvider });
|
||||||
|
}
|
||||||
|
if (a.isPrivate && !a.ownerUserId) {
|
||||||
|
ctx.addIssue({ code: "custom", path: ["ownerUserId"], message: v.privateNeedsOwner });
|
||||||
|
}
|
||||||
|
if (a.type === "credit_card" && a.cardDueKind === "daysAfter" && a.cardDueValue > 30) {
|
||||||
|
ctx.addIssue({ code: "custom", path: ["cardDueValue"], message: v.dueDays });
|
||||||
|
}
|
||||||
|
// Yalnızca banka hesabı (KMH ile) negatif açılabilir; kart borcu pozitif girilir.
|
||||||
|
if (a.openingBalance < 0 && a.type !== "bank") {
|
||||||
|
ctx.addIssue({ code: "custom", path: ["openingBalance"], message: v.moneyNonNegative });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export type AccountFormInput = z.input<typeof accountFormSchema>;
|
||||||
|
export type AccountForm = z.output<typeof accountFormSchema>;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { tr } from "../../i18n/tr";
|
||||||
|
import { ICON_KEYS, SWATCHES } from "../appearance";
|
||||||
|
|
||||||
|
export const CATEGORY_KINDS = ["expense", "income"] as const;
|
||||||
|
export type CategoryKind = (typeof CATEGORY_KINDS)[number];
|
||||||
|
|
||||||
|
export const categoryFormSchema = z.object({
|
||||||
|
kind: z.enum(CATEGORY_KINDS),
|
||||||
|
name: z.string().trim().min(1, tr.common.required).max(80, tr.validation.nameMax),
|
||||||
|
parentId: z
|
||||||
|
.string()
|
||||||
|
.regex(/^([a-f0-9]{24})?$/i)
|
||||||
|
.transform((s) => (s === "" ? null : s)),
|
||||||
|
icon: z.enum(ICON_KEYS),
|
||||||
|
color: z.enum(SWATCHES),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CategoryFormInput = z.input<typeof categoryFormSchema>;
|
||||||
|
export type CategoryForm = z.output<typeof categoryFormSchema>;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { HOUSEHOLD_ROLES } from "../../features/households/types";
|
||||||
|
import { tr } from "../../i18n/tr";
|
||||||
|
|
||||||
|
export const householdRoleSchema = z.enum(HOUSEHOLD_ROLES);
|
||||||
|
|
||||||
|
export const householdNameSchema = z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(2, tr.validation.householdNameMin)
|
||||||
|
.max(80, tr.validation.householdNameMax);
|
||||||
|
|
||||||
|
/** Hane ayarları formu (owner). Tutarlar kuruş cinsinden tamsayı. */
|
||||||
|
export const householdSettingsSchema = z.object({
|
||||||
|
name: householdNameSchema,
|
||||||
|
budgetMonthStartDay: z.coerce.number().int().min(1).max(28),
|
||||||
|
installmentBudgetMode: z.enum(["per_installment", "purchase_month"]),
|
||||||
|
dailyPlanMode: z.enum(["even", "previous_month_pattern"]),
|
||||||
|
includePrivateAccountsInTotals: z.boolean(),
|
||||||
|
extraStoreSavingThresholdMinor: z.coerce.number().int().min(0).max(100_000_00),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const householdCreateSchema = z.object({
|
||||||
|
name: householdNameSchema,
|
||||||
|
/** İlk sahip (owner) olacak kullanıcı. */
|
||||||
|
ownerUserId: z.string().regex(/^[a-f0-9]{24}$/i, tr.validation.selectUser),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const addMemberSchema = z.object({
|
||||||
|
userId: z.string().regex(/^[a-f0-9]{24}$/i, tr.validation.selectUser),
|
||||||
|
role: householdRoleSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type HouseholdSettingsInput = z.input<typeof householdSettingsSchema>;
|
||||||
|
export type HouseholdSettings = z.output<typeof householdSettingsSchema>;
|
||||||
|
export type HouseholdCreateInput = z.input<typeof householdCreateSchema>;
|
||||||
|
export type AddMemberInput = z.input<typeof addMemberSchema>;
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
|
import { expect } from "vitest";
|
||||||
|
import { getDb, getMongoClient } from "@/lib/db/mongo";
|
||||||
|
import { HouseholdModel } from "@/models/household";
|
||||||
|
import { runSeed } from "../../scripts/seed/run";
|
||||||
|
|
||||||
|
/** Entegrasyon testleri için: test veritabanını temizler, seed'i çalıştırır, kimlikleri döner. */
|
||||||
|
export async function setupSeededDb() {
|
||||||
|
expect(getDb().databaseName).toBe("butcem_test");
|
||||||
|
await getDb().dropDatabase();
|
||||||
|
await runSeed({ log: () => {} });
|
||||||
|
const users = new Map<string, string>();
|
||||||
|
for (const u of await getDb().collection("user").find().toArray())
|
||||||
|
users.set(String(u.username), String(u._id));
|
||||||
|
const households = new Map<string, string>();
|
||||||
|
for (const h of await HouseholdModel.find().lean()) households.set(h.name, String(h._id));
|
||||||
|
return {
|
||||||
|
user: (username: string) => users.get(username)!,
|
||||||
|
household: (name: string) => households.get(name)!,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function teardownDb() {
|
||||||
|
await getDb().dropDatabase();
|
||||||
|
await mongoose.disconnect();
|
||||||
|
await getMongoClient().close();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user