18 Commits

Author SHA1 Message Date
suphicakir 2d3a9e3a68 feat: Faz 6c - ek dosyalar, carousel ve mutabakat
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:55:11 +03:00
suphicakir 43053898b4 chore(release): 0.6.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:55:04 +03:00
suphicakir 8a9f5ddc7d feat(ui): ek ekleme alanı, carousel görüntüleyici, ekstre sayfası ve mutabakat penceresi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:55:04 +03:00
suphicakir 2e2e33233f feat(transactions): ek bağlama, hesap ekstresi ve mutabakat servisi, 004 migration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:55:04 +03:00
suphicakir 2e1f4d7929 feat(attachments): depolama soyutlaması, içerikten tür tespiti, sharp/HEIC dönüşümü ve yetkili dosya servisi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:55:04 +03:00
suphicakir 99fc9dfea6 feat: Faz 6b - işlemler
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir 00f8809823 chore: typecheck route tipleri, CHANGELOG (Faz 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir 3acd71fd59 feat(seed): son 6 ayın örnek işlemleri ve 003 migration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir dcfa2f8c8d feat(transactions): işlem formu, bölme, liste, filtreler, ayrıntı ve CSV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir 1208e2d1eb feat(transactions): işlem servisi, bakiye hesaplama, satıcı kuralları ve izolasyon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir d18c8a0d76 feat(shared): işlem şeması, bakiye etkisi, etiket ve CSV yardımcıları
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 03:23:30 +03:00
suphicakir a00c953dc0 feat: Faz 6a - para, hesaplar ve kategoriler
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir 904a969b18 docs: CHANGELOG (Faz 6a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir 0558d92203 feat(seed): varsayılan kategoriler, örnek hesaplar ve 002 migration
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir d2aa9d8ae2 feat(ui): renk paleti, ikonlar, MoneyInput ve navigasyon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir 8dd5fd42e3 feat(accounts): hesaplar (KMH, kredi kartı, yemek kartı, yalnızca ben)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir 380ddaf303 feat(categories): kategori ağacı, varsayılan Türkçe set ve yönetim ekranı
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
suphicakir eaf80c6bb4 feat(shared): para, miktar ve İstanbul günü yardımcıları
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:57:58 +03:00
96 changed files with 12039 additions and 107 deletions
+61
View File
@@ -6,6 +6,67 @@ Biçim [Keep a Changelog](https://keepachangelog.com/tr-TR/1.1.0/) esas alınır
## [Yayınlanmamış]
## [0.6.0] - 2026-11-05
Faz 6: hesaplar, kategoriler, işlemler, ek dosyalar ve mutabakat (6a, 6b, 6c alt fazları).
### Eklendi — Faz 6c: ek dosyalar, carousel, ekstre ve mutabakat
- Depolama soyutlaması `lib/storage/` (`put`, `get`, `delete`); yerel disk sürücüsü (`UPLOAD_DIR`), atomik yazma, rastgele anahtarlar, yol geçişine karşı anahtar doğrulaması.
- Ek dosya yükleme `POST /api/files`: tür dosya içeriğinden (imza) tespit edilir — JPEG, PNG, WebP, HEIC, PDF; uzantıya güvenilmez. Dosya başına `MAX_UPLOAD_MB` (10 MB), kayıt başına 10 dosya. Origin kontrolü.
- Görseller sharp ile EXIF yönüne göre döndürülür, en fazla 2000 px'e küçültülür, WebP'ye çevrilir; EXIF/GPS dahil tüm meta veri silinir; 320 px küçük resim üretilir. iPhone HEIC dosyaları libheif (WASM, `heic-decode`) ile çözülür. PDF'ler yapı kontrolünden sonra olduğu gibi saklanır.
- Yetkili servis `GET /api/files/:id` (`?v=thumb`, `&indir=1`): oturum + hane üyeliği; bekleyen ek yalnızca yükleyene; silinmiş işlemin veya başkasının gizli hesabındaki işlemin eki görünmez (404). Dosyalara özel sıkı CSP, `nosniff`, `private` önbellek.
- `attachments` koleksiyonu (`ownerType`, `ownerId`, tür, boyut, yükleyen, sıra). Ekler işlemle aynı MongoDB transaction'ında bağlanır; hata olursa işlem de oluşmaz. Gider: yalnızca görsel; gelir ve transfer: görsel veya PDF.
- İşlem formunda küçük "Ek ekle" alanı (çoklu seçim, yükleme göstergesi, küçük önizleme, kaldırma, sayaç); yüklemeler bitmeden kaydedilemez. Kopyada ekler taşınmaz.
- Görüntüleyici: shadcn Carousel (Embla) — oklar, kaydırma, klavye okları, tam ekran, "2 / 5" göstergesi, indirme; PDF'ler ikon + "Aç" düğmesiyle. Ayrıntıda en fazla 4 küçük resim + "+N".
- Temizlik `npm run cleanup`: 24 saatten eski bağlanmamış ekler, 30 günden önce kayıttan çıkarılmış ekler ve 30 günden önce silinmiş işlemlerin ekleri (dosyalarıyla) silinir.
- Hesap ekstresi `/hesaplar/:id?ay=YYYY-MM`: ay başı/ay sonu bakiyesi, giriş/çıkış, yürüyen bakiye, mutabakat işaretleri; işlem ayrıntısı ekstreden açılır. Başkasının gizli hesabına transfer ekstrede görünür ama karşı hesap adı gizlenir.
- Mutabakat: ekstre tarihi ve bakiyesi girilir, uygulama bakiyesiyle karşılaştırılır (kredi kartında borç pozitif girilir). Fark varsa onayla "Mutabakat düzeltmesi" işlemi oluşturulur; o tarihe kadarki işlemler hesap bazında işaretlenir; `reconciliations` kaydı ve denetim kaydı (`account.reconcile`) tek transaction'da.
- `004` migration'ı: `attachments` ve `reconciliations` index'leri; işlemlerde `reconciledAccountIds` ve `isAdjustment`.
- Testler: dosya türü tespiti, depolama, ekstre yardımcıları (birim); yükleme/dönüştürme (EXIF silme, yön, boyut, HEIC), bağlama kuralları, erişim izolasyonu, temizlik, ekstre tutarlılığı, mutabakat (entegrasyon).
### Değişti — Faz 6c
- Hesap adı artık hesap ekstresini açar (gizli hesaplarda bağlantı yok).
- Bakiyeyi etkileyen alanı (tutar, tarih, tür, hesap) değiştirilen işlemin mutabakat işareti kalkar. Mutabakat düzeltmesi düzenlenemez, yalnızca silinebilir.
- İşlemlerdeki kullanılmayan `reconciledAt` alanı, hesap bazında `reconciledAccountIds` ile değiştirildi.
### Düzeltildi
- `seed:reset` işlemleri ve satıcıları silmiyordu; artık işlemler, satıcılar, ekler (diskteki dosyalarıyla) ve mutabakatlar da temizlenir.
### Eklendi — Faz 6b: işlemler
- İşlemler (`/islemler`): gelir, gider ve transfer (hesap ↔ hesap). Tutar her zaman pozitif; işaret türden gelir. Hesap bakiyeleri artık açılış bakiyesi + gerçekleşmiş işlemlerden hesaplanır (tek doğruluk kaynağı: işlemler).
- Bölünmüş işlem: en az 2 kalem, kalemler toplamı = tutar (istemci ve sunucuda aynı zod şeması); kalan tutar göstergesi, "kalanı son kaleme ekle"; listede tek satır, ayrıntıda kalemler.
- Akıllı giriş: satıcı önerileri (Türkçe normalize arama, kullanım sıklığı) ve satıcının son kullanılan kategori/hesabı; işlemi kopyalama.
- Liste: güne göre gruplama ve günlük net, gelir/gider/net özetleri, sayfalama; filtreler (tarih aralığı İstanbul gününe göre, tür, durum, hesap — transfer hedefi dahil, kategori — alt kategoriler ve bölünmüş kalemler dahil, ekleyen kişi, tutar aralığı, etiket, metin arama); filtreler URL'de.
- İşlem ayrıntısı, düzenleme ve yumuşak silme; silme bildiriminde "Geri al".
- CSV dışa aktarma (`/islemler/disa-aktar`): listedeki filtrelerle, bölünmüş işlem kalem başına satır; Türkçe Excel uyumlu (noktalı virgül, ondalık virgül, UTF-8 BOM), formül enjeksiyonu koruması.
- Hızlı ekle her ekrandan doğrudan işlem formunu açar (gider/gelir/transfer sekmeleri).
- Gizlilik: başkasının "yalnızca ben" hesabına dokunan işlemler listede, ayrıntıda ve CSV'de görünmez; o hesaba yalnızca sahibi işlem girer.
- Seed: son 6 ayın 221 gerçekçi işlemi (faker.seed(42); maaş, kira, faturalar — kışın doğalgaz yüksek, market — bir kısmı bölünmüş, yakıt, kafe, kart ödemesi, birikim, nakit çekme), satıcı kuralları; idempotent (`seedRef`).
- `003` migration'ı: `transactions` ve `payees` index'leri. Denetim kaydı: işlem silme/geri alma.
- Testler: bakiye tutarlılığı (bağımsız doğrulama dahil), izolasyon, gizli hesap, arşivli kategori, filtreler, satıcı kuralları, CSV.
### Değişti
- `npm run typecheck` önce route tiplerini üretir (`next typegen`).
### 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.
+13 -10
View File
@@ -52,16 +52,19 @@ Giriş kullanıcı adı **veya** e-posta ile yapılır. Kayıt kapalıdır; kull
## Scriptler
| Komut | Açıklama |
| ----------------------------- | -------------------------------- |
| `npm run dev` | Geliştirme sunucusu |
| `npm run build` / `start` | Üretim build'i / sunucusu |
| `npm run lint` | ESLint |
| `npm run typecheck` | `tsc --noEmit` |
| `npm run test` | Vitest birim testleri |
| `npm run format` | Prettier |
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
| Komut | Açıklama |
| ----------------------------- | --------------------------------- |
| `npm run dev` | Geliştirme sunucusu |
| `npm run build` / `start` | Üretim build'i / sunucusu |
| `npm run lint` | ESLint |
| `npm run typecheck` | `tsc --noEmit` |
| `npm run test` | Vitest birim testleri |
| `npm run format` | Prettier |
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
| `npm run test:integration` | Entegrasyon testleri (MongoDB) |
| `npm run migrate` | Bekleyen migration'lar |
| `npm run cleanup` | Eski/bağlanmamış ek dosyaları sil |
## Haneler ve yetki
+24 -1
View File
@@ -42,10 +42,24 @@ const securityHeaders = [
[{ key: "Strict-Transport-Security", value: "max-age=31536000" }]),
];
/**
* /api/files: kullanıcı dosyaları (WebP görsel, PDF). Sayfa CSP'si yerine daha sıkı bir politika:
* betik yok; PDF'in tarayıcı görüntüleyicisinde açılabilmesi için object-src 'self'.
*/
const fileCsp = [
"default-src 'none'",
"img-src 'self'",
"style-src 'unsafe-inline'",
"object-src 'self'",
"frame-ancestors 'self'",
].join("; ");
const nextConfig: NextConfig = {
// Docker imajı için yalnızca gerekli dosyaları .next/standalone altına kopyala.
output: "standalone",
poweredByHeader: false,
// HEIC çözücü (libheif WASM) bundle'a girmesin; Node require ile yüklensin.
serverExternalPackages: ["heic-decode", "libheif-js"],
experimental: {
agentFeedback: true,
},
@@ -60,7 +74,16 @@ const nextConfig: NextConfig = {
},
},
async headers() {
return [{ source: "/:path*", headers: securityHeaders }];
return [
{ source: "/:path((?!api/files/).*)", headers: securityHeaders },
{
source: "/api/files/:path*",
headers: [
...securityHeaders.filter((h) => h.key !== "Content-Security-Policy"),
{ key: "Content-Security-Policy", value: fileCsp },
],
},
];
},
};
+53 -2
View File
@@ -1,18 +1,20 @@
{
"name": "butcem",
"version": "0.1.0",
"version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "butcem",
"version": "0.1.0",
"version": "0.6.0",
"dependencies": {
"@hookform/resolvers": "^7.0.2",
"@tanstack/react-table": "^9.3.1",
"better-auth": "^1.7.17",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.2",
"embla-carousel-react": "^8.6.0",
"heic-decode": "^2.1.0",
"lucide-react": "^1.68.0",
"mongodb": "~7.7",
"mongoose": "^9.11.4",
@@ -6861,6 +6863,34 @@
"integrity": "sha512-LnPnRZ0esKB9NjsSIaC+mffW+5dAtBui6kbK5f9Qykblj4Q33cn6yIhuCcTVjwpvL3YJPqqQ4IlsNyriGNpyFQ==",
"license": "ISC"
},
"node_modules/embla-carousel": {
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT"
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel-react/-/embla-carousel-react-8.6.0.tgz",
"integrity": "sha512-0/PjqU7geVmo6F734pmPqpyHqiM99olvyecY7zdweCw+6tKEXnrE90pBiBbMMU8s5tICemzpQ3hi5EpxzGW+JA==",
"license": "MIT",
"dependencies": {
"embla-carousel": "8.6.0",
"embla-carousel-reactive-utils": "8.6.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.1 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/embla-carousel-reactive-utils": {
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel-reactive-utils/-/embla-carousel-reactive-utils-8.6.0.tgz",
"integrity": "sha512-fMVUDUEx0/uIEDM0Mz3dHznDhfX+znCCDCeIophYb1QGVM7YThSWX+wz11zlYwWFOr74b4QLGg0hrGPJeG2s4A==",
"license": "MIT",
"peerDependencies": {
"embla-carousel": "8.6.0"
}
},
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
@@ -8205,6 +8235,18 @@
"node": ">= 0.4"
}
},
"node_modules/heic-decode": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/heic-decode/-/heic-decode-2.1.0.tgz",
"integrity": "sha512-0fB3O3WMk38+PScbHLVp66jcNhsZ/ErtQ6u2lMYu/YxXgbBtl+oKOhGQHa4RpvE68k8IzbWkABzHnyAIjR758A==",
"license": "ISC",
"dependencies": {
"libheif-js": "^1.19.8"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/hermes-estree": {
"version": "0.25.1",
"resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",
@@ -9076,6 +9118,15 @@
"node": ">= 0.8.0"
}
},
"node_modules/libheif-js": {
"version": "1.23.5",
"resolved": "https://registry.npmjs.org/libheif-js/-/libheif-js-1.23.5.tgz",
"integrity": "sha512-umXZPthnWZtF3iG/5mQG+AZ2V6i0UeYpo3z2CkggTEgL8dKmIIwJT6TDuAMuabXa1yTW8uJ1ZAgR+CxNTklYYw==",
"license": "LGPL-3.0",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+6 -3
View File
@@ -1,6 +1,6 @@
{
"name": "butcem",
"version": "0.5.0",
"version": "0.6.0",
"private": true,
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
"engines": {
@@ -11,7 +11,7 @@
"build": "next build",
"start": "next start",
"lint": "eslint",
"typecheck": "tsc --noEmit",
"typecheck": "next typegen && tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"format": "prettier --write .",
@@ -22,7 +22,8 @@
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
"icons": "tsx scripts/generate-icons.ts",
"test:integration": "vitest run --config vitest.integration.config.mts",
"migrate": "tsx --conditions=react-server --env-file=.env.local scripts/migrate.ts"
"migrate": "tsx --conditions=react-server --env-file=.env.local scripts/migrate.ts",
"cleanup": "tsx --conditions=react-server --env-file=.env.local scripts/cleanup.ts"
},
"dependencies": {
"@hookform/resolvers": "^7.0.2",
@@ -30,6 +31,8 @@
"better-auth": "^1.7.17",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.2",
"embla-carousel-react": "^8.6.0",
"heic-decode": "^2.1.0",
"lucide-react": "^1.68.0",
"mongodb": "~7.7",
"mongoose": "^9.11.4",
+18
View File
@@ -0,0 +1,18 @@
/**
* Ek dosya temizliği: npm run cleanup (canlıda günlük zamanlanmış görev; bkz. Faz 15).
* 24 saatten eski bağlanmamış ekler ve 30 günden önce silinmiş kayıtların ekleri fiziksel olarak silinir.
*/
import mongoose from "mongoose";
import { purgeAttachments } from "@/features/attachments/service";
import { getMongoClient } from "@/lib/db/mongo";
purgeAttachments()
.then(({ removed }) => console.log(`✓ Temizlenen ek dosya: ${removed}`))
.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,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);
}
},
};
+12
View File
@@ -0,0 +1,12 @@
import { PayeeModel } from "@/models/payee";
import { TransactionModel } from "@/models/transaction";
import type { Migration } from "./types";
export const migration: Migration = {
name: "003-transactions",
description: "transactions ve payees index'leri",
async up() {
await TransactionModel.createIndexes();
await PayeeModel.createIndexes();
},
};
@@ -0,0 +1,20 @@
import { AttachmentModel } from "@/models/attachment";
import { ReconciliationModel } from "@/models/reconciliation";
import type { Migration } from "./types";
export const migration: Migration = {
name: "004-attachments-reconciliation",
description: "attachments ve reconciliations index'leri; işlemlerde mutabakat alanları",
async up(db) {
await AttachmentModel.createIndexes();
await ReconciliationModel.createIndexes();
const tx = db.collection("transactions");
// reconciledAt (hiç kullanılmadı) → hesap bazında reconciledAccountIds.
await tx.updateMany({ reconciledAt: { $exists: true } }, { $unset: { reconciledAt: "" } });
await tx.updateMany(
{ reconciledAccountIds: { $exists: false } },
{ $set: { reconciledAccountIds: [] } },
);
await tx.updateMany({ isAdjustment: { $exists: false } }, { $set: { isAdjustment: false } });
},
};
+4 -1
View File
@@ -1,10 +1,13 @@
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 { migration as m003 } from "./003-transactions";
import { migration as m004 } from "./004-attachments-reconciliation";
import type { Migration } from "./types";
/** Sıralı migration listesi. Yeni migration: dosyayı ekle ve buraya sırayla ekle. */
export const MIGRATIONS: Migration[] = [m001];
export const MIGRATIONS: Migration[] = [m001, m002, m003, m004];
const COLLECTION = "migrations";
+4 -2
View File
@@ -11,8 +11,10 @@ import { closeSeedConnections, runSeed } from "./seed/run";
async function main() {
const summary = await runSeed({ reset: process.argv.includes("--reset") });
const { users, households, memberships } = summary.created;
console.log(`\nOluşturulan: ${users} kullanıcı, ${households} hane, ${memberships} üyelik.`);
const { users, households, memberships, categories, accounts, transactions } = summary.created;
console.log(
`\nOluşturulan: ${users} kullanıcı, ${households} hane, ${memberships} üyelik, ${categories} kategori, ${accounts} hesap, ${transactions} işlem.`,
);
// Hesap tablosu yalnızca geliştirme ortamında gösterilir.
if (env().NODE_ENV !== "production" && summary.accounts.length) {
+96
View File
@@ -1,4 +1,6 @@
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";
/** Ö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",
},
];
+12 -2
View File
@@ -24,18 +24,28 @@ describe("seed", () => {
it("ilk çalıştırmada admin, örnek kullanıcılar, haneler ve üyelikleri oluşturur", async () => {
const summary = await runSeed({ log: silent });
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,
households: SEED_HOUSEHOLDS.length,
memberships: memberCount,
});
expect(summary.created.categories).toBeGreaterThan(40);
expect(summary.created.accounts).toBe(7);
expect(summary.created.transactions).toBeGreaterThan(150);
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
expect(await HouseholdMemberModel.countDocuments()).toBe(memberCount);
});
it("idempotenttir: ikinci çalıştırma kopya oluşturmaz", async () => {
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,
transactions: 0,
});
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
expect(await HouseholdModel.countDocuments()).toBe(SEED_HOUSEHOLDS.length);
});
+98 -5
View File
@@ -3,11 +3,21 @@ import { getAuth } from "@/lib/auth";
import { getDb } from "@/lib/db/mongo";
import { connectMongoose } from "@/lib/db/mongoose";
import { env } from "@/lib/env";
import { getStorage } from "@/lib/storage";
import { installDefaultCategories } from "@/features/categories/service";
import { AccountModel } from "@/models/account";
import { HouseholdModel } from "@/models/household";
import { HouseholdMemberModel } from "@/models/household-member";
import { storedEmail } from "@/shared/account-email";
import { runMigrations } from "../migrations";
import { ADMIN_USERNAME, SEED_HOUSEHOLDS, SEED_USERS, type SeedUser } from "./fixtures";
import { seedTransactions } from "./transactions";
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);
@@ -26,12 +36,29 @@ export type SeedAccountRow = {
};
export type SeedSummary = {
created: { users: number; households: number; memberships: number };
created: {
users: number;
households: number;
memberships: number;
categories: number;
accounts: number;
transactions: number;
};
accounts: SeedAccountRow[];
};
const AUTH_COLLECTIONS = ["user", "account", "session", "verification", "rateLimit"];
const DOMAIN_COLLECTIONS = ["households", "householdMembers", "auditLogs"];
const DOMAIN_COLLECTIONS = [
"households",
"householdMembers",
"auditLogs",
"categories",
"accounts",
"transactions",
"payees",
"attachments",
"reconciliations",
];
type AuthApi = ReturnType<typeof getAuth>["api"];
@@ -73,11 +100,26 @@ export async function runSeed({
const db = getDb();
await connectMongoose();
const summary: SeedSummary = {
created: { users: 0, households: 0, memberships: 0 },
created: {
users: 0,
households: 0,
memberships: 0,
categories: 0,
accounts: 0,
transactions: 0,
},
accounts: [],
};
if (reset) {
// Ek dosyaların diskteki kopyaları da silinsin (yetim dosya kalmasın).
const storage = getStorage();
for await (const a of db
.collection("attachments")
.find({}, { projection: { storageKey: 1, thumbKey: 1 } })) {
await storage.delete(String(a.storageKey));
if (a.thumbKey) await storage.delete(String(a.thumbKey));
}
for (const name of [...AUTH_COLLECTIONS, ...DOMAIN_COLLECTIONS]) {
await db.collection(name).deleteMany({});
}
@@ -180,7 +222,58 @@ 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) Son 6 ayın örnek işlemleri (faker.seed(42), idempotent)
const userIdMap = new Map([...ids.entries()]);
summary.created.transactions = await seedTransactions(householdIds, userIdMap);
if (summary.created.transactions) log(`✓ Örnek işlemler: ${summary.created.transactions}`);
// 7) Geliştirme hesapları tablosu
const all = [
{ username: ADMIN_USERNAME, name: "Yönetici", email: adminEmail, role: "admin" as const },
...SEED_USERS,
+496
View File
@@ -0,0 +1,496 @@
import { faker } from "@faker-js/faker";
import { Types } from "mongoose";
import { AccountModel } from "@/models/account";
import { CategoryModel } from "@/models/category";
import { PayeeModel } from "@/models/payee";
import { TransactionModel } from "@/models/transaction";
import { istanbulDayStart, todayIstanbul } from "@/shared/dates";
import { allocate } from "@/shared/money";
import { foldTr } from "@/shared/search";
import type { TransactionType } from "@/shared/transactions";
/**
* Son 6 ayın gerçekçi işlemleri (faker.seed(42) ile tekrarlanabilir).
* Her işlemin sabit `seedRef`'i vardır: tekrar çalıştırmada kopya oluşmaz.
*/
type Ctx = {
householdId: Types.ObjectId;
account: (name: string) => Types.ObjectId;
category: (key: string) => Types.ObjectId;
user: (username: string) => Types.ObjectId;
};
type SeedTx = {
ref: string;
type: TransactionType;
ymd: string;
amountMinor: number;
account: string;
toAccount?: string;
category?: string;
splits?: { category: string; weight: number; note?: string }[];
payee?: string;
description?: string;
tags?: string[];
by: string;
};
const tl = (min: number, max: number) => faker.number.int({ min: min * 100, max: max * 100 });
const pick = <T>(xs: readonly T[]) => faker.helpers.arrayElement(xs);
/** Ayın gün sayısına göre güvenli gün (31 → ayın son günü). */
function ymdOf(year: number, month: number, day: number) {
const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
return `${year}-${String(month).padStart(2, "0")}-${String(Math.min(day, last)).padStart(2, "0")}`;
}
function months(count: number): { y: number; m: number; key: string }[] {
const [ty, tm] = todayIstanbul().split("-").map(Number) as [number, number];
return Array.from({ length: count }, (_, i) => {
const d = new Date(Date.UTC(ty, tm - 1 - (count - 1 - i), 1));
const y = d.getUTCFullYear();
const m = d.getUTCMonth() + 1;
return { y, m, key: `${y}-${String(m).padStart(2, "0")}` };
});
}
function cakirAiles(): SeedTx[] {
const out: SeedTx[] = [];
const marketPayees = ["Migros", "BİM", "A101", "Şok", "CarrefourSA"] as const;
for (const { y, m, key } of months(6)) {
const winter = [11, 12, 1, 2, 3].includes(m);
const d = (day: number) => ymdOf(y, m, day);
const add = (x: Omit<SeedTx, "ref">, n = 0) =>
out.push({ ...x, ref: `cakir:${key}:${x.payee ?? x.category ?? x.type}:${n}` });
add({
type: "income",
ymd: d(15),
amountMinor: 52_000_00,
account: "Ziraat Maaş",
category: "maas",
payee: "Anadolu Yazılım A.Ş.",
by: "admin",
});
add({
type: "income",
ymd: d(1),
amountMinor: 4_500_00,
account: "Ayşe — Pluxee",
category: "yemek-karti",
payee: "Pluxee",
by: "ayse",
});
add({
type: "expense",
ymd: d(3),
amountMinor: 17_500_00,
account: "Ziraat Maaş",
category: "kira",
payee: "Ev sahibi",
description: "Kira",
by: "admin",
});
add({
type: "expense",
ymd: d(5),
amountMinor: 1_250_00,
account: "Ziraat Maaş",
category: "aidat",
payee: "Site yönetimi",
by: "admin",
});
add({
type: "expense",
ymd: d(10),
amountMinor: tl(750, 1_600),
account: "Ziraat Maaş",
category: "faturalar.elektrik",
payee: "Enerjisa",
by: "ayse",
});
add({
type: "expense",
ymd: d(12),
amountMinor: tl(300, 620),
account: "Ziraat Maaş",
category: "faturalar.su",
payee: "İSKİ",
by: "ayse",
});
add({
type: "expense",
ymd: d(14),
amountMinor: winter ? tl(1_800, 3_400) : tl(350, 700),
account: "Ziraat Maaş",
category: "faturalar.dogalgaz",
payee: "İGDAŞ",
by: "ayse",
});
add({
type: "expense",
ymd: d(20),
amountMinor: 499_90,
account: "Garanti Bonus",
category: "faturalar.internet",
payee: "Türk Telekom",
by: "admin",
});
add({
type: "expense",
ymd: d(22),
amountMinor: 714_00,
account: "Garanti Bonus",
category: "faturalar.telefon",
payee: "Turkcell",
description: "2 hat",
by: "admin",
});
add({
type: "expense",
ymd: d(8),
amountMinor: 229_99,
account: "Garanti Bonus",
category: "abonelikler",
payee: "Netflix",
by: "admin",
});
add({
type: "expense",
ymd: d(9),
amountMinor: 99_99,
account: "Garanti Bonus",
category: "abonelikler",
payee: "Spotify",
by: "emre",
});
// Transferler: nakit çekme, kart ödemesi, birikim.
add({
type: "transfer",
ymd: d(2),
amountMinor: 2_000_00,
account: "Ziraat Maaş",
toAccount: "Cüzdan",
description: "ATM",
by: "admin",
});
add({
type: "transfer",
ymd: d(9),
amountMinor: tl(11_000, 15_000),
account: "Ziraat Maaş",
toAccount: "Garanti Bonus",
description: "Kart borcu ödemesi",
by: "admin",
});
add({
type: "transfer",
ymd: d(16),
amountMinor: 5_000_00,
account: "Ziraat Maaş",
toAccount: "Birikim (Vadeli)",
description: "Aylık birikim",
by: "ayse",
});
// Market: haftada 1–2; bir kısmı bölünmüş.
const marketCount = faker.number.int({ min: 6, max: 8 });
for (let i = 0; i < marketCount; i++) {
const payee = pick(marketPayees);
const amountMinor = tl(280, 2_600);
const split = amountMinor > 1_200_00 && faker.datatype.boolean({ probability: 0.5 });
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor,
account: pick(["Garanti Bonus", "Garanti Bonus", "Cüzdan"]),
...(split
? {
splits: [
{ category: "market.gida", weight: faker.number.int({ min: 55, max: 75 }) },
{
category: "market.temizlik",
weight: faker.number.int({ min: 10, max: 25 }),
note: "Deterjan",
},
{
category: "market.kisisel-bakim",
weight: faker.number.int({ min: 5, max: 15 }),
},
],
}
: { category: "market.gida" }),
payee,
tags: faker.datatype.boolean({ probability: 0.15 }) ? ["indirim"] : [],
by: pick(["ayse", "ayse", "admin", "emre"]),
},
i,
);
}
for (let i = 0; i < faker.number.int({ min: 2, max: 3 }); i++) {
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(1_200, 2_300),
account: "Garanti Bonus",
category: "ulasim.yakit",
payee: pick(["Shell", "Opet", "BP"]),
by: "admin",
},
i,
);
}
for (let i = 0; i < faker.number.int({ min: 4, max: 6 }); i++) {
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(110, 340),
account: "Ayşe — Pluxee",
category: "eglence.kafe",
payee: pick(["Starbucks", "Kahve Dünyası", "Simit Sarayı"]),
by: "ayse",
},
i,
);
}
for (let i = 0; i < faker.number.int({ min: 2, max: 4 }); i++) {
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(450, 1_600),
account: pick(["Garanti Bonus", "Ayşe — Pluxee"]),
category: "eglence.disarida-yemek",
payee: pick(["Köfteci Yusuf", "Nusr-Et", "Big Chefs", "Yemeksepeti"]),
by: pick(["ayse", "admin"]),
},
i,
);
}
for (let i = 0; i < 4; i++) {
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(60, 220),
account: "Cüzdan",
category: "ulasim.toplu-tasima",
payee: "İstanbulkart",
by: "emre",
},
i,
);
}
if (faker.datatype.boolean({ probability: 0.6 })) {
add({
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(140, 650),
account: "Cüzdan",
category: "saglik.ilac",
payee: "Eczane",
by: "ayse",
});
}
if (faker.datatype.boolean({ probability: 0.5 })) {
add({
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(600, 3_200),
account: "Garanti Bonus",
category: "giyim",
payee: pick(["LC Waikiki", "Trendyol", "Koton"]),
by: "ayse",
});
}
}
return out;
}
function annemler(): SeedTx[] {
const out: SeedTx[] = [];
for (const { y, m, key } of months(6)) {
const winter = [11, 12, 1, 2, 3].includes(m);
const d = (day: number) => ymdOf(y, m, day);
const add = (x: Omit<SeedTx, "ref">, n = 0) =>
out.push({ ...x, ref: `annemler:${key}:${x.payee ?? x.category ?? x.type}:${n}` });
add({
type: "income",
ymd: d(17),
amountMinor: 24_350_00,
account: "Vakıfbank Emekli",
category: "maas",
payee: "SGK",
description: "Emekli maaşı",
by: "fatma",
});
add({
type: "expense",
ymd: d(11),
amountMinor: tl(450, 900),
account: "Vakıfbank Emekli",
category: "faturalar.elektrik",
payee: "Enerjisa",
by: "mehmet",
});
add({
type: "expense",
ymd: d(13),
amountMinor: winter ? tl(1_400, 2_600) : tl(250, 500),
account: "Vakıfbank Emekli",
category: "faturalar.dogalgaz",
payee: "İGDAŞ",
by: "mehmet",
});
add({
type: "transfer",
ymd: d(18),
amountMinor: 4_000_00,
account: "Vakıfbank Emekli",
toAccount: "Nakit",
description: "ATM",
by: "fatma",
});
for (let i = 0; i < 5; i++) {
add(
{
type: "expense",
ymd: d(faker.number.int({ min: 1, max: 28 })),
amountMinor: tl(200, 1_100),
account: pick(["Nakit", "Vakıfbank Emekli"]),
category: "market.gida",
payee: pick(["BİM", "Şok", "Pazar"]),
by: pick(["fatma", "mehmet"]),
},
i,
);
}
}
return out;
}
export async function seedTransactions(
householdIds: Map<string, Types.ObjectId>,
userIds: Map<string, string>,
): Promise<number> {
faker.seed(42);
let inserted = 0;
const plan: [string, SeedTx[]][] = [
["Çakır Ailesi", cakirAiles()],
["Annemler", annemler()],
];
const today = todayIstanbul();
for (const [householdName, txs] of plan) {
const householdId = householdIds.get(householdName)!;
const [accounts, categories] = await Promise.all([
AccountModel.find({ householdId }).select({ name: 1 }).lean(),
CategoryModel.find({ householdId, defaultKey: { $ne: null } })
.select({ defaultKey: 1 })
.lean(),
]);
const ctx: Ctx = {
householdId,
account: (name) => accounts.find((a) => a.name === name)!._id,
category: (key) => categories.find((c) => c.defaultKey === key)!._id,
user: (username) => new Types.ObjectId(userIds.get(username)!),
};
const payeeStats = new Map<
string,
{
name: string;
type: TransactionType;
account: Types.ObjectId;
category: Types.ObjectId | null;
count: number;
last: Date;
}
>();
for (const x of txs) {
if (x.ymd > today) continue; // Gelecek tarihli seed işlemi yok.
const date = istanbulDayStart(x.ymd)!;
const splits = x.splits
? allocate(
x.amountMinor,
x.splits.map((s) => s.weight),
).map((amountMinor, i) => ({
categoryId: ctx.category(x.splits![i]!.category),
amountMinor,
note: x.splits![i]!.note ?? "",
}))
: [];
const categoryId = x.category ? ctx.category(x.category) : null;
const accountId = ctx.account(x.account);
const by = ctx.user(x.by);
const doc = {
householdId,
type: x.type,
status: "posted",
date,
accountId,
toAccountId: x.toAccount ? ctx.account(x.toAccount) : null,
amountMinor: x.amountMinor,
categoryId: splits.length ? null : categoryId,
splits,
effectiveCategoryIds: splits.length
? [...new Set(splits.map((s) => String(s.categoryId)))].map(
(id) => new Types.ObjectId(id),
)
: categoryId
? [categoryId]
: [],
payeeName: x.payee ?? "",
description: x.description ?? "",
searchText: foldTr(
[x.payee ?? "", x.description ?? "", ...splits.map((s) => s.note)].join(" "),
),
tags: x.tags ?? [],
seedRef: x.ref,
createdBy: by,
updatedBy: by,
};
const res = await TransactionModel.updateOne(
{ householdId, seedRef: x.ref },
{ $setOnInsert: doc },
{ upsert: true },
);
if (res.upsertedCount) inserted++;
if (x.payee) {
const key = foldTr(x.payee);
const prev = payeeStats.get(key);
const latest = !prev || date >= prev.last;
payeeStats.set(key, {
name: x.payee,
type: latest ? x.type : prev!.type,
account: latest ? accountId : prev!.account,
category: latest ? (splits.length ? null : categoryId) : prev!.category,
count: (prev?.count ?? 0) + 1,
last: latest ? date : prev!.last,
});
}
}
for (const [nameKey, p] of payeeStats) {
await PayeeModel.updateOne(
{ householdId, nameKey },
{
$setOnInsert: { householdId, nameKey, name: p.name },
$set: {
lastType: p.type,
lastAccountId: p.account,
lastCategoryId: p.category,
useCount: p.count,
lastUsedAt: p.last,
},
},
{ upsert: true },
);
}
}
return inserted;
}
+31
View File
@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { hasHouseholdRole } from "@/features/households/roles";
import { StatementView } from "@/features/transactions/components/statement-view";
import { currentMonth, getAccountStatement } from "@/features/transactions/statement";
import { tr } from "@/i18n/tr";
import { requireActiveHousehold } from "@/lib/dal";
import { MONTH_PATTERN } from "@/shared/statement";
export const metadata: Metadata = { title: tr.statement.title };
/** /hesaplar/:id?ay=2026-11 — aylık hesap ekstresi (yürüyen bakiye) ve mutabakat. */
export default async function AccountStatementPage({
params,
searchParams,
}: PageProps<"/hesaplar/[id]">) {
const { user, household } = await requireActiveHousehold("viewer");
const [{ id }, sp] = await Promise.all([params, searchParams]);
const now = currentMonth();
const requested = typeof sp.ay === "string" && MONTH_PATTERN.test(sp.ay) ? sp.ay : now;
const month = requested > now ? now : requested;
const statement = await getAccountStatement(user.id, household.id, id, month);
if (!statement) notFound();
return (
<StatementView
key={`${id}-${month}`}
statement={statement}
canWrite={hasHouseholdRole(household.role, "member")}
/>
);
}
+29
View File
@@ -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,44 @@
import { exportTransactions } from "@/features/transactions/service";
import { tr } from "@/i18n/tr";
import { getHouseholdContext } from "@/lib/dal";
import { csvMoney, toCsv } from "@/shared/csv";
import { todayIstanbul } from "@/shared/dates";
import { formatDate } from "@/shared/format";
import { transactionFilterSchema } from "@/shared/schemas/transaction";
/** GET /islemler/disa-aktar?…filtreler → CSV (listedeki filtrelerle, sayfalama yok). */
export async function GET(request: Request) {
const ctx = await getHouseholdContext();
if (!ctx?.household) return new Response(tr.common.unauthorized, { status: 401 });
const params = Object.fromEntries(new URL(request.url).searchParams);
const filters = transactionFilterSchema.parse(params);
const rows = await exportTransactions(ctx.user.id, ctx.household.id, filters);
if (!rows) return new Response(tr.common.unauthorized, { status: 403 });
const t = tr.transactions;
const csv = toCsv(
t.csv.header,
rows.map((r) => [
r.no,
formatDate(`${r.date}T12:00:00+03:00`),
t.types[r.type],
t.statuses[r.status],
r.account,
r.toAccount,
r.category,
r.payee,
r.description,
r.note,
r.tags,
csvMoney(r.amountMinor),
r.createdBy,
]),
);
return new Response(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="${t.csv.filename(todayIstanbul())}"`,
"Cache-Control": "no-store",
},
});
}
+44
View File
@@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/page-header";
import { listMemberOptions } from "@/features/accounts/service";
import { hasHouseholdRole } from "@/features/households/roles";
import { TransactionsView } from "@/features/transactions/components/transactions-view";
import { getTransactionFormOptions, listTransactions } from "@/features/transactions/service";
import { tr } from "@/i18n/tr";
import { requireActiveHousehold } from "@/lib/dal";
import { transactionFilterSchema } from "@/shared/schemas/transaction";
export const metadata: Metadata = { title: tr.transactions.title };
export default async function TransactionsPage({ searchParams }: PageProps<"/islemler">) {
const { user, household } = await requireActiveHousehold("viewer");
const params = await searchParams;
// Yalnızca tekil string değerler (dizi parametreleri yok sayılır).
const raw = Object.fromEntries(
Object.entries(params).filter(
(e): e is [string, string] => typeof e[1] === "string" && e[1] !== "",
),
);
const filters = transactionFilterSchema.parse(raw);
const [data, options, members] = await Promise.all([
listTransactions(user.id, household.id, filters),
getTransactionFormOptions(user.id, household.id),
listMemberOptions(user.id, household.id),
]);
if (!data || !options || !members) notFound();
return (
<>
<PageHeader title={tr.transactions.title} description={tr.transactions.description} />
<TransactionsView
// Filtre değişince istemci durumu (açık diyaloglar) sıfırlansın.
key={JSON.stringify(raw)}
data={data}
filters={filters}
raw={raw}
options={{ ...options, members }}
canWrite={hasHouseholdRole(household.role, "member")}
/>
</>
);
}
+25
View File
@@ -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")}
/>
</>
);
}
+49
View File
@@ -0,0 +1,49 @@
import type { NextRequest } from "next/server";
import { readAttachmentForUser } from "@/features/attachments/service";
import { getCurrentUser } from "@/lib/dal";
/**
* GET /api/files/:id[?v=thumb][&indir=1] — oturum ve hane yetkisi kontrol edilerek ek dosyayı
* servis eder. Erişim yoksa (başka hane, gizli hesap, silinmiş kayıt) 404: varlık sızdırılmaz.
*/
export async function GET(request: NextRequest, ctx: RouteContext<"/api/files/[id]">) {
const user = await getCurrentUser();
if (!user) return new Response(null, { status: 401 });
const { id } = await ctx.params;
const params = request.nextUrl.searchParams;
const file = await readAttachmentForUser(
user.id,
id,
params.get("v") === "thumb" ? "thumb" : "full",
);
if (!file) return new Response(null, { status: 404 });
const disposition = params.get("indir") === "1" ? "attachment" : "inline";
const fallbackName = file.mimeType === "application/pdf" ? "belge.pdf" : "gorsel.webp";
const name = toServedName(file.name || fallbackName, file.mimeType);
return new Response(new Uint8Array(file.bytes), {
headers: {
"Content-Type": file.mimeType,
"Content-Length": String(file.bytes.length),
"Content-Disposition": `${disposition}; filename="${asciiName(name)}"; filename*=UTF-8''${encodeURIComponent(name)}`,
// Yalnızca kullanıcının tarayıcısında; paylaşılan önbelleklere girmez.
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
/** Görseller WebP'ye çevrildiği için indirilen adın uzantısı içerikle uyumlu olsun. */
function toServedName(name: string, mimeType: string): string {
const ext = mimeType === "application/pdf" ? ".pdf" : ".webp";
return name.replace(/\.[a-z0-9]{1,5}$/i, "") + ext;
}
function asciiName(name: string): string {
return (
name
.normalize("NFKD")
.replace(/[^\x20-\x7e]/g, "")
.replace(/["\\]/g, "") || "dosya"
);
}
+53
View File
@@ -0,0 +1,53 @@
import { uploadAttachment } from "@/features/attachments/service";
import { tr } from "@/i18n/tr";
import { fail } from "@/lib/action-result";
import { getHouseholdActionContext } from "@/lib/dal";
import { env } from "@/lib/env";
/** Multipart başlıkları için tolerans. */
const MULTIPART_OVERHEAD = 64 * 1024;
/**
* POST /api/files — tek dosya yükler (`file` alanı), aktif haneye bekleyen ek olarak kaydeder.
* Kayıt (ör. işlem) kaydedilirken ek kimlikleri gönderilir ve ek kayda bağlanır.
*/
export async function POST(request: Request) {
if (!isSameOrigin(request)) return Response.json(fail(tr.common.unauthorized), { status: 403 });
const ctx = await getHouseholdActionContext("member");
if (!ctx) return Response.json(fail(tr.common.unauthorized), { status: 401 });
const maxMb = env().MAX_UPLOAD_MB;
const length = Number(request.headers.get("content-length") ?? 0);
if (length > maxMb * 1024 * 1024 + MULTIPART_OVERHEAD) {
return Response.json(fail(tr.attachments.errors.tooLarge(maxMb)), { status: 413 });
}
let file: FormDataEntryValue | null;
try {
file = (await request.formData()).get("file");
} catch {
return Response.json(fail(tr.attachments.errors.invalid), { status: 400 });
}
if (!(file instanceof File)) {
return Response.json(fail(tr.attachments.errors.empty), { status: 400 });
}
const bytes = Buffer.from(await file.arrayBuffer());
const result = await uploadAttachment(ctx.user.id, ctx.household.id, { name: file.name, bytes });
return Response.json(result, { status: result.ok ? 201 : 400 });
}
/**
* CSRF savunması: tarayıcı isteğinde Origin varsa uygulamanın kendi host'u olmalı.
* (Oturum cookie'si SameSite=Lax; bu ek bir katman.)
*/
function isSameOrigin(request: Request): boolean {
const origin = request.headers.get("origin");
if (!origin) return true;
const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
try {
return new URL(origin).host === host;
} catch {
return false;
}
}
+29
View File
@@ -96,6 +96,21 @@
--chart-4: var(--warning);
--chart-5: oklch(0.65 0.08 230);
--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-foreground: oklch(0.22 0.04 262);
--sidebar-primary: oklch(0.49 0.17 258);
@@ -140,6 +155,20 @@
--chart-3: var(--expense);
--chart-4: var(--warning);
--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-foreground: oklch(0.96 0.01 250);
--sidebar-primary: oklch(0.76 0.12 245);
+108
View File
@@ -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} />;
}
+78
View File
@@ -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>
);
}
+33
View File
@@ -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>
);
}
+1 -1
View File
@@ -56,7 +56,7 @@ export function BottomNav({ canWrite }: { canWrite: boolean }) {
<div className="flex flex-1 items-center justify-center">
<button
type="button"
onClick={openQuickAdd}
onClick={() => openQuickAdd()}
disabled={!canWrite}
title={canWrite ? undefined : tr.households.viewerReadOnly}
aria-label={tr.quickAdd.button}
+10 -5
View File
@@ -8,6 +8,7 @@ import {
Package,
Settings,
ShoppingCart,
Tags,
Target,
UserCog,
Users,
@@ -25,14 +26,16 @@ export type NavItem = {
};
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
export const CURRENT_PHASE = 5;
/** Alt fazlar ondalıkla: 6.1 = Faz 6a. */
export const CURRENT_PHASE = 6.3;
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
export const MAIN_NAV: NavItem[] = [
{ href: "/dashboard", label: tr.nav.dashboard, icon: LayoutDashboard, phase: 2 },
{ href: "/islemler", label: tr.nav.transactions, icon: ArrowLeftRight, phase: 6 },
{ href: "/hesaplar", label: tr.nav.accounts, icon: Wallet, phase: 6 },
{ href: "/islemler", label: tr.nav.transactions, icon: ArrowLeftRight, phase: 6.2 },
{ 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: "/cari", label: tr.nav.contacts, icon: Users, phase: 8 },
{ 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). */
const navByHref = (href: string) => MAIN_NAV.find((i) => i.href === href)!;
export const BOTTOM_NAV = {
left: [MAIN_NAV[0]!, MAIN_NAV[1]!],
right: [MAIN_NAV[6]!],
left: [navByHref("/dashboard"), navByHref("/islemler")],
right: [navByHref("/butce")],
};
export function isActivePath(pathname: string, href: string) {
+21 -72
View File
@@ -1,16 +1,22 @@
"use client";
import { ArrowDownLeft, ArrowLeftRight, ArrowUpRight, Plus } from "lucide-react";
import { Plus } from "lucide-react";
import { createContext, use, useState } from "react";
import { toast } from "sonner";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Button } from "@/components/ui/button";
import {
TransactionFormDialog,
type TransactionFormMode,
} from "@/features/transactions/components/transaction-form";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
type QuickAddKind = "expense" | "income" | "transfer";
type QuickAddApi = {
/** Hızlı ekle: yeni işlem formu (varsayılan gider; sekmelerle gelir/transfer). */
openQuickAdd: (type?: "expense" | "income" | "transfer") => void;
/** Düzenle / kopyala (işlem listesi ve ayrıntısı). */
openTransactionForm: (mode: TransactionFormMode) => void;
};
const QuickAddContext = createContext<{ openQuickAdd: () => void } | null>(null);
const QuickAddContext = createContext<QuickAddApi | null>(null);
export function useQuickAdd() {
const ctx = use(QuickAddContext);
@@ -18,74 +24,17 @@ export function useQuickAdd() {
return ctx;
}
const CHOICES: {
kind: QuickAddKind;
label: string;
hint: string;
icon: typeof Plus;
tone: string;
}[] = [
{
kind: "expense",
label: tr.quickAdd.expense,
hint: tr.quickAdd.expenseHint,
icon: ArrowUpRight,
tone: "text-expense bg-expense/10",
},
{
kind: "income",
label: tr.quickAdd.income,
hint: tr.quickAdd.incomeHint,
icon: ArrowDownLeft,
tone: "text-income bg-income/10",
},
{
kind: "transfer",
label: tr.quickAdd.transfer,
hint: tr.quickAdd.transferHint,
icon: ArrowLeftRight,
tone: "text-budget bg-budget/10",
},
];
/** Hızlı ekle (gider / gelir / transfer) — her ekrandan açılabilir. */
/** Uygulama genelinde tek işlem formu; her ekrandan açılabilir (Bölüm 4). */
export function QuickAddProvider({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
function choose(kind: QuickAddKind) {
setOpen(false);
// FAZ 6: ilgili işlem formu açılacak.
toast.info(`${CHOICES.find((c) => c.kind === kind)?.label}: ${tr.quickAdd.notYet}`);
}
const [mode, setMode] = useState<TransactionFormMode | null>(null);
const api: QuickAddApi = {
openQuickAdd: (type = "expense") => setMode({ kind: "create", type }),
openTransactionForm: setMode,
};
return (
<QuickAddContext value={{ openQuickAdd: () => setOpen(true) }}>
<QuickAddContext value={api}>
{children}
<ResponsiveDialog
open={open}
onOpenChange={setOpen}
title={tr.quickAdd.title}
description={tr.quickAdd.description}
>
<div className="grid gap-2 pb-2 sm:grid-cols-3">
{CHOICES.map(({ kind, label, hint, icon: Icon, tone }) => (
<button
key={kind}
type="button"
onClick={() => choose(kind)}
className="flex items-center gap-3 rounded-xl border p-4 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 sm:flex-col sm:text-center"
>
<span className={cn("flex size-10 items-center justify-center rounded-full", tone)}>
<Icon className="size-5" />
</span>
<span className="flex flex-col">
<span className="font-medium">{label}</span>
<span className="text-xs text-muted-foreground">{hint}</span>
</span>
</button>
))}
</div>
</ResponsiveDialog>
<TransactionFormDialog mode={mode} onOpenChange={(open) => !open && setMode(null)} />
</QuickAddContext>
);
}
@@ -94,7 +43,7 @@ export function QuickAddProvider({ children }: { children: React.ReactNode }) {
export function QuickAddButton({ className }: { className?: string }) {
const { openQuickAdd } = useQuickAdd();
return (
<Button onClick={openQuickAdd} className={className}>
<Button onClick={() => openQuickAdd()} className={className}>
<Plus />
{tr.quickAdd.button}
</Button>
+49
View File
@@ -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>
);
}
+242
View File
@@ -0,0 +1,242 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react";
import { Button } from "@/components/ui/button";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return;
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) return;
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) return;
// İlk durum bir sonraki karede okunur (effect içinde senkron setState yapılmaz).
const frame = requestAnimationFrame(() => onSelect(api));
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
cancelAnimationFrame(frame);
api.off("select", onSelect);
api.off("reInit", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
function CarouselContent({
className,
containerClassName,
...props
}: React.ComponentProps<"div"> & { containerClassName?: string }) {
const { carouselRef, orientation } = useCarousel();
return (
<div
ref={carouselRef}
className={cn("overflow-hidden", containerClassName)}
data-slot="carousel-content"
>
<div
className={cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
{...props}
/>
</div>
);
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon-sm",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute touch-manipulation rounded-full",
orientation === "horizontal"
? "inset-y-0 -left-12 my-auto"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ChevronLeftIcon />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({
className,
variant = "outline",
size = "icon-sm",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute touch-manipulation rounded-full",
orientation === "horizontal"
? "inset-y-0 -right-12 my-auto"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ChevronRightIcon />
<span className="sr-only">Next slide</span>
</Button>
);
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
useCarousel,
};
+75
View File
@@ -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,323 @@
"use client";
import {
Archive,
ArchiveRestore,
ArrowDown,
ArrowUp,
ChevronDown,
EyeOff,
MoreHorizontal,
Pencil,
Plus,
} from "lucide-react";
import Link from "next/link";
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">
{/* Gizli hesabın ekstresi yalnızca sahibine açılır. */}
{a.balanceMinor === null ? (
<span className="block truncate font-medium">{a.name}</span>
) : (
<Link href={`/hesaplar/${a.id}`} className="block truncate font-medium hover:underline">
{a.name}
</Link>
)}
<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>
);
}
+161
View File
@@ -0,0 +1,161 @@
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",
)!;
// Hesap sahibi açılış ve güncel bakiyeyi görür (güncel = açılış + işlemler).
expect((await find("ayse")).openingBalanceMinor).toBe(3_120_00);
expect((await find("ayse")).balanceMinor).not.toBeNull();
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);
const pluxee = (await listAccounts(ids.user("ayse"), cakir))!.accounts.find(
(a) => a.name === "Ayşe — Pluxee",
)!;
expect(withHidden.assetsMinor - without.assetsMinor).toBe(pluxee.balanceMinor);
// 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);
});
});
+380
View File
@@ -0,0 +1,380 @@
import "server-only";
import { Types } from "mongoose";
import { getHouseholdDetail, resolveMembership } from "@/features/households/service";
import { computeAccountDeltas } from "@/features/transactions/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;
/** Güncel bakiye = açılış bakiyesi + gerçekleşmiş işlemlerin etkisi (tek doğruluk kaynağı: işlemler). */
function computeBalance(a: Lean, deltas: ReadonlyMap<string, number>): number {
return a.openingBalanceMinor + (deltas.get(String(a._id)) ?? 0);
}
function toView(a: Lean, viewerId: string, deltas: ReadonlyMap<string, number>): 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, deltas) : 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, deltas] = await Promise.all([
HouseholdModel.findById(m.householdId).select({ settings: 1 }).lean(),
computeAccountDeltas(m.householdId),
]);
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, deltas);
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, deltas)), 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,168 @@
"use client";
import { Loader2, Paperclip, X } from "lucide-react";
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { tr } from "@/i18n/tr";
import type { ActionResult } from "@/lib/action-result";
import { cn } from "@/lib/utils";
import {
acceptAttribute,
MAX_ATTACHMENTS_PER_RECORD,
type AttachmentKind,
} from "@/shared/attachments";
import type { AttachmentInfo } from "../service";
import { AttachmentThumb } from "./attachment-strip";
import { AttachmentViewer } from "./attachment-viewer";
const t = tr.attachments;
/** Tek dosyayı /api/files'a yükler. */
async function uploadFile(file: File): Promise<ActionResult<AttachmentInfo>> {
const body = new FormData();
body.append("file", file);
try {
const res = await fetch("/api/files", { method: "POST", body });
return (await res.json()) as ActionResult<AttachmentInfo>;
} catch {
return { ok: false, error: t.errors.upload };
}
}
/**
* Formdaki küçük "Ek ekle" alanı (Bölüm 6.3): seçilen dosyalar hemen yüklenir (bekleyen ek),
* küçük önizleme ve sayaç gösterilir; kayıt kaydedilince ekler kayda bağlanır.
*/
export function AttachmentPicker({
value,
onChange,
allowedKinds,
onBusyChange,
}: {
value: AttachmentInfo[];
onChange: (items: AttachmentInfo[]) => void;
allowedKinds: readonly AttachmentKind[];
onBusyChange?: (busy: boolean) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(0);
const [errors, setErrors] = useState<string[]>([]);
const [viewer, setViewer] = useState<number | null>(null);
const invalid = value.filter((a) => !allowedKinds.includes(a.kind));
const room = MAX_ATTACHMENTS_PER_RECORD - value.length;
async function onFiles(files: FileList | null) {
if (!files?.length) return;
const list = [...files];
const accepted = list.slice(0, Math.max(0, room));
const nextErrors: string[] = [];
if (list.length > accepted.length)
nextErrors.push(t.errors.tooMany(MAX_ATTACHMENTS_PER_RECORD));
setUploading(accepted.length);
onBusyChange?.(true);
let items = value;
for (const file of accepted) {
const result = await uploadFile(file);
if (result.ok) {
items = [...items, result.data];
onChange(items);
} else {
nextErrors.push(`${file.name}: ${result.error}`);
}
setUploading((n) => n - 1);
}
setErrors(nextErrors);
onBusyChange?.(false);
if (inputRef.current) inputRef.current.value = "";
}
function remove(id: string) {
onChange(value.filter((a) => a.id !== id));
}
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => inputRef.current?.click()}
disabled={room <= 0 || uploading > 0}
>
{uploading > 0 ? <Loader2 className="animate-spin" /> : <Paperclip />}
{uploading > 0 ? t.uploading : t.add}
</Button>
<span className="text-xs text-muted-foreground">
{value.length
? t.count(value.length)
: allowedKinds.includes("pdf")
? t.addHint.imagePdf
: t.addHint.image}
</span>
<input
ref={inputRef}
type="file"
multiple
accept={acceptAttribute(allowedKinds)}
className="sr-only"
tabIndex={-1}
aria-label={t.add}
onChange={(e) => onFiles(e.target.files)}
/>
</div>
{value.length || uploading ? (
<ul className="flex flex-wrap gap-1.5">
{value.map((item, i) => (
<li key={item.id} className="relative">
<AttachmentThumb
item={item}
className={cn(
"size-10",
!allowedKinds.includes(item.kind) && "border-destructive ring-1 ring-destructive",
)}
onClick={() => setViewer(i)}
/>
<button
type="button"
onClick={() => remove(item.id)}
className="absolute -top-1.5 -right-1.5 flex size-5 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm hover:text-foreground"
aria-label={`${t.remove}: ${item.name}`}
>
<X className="size-3" />
</button>
</li>
))}
{Array.from({ length: uploading }, (_, i) => (
<li
key={`up-${i}`}
className="flex size-10 items-center justify-center rounded-md border border-dashed"
aria-label={t.uploading}
>
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</li>
))}
</ul>
) : null}
{invalid.length ? (
<p className="text-xs text-destructive" role="alert">
{t.errors.kindNotAllowed}
</p>
) : null}
{errors.map((e) => (
<p key={e} className="text-xs text-destructive" role="alert">
{e}
</p>
))}
<AttachmentViewer
items={value}
startIndex={viewer ?? 0}
open={viewer !== null}
onOpenChange={(open) => !open && setViewer(null)}
/>
</div>
);
}
@@ -0,0 +1,75 @@
"use client";
import { FileText, Paperclip } from "lucide-react";
import { useState } from "react";
import { tr } from "@/i18n/tr";
import type { AttachmentInfo } from "../service";
import { AttachmentViewer } from "./attachment-viewer";
const t = tr.attachments;
const VISIBLE = 4;
/** Ayrıntıda küçük önizleme şeridi (en fazla 4 + "+N"); tıklayınca görüntüleyici açılır. */
export function AttachmentStrip({ items }: { items: AttachmentInfo[] }) {
const [viewer, setViewer] = useState<number | null>(null);
if (!items.length) return null;
const shown = items.slice(0, VISIBLE);
const rest = items.length - shown.length;
return (
<div className="flex items-center gap-2">
<Paperclip className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="sr-only">{t.count(items.length)}</span>
<ul className="flex gap-1.5">
{shown.map((item, i) => (
<li key={item.id} className="relative">
<AttachmentThumb item={item} onClick={() => setViewer(i)} />
{rest > 0 && i === shown.length - 1 ? (
<button
type="button"
onClick={() => setViewer(i + 1)}
className="absolute inset-0 flex items-center justify-center rounded-md bg-black/55 text-sm font-medium text-white"
aria-label={`${t.viewerTitle}: ${t.moreCount(rest)}`}
>
{t.moreCount(rest)}
</button>
) : null}
</li>
))}
</ul>
<AttachmentViewer
items={items}
startIndex={viewer ?? 0}
open={viewer !== null}
onOpenChange={(open) => !open && setViewer(null)}
/>
</div>
);
}
export function AttachmentThumb({
item,
onClick,
className = "size-12",
}: {
item: AttachmentInfo;
onClick?: () => void;
className?: string;
}) {
return (
<button
type="button"
onClick={onClick}
title={item.name}
aria-label={item.name}
className={`${className} flex items-center justify-center overflow-hidden rounded-md border bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none`}
>
{item.thumbUrl ? (
// eslint-disable-next-line @next/next/no-img-element -- yetkili özel dosya
<img src={item.thumbUrl} alt="" className="size-full object-cover" loading="lazy" />
) : (
<FileText className="size-5 text-muted-foreground" aria-hidden />
)}
</button>
);
}
@@ -0,0 +1,170 @@
"use client";
import { Download, ExternalLink, FileText, Maximize, Minimize } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
type CarouselApi,
} from "@/components/ui/carousel";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { tr } from "@/i18n/tr";
import { formatFileSize } from "@/shared/attachments";
import type { AttachmentInfo } from "../service";
const t = tr.attachments;
/**
* Ek dosya görüntüleyici (Bölüm 6.3): carousel (oklar, kaydırma, klavye okları), tam ekran ve
* "2 / 5" göstergesi. PDF'ler ikon + "Aç" düğmesiyle gösterilir (tarayıcının PDF görüntüleyicisi).
*/
export function AttachmentViewer({
items,
startIndex,
open,
onOpenChange,
}: {
items: AttachmentInfo[];
startIndex: number;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [api, setApi] = useState<CarouselApi>();
const [index, setIndex] = useState(startIndex);
const [fullscreen, setFullscreen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!api) return;
const update = () => setIndex(api.selectedScrollSnap());
api.on("select", update);
api.on("reInit", update);
return () => {
api.off("select", update);
api.off("reInit", update);
};
}, [api]);
useEffect(() => {
const onChange = () => setFullscreen(document.fullscreenElement === containerRef.current);
document.addEventListener("fullscreenchange", onChange);
return () => document.removeEventListener("fullscreenchange", onChange);
}, []);
function handleOpenChange(next: boolean) {
if (!next && document.fullscreenElement) void document.exitFullscreen();
if (next) setIndex(startIndex);
onOpenChange(next);
}
async function toggleFullscreen() {
if (document.fullscreenElement) await document.exitFullscreen();
else await containerRef.current?.requestFullscreen().catch(() => {});
}
/** Odak carousel dışındayken de (ör. kapat düğmesi) ok tuşları çalışsın. */
function onKeyDown(event: React.KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.key === "ArrowLeft") {
event.preventDefault();
api?.scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
api?.scrollNext();
}
}
const current = items[Math.min(index, items.length - 1)];
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
className="flex h-[min(90dvh,900px)] w-[calc(100vw-1rem)] max-w-5xl flex-col gap-0 p-0 sm:max-w-5xl"
onKeyDown={onKeyDown}
>
<div ref={containerRef} className="flex min-h-0 flex-1 flex-col bg-background">
<div className="flex items-center gap-2 border-b px-3 py-2 pr-12">
<DialogTitle className="min-w-0 flex-1 truncate text-sm">
{current?.name ?? t.viewerTitle}
</DialogTitle>
<DialogDescription className="sr-only">{t.viewerTitle}</DialogDescription>
<span
className="shrink-0 text-xs text-muted-foreground tabular-nums"
aria-live="polite"
>
{t.position(index + 1, items.length)}
</span>
{current ? (
<Button asChild variant="ghost" size="icon-sm" aria-label={t.download}>
<a href={`${current.url}?indir=1`} download>
<Download />
</a>
</Button>
) : null}
<Button
variant="ghost"
size="icon-sm"
onClick={toggleFullscreen}
aria-label={fullscreen ? t.exitFullscreen : t.fullscreen}
>
{fullscreen ? <Minimize /> : <Maximize />}
</Button>
</div>
<Carousel
setApi={setApi}
opts={{ startIndex, loop: false }}
className="flex min-h-0 flex-1 flex-col"
aria-label={t.viewerTitle}
>
<CarouselContent className="h-full" containerClassName="h-full min-h-0 flex-1">
{items.map((item) => (
<CarouselItem
key={item.id}
className="flex h-full items-center justify-center p-4 pl-8"
>
{item.kind === "image" ? (
// eslint-disable-next-line @next/next/no-img-element -- yetkili özel dosya; optimizasyon hattına girmez
<img
src={item.url}
alt={item.name}
width={item.width ?? undefined}
height={item.height ?? undefined}
className="max-h-full max-w-full rounded-md object-contain"
draggable={false}
/>
) : (
<div className="flex flex-col items-center gap-3 text-center">
<FileText className="size-16 text-muted-foreground" aria-hidden />
<div>
<p className="font-medium break-all">{item.name}</p>
<p className="text-sm text-muted-foreground">
{t.pdf} · {formatFileSize(item.size)}
</p>
</div>
<Button asChild>
<a href={item.url} target="_blank" rel="noopener">
<ExternalLink />
{t.open}
</a>
</Button>
</div>
)}
</CarouselItem>
))}
</CarouselContent>
{items.length > 1 ? (
<>
<CarouselPrevious className="left-3" aria-label={t.previous} />
<CarouselNext className="right-3" aria-label={t.next} />
</>
) : null}
</Carousel>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,326 @@
import { readFile, rm } from "node:fs/promises";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
getTransaction,
createTransaction,
updateTransaction,
setTransactionDeleted,
} from "@/features/transactions/service";
import { env } from "@/lib/env";
import { getStorage } from "@/lib/storage";
import { AccountModel } from "@/models/account";
import { AttachmentModel } from "@/models/attachment";
import { CategoryModel } from "@/models/category";
import { TransactionModel } from "@/models/transaction";
import type { TransactionForm } from "@/shared/schemas/transaction";
import { setupSeededDb, teardownDb } from "@/test/seeded-db";
import {
purgeAttachments,
readAttachmentForUser,
uploadAttachment,
type AttachmentInfo,
} from "./service";
let ids: Awaited<ReturnType<typeof setupSeededDb>>;
let cakir = "";
let annemler = "";
let ayse = "";
let emre = "";
let zeynep = "";
let fatma = "";
beforeAll(async () => {
await rm(env().UPLOAD_DIR, { recursive: true, force: true });
ids = await setupSeededDb();
cakir = ids.household("Çakır Ailesi");
annemler = ids.household("Annemler");
ayse = ids.user("ayse");
emre = ids.user("emre");
zeynep = ids.user("zeynep");
fatma = ids.user("fatma");
});
afterAll(async () => {
await teardownDb();
await rm(env().UPLOAD_DIR, { recursive: true, force: true });
});
const acc = (name: string, householdId = cakir) =>
AccountModel.findOne({ householdId, name })
.lean()
.then((a) => String(a!._id));
const cat = (key: string) =>
CategoryModel.findOne({ householdId: cakir, defaultKey: key })
.lean()
.then((c) => String(c!._id));
async function form(over: Partial<TransactionForm>): Promise<TransactionForm> {
return {
type: "expense",
amount: 100_00,
date: "2026-06-15",
accountId: await acc("Cüzdan"),
toAccountId: null,
categoryId: await cat("market"),
splits: [],
payee: "",
description: "",
tags: [],
attachmentIds: [],
...over,
};
}
const png = (w = 40, h = 30) =>
sharp({ create: { width: w, height: h, channels: 3, background: "#3366cc" } })
.png()
.toBuffer();
const pdf = Buffer.from("%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n", "latin1");
async function upload(userId: string, bytes: Buffer, name = "fis.png", householdId = cakir) {
const r = await uploadAttachment(userId, householdId, { name, bytes });
if (!r.ok) throw new Error(r.error);
return r.data;
}
describe("yükleme ve dönüştürme", () => {
it("JPEG: EXIF/GPS silinir, yön uygulanır, 2000 px'e küçültülür, WebP + küçük resim", async () => {
const jpeg = await sharp({
create: { width: 3000, height: 1200, channels: 3, background: "#cc3333" },
})
.jpeg()
.withMetadata({ orientation: 6 })
.withExif({ IFD0: { Copyright: "gizli", Artist: "Ayşe" } })
.toBuffer();
expect((await sharp(jpeg).metadata()).exif).toBeDefined();
const info = await upload(ayse, jpeg, "../../etc/fiş.JPG");
expect(info.kind).toBe("image");
expect(info.name).toBe("fiş.JPG");
// Yön 6 (90°): 3000x1200 → 1200x3000 → en fazla 2000: 800x2000
expect([info.width, info.height]).toEqual([800, 2000]);
const doc = await AttachmentModel.findById(info.id).lean();
expect(doc!.mimeType).toBe("image/webp");
expect(doc!.ownerId).toBeNull();
const stored = await getStorage().get(doc!.storageKey);
const meta = await sharp(stored!).metadata();
expect(meta.format).toBe("webp");
expect(meta.exif).toBeUndefined();
expect(meta.orientation).toBeUndefined();
const thumb = await sharp((await getStorage().get(doc!.thumbKey!))!).metadata();
expect(Math.max(thumb.width!, thumb.height!)).toBe(320);
});
it("PNG ve PDF kabul edilir; uzantıya değil içeriğe bakılır", async () => {
expect((await upload(ayse, await png(), "resim.pdf")).kind).toBe("image");
const p = await upload(ayse, pdf, "bordro.jpg");
expect(p.kind).toBe("pdf");
expect(p.thumbUrl).toBeNull();
});
it("desteklenmeyen, bozuk ve boş dosyalar reddedilir", async () => {
const text = await uploadAttachment(ayse, cakir, {
name: "fis.jpg",
bytes: Buffer.from("<script>alert(1)</script>"),
});
expect(text.ok).toBe(false);
const broken = await uploadAttachment(ayse, cakir, {
name: "x.jpg",
bytes: Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3, 4, 5, 6]),
});
expect(broken).toMatchObject({ ok: false });
const fakePdf = await uploadAttachment(ayse, cakir, {
name: "x.pdf",
bytes: Buffer.from("%PDF-1.4 yarım"),
});
expect(fakePdf.ok).toBe(false);
expect((await uploadAttachment(ayse, cakir, { name: "x", bytes: Buffer.alloc(0) })).ok).toBe(
false,
);
});
it("boyut sınırı uygulanır", async () => {
const big = Buffer.alloc(env().MAX_UPLOAD_MB * 1024 * 1024 + 1);
big.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
expect((await uploadAttachment(ayse, cakir, { name: "b.png", bytes: big })).ok).toBe(false);
});
it("izleyici ve hane dışı kullanıcı yükleyemez", async () => {
expect((await uploadAttachment(zeynep, cakir, { name: "a.png", bytes: await png() })).ok).toBe(
false,
);
expect((await uploadAttachment(fatma, cakir, { name: "a.png", bytes: await png() })).ok).toBe(
false,
);
});
it.skipIf(!process.env.HEIC_SAMPLE)("HEIC (iPhone) WebP'ye dönüştürülür", async () => {
const heic = await readFile(process.env.HEIC_SAMPLE!);
const info = await upload(ayse, heic, "IMG_0001.HEIC");
expect(info.kind).toBe("image");
const doc = await AttachmentModel.findById(info.id).lean();
expect(doc!.sourceType).toBe("heic");
expect((await sharp((await getStorage().get(doc!.storageKey))!).metadata()).format).toBe(
"webp",
);
});
});
describe("işleme bağlama", () => {
let a1: AttachmentInfo;
let a2: AttachmentInfo;
let a3: AttachmentInfo;
let txId = "";
it("gider işlemine görseller bağlanır, sıra korunur", async () => {
a1 = await upload(ayse, await png(10, 10));
a2 = await upload(ayse, await png(20, 10));
a3 = await upload(ayse, await png(30, 10));
const r = await createTransaction(
ayse,
cakir,
await form({ attachmentIds: [a2.id, a1.id, a3.id] }),
);
expect(r.ok).toBe(true);
txId = r.ok ? r.data.id : "";
const detail = await getTransaction(ayse, cakir, txId);
expect(detail!.attachmentCount).toBe(3);
expect(detail!.attachments.map((a) => a.id)).toEqual([a2.id, a1.id, a3.id]);
});
it("gider işlemine PDF eklenemez; gelirde eklenir; hata olursa işlem oluşmaz", async () => {
const p = await upload(ayse, pdf, "bordro.pdf");
const before = await TransactionModel.countDocuments({ householdId: cakir });
const bad = await createTransaction(ayse, cakir, await form({ attachmentIds: [p.id] }));
expect(bad).toMatchObject({ ok: false });
expect(await TransactionModel.countDocuments({ householdId: cakir })).toBe(before);
expect((await AttachmentModel.findById(p.id).lean())!.ownerId).toBeNull();
const good = await createTransaction(
ayse,
cakir,
await form({
type: "income",
categoryId: await cat("maas"),
accountId: await acc("Ziraat Maaş"),
attachmentIds: [p.id],
}),
);
expect(good.ok).toBe(true);
});
it("başkasının bekleyen eki, başka hanenin eki veya başka işlemin eki bağlanamaz", async () => {
const emres = await upload(emre, await png());
expect(
(await createTransaction(ayse, cakir, await form({ attachmentIds: [emres.id] }))).ok,
).toBe(false);
const other = await upload(fatma, await png(), "x.png", annemler);
expect(
(await createTransaction(ayse, cakir, await form({ attachmentIds: [other.id] }))).ok,
).toBe(false);
// a1 zaten txId'ye bağlı: başka işleme taşınamaz.
expect((await createTransaction(ayse, cakir, await form({ attachmentIds: [a1.id] }))).ok).toBe(
false,
);
});
it("kayıt başına en fazla 10 ek", async () => {
const many = [];
for (let i = 0; i < 11; i++) many.push((await upload(emre, await png(5 + i, 5))).id);
expect((await createTransaction(emre, cakir, await form({ attachmentIds: many }))).ok).toBe(
false,
);
expect(
(await createTransaction(emre, cakir, await form({ attachmentIds: many.slice(0, 10) }))).ok,
).toBe(true);
});
it("düzenlemede çıkarılan ek kayıttan düşer, yeni ek eklenir (başka üye de düzenleyebilir)", async () => {
const a4 = await upload(emre, await png(44, 10));
const detail = await getTransaction(emre, cakir, txId);
const r = await updateTransaction(
emre,
cakir,
txId,
await form({
accountId: detail!.account.id,
categoryId: detail!.categoryId,
attachmentIds: [a3.id, a4.id],
}),
);
expect(r.ok).toBe(true);
const after = await getTransaction(ayse, cakir, txId);
expect(after!.attachments.map((a) => a.id)).toEqual([a3.id, a4.id]);
expect(after!.attachmentCount).toBe(2);
expect((await AttachmentModel.findById(a1.id).lean())!.deletedAt).toBeInstanceOf(Date);
expect(await readAttachmentForUser(ayse, a1.id, "full")).toBeNull();
});
it("dosya erişimi: hane üyeleri (izleyici dahil) okur; hane dışı ve silinmiş işlem okuyamaz", async () => {
const file = await readAttachmentForUser(zeynep, a3.id, "thumb");
expect(file?.mimeType).toBe("image/webp");
expect(await readAttachmentForUser(fatma, a3.id, "full")).toBeNull();
expect(await readAttachmentForUser(ayse, "not-an-id", "full")).toBeNull();
await setTransactionDeleted(ayse, cakir, txId, true);
expect(await readAttachmentForUser(ayse, a3.id, "full")).toBeNull();
await setTransactionDeleted(ayse, cakir, txId, false);
expect(await readAttachmentForUser(ayse, a3.id, "full")).not.toBeNull();
});
it("bekleyen ek yalnızca yükleyene görünür", async () => {
const pending = await upload(ayse, await png());
expect(await readAttachmentForUser(ayse, pending.id, "full")).not.toBeNull();
expect(await readAttachmentForUser(emre, pending.id, "full")).toBeNull();
});
it("gizli hesaptaki işlemin eki hesap sahibi dışındakilere kapalı", async () => {
const img = await upload(ayse, await png());
const r = await createTransaction(
ayse,
cakir,
await form({ accountId: await acc("Ayşe — Pluxee"), attachmentIds: [img.id] }),
);
expect(r.ok).toBe(true);
expect(await readAttachmentForUser(ayse, img.id, "full")).not.toBeNull();
expect(await readAttachmentForUser(emre, img.id, "full")).toBeNull();
});
});
describe("temizlik", () => {
it("eski bekleyen ekler, çıkarılmış ekler ve 30 günden önce silinmiş işlemlerin ekleri silinir", async () => {
const pending = await upload(ayse, await png());
const old = new Date(Date.now() - 25 * 60 * 60 * 1000);
await AttachmentModel.collection.updateOne(
{ _id: (await AttachmentModel.findById(pending.id))!._id },
{ $set: { createdAt: old } },
);
const kept = await upload(ayse, await png());
const r = await createTransaction(ayse, cakir, await form({ attachmentIds: [kept.id] }));
const tx = r.ok ? r.data.id : "";
await setTransactionDeleted(ayse, cakir, tx, true);
const keptDoc = (await AttachmentModel.findById(kept.id).lean())!;
// Silme 31 gün önce yapılmış gibi.
const now = new Date(Date.now() + 31 * 24 * 60 * 60 * 1000);
const pendingDoc = (await AttachmentModel.findById(pending.id).lean())!;
const { removed } = await purgeAttachments(now);
expect(removed).toBeGreaterThan(0);
expect(await AttachmentModel.findById(pending.id)).toBeNull();
expect(await getStorage().get(pendingDoc.storageKey)).toBeNull();
expect(await AttachmentModel.findById(kept.id)).toBeNull();
expect(await getStorage().get(keptDoc.storageKey)).toBeNull();
expect((await TransactionModel.findById(tx).lean())!.attachmentCount).toBe(0);
});
it("taze bekleyen ekler ve bağlı ekler korunur", async () => {
const fresh = await upload(ayse, await png());
const linked = await upload(ayse, await png());
await createTransaction(ayse, cakir, await form({ attachmentIds: [linked.id] }));
await purgeAttachments();
expect(await AttachmentModel.findById(fresh.id)).not.toBeNull();
expect(await AttachmentModel.findById(linked.id)).not.toBeNull();
});
});
+326
View File
@@ -0,0 +1,326 @@
import "server-only";
import { randomBytes } from "node:crypto";
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 { connectMongoose } from "@/lib/db/mongoose";
import { env } from "@/lib/env";
import { toObjectId } from "@/lib/object-id";
import { getStorage } from "@/lib/storage";
import { isPlausiblePdf, processImage, UnreadableImageError } from "@/lib/uploads/process";
import { AccountModel } from "@/models/account";
import { AttachmentModel, type AttachmentOwnerType } from "@/models/attachment";
import { TransactionModel } from "@/models/transaction";
import {
detectFileType,
MAX_ATTACHMENTS_PER_RECORD,
type AttachmentKind,
} from "@/shared/attachments";
const t = tr.attachments;
/** Bir kullanıcının bir hanede aynı anda bekletebileceği (kayda bağlanmamış) ek sayısı. */
export const MAX_PENDING_PER_USER = 30;
/** Bağlanmamış eklerin ömrü. */
export const PENDING_TTL_MS = 24 * 60 * 60 * 1000;
/** Silinen kayıt/ek dosyalarının fiziksel olarak silinmeden önce bekleme süresi (geri alma payı). */
export const SOFT_DELETE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
export type AttachmentInfo = {
id: string;
kind: AttachmentKind;
name: string;
size: number;
width: number | null;
height: number | null;
url: string;
thumbUrl: string | null;
};
type LeanAttachment = {
_id: Types.ObjectId;
kind: AttachmentKind;
originalName?: string | null;
size: number;
width?: number | null;
height?: number | null;
thumbKey?: string | null;
};
export function toAttachmentInfo(a: LeanAttachment): AttachmentInfo {
const id = String(a._id);
return {
id,
kind: a.kind,
name: a.originalName || (a.kind === "pdf" ? "belge.pdf" : "gorsel.webp"),
size: a.size,
width: a.width ?? null,
height: a.height ?? null,
url: `/api/files/${id}`,
thumbUrl: a.thumbKey ? `/api/files/${id}?v=thumb` : null,
};
}
/** Kullanıcının verdiği dosya adını güvenli hale getirir (yol, kontrol karakteri, uzunluk). */
export function sanitizeFileName(name: string): string {
const base = name.split(/[\\/]/).pop() ?? "";
return base
.replace(/[\u0000-\u001f\u007f"<>]/g, "")
.trim()
.slice(0, 120);
}
function newKey(): string {
const id = randomBytes(16).toString("hex");
return `${id.slice(0, 2)}/${id}`;
}
// --- Yükleme ---
export async function uploadAttachment(
userId: string,
householdId: string,
file: { name: string; bytes: Buffer },
): Promise<ActionResult<AttachmentInfo>> {
const m = await resolveMembership(userId, householdId, "member");
if (!m) return fail(tr.common.unauthorized);
const maxBytes = env().MAX_UPLOAD_MB * 1024 * 1024;
if (file.bytes.length === 0) return fail(t.errors.empty);
if (file.bytes.length > maxBytes) return fail(t.errors.tooLarge(env().MAX_UPLOAD_MB));
const type = detectFileType(file.bytes);
if (!type) return fail(t.errors.unsupported);
const uploader = new Types.ObjectId(userId);
const pending = await AttachmentModel.countDocuments({
householdId: m.householdId,
ownerId: null,
uploadedBy: uploader,
deletedAt: null,
});
if (pending >= MAX_PENDING_PER_USER) return fail(t.errors.tooManyPending);
const key = newKey();
const storage = getStorage();
let doc: Record<string, unknown>;
if (type === "pdf") {
if (!isPlausiblePdf(file.bytes)) return fail(t.errors.unreadable);
await storage.put(`${key}.pdf`, file.bytes);
doc = {
kind: "pdf",
mimeType: "application/pdf",
size: file.bytes.length,
storageKey: `${key}.pdf`,
thumbKey: null,
};
} else {
let processed;
try {
processed = await processImage(file.bytes, type);
} catch (error) {
if (error instanceof UnreadableImageError) return fail(t.errors.unreadable);
throw error;
}
await storage.put(`${key}.webp`, processed.main);
await storage.put(`${key}.thumb.webp`, processed.thumb);
doc = {
kind: "image",
mimeType: "image/webp",
size: processed.main.length,
width: processed.width,
height: processed.height,
storageKey: `${key}.webp`,
thumbKey: `${key}.thumb.webp`,
};
}
const created = await AttachmentModel.create({
...doc,
householdId: m.householdId,
sourceType: type,
originalName: sanitizeFileName(file.name),
originalSize: file.bytes.length,
uploadedBy: uploader,
});
return ok(toAttachmentInfo(created.toObject() as LeanAttachment));
}
// --- Kayda bağlama ---
/**
* Kaydın ek listesini `ids` ile eşitler (sıra korunur). Yeni kimlikler, bu kullanıcının bu hanede
* yüklediği bekleyen ekler olmalı; listede olmayan mevcut ekler kayıttan çıkarılır (`deletedAt`).
* Kayıttaki güncel ek sayısını döner. Transaction içinde çağrılmalı (session).
*/
export async function syncOwnerAttachments(opts: {
householdId: Types.ObjectId;
actorId: string;
ownerType: AttachmentOwnerType;
ownerId: Types.ObjectId;
ids: string[];
allowedKinds: readonly AttachmentKind[];
session?: ClientSession;
}): Promise<ActionResult<number>> {
const { householdId, ownerType, ownerId, session } = opts;
const unique = [...new Set(opts.ids)];
if (unique.length > MAX_ATTACHMENTS_PER_RECORD)
return fail(t.errors.tooMany(MAX_ATTACHMENTS_PER_RECORD));
const objectIds = unique.map(toObjectId);
if (objectIds.some((id) => !id)) return fail(t.errors.invalid);
const current = await AttachmentModel.find(
{ householdId, ownerType, ownerId, deletedAt: null },
{ _id: 1 },
{ session },
).lean();
const currentIds = new Set(current.map((a) => String(a._id)));
const newIds = objectIds.filter((id) => !currentIds.has(String(id))) as Types.ObjectId[];
const candidates = await AttachmentModel.find(
{ _id: { $in: objectIds }, householdId, deletedAt: null },
{ kind: 1, ownerId: 1, uploadedBy: 1 },
{ session },
).lean();
const byId = new Map(candidates.map((a) => [String(a._id), a]));
for (const id of newIds) {
const a = byId.get(String(id));
// Yalnızca kendi yüklediği, henüz hiçbir kayda bağlanmamış ekler bağlanabilir.
if (!a || a.ownerId || String(a.uploadedBy) !== opts.actorId) return fail(t.errors.invalid);
}
for (const id of objectIds) {
const a = byId.get(String(id));
if (a && !opts.allowedKinds.includes(a.kind)) return fail(t.errors.kindNotAllowed);
}
const removed = current.filter((a) => !objectIds.some((id) => id!.equals(a._id)));
if (removed.length) {
await AttachmentModel.updateMany(
{ _id: { $in: removed.map((a) => a._id) }, householdId },
{ $set: { deletedAt: new Date() } },
{ session },
);
}
if (objectIds.length) {
await AttachmentModel.bulkWrite(
objectIds.map((id, order) => ({
updateOne: {
filter: { _id: id!, householdId },
update: { $set: { ownerType, ownerId, order } },
},
})),
{ session },
);
}
return ok(objectIds.length);
}
export async function listOwnerAttachments(
householdId: Types.ObjectId,
ownerType: AttachmentOwnerType,
ownerId: Types.ObjectId,
): Promise<AttachmentInfo[]> {
const rows = await AttachmentModel.find({ householdId, ownerType, ownerId, deletedAt: null })
.sort({ order: 1, createdAt: 1 })
.lean();
return rows.map((a) => toAttachmentInfo(a as unknown as LeanAttachment));
}
// --- Servis etme ---
export type AttachmentFile = {
bytes: Buffer;
mimeType: string;
name: string;
};
/**
* Yetki kontrollü dosya okuma: kullanıcı ekin hanesinin üyesi olmalı; bekleyen ek yalnızca
* yükleyene; işleme bağlı ek, işlem kullanıcıya görünürse (silinmemiş ve başkasının gizli
* hesabına dokunmuyorsa). Erişim yoksa null (çağıran 404 döner; varlık sızdırılmaz).
*/
export async function readAttachmentForUser(
userId: string,
attachmentId: string,
variant: "full" | "thumb",
): Promise<AttachmentFile | null> {
const id = toObjectId(attachmentId);
if (!id) return null;
await connectMongoose();
const a = await AttachmentModel.findOne({ _id: id, deletedAt: null }).lean();
if (!a) return null;
const m = await resolveMembership(userId, String(a.householdId), "viewer");
if (!m) return null;
if (!a.ownerId) {
if (String(a.uploadedBy) !== userId) return null;
} else if (a.ownerType === "transaction") {
const tx = await TransactionModel.findOne(
{ _id: a.ownerId, householdId: a.householdId, deletedAt: null },
{ accountId: 1, toAccountId: 1 },
).lean();
if (!tx) return null;
const hidden = await AccountModel.exists({
_id: { $in: [tx.accountId, tx.toAccountId].filter(Boolean) },
householdId: a.householdId,
isPrivate: true,
ownerUserId: { $ne: new Types.ObjectId(userId) },
});
if (hidden) return null;
} else {
return null;
}
const key = variant === "thumb" && a.thumbKey ? a.thumbKey : a.storageKey;
const bytes = await getStorage().get(key);
if (!bytes) return null;
return {
bytes,
mimeType: variant === "thumb" && a.thumbKey ? "image/webp" : a.mimeType,
name: a.originalName ?? "",
};
}
// --- Temizlik ---
/**
* Fiziksel temizlik (Bölüm 7.4): 24 saatten eski bekleyen ekler, 30 günden önce çıkarılmış
* ekler ve 30 günden önce silinmiş işlemlerin ekleri. Dosyalar silinir, kayıtlar kaldırılır.
*/
export async function purgeAttachments(now = new Date()): Promise<{ removed: number }> {
await connectMongoose();
const retentionCutoff = new Date(now.getTime() - SOFT_DELETE_RETENTION_MS);
const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS);
const deletedTx = await TransactionModel.find(
{ deletedAt: { $ne: null, $lt: retentionCutoff }, attachmentCount: { $gt: 0 } },
{ _id: 1 },
).lean();
const victims = await AttachmentModel.find(
{
$or: [
{ ownerId: null, createdAt: { $lt: pendingCutoff } },
{ deletedAt: { $ne: null, $lt: retentionCutoff } },
...(deletedTx.length
? [{ ownerType: "transaction" as const, ownerId: { $in: deletedTx.map((d) => d._id) } }]
: []),
],
},
{ storageKey: 1, thumbKey: 1 },
).lean();
const storage = getStorage();
for (const v of victims) {
await storage.delete(v.storageKey);
if (v.thumbKey) await storage.delete(v.thumbKey);
await AttachmentModel.deleteOne({ _id: v._id });
}
if (deletedTx.length) {
await TransactionModel.updateMany(
{ _id: { $in: deletedTx.map((d) => d._id) } },
{ $set: { attachmentCount: 0 } },
);
}
return { removed: victims.length };
}
+65
View File
@@ -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>
);
}
+117
View File
@@ -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" },
],
};
+159
View File
@@ -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);
});
});
+331
View File
@@ -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);
}
+121
View File
@@ -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);
});
});
+163
View File
@@ -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;
}
+3 -1
View File
@@ -6,6 +6,7 @@ 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";
@@ -321,7 +322,8 @@ export async function adminCreateHousehold(
},
session,
);
// FAZ 6: varsayılan Türkçe kategori seti bu transaction içinde yüklenecek.
// 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 });
}
+136
View File
@@ -0,0 +1,136 @@
"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 { getHouseholdActionContext } from "@/lib/dal";
import { reconcileSchema } from "@/shared/schemas/reconciliation";
import { transactionFormSchema } from "@/shared/schemas/transaction";
import {
createTransaction,
getTransaction,
getTransactionFormOptions,
searchPayees,
setTransactionDeleted,
updateTransaction,
type PayeeSuggestion,
type TransactionDetail,
type TransactionFormOptions,
} from "./service";
import { previewReconciliation, reconcileAccount, type ReconcilePreview } from "./statement";
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
/** zod hatalarını alan bazlı mesajlara çevirir ("splits.1.amount" gibi yollar korunur). */
function fieldErrors(error: z.ZodError) {
const out: Record<string, string> = {};
for (const issue of error.issues) {
const key = issue.path.join(".");
if (key && !out[key]) out[key] = issue.message;
}
return out;
}
function revalidate() {
// Bakiye, liste ve (ileride) dashboard aynı veriden beslenir.
revalidatePath("/", "layout");
}
export async function createTransactionAction(
input: unknown,
): Promise<ActionResult<{ id: string }>> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const parsed = transactionFormSchema.safeParse(input);
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
const result = await createTransaction(ctx.user.id, ctx.household.id, parsed.data);
if (result.ok) revalidate();
return result;
}
export async function updateTransactionAction(
transactionId: unknown,
input: unknown,
): Promise<ActionResult> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const id = idSchema.safeParse(transactionId);
if (!id.success) return fail(tr.common.notFound);
const parsed = transactionFormSchema.safeParse(input);
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
const result = await updateTransaction(ctx.user.id, ctx.household.id, id.data, parsed.data);
if (result.ok) revalidate();
return result;
}
export async function setTransactionDeletedAction(
transactionId: unknown,
deleted: unknown,
): Promise<ActionResult> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const id = idSchema.safeParse(transactionId);
const d = z.boolean().safeParse(deleted);
if (!id.success || !d.success) return fail(tr.common.genericError);
const result = await setTransactionDeleted(ctx.user.id, ctx.household.id, id.data, d.data);
if (result.ok) revalidate();
return result;
}
/** Form açılırken: yazılabilir hesaplar ve kategoriler (hızlı ekle her ekrandan çağırır). */
export async function getTransactionFormOptionsAction(): Promise<
ActionResult<TransactionFormOptions>
> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const options = await getTransactionFormOptions(ctx.user.id, ctx.household.id);
return options ? ok(options) : fail(tr.common.unauthorized);
}
export async function getTransactionAction(
transactionId: unknown,
): Promise<ActionResult<TransactionDetail>> {
const ctx = await getHouseholdActionContext("viewer");
if (!ctx) return fail(tr.common.unauthorized);
const id = idSchema.safeParse(transactionId);
if (!id.success) return fail(tr.common.notFound);
const detail = await getTransaction(ctx.user.id, ctx.household.id, id.data);
return detail ? ok(detail) : fail(tr.common.notFound);
}
export async function searchPayeesAction(query: unknown): Promise<PayeeSuggestion[]> {
const ctx = await getHouseholdActionContext("member");
const q = z.string().max(80).safeParse(query);
if (!ctx || !q.success) return [];
return searchPayees(ctx.user.id, ctx.household.id, q.data);
}
/** Mutabakat önizlemesi: ekstre bakiyesi ile uygulama bakiyesi arasındaki fark. */
export async function previewReconciliationAction(
accountId: unknown,
input: unknown,
): Promise<ActionResult<ReconcilePreview>> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const id = idSchema.safeParse(accountId);
if (!id.success) return fail(tr.common.notFound);
const parsed = reconcileSchema.safeParse(input);
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
return previewReconciliation(ctx.user.id, ctx.household.id, id.data, parsed.data);
}
export async function reconcileAccountAction(
accountId: unknown,
input: unknown,
): Promise<ActionResult<{ adjustmentId: string | null; markedCount: number }>> {
const ctx = await getHouseholdActionContext("member");
if (!ctx) return fail(tr.common.unauthorized);
const id = idSchema.safeParse(accountId);
if (!id.success) return fail(tr.common.notFound);
const parsed = reconcileSchema.safeParse(input);
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
const result = await reconcileAccount(ctx.user.id, ctx.household.id, id.data, parsed.data);
if (result.ok) revalidate();
return result;
}
@@ -0,0 +1,387 @@
"use client";
import {
ArrowLeft,
CheckCheck,
ChevronLeft,
ChevronRight,
List,
Loader2,
Scale,
} from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
import { MoneyInput } from "@/components/money-input";
import { PageHeader } from "@/components/page-header";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { todayIstanbul } from "@/shared/dates";
import { formatDate, formatMoney } from "@/shared/format";
import { previewReconciliationAction, reconcileAccountAction } from "../actions";
import type { AccountStatement, ReconcilePreview, StatementRow } from "../statement";
import { RowIcon, rowSubtitle, rowTitle, useTransactionDetail } from "./transaction-parts";
const t = tr.statement;
const r = t.reconcile;
const monthFmt = new Intl.DateTimeFormat("tr-TR", {
month: "long",
year: "numeric",
timeZone: "Europe/Istanbul",
});
const monthLabel = (ym: string) => monthFmt.format(new Date(`${ym}-15T12:00:00+03:00`));
const dateLabel = (ymd: string) => formatDate(new Date(`${ymd}T12:00:00+03:00`));
function SignedMoney({ minor, className }: { minor: number; className?: string }) {
return (
<span
className={cn(
"font-semibold whitespace-nowrap tabular-nums",
minor > 0 && "text-income",
minor < 0 && "text-expense",
className,
)}
>
{minor > 0 ? "+" : minor < 0 ? "−" : ""}
{formatMoney(Math.abs(minor))}
</span>
);
}
export function StatementView({
statement: s,
canWrite,
}: {
statement: AccountStatement;
canWrite: boolean;
}) {
const { openDetail, element: detailElement } = useTransactionDetail(canWrite);
const [reconcileOpen, setReconcileOpen] = useState(false);
const base = `/hesaplar/${s.account.id}`;
return (
<div className="flex flex-col gap-4">
<Button variant="ghost" size="sm" asChild className="-ml-2 w-fit">
<Link href="/hesaplar">
<ArrowLeft />
{t.back}
</Link>
</Button>
<PageHeader
title={s.account.name}
description={`${tr.accounts.types[s.account.type]} · ${t.current}: ${formatMoney(s.currentBalanceMinor)}`}
actions={
<>
<Button variant="outline" asChild>
<Link href={`/islemler?hesap=${s.account.id}`}>
<List />
<span className="hidden sm:inline">{t.allTransactions}</span>
</Link>
</Button>
{canWrite && s.canReconcile ? (
<Button onClick={() => setReconcileOpen(true)}>
<Scale />
{r.open}
</Button>
) : null}
</>
}
/>
<div className="flex items-center justify-between gap-2">
<Button variant="outline" size="icon-sm" asChild aria-label={t.prevMonth}>
<Link href={`${base}?ay=${s.prevMonth}`}>
<ChevronLeft />
</Link>
</Button>
<h2 className="text-base font-medium capitalize">{monthLabel(s.month)}</h2>
{s.nextMonth ? (
<Button variant="outline" size="icon-sm" asChild aria-label={t.nextMonth}>
<Link href={`${base}?ay=${s.nextMonth}`}>
<ChevronRight />
</Link>
</Button>
) : (
<Button variant="outline" size="icon-sm" disabled aria-label={t.nextMonth}>
<ChevronRight />
</Button>
)}
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{(
[
[t.opening, s.openingMinor, false],
[t.inflow, s.inflowMinor, true],
[t.outflow, -s.outflowMinor, true],
[t.closing, s.closingMinor, false],
] as const
).map(([label, value, colored]) => (
<Card key={label} size="sm">
<CardHeader>
<CardDescription>{label}</CardDescription>
<CardTitle className="text-base">
{colored ? (
<SignedMoney minor={value} />
) : (
<span className="tabular-nums">{formatMoney(value)}</span>
)}
</CardTitle>
</CardHeader>
</Card>
))}
</div>
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<CheckCheck className="size-3.5" aria-hidden />
{s.lastReconciliation
? t.lastReconciliation(
dateLabel(s.lastReconciliation.date),
formatMoney(s.lastReconciliation.statementBalanceMinor),
)
: t.noReconciliation}
</p>
{s.rows.length === 0 ? (
<Card>
<CardHeader>
<CardDescription>{t.empty}</CardDescription>
</CardHeader>
</Card>
) : (
<ul className="divide-y rounded-xl border bg-card">
{s.rows.map((row) => (
<li key={row.item.id}>
<StatementRowView row={row} onOpen={() => openDetail(row.item.id)} />
</li>
))}
</ul>
)}
{s.truncated ? <p className="text-xs text-muted-foreground">{t.truncated}</p> : null}
{detailElement}
<ReconcileDialog
open={reconcileOpen}
onOpenChange={setReconcileOpen}
accountId={s.account.id}
isLiability={s.account.isLiability}
/>
</div>
);
}
function StatementRowView({ row, onOpen }: { row: StatementRow; onOpen: () => void }) {
const content = (
<>
<RowIcon item={row.item} />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
<span className="truncate font-medium">{rowTitle(row.item)}</span>
{row.reconciled ? (
<CheckCheck className="size-3.5 shrink-0 text-income" aria-label={t.reconciledHint} />
) : null}
</span>
<span className="block truncate text-xs text-muted-foreground">
{dateLabel(row.item.date)} · {rowSubtitle(row.item)}
</span>
</span>
<span className="flex flex-col items-end">
<SignedMoney minor={row.deltaMinor} />
<span className="text-xs text-muted-foreground tabular-nums" title={t.balanceAfter}>
{formatMoney(row.balanceMinor)}
</span>
</span>
</>
);
const cls = "flex w-full items-center gap-3 p-3 text-left";
// Gizli karşı hesaba dokunan işlemin ayrıntısı açılmaz.
return row.restricted ? (
<div className={cls}>{content}</div>
) : (
<button
type="button"
onClick={onOpen}
className={cn(cls, "outline-none hover:bg-muted/50 focus-visible:bg-muted")}
>
{content}
</button>
);
}
function ReconcileDialog({
open,
onOpenChange,
accountId,
isLiability,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
accountId: string;
isLiability: boolean;
}) {
const [date, setDate] = useState(todayIstanbul);
const [balance, setBalance] = useState("");
const [preview, setPreview] = useState<ReconcilePreview | null>(null);
const [accept, setAccept] = useState(false);
const [errors, setErrors] = useState<Record<string, string | undefined>>({});
const [pending, setPending] = useState(false);
function reset(next: boolean) {
if (!next) {
setPreview(null);
setAccept(false);
setErrors({});
setBalance("");
setDate(todayIstanbul());
}
onOpenChange(next);
}
const input = () => ({
statementDate: date,
statementBalance: balance,
acceptAdjustment: accept,
});
async function check() {
setPending(true);
const res = await previewReconciliationAction(accountId, input());
setPending(false);
if (!res.ok) {
setErrors({ ...res.fieldErrors, root: res.fieldErrors ? undefined : res.error });
return;
}
setErrors({});
setAccept(false);
setPreview(res.data);
}
async function confirm() {
setPending(true);
const res = await reconcileAccountAction(accountId, input());
setPending(false);
if (!res.ok) {
setErrors({ root: res.error });
return;
}
toast.success(
res.data.adjustmentId
? r.doneWithAdjustment(res.data.markedCount)
: r.done(res.data.markedCount),
);
reset(false);
}
const diff = preview?.differenceMinor ?? 0;
const display = (minor: number) => formatMoney(isLiability ? -minor : minor);
return (
<ResponsiveDialog
open={open}
onOpenChange={reset}
title={r.title}
description={r.description}
footer={
<>
<Button variant="outline" type="button" onClick={() => reset(false)}>
{tr.common.cancel}
</Button>
{preview ? (
<Button onClick={confirm} disabled={pending || (diff !== 0 && !accept)}>
{pending ? <Loader2 className="animate-spin" /> : null}
{diff !== 0 ? r.confirmWithAdjustment : r.confirm}
</Button>
) : (
<Button onClick={check} disabled={pending || !balance.trim()}>
{pending ? <Loader2 className="animate-spin" /> : null}
{r.check}
</Button>
)}
</>
}
>
<FieldGroup>
<Field data-invalid={Boolean(errors.statementDate)}>
<FieldLabel htmlFor="rec-date">{r.date}</FieldLabel>
<Input
id="rec-date"
type="date"
value={date}
max={todayIstanbul()}
onChange={(e) => {
setDate(e.target.value);
setPreview(null);
}}
/>
{errors.statementDate ? <FieldError>{errors.statementDate}</FieldError> : null}
</Field>
<Field data-invalid={Boolean(errors.statementBalance)}>
<FieldLabel htmlFor="rec-balance">{isLiability ? r.debt : r.balance}</FieldLabel>
<MoneyInput
id="rec-balance"
value={balance}
allowNegative
onChange={(v) => {
setBalance(v);
setPreview(null);
}}
/>
<FieldDescription>{isLiability ? r.debtHint : r.balanceHint}</FieldDescription>
{errors.statementBalance ? <FieldError>{errors.statementBalance}</FieldError> : null}
</Field>
{preview ? (
<div className="flex flex-col gap-3 rounded-xl border p-3" aria-live="polite">
<dl className="grid grid-cols-3 gap-2 text-sm">
<div>
<dt className="text-xs text-muted-foreground">{r.statementBalance}</dt>
<dd className="tabular-nums">{display(preview.statementBalanceMinor)}</dd>
</div>
<div>
<dt className="text-xs text-muted-foreground">{r.appBalance}</dt>
<dd className="tabular-nums">{display(preview.appBalanceMinor)}</dd>
</div>
<div>
<dt className="text-xs text-muted-foreground">{r.difference}</dt>
<dd>
<SignedMoney minor={diff} />
</dd>
</div>
</dl>
{diff === 0 ? (
<p className="text-sm text-income">{r.matches}</p>
) : (
<>
<p className="text-sm text-expense">{r.mismatch}</p>
<label className="flex items-start gap-2 text-sm">
<Checkbox
checked={accept}
onCheckedChange={(v) => setAccept(v === true)}
className="mt-0.5"
/>
<span>
{r.adjustmentOffer(
formatMoney(Math.abs(diff)),
diff > 0 ? tr.transactions.types.income : tr.transactions.types.expense,
)}
</span>
</label>
</>
)}
<Badge variant="secondary" className="w-fit">
{r.unreconciled(preview.unreconciledCount)}
</Badge>
</div>
) : null}
{errors.root ? <FieldError>{errors.root}</FieldError> : null}
</FieldGroup>
</ResponsiveDialog>
);
}
@@ -0,0 +1,856 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChevronDown, Loader2, Plus, Split, Trash2, Wand2 } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { Controller, useFieldArray, useForm, useWatch, type Resolver } from "react-hook-form";
import { toast } from "sonner";
import { IconBadge } from "@/components/appearance/swatch";
import { MoneyInput } from "@/components/money-input";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
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 { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { todayIstanbul } from "@/shared/dates";
import { formatMoney } from "@/shared/format";
import { formatMoneyInput, parseMoney } from "@/shared/money";
import { allowedAttachmentKinds } from "@/shared/attachments";
import { AttachmentPicker } from "@/features/attachments/components/attachment-picker";
import type { AttachmentInfo } from "@/features/attachments/service";
import { transactionFormSchema, type TransactionForm } from "@/shared/schemas/transaction";
import { MAX_SPLITS, TRANSACTION_TYPES, type TransactionType } from "@/shared/transactions";
import {
createTransactionAction,
getTransactionFormOptionsAction,
searchPayeesAction,
updateTransactionAction,
} from "../actions";
import type { PayeeSuggestion, TransactionDetail, TransactionFormOptions } from "../service";
const t = tr.transactions;
const f = t.fields;
export type TransactionFormMode =
| { kind: "create"; type: TransactionType }
| { kind: "edit"; transaction: TransactionDetail }
| { kind: "copy"; transaction: TransactionDetail };
type SplitValue = { categoryId: string; amount: string; note: string };
type FormValues = {
type: TransactionType;
amount: string;
date: string;
accountId: string;
toAccountId: string;
categoryId: string;
splits: SplitValue[];
payee: string;
description: string;
tags: string;
/** Önizleme bilgisiyle ekler; sunucuya yalnızca kimlikleri gider. */
attachments: AttachmentInfo[];
};
function toValues(mode: TransactionFormMode, options: TransactionFormOptions | null): FormValues {
if (mode.kind === "create") {
return {
type: mode.type,
amount: "",
date: todayIstanbul(),
accountId: options?.accounts[0]?.id ?? "",
toAccountId: "",
categoryId: "",
splits: [],
payee: "",
description: "",
tags: "",
attachments: [],
};
}
const x = mode.transaction;
return {
type: x.type,
amount: formatMoneyInput(x.amountMinor),
date: mode.kind === "copy" ? todayIstanbul() : x.date,
accountId: x.account.id,
toAccountId: x.toAccount?.id ?? "",
categoryId: x.categoryId ?? "",
splits: x.splits.map((s) => ({
categoryId: s.categoryId,
amount: formatMoneyInput(s.amountMinor),
note: s.note,
})),
payee: x.payeeName,
description: x.description,
tags: x.tags.join(", "),
// Kopyada ekler taşınmaz (fiş o işleme aittir).
attachments: mode.kind === "edit" ? x.attachments : [],
};
}
function AccountSelect({
id,
value,
onChange,
accounts,
invalid,
exclude,
}: {
id: string;
value: string;
onChange: (v: string) => void;
accounts: {
id: string;
name: string;
icon?: TransactionFormOptions["accounts"][number]["icon"];
color?: TransactionFormOptions["accounts"][number]["color"];
}[];
invalid?: boolean;
exclude?: string;
}) {
const current = accounts.find((a) => a.id === value);
return (
<Select value={value || undefined} onValueChange={onChange}>
<SelectTrigger id={id} className="w-full" aria-invalid={invalid}>
<SelectValue placeholder={f.selectAccount}>{current?.name}</SelectValue>
</SelectTrigger>
<SelectContent className="max-h-72">
{accounts
.filter((a) => a.id !== exclude)
.map((a) => (
<SelectItem key={a.id} value={a.id}>
{a.icon && a.color ? (
<IconBadge
icon={a.icon}
color={a.color}
size="sm"
className="size-5 [&_svg]:size-3"
/>
) : null}
{a.name}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
function CategorySelect({
id,
value,
onChange,
options,
appearance,
invalid,
className,
}: {
id: string;
value: string;
onChange: (v: string) => void;
options: TransactionFormOptions["categories"];
appearance: TransactionFormOptions["categoryAppearance"];
invalid?: boolean;
className?: string;
}) {
const current = options.find((o) => o.id === value);
return (
<Select value={value || undefined} onValueChange={onChange}>
<SelectTrigger id={id} className={cn("w-full", className)} aria-invalid={invalid}>
<SelectValue placeholder={f.selectCategory}>{current?.path}</SelectValue>
</SelectTrigger>
<SelectContent className="max-h-80">
{options.map((o) => {
const look = appearance[o.id];
return (
<SelectItem key={o.id} value={o.id}>
<span
className="flex items-center gap-2"
style={{ paddingInlineStart: `${o.depth * 1}rem` }}
>
{look ? (
<IconBadge
icon={look.icon}
color={look.color}
size="sm"
className="size-5 [&_svg]:size-3"
/>
) : null}
<span className={o.depth === 0 ? "font-medium" : undefined}>{o.label}</span>
</span>
</SelectItem>
);
})}
</SelectContent>
</Select>
);
}
/** Satıcı alanı: yazdıkça öneri; seçilince son kullanılan kategori/hesap önerilir. */
function PayeeInput({
value,
onChange,
onPick,
}: {
value: string;
onChange: (v: string) => void;
onPick: (p: PayeeSuggestion) => void;
}) {
const [items, setItems] = useState<PayeeSuggestion[]>([]);
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
function query(v: string) {
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(async () => {
const res = await searchPayeesAction(v);
setItems(
res.filter(
(p) =>
p.name.toLocaleLowerCase("tr-TR") !== v.trim().toLocaleLowerCase("tr-TR") ||
res.length > 1,
),
);
setActive(-1);
}, 150);
}
function pick(p: PayeeSuggestion) {
onChange(p.name);
onPick(p);
setOpen(false);
}
return (
<div className="relative">
<Input
id="tx-payee"
value={value}
placeholder={f.payeePlaceholder}
autoComplete="off"
role="combobox"
aria-expanded={open && items.length > 0}
aria-controls="tx-payee-list"
aria-autocomplete="list"
onChange={(e) => {
onChange(e.target.value);
setOpen(true);
query(e.target.value);
}}
onFocus={() => {
setOpen(true);
query(value);
}}
onBlur={() => setTimeout(() => setOpen(false), 150)}
onKeyDown={(e) => {
if (!open || !items.length) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((i) => Math.min(i + 1, items.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter" && active >= 0) {
e.preventDefault();
pick(items[active]!);
} else if (e.key === "Escape") setOpen(false);
}}
/>
{open && items.length > 0 ? (
<ul
id="tx-payee-list"
role="listbox"
className="absolute z-50 mt-1 max-h-56 w-full overflow-y-auto rounded-lg border bg-popover p-1 text-popover-foreground shadow-md"
>
{items.map((p, i) => (
<li
key={p.name}
role="option"
aria-selected={i === active}
onMouseDown={(e) => {
e.preventDefault();
pick(p);
}}
className="cursor-pointer rounded-md px-2 py-1.5 text-sm hover:bg-accent aria-selected:bg-accent"
>
{p.name}
</li>
))}
</ul>
) : null}
</div>
);
}
export function TransactionFormDialog({
mode,
onOpenChange,
}: {
mode: TransactionFormMode | null;
onOpenChange: (open: boolean) => void;
}) {
const [options, setOptions] = useState<TransactionFormOptions | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [suggested, setSuggested] = useState(false);
const [uploadBusy, setUploadBusy] = useState(false);
const form = useForm<FormValues, unknown, TransactionForm>({
// FormValues, şemanın giriş şekliyle birebir (tutarlar string; zod kuruşa çevirir).
resolver: zodResolver(transactionFormSchema) as unknown as Resolver<
FormValues,
unknown,
TransactionForm
>,
defaultValues: toValues({ kind: "create", type: "expense" }, null),
});
const splits = useFieldArray({ control: form.control, name: "splits" });
// Form her açıldığında seçenekleri sunucudan al (hesaplar/kategoriler güncel olsun).
useEffect(() => {
if (!mode) return;
let cancelled = false;
getTransactionFormOptionsAction().then((res) => {
if (cancelled) return;
if (!res.ok) {
setLoadError(res.error);
return;
}
setLoadError(null);
setOptions(res.data);
form.reset(toValues(mode, res.data));
});
return () => {
cancelled = true;
};
}, [mode, form]);
const type = useWatch({ control: form.control, name: "type" });
const amount = useWatch({ control: form.control, name: "amount" });
const accountId = useWatch({ control: form.control, name: "accountId" });
const splitValues = useWatch({ control: form.control, name: "splits" });
const attachmentCount = useWatch({ control: form.control, name: "attachments" })?.length ?? 0;
const splitMode = splits.fields.length > 0;
// Düzenlemede arşivli/kapalı hesap veya kategori seçenek listesinde yoksa ekle (kaybolmasın).
const accounts = useMemo(() => {
const list = [...(options?.accounts ?? [])];
if (mode && mode.kind !== "create") {
for (const a of [mode.transaction.account, mode.transaction.toAccount]) {
if (a && !list.some((x) => x.id === a.id))
list.push({ ...a, type: "bank", icon: "wallet", color: "slate" });
}
}
return list;
}, [options, mode]);
const categories = useMemo(() => {
const kind = type === "income" ? "income" : "expense";
const list = (options?.categories ?? []).filter((c) => c.kind === kind);
if (mode && mode.kind !== "create") {
const extra = [
...(mode.transaction.category
? [{ id: mode.transaction.category.id, path: mode.transaction.category.path }]
: []),
...mode.transaction.splits.map((s) => ({ id: s.categoryId, path: s.path })),
];
for (const c of extra) {
if (!list.some((x) => x.id === c.id))
list.push({ id: c.id, label: c.path, path: c.path, depth: 0, kind });
}
}
return list;
}, [options, type, mode]);
const totalMinor = parseMoney(amount ?? "") ?? 0;
const splitSum = (splitValues ?? []).reduce((a, s) => a + (parseMoney(s.amount ?? "") ?? 0), 0);
const remaining = totalMinor - splitSum;
function handleOpenChange(open: boolean) {
if (!open) {
setAdvancedOpen(false);
setSuggested(false);
}
onOpenChange(open);
}
function changeType(next: TransactionType) {
form.setValue("type", next);
// Kategoriler türe bağlıdır; tür değişince temizlenir.
form.setValue("categoryId", "");
splits.replace([]);
if (next !== "transfer") form.setValue("toAccountId", "");
form.clearErrors();
}
function toggleSplit() {
if (splitMode) {
splits.replace([]);
return;
}
const first = form.getValues("categoryId");
splits.replace([
{ categoryId: first, amount: form.getValues("amount"), note: "" },
{ categoryId: "", amount: "", note: "" },
]);
form.setValue("categoryId", "");
setAdvancedOpen(true);
}
function fillRemaining() {
const last = splits.fields.length - 1;
if (last < 0) return;
const current = parseMoney(form.getValues(`splits.${last}.amount`) ?? "") ?? 0;
const next = current + remaining;
if (next > 0)
form.setValue(`splits.${last}.amount`, formatMoneyInput(next), { shouldValidate: true });
}
function onPayeePicked(p: PayeeSuggestion) {
let changed = false;
// Kullanıcı seçimini ezme: yalnızca boş alanları doldur.
if (p.lastAccountId && !form.getValues("accountId")) {
form.setValue("accountId", p.lastAccountId);
changed = true;
} else if (p.lastAccountId && form.formState.dirtyFields.accountId === undefined) {
form.setValue("accountId", p.lastAccountId);
changed = true;
}
if (
p.lastCategoryId &&
!splitMode &&
!form.getValues("categoryId") &&
p.lastType === form.getValues("type")
) {
form.setValue("categoryId", p.lastCategoryId);
changed = true;
}
setSuggested(changed);
}
async function onSubmit() {
if (!mode) return;
if (uploadBusy) {
form.setError("root", { message: tr.attachments.waitForUploads });
return;
}
const { attachments, ...values } = form.getValues();
const payload = {
...values,
attachmentIds: attachments.map((a) => a.id),
toAccountId: values.type === "transfer" ? values.toAccountId : "",
categoryId: values.type === "transfer" || values.splits.length ? "" : values.categoryId,
splits: values.type === "transfer" ? [] : values.splits,
};
const result =
mode.kind === "edit"
? await updateTransactionAction(mode.transaction.id, payload)
: await createTransactionAction(payload);
if (result.ok) {
toast.success(mode.kind === "edit" ? t.toast.updated : t.toast.created);
handleOpenChange(false);
return;
}
for (const [name, message] of Object.entries(result.fieldErrors ?? {})) {
if (!message) continue;
form.setError(name as keyof FormValues, { message });
if (name.startsWith("splits") || name === "tags") setAdvancedOpen(true);
}
if (!result.fieldErrors) form.setError("root", { message: result.error });
}
const title =
mode?.kind === "edit"
? t.editTitle
: mode?.kind === "copy"
? t.copyTitle
: t.createTitle[mode?.type ?? "expense"];
const loading = Boolean(mode) && !options && !loadError;
const noAccounts = options && options.accounts.length === 0;
const errors = form.formState.errors;
return (
<ResponsiveDialog
open={Boolean(mode)}
onOpenChange={handleOpenChange}
title={title}
footer={
noAccounts || loadError ? null : (
<>
<Button variant="outline" type="button" onClick={() => handleOpenChange(false)}>
{tr.common.cancel}
</Button>
<Button
type="submit"
form="transaction-form"
disabled={form.formState.isSubmitting || loading || uploadBusy}
>
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
{tr.common.save}
</Button>
</>
)
}
>
{loadError ? (
<p className="text-sm text-destructive">{loadError}</p>
) : loading ? (
<div className="flex flex-col gap-4" role="status" aria-label={tr.common.loading}>
<Skeleton className="h-9 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-9 w-full" />
<Skeleton className="h-9 w-full" />
</div>
) : noAccounts ? (
<div className="flex flex-col items-start gap-3 text-sm">
<p className="text-muted-foreground">{t.noAccounts}</p>
<Button asChild size="sm" onClick={() => handleOpenChange(false)}>
<Link href="/hesaplar">{t.noAccountsLink}</Link>
</Button>
</div>
) : (
<form id="transaction-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
<FieldGroup>
{mode?.kind !== "edit" ? (
<Tabs value={type} onValueChange={(v) => changeType(v as TransactionType)}>
<TabsList className="w-full">
{TRANSACTION_TYPES.map((x) => (
<TabsTrigger key={x} value={x} className="flex-1">
{t.types[x]}
</TabsTrigger>
))}
</TabsList>
</Tabs>
) : null}
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
<Controller
name="amount"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-amount">{f.amount}</FieldLabel>
<MoneyInput
id="tx-amount"
name={field.name}
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
placeholder="0,00"
className="h-11 text-lg"
autoFocus={mode?.kind === "create"}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Controller
name="date"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-date">{f.date}</FieldLabel>
<Input
{...field}
id="tx-date"
type="date"
className="h-11"
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
</div>
<div className={cn("grid gap-4", type === "transfer" && "sm:grid-cols-2")}>
<Controller
name="accountId"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-account">
{type === "transfer" ? f.fromAccount : f.account}
</FieldLabel>
<AccountSelect
id="tx-account"
value={field.value}
onChange={field.onChange}
accounts={accounts}
invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
{type === "transfer" ? (
<Controller
name="toAccountId"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-to-account">{f.toAccount}</FieldLabel>
<AccountSelect
id="tx-to-account"
value={field.value}
onChange={field.onChange}
accounts={accounts}
exclude={accountId}
invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
) : null}
</div>
{type !== "transfer" && !splitMode ? (
<Controller
name="categoryId"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-category">{f.category}</FieldLabel>
<div className="flex gap-2">
<CategorySelect
id="tx-category"
value={field.value}
onChange={field.onChange}
options={categories}
appearance={options?.categoryAppearance ?? {}}
invalid={fieldState.invalid}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={toggleSplit}
title={f.split}
aria-label={f.split}
>
<Split />
</Button>
</div>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
) : null}
<Controller
name="payee"
control={form.control}
render={({ field }) => (
<Field>
<FieldLabel htmlFor="tx-payee">{f.payee}</FieldLabel>
<PayeeInput
value={field.value}
onChange={field.onChange}
onPick={onPayeePicked}
/>
{suggested ? <FieldDescription>{f.suggested}</FieldDescription> : null}
</Field>
)}
/>
<Controller
name="description"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-description">{f.description}</FieldLabel>
<Input {...field} id="tx-description" aria-invalid={fieldState.invalid} />
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
<CollapsibleTrigger asChild>
<Button type="button" variant="ghost" className="-ml-2 w-fit">
<ChevronDown
className={cn("transition-transform", advancedOpen && "rotate-180")}
/>
{f.advanced}
{splitMode ? (
<span className="text-xs text-muted-foreground">
· {t.list.split(splits.fields.length)}
</span>
) : null}
{attachmentCount ? (
<span className="text-xs text-muted-foreground">
· {tr.attachments.count(attachmentCount)}
</span>
) : null}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-3">
<FieldGroup>
<Controller
name="attachments"
control={form.control}
render={({ field }) => (
<Field>
<FieldLabel>{tr.attachments.title}</FieldLabel>
<AttachmentPicker
value={field.value}
onChange={field.onChange}
allowedKinds={allowedAttachmentKinds(type)}
onBusyChange={setUploadBusy}
/>
</Field>
)}
/>
<Controller
name="tags"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="tx-tags">{f.tags}</FieldLabel>
<Input {...field} id="tx-tags" aria-describedby="tx-tags-hint" />
<FieldDescription id="tx-tags-hint">{f.tagsHint}</FieldDescription>
</Field>
)}
/>
{type !== "transfer" ? (
<div className="flex flex-col gap-3 rounded-xl border p-3">
<div className="flex items-center justify-between gap-2">
<div>
<p className="text-sm font-medium">{f.split}</p>
<p className="text-xs text-muted-foreground">{f.splitHint}</p>
</div>
<Button
type="button"
variant={splitMode ? "outline" : "secondary"}
size="sm"
onClick={toggleSplit}
>
<Split />
{splitMode ? tr.common.cancel : f.split}
</Button>
</div>
{splits.fields.map((row, i) => (
<div
key={row.id}
className="grid grid-cols-[1fr_8rem_auto] items-start gap-2"
>
<Controller
name={`splits.${i}.categoryId`}
control={form.control}
render={({ field, fieldState }) => (
<div>
<CategorySelect
id={`tx-split-${i}-category`}
value={field.value}
onChange={field.onChange}
options={categories}
appearance={options?.categoryAppearance ?? {}}
invalid={fieldState.invalid}
/>
{fieldState.invalid ? (
<FieldError errors={[fieldState.error]} />
) : null}
</div>
)}
/>
<Controller
name={`splits.${i}.amount`}
control={form.control}
render={({ field, fieldState }) => (
<MoneyInput
id={`tx-split-${i}-amount`}
aria-label={`${f.amount} ${i + 1}`}
name={field.name}
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
placeholder="0,00"
aria-invalid={fieldState.invalid}
/>
)}
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => splits.remove(i)}
disabled={splits.fields.length <= 2}
aria-label={f.removeSplit}
>
<Trash2 />
</Button>
<Controller
name={`splits.${i}.note`}
control={form.control}
render={({ field }) => (
<Input
{...field}
placeholder={f.splitNote}
aria-label={`${f.splitNote} ${i + 1}`}
className="col-span-2 h-8 text-sm"
/>
)}
/>
</div>
))}
{splitMode ? (
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => splits.append({ categoryId: "", amount: "", note: "" })}
disabled={splits.fields.length >= MAX_SPLITS}
>
<Plus />
{f.addSplit}
</Button>
<span
role="status"
className={cn(
"ml-auto text-sm tabular-nums",
remaining === 0 ? "text-income" : "text-expense",
)}
>
{remaining === 0
? f.remainingOk
: `${f.remaining}: ${formatMoney(remaining)}`}
</span>
{remaining !== 0 ? (
<Button type="button" variant="ghost" size="sm" onClick={fillRemaining}>
<Wand2 />
{f.fillRemaining}
</Button>
) : null}
</div>
) : null}
{errors.splits?.message || errors.splits?.root?.message ? (
<FieldError>
{errors.splits.message ?? errors.splits.root?.message}
</FieldError>
) : null}
</div>
) : null}
</FieldGroup>
</CollapsibleContent>
</Collapsible>
{errors.root ? <FieldError>{errors.root.message}</FieldError> : null}
</FieldGroup>
</form>
)}
</ResponsiveDialog>
);
}
@@ -0,0 +1,344 @@
"use client";
import { ArrowLeftRight, CheckCheck, Copy, Pencil, Scale, Split, Trash2 } from "lucide-react";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { IconBadge } from "@/components/appearance/swatch";
import { useQuickAdd } from "@/components/layout/quick-add";
import { ResponsiveDialog } from "@/components/responsive-dialog";
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 { Skeleton } from "@/components/ui/skeleton";
import { AttachmentStrip } from "@/features/attachments/components/attachment-strip";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { formatDate, formatDateTime, formatMoney } from "@/shared/format";
import type { TransactionType } from "@/shared/transactions";
import { getTransactionAction, setTransactionDeletedAction } from "../actions";
import type { TransactionDetail, TransactionListItem } from "../service";
/** İşlem listesi, ayrıntı ve hesap ekstresinin paylaştığı parçalar. */
const t = tr.transactions;
const weekday = new Intl.DateTimeFormat("tr-TR", { weekday: "long", timeZone: "Europe/Istanbul" });
/** "2026-11-05" → "05.11.2026 · Perşembe" */
export function dayLabel(ymd: string) {
const d = new Date(`${ymd}T12:00:00+03:00`);
return `${formatDate(d)} · ${weekday.format(d)}`;
}
export function signed(type: TransactionType, amountMinor: number) {
return type === "income" ? amountMinor : type === "expense" ? -amountMinor : 0;
}
export function Amount({
type,
amountMinor,
className,
}: {
type: TransactionType;
amountMinor: number;
className?: string;
}) {
const text =
type === "income"
? `+${formatMoney(amountMinor)}`
: type === "expense"
? `−${formatMoney(amountMinor)}`
: formatMoney(amountMinor);
return (
<span
className={cn(
"font-semibold whitespace-nowrap tabular-nums",
type === "income" && "text-income",
type === "expense" && "text-expense",
type === "transfer" && "text-muted-foreground",
className,
)}
>
{text}
</span>
);
}
export function RowIcon({ item }: { item: TransactionListItem }) {
if (item.type === "transfer") {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<ArrowLeftRight className="size-4.5" />
</span>
);
}
if (item.isAdjustment) {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<Scale className="size-4.5" />
</span>
);
}
if (item.splitCount) {
return (
<span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-budget/15 text-budget">
<Split className="size-4.5" />
</span>
);
}
return item.category ? (
<IconBadge icon={item.category.icon} color={item.category.color} />
) : (
<IconBadge icon="tag" color="slate" />
);
}
export function rowTitle(item: TransactionListItem) {
if (item.isAdjustment) return t.adjustment;
if (item.payeeName) return item.payeeName;
if (item.description) return item.description;
if (item.type === "transfer") return t.types.transfer;
return item.category?.name ?? t.types[item.type];
}
export function rowSubtitle(item: TransactionListItem) {
if (item.type === "transfer")
return t.list.transfer(item.account.name, item.toAccount?.name ?? "—");
const what = item.isAdjustment
? item.description
: item.splitCount
? t.list.split(item.splitCount)
: (item.category?.path ?? "—");
return `${what} · ${item.account.name}`;
}
function DetailDialog({
detail,
loading,
canWrite,
onOpenChange,
onEdit,
onCopy,
onDelete,
}: {
detail: TransactionDetail | null;
loading: boolean;
canWrite: boolean;
onOpenChange: (o: boolean) => void;
onEdit: (d: TransactionDetail) => void;
onCopy: (d: TransactionDetail) => void;
onDelete: (d: TransactionDetail) => void;
}) {
const d = t.detail;
const row = (label: string, value: React.ReactNode) => (
<div className="flex items-start justify-between gap-4 py-2 text-sm">
<dt className="text-muted-foreground">{label}</dt>
<dd className="text-right">{value}</dd>
</div>
);
return (
<ResponsiveDialog
open={loading || Boolean(detail)}
onOpenChange={onOpenChange}
title={d.title}
footer={
detail && canWrite ? (
<>
<Button variant="destructive" onClick={() => onDelete(detail)}>
<Trash2 />
{t.actions.delete}
</Button>
{/* Mutabakat düzeltmesi düzenlenemez/kopyalanamaz; yalnızca silinebilir. */}
{detail.isAdjustment ? null : (
<>
<Button variant="outline" onClick={() => onCopy(detail)}>
<Copy />
{t.actions.copy}
</Button>
<Button onClick={() => onEdit(detail)}>
<Pencil />
{t.actions.edit}
</Button>
</>
)}
</>
) : null
}
>
{!detail ? (
<div className="flex flex-col gap-3" role="status" aria-label={tr.common.loading}>
<Skeleton className="h-10 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-3">
<RowIcon item={detail} />
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{rowTitle(detail)}</p>
<p className="text-xs text-muted-foreground">{dayLabel(detail.date)}</p>
</div>
<Amount type={detail.type} amountMinor={detail.amountMinor} className="text-lg" />
</div>
<dl className="divide-y border-y">
{row(t.filters.type, <Badge variant="secondary">{t.types[detail.type]}</Badge>)}
{detail.status !== "posted" ? row(t.filters.status, t.statuses[detail.status]) : null}
{row(
detail.type === "transfer" ? t.fields.fromAccount : t.fields.account,
detail.account.name,
)}
{detail.toAccount ? row(t.fields.toAccount, detail.toAccount.name) : null}
{detail.category ? row(t.fields.category, detail.category.path) : null}
{detail.isAdjustment ? row(t.fields.category, t.adjustment) : null}
{detail.payeeName ? row(t.fields.payee, detail.payeeName) : null}
{detail.description ? row(t.fields.description, detail.description) : null}
{detail.tags.length
? row(
t.fields.tags,
<span className="flex flex-wrap justify-end gap-1">
{detail.tags.map((tag) => (
<Badge key={tag} variant="outline">
#{tag}
</Badge>
))}
</span>,
)
: null}
{detail.attachments.length
? row(
tr.attachments.title,
<span className="flex justify-end">
<AttachmentStrip items={detail.attachments} />
</span>,
)
: null}
{detail.reconciledAccountIds.length
? row(
tr.statement.reconcile.title,
<span className="inline-flex items-center gap-1 text-income">
<CheckCheck className="size-4" aria-hidden />
{t.reconciled}
</span>,
)
: null}
{row(d.createdBy, `${detail.createdBy.name} · ${formatDateTime(detail.createdAt)}`)}
{new Date(detail.updatedAt).getTime() - new Date(detail.createdAt).getTime() > 1000
? row(d.updatedBy, `${detail.updatedBy.name} · ${formatDateTime(detail.updatedAt)}`)
: null}
</dl>
{detail.splits.length ? (
<section aria-labelledby="tx-lines">
<h3 id="tx-lines" className="mb-1 text-sm font-medium">
{d.lines}
</h3>
<ul className="divide-y rounded-lg border">
{detail.splits.map((s, i) => (
<li key={i} className="flex items-center gap-3 p-2 text-sm">
<IconBadge icon={s.icon} color={s.color} size="sm" />
<span className="min-w-0 flex-1">
<span className="block truncate">{s.path}</span>
{s.note ? (
<span className="block truncate text-xs text-muted-foreground">
{s.note}
</span>
) : null}
</span>
<span className="tabular-nums">{formatMoney(s.amountMinor)}</span>
</li>
))}
</ul>
</section>
) : null}
</div>
)}
</ResponsiveDialog>
);
}
/**
* Ayrıntı penceresi + silme onayı + geri al bildirimi. Liste ve ekstre aynı davranışı kullanır;
* düzenle/kopyala uygulama genelindeki işlem formunu açar.
*/
export function useTransactionDetail(canWrite: boolean) {
const { openTransactionForm } = useQuickAdd();
const [detail, setDetail] = useState<TransactionDetail | null>(null);
const [loading, setLoading] = useState(false);
const [deleting, setDeleting] = useState<TransactionDetail | null>(null);
const [, startTransition] = useTransition();
async function openDetail(id: string) {
setLoading(true);
setDetail(null);
const res = await getTransactionAction(id);
setLoading(false);
if (res.ok) setDetail(res.data);
else toast.error(res.error);
}
function close() {
setDetail(null);
setLoading(false);
}
function remove(d: TransactionDetail) {
setDeleting(null);
close();
startTransition(async () => {
const res = await setTransactionDeletedAction(d.id, true);
if (!res.ok) return void toast.error(res.error);
toast.success(t.toast.deleted, {
duration: 10_000,
action: {
label: t.actions.restore,
onClick: async () => {
const r = await setTransactionDeletedAction(d.id, false);
if (r.ok) toast.success(t.toast.restored);
else toast.error(r.error);
},
},
});
});
}
const element = (
<>
<DetailDialog
detail={detail}
loading={loading}
canWrite={canWrite}
onOpenChange={(o) => !o && close()}
onEdit={(d) => {
close();
openTransactionForm({ kind: "edit", transaction: d });
}}
onCopy={(d) => {
close();
openTransactionForm({ kind: "copy", transaction: d });
}}
onDelete={setDeleting}
/>
<AlertDialog open={Boolean(deleting)} onOpenChange={(o) => !o && setDeleting(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t.deleteTitle}</AlertDialogTitle>
<AlertDialogDescription>{t.deleteDescription}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tr.common.cancel}</AlertDialogCancel>
<Button variant="destructive" onClick={() => deleting && remove(deleting)}>
{t.actions.delete}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
return { openDetail, element };
}
@@ -0,0 +1,425 @@
"use client";
import { ChevronLeft, ChevronRight, Download, Filter, Paperclip, Plus, X } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { useQuickAdd } from "@/components/layout/quick-add";
import { MoneyInput } from "@/components/money-input";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, 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 { cn } from "@/lib/utils";
import { formatMoney } from "@/shared/format";
import type { TransactionFilters } from "@/shared/schemas/transaction";
import { TRANSACTION_STATUSES, TRANSACTION_TYPES } from "@/shared/transactions";
import type { TransactionFormOptions, TransactionListItem, TransactionPage } from "../service";
import {
Amount,
dayLabel,
RowIcon,
rowSubtitle,
rowTitle,
signed,
useTransactionDetail,
} from "./transaction-parts";
const t = tr.transactions;
const ALL = "__all__";
// --- Filtreler ---
type Options = TransactionFormOptions & { members: { id: string; name: string }[] };
function countActive(f: TransactionFilters) {
return (
[
"from",
"to",
"type",
"hesap",
"kategori",
"kisi",
"durum",
"min",
"max",
"etiket",
"q",
] as const
).filter((k) => f[k] !== undefined && f[k] !== "").length;
}
function FiltersDialog({
open,
onOpenChange,
filters,
raw,
options,
}: {
open: boolean;
onOpenChange: (o: boolean) => void;
filters: TransactionFilters;
raw: Record<string, string>;
options: Options;
}) {
const router = useRouter();
const pathname = usePathname();
const [v, setV] = useState<Record<string, string>>(raw);
const set = (k: string, value: string) => setV((prev) => ({ ...prev, [k]: value }));
const f = t.filters;
function apply(next: Record<string, string>) {
const params = new URLSearchParams();
for (const [k, value] of Object.entries(next)) if (value && k !== "sayfa") params.set(k, value);
router.push(params.size ? `${pathname}?${params}` : pathname);
onOpenChange(false);
}
const select = (key: string, label: string, items: { value: string; label: string }[]) => (
<Field>
<FieldLabel htmlFor={`flt-${key}`}>{label}</FieldLabel>
<Select value={v[key] || ALL} onValueChange={(x) => set(key, x === ALL ? "" : x)}>
<SelectTrigger id={`flt-${key}`} className="w-full">
<SelectValue>{items.find((i) => i.value === v[key])?.label ?? f.all}</SelectValue>
</SelectTrigger>
<SelectContent className="max-h-72">
<SelectItem value={ALL}>{f.all}</SelectItem>
{items.map((i) => (
<SelectItem key={i.value} value={i.value}>
{i.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
);
return (
<ResponsiveDialog
open={open}
onOpenChange={(o) => {
if (o) setV(raw);
onOpenChange(o);
}}
title={f.title}
footer={
<>
<Button variant="outline" onClick={() => apply({})} disabled={!countActive(filters)}>
{f.clear}
</Button>
<Button onClick={() => apply(v)}>{f.apply}</Button>
</>
}
>
<form
onSubmit={(e) => {
e.preventDefault();
apply(v);
}}
>
<FieldGroup>
<Field>
<FieldLabel htmlFor="flt-q">{f.search}</FieldLabel>
<Input
id="flt-q"
value={v.q ?? ""}
onChange={(e) => set("q", e.target.value)}
placeholder={f.searchPlaceholder}
/>
</Field>
<div className="grid grid-cols-2 gap-3">
<Field>
<FieldLabel htmlFor="flt-from">{f.from}</FieldLabel>
<Input
id="flt-from"
type="date"
value={v.from ?? ""}
onChange={(e) => set("from", e.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="flt-to">{f.to}</FieldLabel>
<Input
id="flt-to"
type="date"
value={v.to ?? ""}
onChange={(e) => set("to", e.target.value)}
/>
</Field>
</div>
<div className="grid grid-cols-2 gap-3">
{select(
"type",
f.type,
TRANSACTION_TYPES.map((x) => ({ value: x, label: t.types[x] })),
)}
{select(
"durum",
f.status,
TRANSACTION_STATUSES.map((x) => ({ value: x, label: t.statuses[x] })),
)}
</div>
{select(
"hesap",
f.account,
options.accounts.map((a) => ({ value: a.id, label: a.name })),
)}
{select(
"kategori",
f.category,
options.categories.map((c) => ({
value: c.id,
label: `${c.kind === "income" ? "↑" : "↓"} ${c.path}`,
})),
)}
{select(
"kisi",
f.person,
options.members.map((m) => ({ value: m.id, label: m.name })),
)}
<div className="grid grid-cols-2 gap-3">
<Field>
<FieldLabel htmlFor="flt-min">{f.min}</FieldLabel>
<MoneyInput id="flt-min" value={v.min ?? ""} onChange={(x) => set("min", x)} />
</Field>
<Field>
<FieldLabel htmlFor="flt-max">{f.max}</FieldLabel>
<MoneyInput id="flt-max" value={v.max ?? ""} onChange={(x) => set("max", x)} />
</Field>
</div>
<Field>
<FieldLabel htmlFor="flt-tag">{f.tag}</FieldLabel>
<Input
id="flt-tag"
value={v.etiket ?? ""}
onChange={(e) => set("etiket", e.target.value)}
/>
</Field>
<button type="submit" hidden />
</FieldGroup>
</form>
</ResponsiveDialog>
);
}
// --- Ayrıntı ---
// --- Ana görünüm ---
export function TransactionsView({
data,
filters,
raw,
options,
canWrite,
}: {
data: TransactionPage;
filters: TransactionFilters;
raw: Record<string, string>;
options: Options;
canWrite: boolean;
}) {
const pathname = usePathname();
const { openQuickAdd } = useQuickAdd();
const [filtersOpen, setFiltersOpen] = useState(false);
const { openDetail, element: detailElement } = useTransactionDetail(canWrite);
const active = countActive(filters);
const pageHref = (page: number) => {
const params = new URLSearchParams(raw);
if (page > 1) params.set("sayfa", String(page));
else params.delete("sayfa");
return params.size ? `${pathname}?${params}` : pathname;
};
const exportHref = () => {
const params = new URLSearchParams(raw);
params.delete("sayfa");
return `/islemler/disa-aktar${params.size ? `?${params}` : ""}`;
};
// Sayfadaki işlemleri güne göre grupla (liste zaten tarihe göre sıralı).
const groups: { date: string; items: TransactionListItem[] }[] = [];
for (const item of data.items) {
const last = groups.at(-1);
if (last?.date === item.date) last.items.push(item);
else groups.push({ date: item.date, items: [item] });
}
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" onClick={() => setFiltersOpen(true)}>
<Filter />
{t.filters.open}
{active ? <Badge className="ml-1">{t.filters.active(active)}</Badge> : null}
</Button>
{active ? (
<Button variant="ghost" asChild>
<Link href={pathname}>
<X />
{t.filters.clear}
</Link>
</Button>
) : null}
<Button variant="ghost" asChild className="ml-auto">
{/* Dosya indirme: istemci gezinmesi değil, tam istek. */}
<a href={exportHref()} download>
<Download />
<span className="hidden sm:inline">{t.export}</span>
</a>
</Button>
{canWrite ? (
<Button onClick={() => openQuickAdd()}>
<Plus />
{t.new}
</Button>
) : null}
</div>
<div className="grid grid-cols-3 gap-3">
{(
[
["income", data.sums.incomeMinor, "text-income"],
["expense", data.sums.expenseMinor, "text-expense"],
["net", data.sums.incomeMinor - data.sums.expenseMinor, ""],
] as const
).map(([key, value, tone]) => (
<Card key={key} size="sm">
<CardHeader>
<CardDescription>{t.list.sums[key]}</CardDescription>
<CardTitle
className={cn(
"text-base tabular-nums sm:text-lg",
tone,
key === "net" && value < 0 && "text-expense",
)}
>
{formatMoney(value)}
</CardTitle>
</CardHeader>
</Card>
))}
</div>
{data.items.length === 0 ? (
<p className="rounded-xl border border-dashed p-8 text-center text-muted-foreground">
{active ? t.list.empty : t.list.emptyAll}
</p>
) : (
groups.map((g) => {
const net = g.items.reduce(
(a, i) => a + (i.status === "posted" ? signed(i.type, i.amountMinor) : 0),
0,
);
return (
<section key={g.date} aria-label={dayLabel(g.date)} className="flex flex-col gap-1.5">
<div className="flex items-center justify-between px-1 text-xs font-medium text-muted-foreground">
<h2 className="first-letter:uppercase">{dayLabel(g.date)}</h2>
<span
className={cn(
"tabular-nums",
net > 0 && "text-income",
net < 0 && "text-expense",
)}
title={t.list.dayTotal}
>
{net === 0 ? "" : `${net > 0 ? "+" : "−"}${formatMoney(Math.abs(net))}`}
</span>
</div>
<ul className="divide-y rounded-xl border bg-card">
{g.items.map((item) => (
<li key={item.id}>
<button
type="button"
onClick={() => openDetail(item.id)}
className="flex w-full items-center gap-3 p-3 text-left outline-none hover:bg-muted/50 focus-visible:bg-muted"
>
<RowIcon item={item} />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
<span className="truncate font-medium">{rowTitle(item)}</span>
{item.status !== "posted" ? (
<Badge variant="outline">{t.statuses[item.status]}</Badge>
) : null}
{item.attachmentCount ? (
<Paperclip className="size-3.5 shrink-0 text-muted-foreground" />
) : null}
</span>
<span className="block truncate text-xs text-muted-foreground">
{rowSubtitle(item)}
</span>
</span>
<Amount
type={item.type}
amountMinor={item.amountMinor}
className={cn(item.status !== "posted" && "opacity-60")}
/>
</button>
</li>
))}
</ul>
</section>
);
})
)}
{data.pageCount > 1 ? (
<nav
aria-label={tr.common.page(data.page, data.pageCount)}
className="flex items-center justify-between text-sm text-muted-foreground"
>
<span>{t.list.total(data.total)}</span>
<div className="flex items-center gap-2">
<span className="tabular-nums">{tr.common.page(data.page, data.pageCount)}</span>
<Button
variant="outline"
size="icon-sm"
asChild
disabled={data.page <= 1}
aria-label={tr.common.previous}
>
<Link
href={pageHref(data.page - 1)}
aria-disabled={data.page <= 1}
className={cn(data.page <= 1 && "pointer-events-none opacity-50")}
>
<ChevronLeft />
</Link>
</Button>
<Button variant="outline" size="icon-sm" asChild aria-label={tr.common.next}>
<Link
href={pageHref(data.page + 1)}
aria-disabled={data.page >= data.pageCount}
className={cn(data.page >= data.pageCount && "pointer-events-none opacity-50")}
>
<ChevronRight />
</Link>
</Button>
</div>
</nav>
) : data.total ? (
<p className="text-sm text-muted-foreground">{t.list.total(data.total)}</p>
) : null}
<FiltersDialog
open={filtersOpen}
onOpenChange={setFiltersOpen}
filters={filters}
raw={raw}
options={options}
/>
{detailElement}
</div>
);
}
@@ -0,0 +1,435 @@
import { Types } from "mongoose";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createAccount, listAccounts } from "@/features/accounts/service";
import { setCategoryArchived } from "@/features/categories/service";
import { AccountModel } from "@/models/account";
import { CategoryModel } from "@/models/category";
import { TransactionModel } from "@/models/transaction";
import { transactionFilterSchema, type TransactionForm } from "@/shared/schemas/transaction";
import { transactionEffects } from "@/shared/transactions";
import { setupSeededDb, teardownDb } from "@/test/seeded-db";
import {
createTransaction,
exportTransactions,
getTransaction,
listTransactions,
searchPayees,
setTransactionDeleted,
updateTransaction,
} 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 acc = (name: string, householdId = cakir) =>
AccountModel.findOne({ householdId, name })
.lean()
.then((a) => String(a!._id));
const cat = (key: string, householdId = cakir) =>
CategoryModel.findOne({ householdId, defaultKey: key })
.lean()
.then((c) => String(c!._id));
const filters = (x: Record<string, string> = {}) => transactionFilterSchema.parse(x);
function form(over: Partial<TransactionForm>): TransactionForm {
return {
type: "expense",
amount: 100_00,
date: "2026-06-15",
accountId: "",
toAccountId: null,
categoryId: null,
splits: [],
payee: "",
description: "",
tags: [],
attachmentIds: [],
...over,
};
}
async function mustCreate(user: string, f: TransactionForm, householdId = cakir) {
const r = await createTransaction(ids.user(user), householdId, f);
if (!r.ok) throw new Error(`oluşturulamadı: ${r.error} ${JSON.stringify(r.fieldErrors)}`);
return r.data.id;
}
describe("bakiye tutarlılığı", () => {
let bank = "";
let card = "";
it("gelir, gider, kart harcaması, karta transfer ve bölünmüş işlem bakiyeye doğru yansır", async () => {
const base = {
institution: "",
mealCardProvider: null,
openingDate: "2026-01-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 b = await createAccount(ids.user("ayse"), cakir, {
...base,
name: "T Banka",
type: "bank",
openingBalance: 1_000_00,
});
const c = await createAccount(ids.user("ayse"), cakir, {
...base,
name: "T Kart",
type: "credit_card",
openingBalance: 0,
});
bank = b.ok ? b.data.id : "";
card = c.ok ? c.data.id : "";
const gida = await cat("market.gida");
const temizlik = await cat("market.temizlik");
await mustCreate(
"ayse",
form({ type: "income", amount: 500_00, accountId: bank, categoryId: await cat("ek-gelir") }),
);
await mustCreate("ayse", form({ amount: 200_00, accountId: bank, categoryId: gida }));
await mustCreate("ayse", form({ amount: 300_00, accountId: card, categoryId: gida }));
await mustCreate(
"ayse",
form({ type: "transfer", amount: 300_00, accountId: bank, toAccountId: card }),
);
await mustCreate(
"ayse",
form({
amount: 120_00,
accountId: bank,
splits: [
{ categoryId: gida, amount: 80_00, note: "" },
{ categoryId: temizlik, amount: 40_00, note: "Deterjan" },
],
}),
);
const balances = (await listAccounts(ids.user("ayse"), cakir))!.accounts;
expect(balances.find((a) => a.id === bank)?.balanceMinor).toBe(
1_000_00 + 500_00 - 200_00 - 300_00 - 120_00,
);
expect(balances.find((a) => a.id === card)?.balanceMinor).toBe(-300_00 + 300_00);
});
it("silme bakiyeden düşer, geri alma geri getirir", async () => {
const id = await mustCreate(
"emre",
form({ amount: 50_00, accountId: bank, categoryId: await cat("market.gida") }),
);
const bal = async () =>
(await listAccounts(ids.user("ayse"), cakir))!.accounts.find((a) => a.id === bank)!
.balanceMinor;
const before = await bal();
expect((await setTransactionDeleted(ids.user("emre"), cakir, id, true)).ok).toBe(true);
expect(await bal()).toBe(before! + 50_00);
expect(await getTransaction(ids.user("emre"), cakir, id)).toBeNull();
expect((await setTransactionDeleted(ids.user("emre"), cakir, id, false)).ok).toBe(true);
expect(await bal()).toBe(before);
});
it("tüm hesaplarda bakiye = açılış + Σ transactionEffects (bağımsız doğrulama)", async () => {
const accounts = await AccountModel.find({ householdId: cakir }).lean();
const txs = await TransactionModel.find({ householdId: cakir }).lean();
const expected = new Map(accounts.map((a) => [String(a._id), a.openingBalanceMinor]));
for (const tx of txs) {
for (const e of transactionEffects({
type: tx.type,
status: tx.status,
amountMinor: tx.amountMinor,
accountId: String(tx.accountId),
toAccountId: tx.toAccountId ? String(tx.toAccountId) : null,
deleted: Boolean(tx.deletedAt),
})) {
expected.set(e.accountId, (expected.get(e.accountId) ?? 0) + e.deltaMinor);
}
}
// ayse "yalnızca ben" hesabının sahibi; tüm bakiyeleri görür.
for (const a of (await listAccounts(ids.user("ayse"), cakir, { includeArchived: true }))!
.accounts) {
expect(a.balanceMinor, a.name).toBe(expected.get(a.id));
}
});
});
describe("doğrulama ve izolasyon", () => {
it("gider için gelir kategorisi, başka hanenin hesabı/kategorisi reddedilir", async () => {
const ziraat = await acc("Ziraat Maaş");
const r1 = await createTransaction(
ids.user("ayse"),
cakir,
form({ accountId: ziraat, categoryId: await cat("maas") }),
);
expect(r1.ok).toBe(false);
const r2 = await createTransaction(
ids.user("ayse"),
cakir,
form({ accountId: await acc("Nakit", annemler), categoryId: await cat("market.gida") }),
);
expect(r2.ok).toBe(false);
const r3 = await createTransaction(
ids.user("ayse"),
cakir,
form({ accountId: ziraat, categoryId: await cat("market.gida", annemler) }),
);
expect(r3.ok).toBe(false);
const r4 = await createTransaction(
ids.user("ayse"),
cakir,
form({
accountId: ziraat,
splits: [
{ categoryId: await cat("market.gida"), amount: 50_00, note: "" },
{ categoryId: await cat("market.gida", annemler), amount: 50_00, note: "" },
],
}),
);
expect(r4.ok).toBe(false);
const r5 = await createTransaction(
ids.user("ayse"),
cakir,
form({
type: "transfer",
accountId: ziraat,
toAccountId: await acc("Vakıfbank Emekli", annemler),
}),
);
expect(r5.ok).toBe(false);
});
it("izleyici işlem giremez; başka hane üyesi işlemleri göremez", async () => {
const r = await createTransaction(
ids.user("zeynep"),
cakir,
form({ accountId: await acc("Cüzdan"), categoryId: await cat("market.gida") }),
);
expect(r.ok).toBe(false);
expect(await listTransactions(ids.user("fatma"), cakir, filters())).toBeNull();
const cakirTx = await TransactionModel.findOne({ householdId: cakir }).lean();
// fatma kendi hane kimliğiyle Çakır'ın işlemini isterse bulunamaz.
expect(await getTransaction(ids.user("fatma"), annemler, String(cakirTx!._id))).toBeNull();
expect(
(await setTransactionDeleted(ids.user("fatma"), annemler, String(cakirTx!._id), true)).ok,
).toBe(false);
});
});
describe("“yalnızca ben” hesabı işlemleri", () => {
it("başkasından tamamen gizlenir; o hesaba yalnızca sahibi işlem girer", async () => {
const pluxee = await acc("Ayşe — Pluxee");
const tx = await TransactionModel.findOne({ householdId: cakir, accountId: pluxee }).lean();
const ofEmre = await listTransactions(ids.user("emre"), cakir, filters({ hesap: pluxee }));
expect(ofEmre!.total).toBe(0);
expect(await getTransaction(ids.user("emre"), cakir, String(tx!._id))).toBeNull();
const ofAyse = await listTransactions(ids.user("ayse"), cakir, filters({ hesap: pluxee }));
expect(ofAyse!.total).toBeGreaterThan(0);
const exportEmre = await exportTransactions(ids.user("emre"), cakir, filters());
expect(exportEmre!.some((r) => r.account === "Ayşe — Pluxee")).toBe(false);
const kafe = await cat("eglence.kafe");
expect(
(
await createTransaction(
ids.user("emre"),
cakir,
form({ accountId: pluxee, categoryId: kafe }),
)
).ok,
).toBe(false);
expect(
(
await updateTransaction(
ids.user("emre"),
cakir,
String(tx!._id),
form({ accountId: pluxee, categoryId: kafe }),
)
).ok,
).toBe(false);
expect(
(
await createTransaction(
ids.user("ayse"),
cakir,
form({ accountId: pluxee, categoryId: kafe }),
)
).ok,
).toBe(true);
});
});
describe("arşivli kategori", () => {
it("yeni işlemde kullanılamaz, mevcut işlemde korunur", async () => {
const giyim = await cat("giyim");
const cuzdan = await acc("Cüzdan");
const id = await mustCreate("ayse", form({ accountId: cuzdan, categoryId: giyim }));
expect((await setCategoryArchived(ids.user("ayse"), cakir, giyim, true)).ok).toBe(true);
expect(
(
await createTransaction(
ids.user("ayse"),
cakir,
form({ accountId: cuzdan, categoryId: giyim }),
)
).ok,
).toBe(false);
expect(
(
await updateTransaction(
ids.user("ayse"),
cakir,
id,
form({ accountId: cuzdan, categoryId: giyim, description: "düzeltme" }),
)
).ok,
).toBe(true);
await setCategoryArchived(ids.user("ayse"), cakir, giyim, false);
});
});
describe("filtreler", () => {
it("üst kategori filtresi alt kategorileri ve bölünmüş kalemleri kapsar", async () => {
const market = await cat("market");
const page = await listTransactions(ids.user("ayse"), cakir, filters({ kategori: market }));
expect(page!.total).toBe(
await TransactionModel.countDocuments({
householdId: cakir,
deletedAt: null,
effectiveCategoryIds: {
$in: await CategoryModel.find({
householdId: cakir,
$or: [{ _id: market }, { ancestors: new Types.ObjectId(market) }],
}).distinct("_id"),
},
}),
);
expect(page!.items.some((i) => i.splitCount > 0)).toBe(true);
});
it("tarih aralığı İstanbul gününe göre (gün dahil)", async () => {
const id = await mustCreate(
"ayse",
form({
date: "2026-01-15",
accountId: await acc("Cüzdan"),
categoryId: await cat("market.gida"),
payee: "Tarih Testi",
}),
);
const same = await listTransactions(
ids.user("ayse"),
cakir,
filters({ from: "2026-01-15", to: "2026-01-15", q: "tarih testi" }),
);
expect(same!.items.map((i) => i.id)).toEqual([id]);
const after = await listTransactions(
ids.user("ayse"),
cakir,
filters({ from: "2026-01-16", q: "tarih testi" }),
);
expect(after!.total).toBe(0);
});
it("Türkçe arama, tutar aralığı, kişi, etiket ve hesap (transfer hedefi dahil)", async () => {
const q = await listTransactions(ids.user("ayse"), cakir, filters({ q: "MİGROS" }));
expect(q!.total).toBeGreaterThan(0);
expect(q!.items.every((i) => i.payeeName === "Migros")).toBe(true);
const range = await listTransactions(
ids.user("ayse"),
cakir,
filters({ min: "1.000", max: "2.000" }),
);
expect(range!.items.every((i) => i.amountMinor >= 1_000_00 && i.amountMinor <= 2_000_00)).toBe(
true,
);
const byEmre = await listTransactions(
ids.user("ayse"),
cakir,
filters({ kisi: ids.user("emre") }),
);
expect(byEmre!.items.every((i) => i.createdBy.id === ids.user("emre"))).toBe(true);
const tagged = await listTransactions(ids.user("ayse"), cakir, filters({ etiket: "İndirim" }));
expect(tagged!.items.every((i) => i.tags.includes("indirim"))).toBe(true);
const cuzdan = await acc("Cüzdan");
const byAccount = await listTransactions(
ids.user("ayse"),
cakir,
filters({ hesap: cuzdan, type: "transfer" }),
);
expect(byAccount!.total).toBeGreaterThan(0);
expect(
byAccount!.items.every((i) => i.toAccount?.id === cuzdan || i.account.id === cuzdan),
).toBe(true);
});
it("geçersiz filtre değerleri yok sayılır (enjeksiyon yok)", async () => {
const f = transactionFilterSchema.parse({
hesap: "{$ne:null}",
kategori: "x",
min: "abc",
sayfa: "-3",
q: ".*",
});
expect(f.hesap).toBeUndefined();
expect(f.kategori).toBeUndefined();
expect(f.min).toBeUndefined();
expect(f.sayfa).toBe(1);
// ".*" düz metin olarak aranır (regex kaçışı).
expect((await listTransactions(ids.user("ayse"), cakir, f))!.total).toBe(0);
});
});
describe("satıcı kuralları", () => {
it("son kullanılan kategori ve hesap önerilir", async () => {
const cuzdan = await acc("Cüzdan");
const ilac = await cat("saglik.ilac");
await mustCreate("ayse", form({ accountId: cuzdan, categoryId: ilac, payee: "Şifa Eczanesi" }));
const [s] = await searchPayees(ids.user("ayse"), cakir, "sifa");
expect(s).toMatchObject({
name: "Şifa Eczanesi",
lastAccountId: cuzdan,
lastCategoryId: ilac,
lastType: "expense",
});
// Başka hane satıcıyı görmez.
expect(await searchPayees(ids.user("fatma"), annemler, "sifa")).toEqual([]);
});
});
describe("CSV", () => {
it("bölünmüş işlem kalem başına satır üretir, işaret türe göre", async () => {
const rows = (await exportTransactions(ids.user("ayse"), cakir, filters()))!;
const split = await TransactionModel.findOne({
householdId: cakir,
"splits.1": { $exists: true },
deletedAt: null,
}).lean();
const lines = rows.filter((r) => r.no === String(split!._id));
expect(lines).toHaveLength(split!.splits.length);
expect(lines.reduce((a, r) => a + r.amountMinor, 0)).toBe(-split!.amountMinor);
expect(rows.find((r) => r.type === "income")!.amountMinor).toBeGreaterThan(0);
});
});
+828
View File
@@ -0,0 +1,828 @@
import "server-only";
import mongoose, { Types, type ClientSession, type PipelineStage } from "mongoose";
import {
listOwnerAttachments,
syncOwnerAttachments,
type AttachmentInfo,
} from "@/features/attachments/service";
import { resolveMembership } from "@/features/households/service";
import { buildTree, toOptions, type CategoryOption } from "@/features/categories/tree";
import { tr } from "@/i18n/tr";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { writeAudit } from "@/lib/audit";
import { getDb } from "@/lib/db/mongo";
import { toObjectId } from "@/lib/object-id";
import { AccountModel } from "@/models/account";
import { CategoryModel } from "@/models/category";
import { PayeeModel } from "@/models/payee";
import { TransactionModel } from "@/models/transaction";
import type { AccountType } from "@/shared/accounts";
import { allowedAttachmentKinds } from "@/shared/attachments";
import type { IconKey, Swatch } from "@/shared/appearance";
import { istanbulDayStart, toIstanbulYmd } from "@/shared/dates";
import type { CategoryKind } from "@/shared/schemas/category";
import type { TransactionFilters, TransactionForm } from "@/shared/schemas/transaction";
import { compareTr, foldTr } from "@/shared/search";
import { normalizeTags, type TransactionStatus, type TransactionType } from "@/shared/transactions";
/**
* İşlem servisi (Bölüm 6.3). Okuma: viewer; yazma: member.
* Başkasının "yalnızca ben" hesabına dokunan işlemler o kullanıcıdan tamamen gizlenir
* (işlemler bakiyeyi ele verir) ve bu hesaplara yalnızca hesap sahibi işlem girebilir.
*/
const t = tr.transactions;
export const PAGE_SIZE = 25;
const DAY_MS = 24 * 60 * 60 * 1000;
// --- Hane bağlamı: hesaplar, kategoriler, görünürlük ---
type AccountInfo = {
id: Types.ObjectId;
name: string;
type: AccountType;
archived: boolean;
hidden: boolean;
icon: IconKey;
color: Swatch;
};
type CategoryInfo = {
id: Types.ObjectId;
kind: CategoryKind;
name: string;
path: string;
archived: boolean;
icon: IconKey;
color: Swatch;
ancestors: string[];
};
/** Hane bağlamı (hesap/kategori haritaları, gizli hesaplar). İşlemler modülü içinde paylaşılır. */
export async function loadContext(
userId: string,
householdId: string,
minRole: "viewer" | "member",
) {
const m = await resolveMembership(userId, householdId, minRole);
if (!m) return null;
const [accounts, categories] = await Promise.all([
AccountModel.find({ householdId: m.householdId })
.select({ name: 1, type: 1, archivedAt: 1, isPrivate: 1, ownerUserId: 1, icon: 1, color: 1 })
.lean(),
CategoryModel.find({ householdId: m.householdId })
.select({
name: 1,
kind: 1,
parentId: 1,
order: 1,
archivedAt: 1,
icon: 1,
color: 1,
ancestors: 1,
})
.lean(),
]);
const accountMap = new Map<string, AccountInfo>(
accounts.map((a) => [
String(a._id),
{
id: a._id,
name: a.name,
type: a.type,
archived: Boolean(a.archivedAt),
hidden: Boolean(a.isPrivate) && String(a.ownerUserId) !== userId,
icon: a.icon as IconKey,
color: a.color as Swatch,
},
]),
);
const flat = categories.map((c) => ({
id: String(c._id),
kind: c.kind,
name: c.name,
parentId: c.parentId ? String(c.parentId) : null,
order: c.order,
archived: Boolean(c.archivedAt),
}));
const paths = new Map(
toOptions(buildTree(flat), { includeArchived: true }).map((o) => [o.id, o.path]),
);
const categoryMap = new Map<string, CategoryInfo>(
categories.map((c) => [
String(c._id),
{
id: c._id,
kind: c.kind,
name: c.name,
path: paths.get(String(c._id)) ?? c.name,
archived: Boolean(c.archivedAt),
icon: c.icon as IconKey,
color: c.color as Swatch,
ancestors: c.ancestors.map(String),
},
]),
);
const hiddenAccountIds = [...accountMap.values()].filter((a) => a.hidden).map((a) => a.id);
return { m, accountMap, categoryMap, hiddenAccountIds, flatCategories: flat };
}
export type Ctx = NonNullable<Awaited<ReturnType<typeof loadContext>>>;
/** Gizli hesaplara dokunan işlemleri dışlayan temel filtre. */
function baseFilter(ctx: Ctx): Record<string, unknown> {
const f: Record<string, unknown> = { householdId: ctx.m.householdId, deletedAt: null };
if (ctx.hiddenAccountIds.length) {
f.accountId = { $nin: ctx.hiddenAccountIds };
f.toAccountId = { $nin: ctx.hiddenAccountIds };
}
return f;
}
// --- Bakiye ---
/**
* Hesap bazında işlem etkileri toplamı (kuruş): yalnızca posted ve silinmemiş işlemler.
* transactionEffects ile aynı kural: gelir +, gider −, transfer kaynak − / hedef +.
*/
export async function computeAccountDeltas(
householdId: Types.ObjectId,
): Promise<Map<string, number>> {
const pipeline: PipelineStage[] = [
{ $match: { householdId, status: "posted", deletedAt: null } },
{
$project: {
effects: [
{
a: "$accountId",
d: {
$cond: [
{ $eq: ["$type", "income"] },
"$amountMinor",
{ $multiply: ["$amountMinor", -1] },
],
},
},
{
a: { $cond: [{ $eq: ["$type", "transfer"] }, "$toAccountId", null] },
d: "$amountMinor",
},
],
},
},
{ $unwind: "$effects" },
{ $match: { "effects.a": { $ne: null } } },
{ $group: { _id: "$effects.a", delta: { $sum: "$effects.d" } } },
];
const rows = await TransactionModel.aggregate<{ _id: Types.ObjectId; delta: number }>(pipeline);
return new Map(rows.map((r) => [String(r._id), r.delta]));
}
// --- Doğrulama ---
function checkAccount(ctx: Ctx, id: string | null, keep?: string | null): Types.ObjectId | null {
if (!id) return null;
const a = ctx.accountMap.get(id);
// Düzenlemede işlemin zaten bağlı olduğu arşivli hesap korunabilir.
if (!a || a.hidden || (a.archived && id !== keep)) return null;
return a.id;
}
function checkCategory(
ctx: Ctx,
id: string,
kind: CategoryKind,
keep: Set<string>,
): Types.ObjectId | null {
const c = ctx.categoryMap.get(id);
if (!c || c.kind !== kind || (c.archived && !keep.has(id))) return null;
return c.id;
}
type Existing = {
accountId: Types.ObjectId;
toAccountId?: Types.ObjectId | null;
categoryId?: Types.ObjectId | null;
splits?: { categoryId: Types.ObjectId }[];
};
function buildDoc(
ctx: Ctx,
input: TransactionForm,
existing?: Existing,
): ActionResult<Record<string, unknown>> {
const date = istanbulDayStart(input.date);
if (!date) return fail(tr.validation.date, { date: tr.validation.date });
const accountId = checkAccount(
ctx,
input.accountId,
existing ? String(existing.accountId) : null,
);
if (!accountId)
return fail(t.validation.accountInvalid, { accountId: t.validation.accountInvalid });
let toAccountId: Types.ObjectId | null = null;
let categoryId: Types.ObjectId | null = null;
let splits: { categoryId: Types.ObjectId; amountMinor: number; note: string }[] = [];
if (input.type === "transfer") {
toAccountId = checkAccount(
ctx,
input.toAccountId,
existing?.toAccountId ? String(existing.toAccountId) : null,
);
if (!toAccountId || toAccountId.equals(accountId)) {
return fail(t.validation.accountInvalid, { toAccountId: t.validation.accountInvalid });
}
} else {
const kind: CategoryKind = input.type;
const keep = new Set(
[existing?.categoryId, ...(existing?.splits ?? []).map((s) => s.categoryId)]
.filter(Boolean)
.map(String),
);
if (input.splits.length >= 2) {
for (const [i, s] of input.splits.entries()) {
const cid = checkCategory(ctx, s.categoryId, kind, keep);
if (!cid)
return fail(t.validation.categoryInvalid, {
[`splits.${i}.categoryId`]: t.validation.categoryInvalid,
});
splits.push({ categoryId: cid, amountMinor: s.amount, note: s.note });
}
} else {
categoryId = input.categoryId ? checkCategory(ctx, input.categoryId, kind, keep) : null;
if (!categoryId)
return fail(t.validation.categoryInvalid, { categoryId: t.validation.categoryInvalid });
splits = [];
}
}
const effective = [
...new Set([categoryId, ...splits.map((s) => s.categoryId)].filter(Boolean).map(String)),
].map((id) => new Types.ObjectId(id));
const payeeName = input.payee.trim();
return ok({
type: input.type,
date,
accountId,
toAccountId,
amountMinor: input.amount,
categoryId,
splits,
effectiveCategoryIds: effective,
payeeName,
description: input.description,
searchText: foldTr([payeeName, input.description, ...splits.map((s) => s.note)].join(" ")),
tags: normalizeTags(input.tags),
});
}
/** Satıcı kuralını günceller (son kategori ve hesap) ve kimliğini döner. */
async function touchPayee(
householdId: Types.ObjectId,
name: string,
type: TransactionType,
accountId: Types.ObjectId,
categoryId: Types.ObjectId | null,
): Promise<Types.ObjectId | null> {
if (!name) return null;
const doc = await PayeeModel.findOneAndUpdate(
{ householdId, nameKey: foldTr(name) },
{
$setOnInsert: { householdId, nameKey: foldTr(name) },
$set: {
name,
lastType: type,
lastAccountId: accountId,
lastCategoryId: categoryId,
lastUsedAt: new Date(),
},
$inc: { useCount: 1 },
},
{ upsert: true, returnDocument: "after" },
).lean();
return doc?._id ?? null;
}
// --- Yazma ---
export async function createTransaction(
actorId: string,
householdId: string,
input: TransactionForm,
): Promise<ActionResult<{ id: string }>> {
const ctx = await loadContext(actorId, householdId, "member");
if (!ctx) return fail(tr.common.unauthorized);
const built = buildDoc(ctx, input);
if (!built.ok) return built;
const d = built.data as { accountId: Types.ObjectId; categoryId: Types.ObjectId | null };
// Bölünmüş işlemde tek bir kategori önerilemez; satıcı kuralı yalnızca hesabı hatırlar.
const payeeId = await touchPayee(
ctx.m.householdId,
input.payee,
input.type,
d.accountId,
d.categoryId,
);
const actor = new Types.ObjectId(actorId);
try {
let id = "";
await mongoose.connection.transaction(async (session) => {
const [doc] = await TransactionModel.create(
[
{
...built.data,
householdId: ctx.m.householdId,
status: "posted",
payeeId,
createdBy: actor,
updatedBy: actor,
},
],
{ session },
);
id = String(doc!._id);
await attach(ctx, actorId, doc!._id, input, session);
});
return ok({ id });
} catch (error) {
if (error instanceof AttachmentError) return error.result;
throw error;
}
}
/** Ek senkronizasyonu başarısızsa transaction'ı geri almak için fırlatılır. */
class AttachmentError extends Error {
constructor(readonly result: ActionResult<never>) {
super(result.ok ? "" : result.error);
}
}
async function attach(
ctx: Ctx,
actorId: string,
transactionId: Types.ObjectId,
input: TransactionForm,
session: ClientSession,
) {
const synced = await syncOwnerAttachments({
householdId: ctx.m.householdId,
actorId,
ownerType: "transaction",
ownerId: transactionId,
ids: input.attachmentIds,
allowedKinds: allowedAttachmentKinds(input.type),
session,
});
if (!synced.ok) throw new AttachmentError(synced);
await TransactionModel.updateOne(
{ _id: transactionId, householdId: ctx.m.householdId },
{ $set: { attachmentCount: synced.data } },
{ session },
);
}
async function loadOwnTransaction(
ctx: Ctx,
transactionId: string,
{ includeDeleted = false } = {},
) {
const id = toObjectId(transactionId);
if (!id) return null;
const filter: Record<string, unknown> = { ...baseFilter(ctx), _id: id };
if (includeDeleted) delete filter.deletedAt;
return TransactionModel.findOne(filter).lean();
}
export async function updateTransaction(
actorId: string,
householdId: string,
transactionId: string,
input: TransactionForm,
): Promise<ActionResult> {
const ctx = await loadContext(actorId, householdId, "member");
if (!ctx) return fail(tr.common.unauthorized);
const current = await loadOwnTransaction(ctx, transactionId);
if (!current) return fail(tr.common.notFound);
if (current.isAdjustment) return fail(t.adjustmentReadOnly);
const built = buildDoc(ctx, input, current);
if (!built.ok) return built;
const d = built.data as {
type: TransactionType;
date: Date;
amountMinor: number;
accountId: Types.ObjectId;
toAccountId: Types.ObjectId | null;
categoryId: Types.ObjectId | null;
};
const payeeId = await touchPayee(
ctx.m.householdId,
input.payee,
input.type,
d.accountId,
d.categoryId,
);
// Bakiyeyi etkileyen bir alan değiştiyse mutabakat işareti geçersizleşir.
const balanceChanged =
d.type !== current.type ||
d.amountMinor !== current.amountMinor ||
d.date.getTime() !== new Date(current.date).getTime() ||
!d.accountId.equals(current.accountId) ||
String(d.toAccountId ?? "") !== String(current.toAccountId ?? "");
try {
await mongoose.connection.transaction(async (session) => {
await TransactionModel.updateOne(
{ _id: current._id, householdId: ctx.m.householdId },
{
$set: {
...built.data,
payeeId,
updatedBy: new Types.ObjectId(actorId),
...(balanceChanged ? { reconciledAccountIds: [] } : {}),
},
},
{ session },
);
await attach(ctx, actorId, current._id, input, session);
});
} catch (error) {
if (error instanceof AttachmentError) return error.result;
throw error;
}
return ok(undefined);
}
export async function setTransactionDeleted(
actorId: string,
householdId: string,
transactionId: string,
deleted: boolean,
): Promise<ActionResult> {
const ctx = await loadContext(actorId, householdId, "member");
if (!ctx) return fail(tr.common.unauthorized);
const current = await loadOwnTransaction(ctx, transactionId, { includeDeleted: true });
if (!current || Boolean(current.deletedAt) === deleted) return fail(tr.common.notFound);
const actor = new Types.ObjectId(actorId);
await TransactionModel.updateOne(
{ _id: current._id, householdId: ctx.m.householdId },
{ $set: { deletedAt: deleted ? new Date() : null, updatedBy: actor } },
);
await writeAudit({
action: deleted ? "transaction.delete" : "transaction.restore",
actorId: actor,
householdId: ctx.m.householdId,
targetType: "transaction",
targetId: transactionId,
diff: {
type: current.type,
amountMinor: current.amountMinor,
date: toIstanbulYmd(current.date),
},
});
return ok(undefined);
}
// --- Okuma ---
export type TransactionListItem = {
id: string;
type: TransactionType;
status: TransactionStatus;
date: string;
amountMinor: number;
account: { id: string; name: string };
toAccount: { id: string; name: string } | null;
category: { id: string; name: string; path: string; icon: IconKey; color: Swatch } | null;
splitCount: number;
payeeName: string;
description: string;
tags: string[];
createdBy: { id: string; name: string };
attachmentCount: number;
/** Mutabakat düzeltmesi (kategorisiz, düzenlenemez). */
isAdjustment: boolean;
/** Mutabakatı yapılmış hesaplar. */
reconciledAccountIds: string[];
};
export type TransactionDetail = TransactionListItem & {
splits: {
categoryId: string;
path: string;
icon: IconKey;
color: Swatch;
amountMinor: number;
note: string;
}[];
updatedBy: { id: string; name: string };
createdAt: string;
updatedAt: string;
/** Düzenleme formu için ham kimlikler. */
categoryId: string | null;
attachments: AttachmentInfo[];
};
export async function userNames(ids: Types.ObjectId[]): Promise<Map<string, string>> {
const unique = [...new Set(ids.map(String))].map((id) => new Types.ObjectId(id));
const users = await getDb()
.collection("user")
.find({ _id: { $in: unique } }, { projection: { name: 1 } })
.toArray();
return new Map(users.map((u) => [String(u._id), String(u.name ?? "—")]));
}
export type LeanTx = Awaited<ReturnType<typeof TransactionModel.find>>[number] & {
_id: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
};
export function toItem(ctx: Ctx, tx: LeanTx, names: Map<string, string>): TransactionListItem {
const acc = (id: Types.ObjectId | null | undefined) => {
if (!id) return null;
const a = ctx.accountMap.get(String(id));
return { id: String(id), name: a?.name ?? "—" };
};
const cat = tx.categoryId ? ctx.categoryMap.get(String(tx.categoryId)) : undefined;
return {
id: String(tx._id),
type: tx.type,
status: tx.status,
date: toIstanbulYmd(tx.date),
amountMinor: tx.amountMinor,
account: acc(tx.accountId)!,
toAccount: acc(tx.toAccountId),
category: cat
? { id: String(cat.id), name: cat.name, path: cat.path, icon: cat.icon, color: cat.color }
: null,
splitCount: tx.splits?.length ?? 0,
payeeName: tx.payeeName ?? "",
description: tx.description ?? "",
tags: tx.tags ?? [],
createdBy: { id: String(tx.createdBy), name: names.get(String(tx.createdBy)) ?? "—" },
attachmentCount: tx.attachmentCount ?? 0,
isAdjustment: Boolean(tx.isAdjustment),
reconciledAccountIds: (tx.reconciledAccountIds ?? []).map(String),
};
}
const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
function filterQuery(ctx: Ctx, f: TransactionFilters): Record<string, unknown> {
const q: Record<string, unknown> = baseFilter(ctx);
const and: Record<string, unknown>[] = [];
const from = f.from ? istanbulDayStart(f.from) : null;
const to = f.to ? istanbulDayStart(f.to) : null;
if (from || to) {
q.date = {
...(from ? { $gte: from } : {}),
...(to ? { $lt: new Date(to.getTime() + DAY_MS) } : {}),
};
}
if (f.type) q.type = f.type;
if (f.durum) q.status = f.durum;
if (f.hesap) {
const id = toObjectId(f.hesap);
// Gizli hesap filtresi sonuç vermez (baseFilter zaten dışlar).
and.push({ $or: [{ accountId: id }, { toAccountId: id }] });
}
if (f.kategori) {
// Alt kategoriler dahil.
const ids = [...ctx.categoryMap.values()]
.filter((c) => String(c.id) === f.kategori || c.ancestors.includes(f.kategori!))
.map((c) => c.id);
q.effectiveCategoryIds = { $in: ids };
}
if (f.kisi) q.createdBy = toObjectId(f.kisi);
if (f.min !== undefined || f.max !== undefined) {
q.amountMinor = {
...(f.min !== undefined ? { $gte: f.min } : {}),
...(f.max !== undefined ? { $lte: f.max } : {}),
};
}
if (f.etiket) q.tags = normalizeTags(f.etiket)[0] ?? "";
if (f.q) q.searchText = { $regex: escapeRegex(foldTr(f.q)) };
if (and.length) q.$and = and;
return q;
}
export type TransactionPage = {
items: TransactionListItem[];
total: number;
page: number;
pageCount: number;
sums: { incomeMinor: number; expenseMinor: number };
};
export async function listTransactions(
userId: string,
householdId: string,
filters: TransactionFilters,
): Promise<TransactionPage | null> {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return null;
const query = filterQuery(ctx, filters);
const [total, sumRows] = await Promise.all([
TransactionModel.countDocuments(query),
TransactionModel.aggregate<{ _id: TransactionType; sum: number }>([
{
$match: {
...query,
status: query.status ?? "posted",
type: query.type ?? { $in: ["income", "expense"] },
},
},
{ $group: { _id: "$type", sum: { $sum: "$amountMinor" } } },
]),
]);
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE));
const page = Math.min(filters.sayfa, pageCount);
const rows = (await TransactionModel.find(query)
.sort({ date: -1, createdAt: -1 })
.skip((page - 1) * PAGE_SIZE)
.limit(PAGE_SIZE)
.lean()) as unknown as LeanTx[];
const names = await userNames(rows.map((r) => r.createdBy as Types.ObjectId));
return {
items: rows.map((r) => toItem(ctx, r, names)),
total,
page,
pageCount,
sums: {
incomeMinor: sumRows.find((r) => r._id === "income")?.sum ?? 0,
expenseMinor: sumRows.find((r) => r._id === "expense")?.sum ?? 0,
},
};
}
export async function getTransaction(
userId: string,
householdId: string,
transactionId: string,
): Promise<TransactionDetail | null> {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return null;
const tx = (await loadOwnTransaction(ctx, transactionId)) as unknown as LeanTx | null;
if (!tx) return null;
const [names, attachments] = await Promise.all([
userNames([tx.createdBy as Types.ObjectId, tx.updatedBy as Types.ObjectId]),
tx.attachmentCount
? listOwnerAttachments(ctx.m.householdId, "transaction", tx._id)
: Promise.resolve([]),
]);
return {
attachments,
...toItem(ctx, tx, names),
categoryId: tx.categoryId ? String(tx.categoryId) : null,
splits: (tx.splits ?? []).map((s) => {
const c = ctx.categoryMap.get(String(s.categoryId));
return {
categoryId: String(s.categoryId),
path: c?.path ?? "—",
icon: c?.icon ?? "tag",
color: c?.color ?? "slate",
amountMinor: s.amountMinor,
note: s.note ?? "",
};
}),
updatedBy: { id: String(tx.updatedBy), name: names.get(String(tx.updatedBy)) ?? "—" },
createdAt: new Date(tx.createdAt).toISOString(),
updatedAt: new Date(tx.updatedAt).toISOString(),
};
}
/** CSV için tüm eşleşen işlemler (sayfalama yok; üst sınır 20.000). Bölünmüş işlem kalem başına satır. */
export async function exportTransactions(
userId: string,
householdId: string,
filters: TransactionFilters,
) {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return null;
const rows = await TransactionModel.find(filterQuery(ctx, filters))
.sort({ date: -1, createdAt: -1 })
.limit(20_000)
.lean();
const names = await userNames(rows.map((r) => r.createdBy as Types.ObjectId));
const accountName = (id: Types.ObjectId | null | undefined) =>
id ? (ctx.accountMap.get(String(id))?.name ?? "") : "";
const categoryPath = (id: Types.ObjectId | null | undefined) =>
id ? (ctx.categoryMap.get(String(id))?.path ?? "") : "";
const sign = (type: TransactionType) => (type === "income" ? 1 : type === "expense" ? -1 : 1);
const out: {
no: string;
date: string;
type: TransactionType;
status: TransactionStatus;
account: string;
toAccount: string;
category: string;
payee: string;
description: string;
note: string;
tags: string;
amountMinor: number;
createdBy: string;
}[] = [];
for (const r of rows) {
const common = {
no: String(r._id),
date: toIstanbulYmd(r.date),
type: r.type,
status: r.status,
account: accountName(r.accountId),
toAccount: accountName(r.toAccountId),
payee: r.payeeName ?? "",
description: r.description ?? "",
tags: (r.tags ?? []).join(", "),
createdBy: names.get(String(r.createdBy)) ?? "",
};
if (r.splits?.length) {
for (const s of r.splits) {
out.push({
...common,
category: categoryPath(s.categoryId),
note: s.note ?? "",
amountMinor: sign(r.type) * s.amountMinor,
});
}
} else {
out.push({
...common,
category: r.isAdjustment ? t.adjustment : categoryPath(r.categoryId),
note: "",
amountMinor: sign(r.type) * r.amountMinor,
});
}
}
return out;
}
// --- Form seçenekleri ve satıcı önerileri ---
export type TransactionFormOptions = {
accounts: { id: string; name: string; type: AccountType; icon: IconKey; color: Swatch }[];
categories: CategoryOption[];
categoryAppearance: Record<string, { icon: IconKey; color: Swatch }>;
};
export async function getTransactionFormOptions(
userId: string,
householdId: string,
): Promise<TransactionFormOptions | null> {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return null;
const accounts = (
await AccountModel.find({ householdId: ctx.m.householdId, archivedAt: null })
.select({ name: 1, type: 1, icon: 1, color: 1, order: 1, isPrivate: 1, ownerUserId: 1 })
.lean()
)
.filter((a) => !a.isPrivate || String(a.ownerUserId) === userId)
.sort((a, b) => a.order - b.order || compareTr(a.name, b.name))
.map((a) => ({
id: String(a._id),
name: a.name,
type: a.type,
icon: a.icon as IconKey,
color: a.color as Swatch,
}));
const categories = toOptions(buildTree(ctx.flatCategories));
const categoryAppearance = Object.fromEntries(
[...ctx.categoryMap.values()].map((c) => [String(c.id), { icon: c.icon, color: c.color }]),
);
return { accounts, categories, categoryAppearance };
}
export type PayeeSuggestion = {
name: string;
lastType: TransactionType;
lastCategoryId: string | null;
lastAccountId: string | null;
};
/** Satıcı önerileri: ada göre (Türkçe normalize, baştan veya içinden), kullanım sıklığına göre. */
export async function searchPayees(
userId: string,
householdId: string,
query: string,
): Promise<PayeeSuggestion[]> {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return [];
const key = foldTr(query);
const filter: Record<string, unknown> = { householdId: ctx.m.householdId };
if (key) filter.nameKey = { $regex: escapeRegex(key) };
const rows = await PayeeModel.find(filter).sort({ useCount: -1, lastUsedAt: -1 }).limit(8).lean();
return rows.map((p) => {
const acc = p.lastAccountId ? ctx.accountMap.get(String(p.lastAccountId)) : undefined;
const cat = p.lastCategoryId ? ctx.categoryMap.get(String(p.lastCategoryId)) : undefined;
return {
name: p.name,
lastType: p.lastType,
// Öneri yalnızca hâlâ kullanılabilir hesap/kategoriyi gösterir.
lastAccountId: acc && !acc.hidden && !acc.archived ? String(acc.id) : null,
lastCategoryId: cat && !cat.archived ? String(cat.id) : null,
};
});
}
@@ -0,0 +1,242 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { listAccounts } from "@/features/accounts/service";
import { AccountModel } from "@/models/account";
import { AuditLogModel } from "@/models/audit-log";
import { CategoryModel } from "@/models/category";
import { ReconciliationModel } from "@/models/reconciliation";
import { TransactionModel } from "@/models/transaction";
import { todayIstanbul } from "@/shared/dates";
import { reconcileSchema } from "@/shared/schemas/reconciliation";
import type { TransactionForm } from "@/shared/schemas/transaction";
import { shiftMonth } from "@/shared/statement";
import { setupSeededDb, teardownDb } from "@/test/seeded-db";
import {
createTransaction,
getTransaction,
setTransactionDeleted,
updateTransaction,
} from "./service";
import {
currentMonth,
getAccountStatement,
previewReconciliation,
reconcileAccount,
} from "./statement";
let ids: Awaited<ReturnType<typeof setupSeededDb>>;
let cakir = "";
let ayse = "";
let emre = "";
let zeynep = "";
let fatma = "";
beforeAll(async () => {
ids = await setupSeededDb();
cakir = ids.household("Çakır Ailesi");
ayse = ids.user("ayse");
emre = ids.user("emre");
zeynep = ids.user("zeynep");
fatma = ids.user("fatma");
});
afterAll(teardownDb);
const acc = (name: string) =>
AccountModel.findOne({ householdId: cakir, name })
.lean()
.then((a) => String(a!._id));
const cat = (key: string) =>
CategoryModel.findOne({ householdId: cakir, defaultKey: key })
.lean()
.then((c) => String(c!._id));
const input = (statementDate: string, statementBalance: string, acceptAdjustment = false) =>
reconcileSchema.parse({ statementDate, statementBalance, acceptAdjustment });
const tl = (minor: number) => (minor / 100).toFixed(2).replace(".", ",");
async function balanceOf(userId: string, accountId: string) {
const list = await listAccounts(userId, cakir);
return list!.accounts.find((a) => a.id === accountId)!.balanceMinor!;
}
describe("hesap ekstresi", () => {
it("yürüyen bakiye tutarlı; ay sonu = sonraki ay başı; güncel bakiye hesap listesiyle aynı", async () => {
const ziraat = await acc("Ziraat Maaş");
const month = shiftMonth(currentMonth(), -1);
const s = (await getAccountStatement(ayse, cakir, ziraat, month))!;
expect(s.rows.length).toBeGreaterThan(0);
// Yeniden eskiye: ilk satırın bakiyesi ay sonu bakiyesi.
expect(s.rows[0]!.balanceMinor).toBe(s.closingMinor);
expect(s.closingMinor).toBe(s.openingMinor + s.inflowMinor - s.outflowMinor);
const asc = [...s.rows].reverse();
let running = s.openingMinor;
for (const r of asc) {
running += r.deltaMinor;
expect(r.balanceMinor).toBe(running);
}
const next = (await getAccountStatement(ayse, cakir, ziraat, currentMonth()))!;
expect(next.openingMinor).toBe(s.closingMinor);
expect(next.nextMonth).toBeNull();
expect(s.currentBalanceMinor).toBe(await balanceOf(ayse, ziraat));
});
it("gizli hesabın ekstresi yalnızca sahibine; hane dışına kapalı", async () => {
const pluxee = await acc("Ayşe — Pluxee");
expect(await getAccountStatement(ayse, cakir, pluxee, currentMonth())).not.toBeNull();
expect(await getAccountStatement(emre, cakir, pluxee, currentMonth())).toBeNull();
expect(await getAccountStatement(fatma, cakir, await acc("Cüzdan"), currentMonth())).toBeNull();
});
it("gizli hesaba transfer ekstrede görünür ama karşı hesap adı gizlenir", async () => {
const ziraat = await acc("Ziraat Maaş");
const pluxee = await acc("Ayşe — Pluxee");
const r = await createTransaction(ayse, cakir, {
type: "transfer",
amount: 123_45,
date: todayIstanbul(),
accountId: ziraat,
toAccountId: pluxee,
categoryId: null,
splits: [],
payee: "",
description: "",
tags: [],
attachmentIds: [],
} satisfies TransactionForm);
expect(r.ok).toBe(true);
const s = (await getAccountStatement(emre, cakir, ziraat, currentMonth()))!;
const row = s.rows.find((x) => x.item.id === (r.ok ? r.data.id : ""))!;
expect(row.restricted).toBe(true);
expect(row.deltaMinor).toBe(-123_45);
expect(row.item.toAccount!.name).not.toContain("Pluxee");
expect(s.currentBalanceMinor).toBe(await balanceOf(emre, ziraat));
});
});
describe("mutabakat", () => {
it("bakiye tutuyorsa işlemler işaretlenir, düzeltme oluşmaz", async () => {
const cuzdan = await acc("Cüzdan");
const today = todayIstanbul();
const balance = await balanceOf(ayse, cuzdan);
const preview = await previewReconciliation(ayse, cakir, cuzdan, input(today, tl(balance)));
expect(preview).toMatchObject({
ok: true,
data: { differenceMinor: 0, appBalanceMinor: balance },
});
const unreconciled = preview.ok ? preview.data.unreconciledCount : 0;
expect(unreconciled).toBeGreaterThan(0);
const r = await reconcileAccount(ayse, cakir, cuzdan, input(today, tl(balance)));
expect(r).toMatchObject({ ok: true, data: { adjustmentId: null, markedCount: unreconciled } });
const again = await reconcileAccount(ayse, cakir, cuzdan, input(today, tl(balance)));
expect(again).toMatchObject({ ok: true, data: { markedCount: 0 } });
const s = (await getAccountStatement(ayse, cakir, cuzdan, currentMonth()))!;
expect(s.rows.every((row) => row.reconciled)).toBe(true);
expect(s.lastReconciliation).toMatchObject({ date: today, differenceMinor: 0 });
});
it("fark varsa onay ister; onaylanınca düzeltme işlemi oluşur ve bakiye ekstreyle eşitlenir", async () => {
const ziraat = await acc("Ziraat Maaş");
const today = todayIstanbul();
const balance = await balanceOf(ayse, ziraat);
const target = balance - 250_00;
const refused = await reconcileAccount(ayse, cakir, ziraat, input(today, tl(target)));
expect(refused.ok).toBe(false);
expect(await ReconciliationModel.countDocuments({ accountId: ziraat })).toBe(0);
const r = await reconcileAccount(ayse, cakir, ziraat, input(today, tl(target), true));
expect(r.ok).toBe(true);
const adjustmentId = r.ok ? r.data.adjustmentId! : "";
const adj = (await TransactionModel.findById(adjustmentId).lean())!;
expect(adj).toMatchObject({ type: "expense", amountMinor: 250_00, isAdjustment: true });
expect(await balanceOf(ayse, ziraat)).toBe(target);
const audit = await AuditLogModel.findOne({
action: "account.reconcile",
targetId: ziraat,
}).lean();
expect(audit!.diff).toMatchObject({ differenceMinor: -250_00 });
// Düzeltme işlemi düzenlenemez, silinebilir.
const detail = (await getTransaction(ayse, cakir, adjustmentId))!;
expect(detail.isAdjustment).toBe(true);
const edit = await updateTransaction(ayse, cakir, adjustmentId, {
type: "expense",
amount: 1_00,
date: today,
accountId: ziraat,
toAccountId: null,
categoryId: await cat("market"),
splits: [],
payee: "",
description: "",
tags: [],
attachmentIds: [],
});
expect(edit.ok).toBe(false);
expect((await setTransactionDeleted(ayse, cakir, adjustmentId, true)).ok).toBe(true);
});
it("kredi kartında borç pozitif girilir, uygulamada eksi bakiyeyle karşılaştırılır", async () => {
const kart = await acc("Garanti Bonus");
const balance = await balanceOf(ayse, kart);
expect(balance).toBeLessThan(0);
const preview = await previewReconciliation(
ayse,
cakir,
kart,
input(todayIstanbul(), tl(-balance)),
);
expect(preview).toMatchObject({
ok: true,
data: { statementBalanceMinor: balance, differenceMinor: 0 },
});
});
it("işaretli işlemin tutarı değişince işaret kalkar; yalnızca açıklama değişince kalır", async () => {
const cuzdan = await acc("Cüzdan");
const tx = await TransactionModel.findOne({
accountId: cuzdan,
type: "expense",
reconciledAccountIds: cuzdan,
splits: { $size: 0 },
deletedAt: null,
}).lean();
const d = (await getTransaction(ayse, cakir, String(tx!._id)))!;
const base: TransactionForm = {
type: "expense",
amount: d.amountMinor,
date: d.date,
accountId: cuzdan,
toAccountId: null,
categoryId: d.categoryId,
splits: [],
payee: d.payeeName,
description: "yeni açıklama",
tags: d.tags,
attachmentIds: [],
};
expect((await updateTransaction(ayse, cakir, d.id, base)).ok).toBe(true);
expect(
(await TransactionModel.findById(d.id).lean())!.reconciledAccountIds.map(String),
).toEqual([cuzdan]);
expect(
(await updateTransaction(ayse, cakir, d.id, { ...base, amount: d.amountMinor + 1 })).ok,
).toBe(true);
expect((await TransactionModel.findById(d.id).lean())!.reconciledAccountIds).toEqual([]);
});
it("yetki ve doğrulama: izleyici, gizli hesap, gelecek tarih", async () => {
const cuzdan = await acc("Cüzdan");
expect((await reconcileAccount(zeynep, cakir, cuzdan, input(todayIstanbul(), "0"))).ok).toBe(
false,
);
expect(
(await reconcileAccount(emre, cakir, await acc("Ayşe — Pluxee"), input(todayIstanbul(), "0")))
.ok,
).toBe(false);
expect((await previewReconciliation(ayse, cakir, cuzdan, input("2999-01-01", "0"))).ok).toBe(
false,
);
});
});
+455
View File
@@ -0,0 +1,455 @@
import "server-only";
import mongoose, { Types, type ClientSession, type PipelineStage } from "mongoose";
import { tr } from "@/i18n/tr";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { writeAudit } from "@/lib/audit";
import { toObjectId } from "@/lib/object-id";
import { AccountModel } from "@/models/account";
import { ReconciliationModel } from "@/models/reconciliation";
import { TransactionModel } from "@/models/transaction";
import { isLiabilityType, type AccountType } from "@/shared/accounts";
import type { IconKey, Swatch } from "@/shared/appearance";
import { istanbulDayStart, todayIstanbul, toIstanbulYmd } from "@/shared/dates";
import { formatMoney } from "@/shared/format";
import { hasHouseholdRole } from "@/features/households/roles";
import type { ReconcileForm } from "@/shared/schemas/reconciliation";
import { foldTr } from "@/shared/search";
import { accountEffect, monthRange, shiftMonth, withRunningBalance } from "@/shared/statement";
import {
loadContext,
toItem,
userNames,
type Ctx,
type LeanTx,
type TransactionListItem,
} from "./service";
/**
* Hesap ekstresi (aylık, yürüyen bakiye) ve mutabakat (Bölüm 6.1).
* Ekstre yalnızca bakiyesini görebildiği hesaplar için açılır (gizli hesap → yalnızca sahibi).
* Başka birinin gizli hesabına yapılan transferler bakiyeyi etkilediği için ekstrede görünür,
* ama karşı hesap adı gizlenir ve ayrıntı açılmaz.
*/
const t = tr.statement;
const DAY_MS = 24 * 60 * 60 * 1000;
const MAX_ROWS = 2000;
/** Hesap bazında bakiyeyi etkileyen işlemler (posted, silinmemiş). */
function accountMatch(householdId: Types.ObjectId, accountId: Types.ObjectId) {
return {
householdId,
status: "posted" as const,
deletedAt: null,
$or: [{ accountId }, { toAccountId: accountId }],
};
}
/** Açılış bakiyesi + (isteğe bağlı tarihten önceki) işlem etkileri. */
async function balanceBefore(
householdId: Types.ObjectId,
account: { _id: Types.ObjectId; openingBalanceMinor: number },
before: Date | null,
session?: ClientSession,
): Promise<number> {
const pipeline: PipelineStage[] = [
{
$match: {
...accountMatch(householdId, account._id),
...(before ? { date: { $lt: before } } : {}),
},
},
{
$group: {
_id: null,
total: {
$sum: {
$cond: [
{ $eq: ["$type", "transfer"] },
{
$cond: [
{ $eq: ["$accountId", account._id] },
{ $multiply: ["$amountMinor", -1] },
"$amountMinor",
],
},
{
$cond: [
{ $eq: ["$type", "income"] },
"$amountMinor",
{ $multiply: ["$amountMinor", -1] },
],
},
],
},
},
},
},
];
const agg = TransactionModel.aggregate<{ total: number }>(pipeline);
if (session) agg.session(session);
const [row] = await agg;
return account.openingBalanceMinor + (row?.total ?? 0);
}
type VisibleAccount = {
_id: Types.ObjectId;
name: string;
type: AccountType;
icon: string;
color: string;
openingBalanceMinor: number;
archivedAt?: Date | null;
};
async function loadVisibleAccount(
ctx: Ctx,
accountId: string,
session?: ClientSession,
): Promise<VisibleAccount | null> {
const id = toObjectId(accountId);
const info = id ? ctx.accountMap.get(String(id)) : undefined;
if (!id || !info || info.hidden) return null;
return AccountModel.findOne({ _id: id, householdId: ctx.m.householdId }, null, { session })
.select({ name: 1, type: 1, icon: 1, color: 1, openingBalanceMinor: 1, archivedAt: 1 })
.lean<VisibleAccount>();
}
// --- Ekstre ---
export type StatementRow = {
item: TransactionListItem;
deltaMinor: number;
balanceMinor: number;
reconciled: boolean;
/** Karşı hesap başkasının gizli hesabıysa ayrıntı açılmaz. */
restricted: boolean;
};
export type LastReconciliation = {
date: string;
statementBalanceMinor: number;
differenceMinor: number;
createdAt: string;
createdBy: string;
};
export type AccountStatement = {
account: {
id: string;
name: string;
type: AccountType;
icon: IconKey;
color: Swatch;
archived: boolean;
isLiability: boolean;
};
month: string;
prevMonth: string;
nextMonth: string | null;
openingMinor: number;
closingMinor: number;
inflowMinor: number;
outflowMinor: number;
currentBalanceMinor: number;
/** Yeniden eskiye. */
rows: StatementRow[];
truncated: boolean;
lastReconciliation: LastReconciliation | null;
canReconcile: boolean;
};
export function currentMonth(now = new Date()): string {
return todayIstanbul(now).slice(0, 7);
}
export async function getAccountStatement(
userId: string,
householdId: string,
accountId: string,
month: string,
): Promise<AccountStatement | null> {
const ctx = await loadContext(userId, householdId, "viewer");
if (!ctx) return null;
const account = await loadVisibleAccount(ctx, accountId);
if (!account) return null;
const range = monthRange(month);
const start = istanbulDayStart(range.start)!;
const end = istanbulDayStart(range.end)!;
const hh = ctx.m.householdId;
const [openingMinor, currentBalanceMinor, txs, last] = await Promise.all([
balanceBefore(hh, account, start),
balanceBefore(hh, account, null),
TransactionModel.find({ ...accountMatch(hh, account._id), date: { $gte: start, $lt: end } })
.sort({ date: 1, createdAt: 1 })
.limit(MAX_ROWS + 1)
.lean() as unknown as Promise<LeanTx[]>,
ReconciliationModel.findOne({ householdId: hh, accountId: account._id })
.sort({ statementDate: -1, createdAt: -1 })
.lean(),
]);
const truncated = txs.length > MAX_ROWS;
const rowsAsc = txs.slice(0, MAX_ROWS);
const names = await userNames([
...rowsAsc.map((r) => r.createdBy as Types.ObjectId),
...(last ? [last.createdBy] : []),
]);
const accountKey = String(account._id);
const effects = rowsAsc.map((tx) => {
const item = toItem(ctx, tx, names);
const counterpart = tx.type === "transfer" ? [item.account, item.toAccount] : [];
const restricted = counterpart.some((a) => a && ctx.accountMap.get(a.id)?.hidden);
if (restricted) {
// Gizli karşı hesabın adı sızmasın.
for (const a of counterpart) {
if (a && ctx.accountMap.get(a.id)?.hidden) a.name = tr.transactions.list.hiddenAccount;
}
}
return {
item,
restricted,
reconciled: item.reconciledAccountIds.includes(accountKey),
deltaMinor: accountEffect(
{
type: tx.type,
amountMinor: tx.amountMinor,
accountId: String(tx.accountId),
toAccountId: tx.toAccountId ? String(tx.toAccountId) : null,
},
accountKey,
),
};
});
const running = withRunningBalance(openingMinor, effects);
const inflowMinor = effects.filter((e) => e.deltaMinor > 0).reduce((a, e) => a + e.deltaMinor, 0);
const outflowMinor = effects
.filter((e) => e.deltaMinor < 0)
.reduce((a, e) => a - e.deltaMinor, 0);
const now = currentMonth();
return {
account: {
id: accountKey,
name: account.name,
type: account.type,
icon: account.icon as IconKey,
color: account.color as Swatch,
archived: Boolean(account.archivedAt),
isLiability: isLiabilityType(account.type),
},
month,
prevMonth: shiftMonth(month, -1),
nextMonth: month < now ? shiftMonth(month, 1) : null,
openingMinor,
closingMinor: running.at(-1)?.balanceMinor ?? openingMinor,
inflowMinor,
outflowMinor,
currentBalanceMinor,
rows: running.reverse(),
truncated,
lastReconciliation: last
? {
date: toIstanbulYmd(last.statementDate),
statementBalanceMinor: last.statementBalanceMinor,
differenceMinor: last.differenceMinor,
createdAt: new Date(last.createdAt).toISOString(),
createdBy: names.get(String(last.createdBy)) ?? "—",
}
: null,
canReconcile: hasHouseholdRole(ctx.m.role, "member") && !account.archivedAt,
};
}
// --- Mutabakat ---
export type ReconcilePreview = {
statementDate: string;
/** Uygulamadaki işaretle (kredi kartında eksi). */
statementBalanceMinor: number;
appBalanceMinor: number;
/** ekstre − uygulama: + ise uygulamada eksik gelir, − ise eksik gider. */
differenceMinor: number;
/** O tarihe kadar henüz işaretlenmemiş işlem sayısı. */
unreconciledCount: number;
};
function validateDate(ymd: string): Date | null {
const start = istanbulDayStart(ymd);
if (!start || ymd > todayIstanbul()) return null;
return start;
}
async function computePreview(
ctx: Ctx,
account: VisibleAccount,
input: ReconcileForm,
session?: ClientSession,
): Promise<ActionResult<ReconcilePreview & { endExclusive: Date; dayStart: Date }>> {
const dayStart = validateDate(input.statementDate);
if (!dayStart) return fail(t.errors.date, { statementDate: t.errors.date });
const endExclusive = new Date(dayStart.getTime() + DAY_MS);
// Kredi kartında kullanıcı borcu pozitif girer; uygulamada borç eksi bakiyedir.
const statementBalanceMinor = isLiabilityType(account.type)
? -input.statementBalance
: input.statementBalance;
const appBalanceMinor = await balanceBefore(ctx.m.householdId, account, endExclusive, session);
const unreconciledCount = await TransactionModel.countDocuments(
{
...accountMatch(ctx.m.householdId, account._id),
date: { $lt: endExclusive },
reconciledAccountIds: { $ne: account._id },
},
{ session },
);
return ok({
statementDate: input.statementDate,
statementBalanceMinor,
appBalanceMinor,
differenceMinor: statementBalanceMinor - appBalanceMinor,
unreconciledCount,
endExclusive,
dayStart,
});
}
export async function previewReconciliation(
userId: string,
householdId: string,
accountId: string,
input: ReconcileForm,
): Promise<ActionResult<ReconcilePreview>> {
const ctx = await loadContext(userId, householdId, "member");
if (!ctx) return fail(tr.common.unauthorized);
const account = await loadVisibleAccount(ctx, accountId);
if (!account) return fail(tr.common.notFound);
const result = await computePreview(ctx, account, input);
if (!result.ok) return result;
const { endExclusive: _e, dayStart: _d, ...preview } = result.data;
return ok(preview);
}
class ReconcileAbort extends Error {
constructor(readonly result: ActionResult<never>) {
super("abort");
}
}
/**
* Mutabakatı uygular (tek transaction): fark varsa (ve onaylandıysa) düzeltme işlemi oluşturur,
* ekstre tarihine kadarki işlemleri bu hesap için işaretler, kaydı ve denetim kaydını yazar.
*/
export async function reconcileAccount(
actorId: string,
householdId: string,
accountId: string,
input: ReconcileForm,
): Promise<
ActionResult<{ adjustmentId: string | null; markedCount: number; differenceMinor: number }>
> {
const ctx = await loadContext(actorId, householdId, "member");
if (!ctx) return fail(tr.common.unauthorized);
const pre = await loadVisibleAccount(ctx, accountId);
if (!pre) return fail(tr.common.notFound);
if (pre.archivedAt) return fail(t.errors.archived);
const actor = new Types.ObjectId(actorId);
const hh = ctx.m.householdId;
try {
let out = { adjustmentId: null as string | null, markedCount: 0, differenceMinor: 0 };
await mongoose.connection.transaction(async (session) => {
const account = (await loadVisibleAccount(ctx, accountId, session))!;
const preview = await computePreview(ctx, account, input, session);
if (!preview.ok) throw new ReconcileAbort(preview);
const p = preview.data;
if (p.differenceMinor !== 0 && !input.acceptAdjustment) {
throw new ReconcileAbort(fail(t.errors.needsAdjustment));
}
let adjustmentId: Types.ObjectId | null = null;
if (p.differenceMinor !== 0) {
const description = t.adjustmentDescription(formatMoney(p.statementBalanceMinor));
const [adj] = await TransactionModel.create(
[
{
householdId: hh,
type: p.differenceMinor > 0 ? "income" : "expense",
status: "posted",
date: p.dayStart,
accountId: account._id,
amountMinor: Math.abs(p.differenceMinor),
categoryId: null,
splits: [],
effectiveCategoryIds: [],
payeeName: "",
description,
searchText: foldTr(`${tr.transactions.adjustment} ${description}`),
isAdjustment: true,
reconciledAccountIds: [account._id],
createdBy: actor,
updatedBy: actor,
},
],
{ session },
);
adjustmentId = adj!._id;
}
const marked = await TransactionModel.updateMany(
{
...accountMatch(hh, account._id),
date: { $lt: p.endExclusive },
reconciledAccountIds: { $ne: account._id },
},
{ $addToSet: { reconciledAccountIds: account._id } },
{ session },
);
await ReconciliationModel.create(
[
{
householdId: hh,
accountId: account._id,
statementDate: p.dayStart,
statementBalanceMinor: p.statementBalanceMinor,
appBalanceMinor: p.appBalanceMinor,
differenceMinor: p.differenceMinor,
adjustmentTransactionId: adjustmentId,
markedCount: marked.modifiedCount,
createdBy: actor,
},
],
{ session },
);
await writeAudit(
{
action: "account.reconcile",
actorId: actor,
householdId: hh,
targetType: "account",
targetId: String(account._id),
diff: {
statementDate: p.statementDate,
statementBalanceMinor: p.statementBalanceMinor,
appBalanceMinor: p.appBalanceMinor,
differenceMinor: p.differenceMinor,
adjustmentTransactionId: adjustmentId ? String(adjustmentId) : null,
markedCount: marked.modifiedCount,
},
},
session,
);
out = {
adjustmentId: adjustmentId ? String(adjustmentId) : null,
markedCount: marked.modifiedCount,
differenceMinor: p.differenceMinor,
};
});
return ok(out);
} catch (error) {
if (error instanceof ReconcileAbort) return error.result;
throw error;
}
}
+362 -1
View File
@@ -34,6 +34,21 @@ export const tr = {
unauthorized: "Bu işlem için yetkiniz yok.",
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: {
label: "Tema",
light: "Açık",
@@ -45,6 +60,7 @@ export const tr = {
dashboard: "Ana sayfa",
transactions: "İşlemler",
accounts: "Hesaplar",
categories: "Kategoriler",
budget: "Bütçe",
planned: "Planlı işlemler",
contacts: "Cari hesaplar",
@@ -122,6 +138,344 @@ export const tr = {
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.",
},
transactions: {
title: "İşlemler",
description: "Gelir, gider ve transferler.",
new: "Yeni işlem",
types: { expense: "Gider", income: "Gelir", transfer: "Transfer" },
statuses: { posted: "Gerçekleşti", planned: "Planlı", void: "İptal" },
createTitle: { expense: "Yeni gider", income: "Yeni gelir", transfer: "Yeni transfer" },
editTitle: "İşlemi düzenle",
copyTitle: "İşlemi kopyala",
fields: {
amount: "Tutar",
date: "Tarih",
account: "Hesap",
fromAccount: "Kaynak hesap",
toAccount: "Hedef hesap",
category: "Kategori",
selectCategory: "Kategori seçin",
selectAccount: "Hesap seçin",
payee: "Satıcı / karşı taraf",
payeePlaceholder: "ör. Migros",
description: "Açıklama",
tags: "Etiketler",
tagsHint: "Virgülle ayırın (ör. tatil, indirim)",
advanced: "Gelişmiş: ek, etiket, bölme",
split: "Bölünmüş işlem",
splitHint: "Tutarı birden çok kategoriye bölün; kalemlerin toplamı tutara eşit olmalı.",
addSplit: "Kalem ekle",
removeSplit: "Kalemi kaldır",
splitNote: "Not",
remaining: "Kalan",
remainingOk: "Kalemler toplamı tutara eşit",
fillRemaining: "Kalanı son kaleme ekle",
suggested: "Bu satıcı için son kullanılan kategori ve hesap önerildi.",
},
validation: {
amountPositive: "Tutar sıfırdan büyük olmalı",
selectAccount: "Hesap seçin",
selectToAccount: "Hedef hesabı seçin",
sameAccount: "Kaynak ve hedef hesap aynı olamaz",
selectCategory: "Kategori seçin",
splitMin: "Bölünmüş işlemde en az 2 kalem olmalı",
splitSum: "Kalemlerin toplamı tutara eşit olmalı",
accountInvalid: "Hesap bu hanede yok, arşivli veya size kapalı.",
categoryInvalid: "Kategori bu hanede yok, arşivli veya işlem türüyle uyuşmuyor.",
},
list: {
empty: "Bu filtrelerle işlem bulunamadı.",
emptyAll: "Henüz işlem yok.",
split: (n: number) => `Bölünmüş · ${n} kalem`,
transfer: (from: string, to: string) => `${from} → ${to}`,
dayTotal: "Günlük net",
total: (n: number) => `${n} işlem`,
sums: { income: "Gelir", expense: "Gider", net: "Net" },
hiddenAccount: "Gizli hesap",
},
filters: {
title: "Filtreler",
open: "Filtrele",
apply: "Uygula",
clear: "Temizle",
from: "Başlangıç",
to: "Bitiş",
type: "Tür",
account: "Hesap",
category: "Kategori",
person: "Ekleyen",
status: "Durum",
min: "En az (TL)",
max: "En çok (TL)",
tag: "Etiket",
search: "Ara",
searchPlaceholder: "Açıklama, satıcı veya not…",
all: "Tümü",
active: (n: number) => `${n} filtre`,
},
detail: {
title: "İşlem ayrıntısı",
lines: "Kalemler",
createdBy: "Ekleyen",
updatedBy: "Son düzenleyen",
createdAt: "Oluşturulma",
},
actions: { edit: "Düzenle", copy: "Kopyala", delete: "Sil", restore: "Geri al" },
toast: {
created: "İşlem kaydedildi.",
updated: "İşlem güncellendi.",
deleted: "İşlem silindi.",
restored: "İşlem geri alındı.",
},
deleteTitle: "İşlem silinsin mi?",
deleteDescription:
"İşlem listeden ve bakiyelerden kaldırılır. Bildirimdeki “Geri al” ile geri getirebilirsiniz.",
export: "CSV indir",
csv: {
header: [
"İşlem No",
"Tarih",
"Tür",
"Durum",
"Hesap",
"Hedef hesap",
"Kategori",
"Satıcı",
"Açıklama",
"Kalem notu",
"Etiketler",
"Tutar",
"Ekleyen",
],
filename: (date: string) => `butcem-islemler-${date}.csv`,
},
adjustment: "Mutabakat düzeltmesi",
adjustmentReadOnly:
"Mutabakat düzeltmesi düzenlenemez; gerekirse silip mutabakatı yeniden yapın.",
reconciled: "Mutabakatı yapıldı",
readOnly: "İzleyici rolündesiniz; işlem ekleyemezsiniz.",
noAccounts: "İşlem girmek için önce bir hesap gerekli.",
noAccountsLink: "Hesaplara git",
},
attachments: {
title: "Ekler",
add: "Ek ekle",
addHint: { image: "Fiş veya fatura fotoğrafı", imagePdf: "Görsel veya PDF (ör. bordro)" },
count: (n: number) => `${n} ek`,
uploading: "Yükleniyor…",
remove: "Eki kaldır",
open: "Aç",
download: "İndir",
fullscreen: "Tam ekran",
exitFullscreen: "Tam ekrandan çık",
previous: "Önceki",
next: "Sonraki",
position: (i: number, n: number) => `${i} / ${n}`,
viewerTitle: "Ek dosyalar",
pdf: "PDF belgesi",
moreCount: (n: number) => `+${n}`,
waitForUploads: "Yüklemeler bitmeden kaydedilemez.",
errors: {
empty: "Dosya seçilmedi veya dosya boş.",
tooLarge: (mb: number) => `Dosya çok büyük (en fazla ${mb} MB).`,
tooMany: (n: number) => `Bir kayda en fazla ${n} dosya eklenebilir.`,
tooManyPending: "Kaydedilmemiş çok fazla ek var; önce formu kaydedin.",
unsupported: "Desteklenmeyen dosya türü. JPEG, PNG, WebP, HEIC veya PDF yükleyin.",
unreadable: "Dosya okunamadı veya bozuk.",
kindNotAllowed: "Gider işlemlerine yalnızca görsel eklenebilir (PDF gelir ve transferlerde).",
invalid: "Ek dosya bulunamadı veya bu kayda eklenemez.",
upload: "Dosya yüklenemedi.",
},
},
statement: {
title: "Hesap ekstresi",
back: "Hesaplar",
allTransactions: "Tüm işlemler",
prevMonth: "Önceki ay",
nextMonth: "Sonraki ay",
opening: "Ay başı bakiye",
inflow: "Giriş",
outflow: "Çıkış",
closing: "Ay sonu bakiye",
current: "Güncel bakiye",
balanceAfter: "Bakiye",
empty: "Bu ayda işlem yok.",
truncated: "Çok fazla işlem var; yalnızca ilk 2.000 işlem gösteriliyor.",
lastReconciliation: (date: string, balance: string) =>
`Son mutabakat: ${date} · ekstre bakiyesi ${balance}`,
noReconciliation: "Henüz mutabakat yapılmadı.",
reconciledHint: "Mutabakatı yapılmış işlem",
adjustmentDescription: (statementBalance: string) =>
`Ekstre bakiyesi ${statementBalance} ile fark`,
reconcile: {
open: "Mutabakat yap",
title: "Mutabakat",
description:
"Banka veya kart ekstrenizdeki tarihi ve bakiyeyi girin; uygulamadaki bakiye ile karşılaştırılır.",
date: "Ekstre tarihi",
balance: "Ekstredeki bakiye (TL)",
debt: "Ekstredeki borç (TL)",
balanceHint: "Eksi bakiye için başına - koyun (ör. KMH kullanımı).",
debtHint: "Karttaki toplam borcu pozitif girin.",
check: "Karşılaştır",
statementBalance: "Ekstre",
appBalance: "Uygulama",
difference: "Fark",
matches: "Bakiyeler tutuyor.",
mismatch: "Bakiyeler tutmuyor. Eksik veya hatalı işlem olabilir.",
adjustmentOffer: (amount: string, kind: string) =>
`Farkı kapatmak için ${amount} tutarında bir “${kind}” düzeltme işlemi oluşturulsun.`,
acceptAdjustment: "Düzeltme işlemi oluştur",
unreconciled: (n: number) => `${n} işlem işaretlenecek.`,
confirm: "Mutabakatı tamamla",
confirmWithAdjustment: "Düzelt ve tamamla",
done: (n: number) => `Mutabakat tamamlandı; ${n} işlem işaretlendi.`,
doneWithAdjustment: (n: number) => `Düzeltme işlemi oluşturuldu ve ${n} işlem işaretlendi.`,
},
errors: {
date: "Geçerli ve bugünden ileri olmayan bir tarih girin.",
archived: "Arşivlenmiş hesapta mutabakat yapılamaz.",
needsAdjustment:
"Bakiyeler tutmuyor; düzeltme işlemini onaylayın veya işlemleri kontrol edin.",
},
},
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.",
@@ -162,7 +516,7 @@ export const tr = {
expenseHint: "Harcama, fatura, alışveriş",
incomeHint: "Maaş, ek gelir, iade",
transferHint: "Hesaplar ve cariler arası",
notYet: "İşlem formu Faz 6'da eklenecek.",
noAccounts: "İşlem girmek için önce bir hesap gerekli.",
},
auth: {
loginTitle: "Giriş yap",
@@ -281,6 +635,13 @@ export const tr = {
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: {
notFoundTitle: "Sayfa bulunamadı",
View File
+18
View File
@@ -0,0 +1,18 @@
import "server-only";
import { env } from "@/lib/env";
import { createLocalDriver } from "./local";
import type { StorageDriver } from "./types";
export type { StorageDriver } from "./types";
export { isValidStorageKey } from "./types";
/**
* Depolama soyutlaması (Bölüm 7.4): `put`, `get`, `delete`. İlk sürücü yerel disk (`UPLOAD_DIR`,
* canlıda Docker volume). İleride S3 uyumlu (MinIO) sürücü aynı arayüzle eklenebilir.
*/
const g = globalThis as unknown as { __butcemStorage?: StorageDriver };
export function getStorage(): StorageDriver {
g.__butcemStorage ??= createLocalDriver(env().UPLOAD_DIR);
return g.__butcemStorage;
}
+35
View File
@@ -0,0 +1,35 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { createLocalDriver } from "./local";
import { isValidStorageKey } from "./types";
const dirs: string[] = [];
afterAll(() => Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true }))));
describe("yerel depolama", () => {
it("anahtar biçimi: yol geçişi ve beklenmeyen uzantılar reddedilir", () => {
expect(isValidStorageKey("ab/0123456789abcdef0123.webp")).toBe(true);
expect(isValidStorageKey("ab/0123456789abcdef0123.thumb.webp")).toBe(true);
expect(isValidStorageKey("ab/0123456789abcdef0123.pdf")).toBe(true);
expect(isValidStorageKey("../0123456789abcdef0123.webp")).toBe(false);
expect(isValidStorageKey("ab/../../etc/passwd")).toBe(false);
expect(isValidStorageKey("/ab/0123456789abcdef0123.webp")).toBe(false);
expect(isValidStorageKey("ab/0123456789abcdef0123.html")).toBe(false);
});
it("put/get/delete", async () => {
const dir = await mkdtemp(path.join(tmpdir(), "butcem-storage-"));
dirs.push(dir);
const s = createLocalDriver(dir);
const key = "cd/cdef0123456789abcdef.pdf";
expect(await s.get(key)).toBeNull();
await s.put(key, new TextEncoder().encode("merhaba"));
expect((await s.get(key))!.toString()).toBe("merhaba");
await s.delete(key);
await s.delete(key);
expect(await s.get(key)).toBeNull();
await expect(s.put("../x.pdf", new Uint8Array())).rejects.toThrow();
});
});
+37
View File
@@ -0,0 +1,37 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { isValidStorageKey, type StorageDriver } from "./types";
/** Yerel disk sürücüsü. Yazma atomiktir (geçici dosya + rename); yarım dosya servis edilmez. */
export function createLocalDriver(baseDir: string): StorageDriver {
const root = path.resolve(baseDir);
function resolve(key: string): string {
if (!isValidStorageKey(key)) throw new Error(`Geçersiz depolama anahtarı: ${key}`);
const full = path.resolve(root, key);
if (!full.startsWith(root + path.sep)) throw new Error("Depolama kökü dışına çıkılamaz.");
return full;
}
return {
async put(key, data) {
const full = resolve(key);
await mkdir(path.dirname(full), { recursive: true, mode: 0o750 });
const tmp = `${full}.${randomBytes(6).toString("hex")}.tmp`;
await writeFile(tmp, data, { mode: 0o640 });
await rename(tmp, full);
},
async get(key) {
try {
return await readFile(resolve(key));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
},
async delete(key) {
await rm(resolve(key), { force: true });
},
};
}
+18
View File
@@ -0,0 +1,18 @@
export interface StorageDriver {
/** Dosyayı yazar (varsa üzerine yazar). */
put(key: string, data: Uint8Array): Promise<void>;
/** Dosyayı okur; yoksa null. */
get(key: string): Promise<Buffer | null>;
/** Dosyayı siler; yoksa sessizce geçer. */
delete(key: string): Promise<void>;
}
/**
* Anahtar biçimi: "ab/<rastgele-id>[.thumb].webp|pdf". Yalnızca küçük harf, rakam, tire, nokta
* ve tek bir alt klasör; ".." veya mutlak yol olamaz (dizin dışına çıkma engellenir).
*/
const KEY_PATTERN = /^[a-z0-9]{2}\/[a-z0-9-]{16,64}(\.thumb)?\.(webp|pdf)$/;
export function isValidStorageKey(key: string): boolean {
return KEY_PATTERN.test(key);
}
+74
View File
@@ -0,0 +1,74 @@
import "server-only";
import sharp from "sharp";
import type { DetectedType } from "@/shared/attachments";
/** Ana görsel uzun kenar sınırı (fiş okunabilir kalsın, dosya küçülsün). */
export const MAX_IMAGE_EDGE = 2000;
export const THUMB_EDGE = 320;
/** Dekompresyon bombasına karşı piksel sınırı (~50 MP). */
const MAX_INPUT_PIXELS = 50_000_000;
export type ProcessedImage = {
main: Buffer;
thumb: Buffer;
width: number;
height: number;
};
export class UnreadableImageError extends Error {}
/**
* Görseli normalize eder: EXIF yönüne göre döndürür, en fazla 2000 px'e küçültür ve WebP'ye
* çevirir. sharp çıktıya meta veri yazmaz (withMetadata kullanılmadığı için EXIF/GPS/ICC dahil
* tüm meta veri düşer). HEIC (iPhone, HEVC) sharp'ın hazır derlemesinde çözülemediği için
* libheif (WASM) ile çözülür.
*/
export async function processImage(bytes: Buffer, type: DetectedType): Promise<ProcessedImage> {
try {
const source = type === "heic" ? await decodeHeic(bytes) : sharpFrom(bytes).rotate();
const { data, info } = await source
.resize({
width: MAX_IMAGE_EDGE,
height: MAX_IMAGE_EDGE,
fit: "inside",
withoutEnlargement: true,
})
.webp({ quality: 82 })
.toBuffer({ resolveWithObject: true });
const thumb = await sharp(data)
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: 70 })
.toBuffer();
return { main: data, thumb, width: info.width, height: info.height };
} catch (error) {
throw new UnreadableImageError(error instanceof Error ? error.message : String(error));
}
}
function sharpFrom(bytes: Buffer) {
return sharp(bytes, { failOn: "error", limitInputPixels: MAX_INPUT_PIXELS });
}
async function decodeHeic(bytes: Buffer) {
// Bazı .heic dosyaları aslında AV1 (AVIF) içerir; sharp bunları doğrudan çözebilir.
try {
const meta = await sharpFrom(bytes).metadata();
if (meta.compression === "av1") return sharpFrom(bytes).rotate();
} catch {
// libheif ile denenecek.
}
const { default: decode } = await import("heic-decode");
const image = await decode({ buffer: bytes });
if (image.width * image.height > MAX_INPUT_PIXELS) throw new Error("Görsel çok büyük.");
// libheif yönlendirmeyi (irot/imir) çözerken uygular; ham RGBA piksellerden devam edilir.
return sharp(Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength), {
raw: { width: image.width, height: image.height, channels: 4 },
});
}
/** PDF'ler değiştirilmeden saklanır; yalnızca yapı kontrolü (başlık + dosya sonu işareti). */
export function isPlausiblePdf(bytes: Buffer): boolean {
if (bytes.subarray(0, 5).toString("latin1") !== "%PDF-") return false;
const tail = bytes.subarray(Math.max(0, bytes.length - 2048)).toString("latin1");
return tail.includes("%%EOF");
}
+67
View File
@@ -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);
+51
View File
@@ -0,0 +1,51 @@
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
import { ATTACHMENT_KINDS } from "@/shared/attachments";
/** Ek dosyanın bağlanabileceği kayıt türleri (ileride: alışveriş fişi, cari hareket…). */
export const ATTACHMENT_OWNER_TYPES = ["transaction"] as const;
export type AttachmentOwnerType = (typeof ATTACHMENT_OWNER_TYPES)[number];
/**
* Ek dosya meta verisi (Bölüm 7.4). Dosyanın kendisi depolama sürücüsünde, rastgele anahtarla.
* - Yüklenince `ownerId: null` (bekleyen); kayıt kaydedilince sahibine bağlanır.
* - Bekleyen ek yalnızca yükleyene görünür ve 24 saat içinde bağlanmazsa temizlenir.
* - Kayıttan çıkarılan ek `deletedAt` alır; dosya saklama süresi sonunda silinir.
*/
const attachmentSchema = new Schema(
{
householdId: { type: Schema.Types.ObjectId, required: true },
ownerType: { type: String, enum: ATTACHMENT_OWNER_TYPES, default: null },
ownerId: { type: Schema.Types.ObjectId, default: null },
kind: { type: String, enum: ATTACHMENT_KINDS, required: true },
/** Saklanan içeriğin türü (görseller her zaman WebP'ye çevrilir). */
mimeType: { type: String, enum: ["image/webp", "application/pdf"], required: true },
/** Kaynak tür (jpeg, png, webp, heic, pdf) — bilgi amaçlı. */
sourceType: { type: String, required: true },
originalName: { type: String, default: "", maxlength: 120 },
size: { type: Number, required: true },
originalSize: { type: Number, required: true },
width: { type: Number, default: null },
height: { type: Number, default: null },
storageKey: { type: String, required: true },
thumbKey: { type: String, default: null },
uploadedBy: { type: Schema.Types.ObjectId, required: true },
/** Kayıt içindeki sıra (carousel sırası). */
order: { type: Number, default: 0 },
deletedAt: { type: Date, default: null },
},
{ timestamps: true, collection: "attachments" },
);
attachmentSchema.index({ householdId: 1, ownerType: 1, ownerId: 1, deletedAt: 1, order: 1 });
attachmentSchema.index({ ownerId: 1, createdAt: 1 });
attachmentSchema.index(
{ deletedAt: 1 },
{ partialFilterExpression: { deletedAt: { $type: "date" } } },
);
attachmentSchema.index({ storageKey: 1 }, { unique: true });
export type Attachment = InferSchemaType<typeof attachmentSchema>;
export const AttachmentModel: Model<Attachment> =
(models.Attachment as Model<Attachment> | undefined) ??
model<Attachment>("Attachment", attachmentSchema);
+10
View File
@@ -17,6 +17,16 @@ export const AUDIT_ACTIONS = [
"user.ban",
"user.unban",
"user.remove",
"account.create",
"account.update",
"account.archive",
"account.unarchive",
"account.reconcile",
"category.archive",
"category.unarchive",
"category.move",
"transaction.delete",
"transaction.restore",
] as const;
export type AuditAction = (typeof AUDIT_ACTIONS)[number];
+38
View File
@@ -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);
+25
View File
@@ -0,0 +1,25 @@
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
import { TRANSACTION_TYPES } from "@/shared/transactions";
/** Satıcı / karşı taraf ve "akıllı giriş" kuralı: son kullanılan kategori ve hesap (Bölüm 6.3). */
const payeeSchema = new Schema(
{
householdId: { type: Schema.Types.ObjectId, required: true },
name: { type: String, required: true, trim: true, maxlength: 80 },
nameKey: { type: String, required: true },
lastType: { type: String, enum: TRANSACTION_TYPES, default: "expense" },
lastCategoryId: { type: Schema.Types.ObjectId, default: null },
lastAccountId: { type: Schema.Types.ObjectId, default: null },
useCount: { type: Number, default: 0 },
lastUsedAt: { type: Date, default: () => new Date() },
},
{ timestamps: true, collection: "payees" },
);
payeeSchema.index({ householdId: 1, nameKey: 1 }, { unique: true });
payeeSchema.index({ householdId: 1, useCount: -1 });
export type Payee = InferSchemaType<typeof payeeSchema>;
export const PayeeModel: Model<Payee> =
(models.Payee as Model<Payee> | undefined) ?? model<Payee>("Payee", payeeSchema);
+30
View File
@@ -0,0 +1,30 @@
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
/**
* Mutabakat kaydı (Bölüm 6.1): kullanıcı ekstre bakiyesini girdi, uygulama bakiyesiyle
* karşılaştırıldı, fark varsa düzeltme işlemi oluşturuldu ve o tarihe kadarki işlemler işaretlendi.
*/
const reconciliationSchema = new Schema(
{
householdId: { type: Schema.Types.ObjectId, required: true },
accountId: { type: Schema.Types.ObjectId, required: true },
/** İstanbul gününün başlangıç anı (UTC); o günün sonuna kadarki işlemler dahil. */
statementDate: { type: Date, required: true },
/** Uygulamadaki işaretle (kredi kartında eksi = borç). */
statementBalanceMinor: { type: Number, required: true },
appBalanceMinor: { type: Number, required: true },
differenceMinor: { type: Number, required: true },
adjustmentTransactionId: { type: Schema.Types.ObjectId, default: null },
markedCount: { type: Number, default: 0 },
createdBy: { type: Schema.Types.ObjectId, required: true },
},
{ timestamps: { createdAt: true, updatedAt: false }, collection: "reconciliations" },
);
reconciliationSchema.index({ householdId: 1, accountId: 1, statementDate: -1, createdAt: -1 });
export type Reconciliation = InferSchemaType<typeof reconciliationSchema>;
export const ReconciliationModel: Model<Reconciliation> =
(models.Reconciliation as Model<Reconciliation> | undefined) ??
model<Reconciliation>("Reconciliation", reconciliationSchema);
+82
View File
@@ -0,0 +1,82 @@
import { model, models, Schema, type InferSchemaType, type Model } from "mongoose";
import { TRANSACTION_STATUSES, TRANSACTION_TYPES } from "@/shared/transactions";
/**
* İşlem (Bölüm 6.3). `amountMinor` her zaman pozitif; işaret türden gelir (transactionEffects).
* Bakiyenin tek doğruluk kaynağıdır. Silme yumuşaktır (`deletedAt`).
*/
const splitSchema = new Schema(
{
categoryId: { type: Schema.Types.ObjectId, required: true },
amountMinor: { type: Number, required: true, min: 1 },
note: { type: String, default: "", maxlength: 120 },
},
{ _id: true },
);
const transactionSchema = new Schema(
{
householdId: { type: Schema.Types.ObjectId, required: true },
type: { type: String, enum: TRANSACTION_TYPES, required: true },
status: { type: String, enum: TRANSACTION_STATUSES, default: "posted" },
/** İstanbul gününün başlangıç anı (UTC). */
date: { type: Date, required: true },
accountId: { type: Schema.Types.ObjectId, required: true },
toAccountId: { type: Schema.Types.ObjectId, default: null },
amountMinor: { type: Number, required: true, min: 1 },
/** Bölünmemiş gelir/giderde kategori; bölünmüşte null ve kalemler `splits`te. */
categoryId: { type: Schema.Types.ObjectId, default: null },
splits: { type: [splitSchema], default: [] },
/** Kategori filtresi/raporlar için: categoryId veya kalem kategorileri (tekilleştirilmiş). */
effectiveCategoryIds: { type: [Schema.Types.ObjectId], default: [] },
payeeId: { type: Schema.Types.ObjectId, default: null },
payeeName: { type: String, default: "", maxlength: 80 },
description: { type: String, default: "", maxlength: 500 },
/** Arama için normalize metin (açıklama + satıcı + kalem notları). */
searchText: { type: String, default: "" },
tags: { type: [String], default: [] },
/** Bağlı (silinmemiş) ek dosya sayısı; liste ikonu için (asıl kayıt attachments'ta). */
attachmentCount: { type: Number, default: 0 },
// İleri fazlar: planlı işlem kuralı (7), taksit (7), kart dönemi (7), cari (8).
recurringRuleId: { type: Schema.Types.ObjectId, default: null },
installment: {
type: new Schema(
{ planId: Schema.Types.ObjectId, index: Number, count: Number },
{ _id: false },
),
default: null,
},
statementId: { type: Schema.Types.ObjectId, default: null },
contactId: { type: Schema.Types.ObjectId, default: null },
/**
* Mutabakatı yapılmış hesaplar (Bölüm 6.1). Transfer iki hesaba dokunduğu için hesap bazında
* tutulur. Tutar, tarih, tür veya hesap değişirse işaret kalkar.
*/
reconciledAccountIds: { type: [Schema.Types.ObjectId], default: [] },
/** Mutabakat düzeltme işlemi: kategorisiz; düzenlenemez, yalnızca silinebilir. */
isAdjustment: { type: Boolean, default: false },
deletedAt: { type: Date, default: null },
/** Seed verisinin idempotent yüklenmesi için sabit anahtar. */
seedRef: { type: String, default: null },
createdBy: { type: Schema.Types.ObjectId, required: true },
updatedBy: { type: Schema.Types.ObjectId, required: true },
},
{ timestamps: true, collection: "transactions" },
);
transactionSchema.index({ householdId: 1, deletedAt: 1, date: -1, createdAt: -1 });
transactionSchema.index({ householdId: 1, status: 1, date: 1 });
transactionSchema.index({ householdId: 1, accountId: 1, date: -1 });
transactionSchema.index({ householdId: 1, toAccountId: 1, date: -1 });
transactionSchema.index({ householdId: 1, effectiveCategoryIds: 1, date: -1 });
transactionSchema.index({ householdId: 1, tags: 1 });
transactionSchema.index(
{ householdId: 1, seedRef: 1 },
{ unique: true, partialFilterExpression: { seedRef: { $type: "string" } } },
);
export type Transaction = InferSchemaType<typeof transactionSchema>;
export const TransactionModel: Model<Transaction> =
(models.Transaction as Model<Transaction> | undefined) ??
model<Transaction>("Transaction", transactionSchema);
+3 -1
View File
@@ -16,7 +16,9 @@ export function proxy(request: NextRequest) {
export const config = {
// Herkese açık yollar hariç: giriş, auth ve health API'leri, statik dosyalar, ikonlar, manifest.
// /api/files da hariç: route oturumu kendisi kontrol eder (401) ve proxy büyük yükleme
// gövdelerini tamponlamasın (proxyClientMaxBodySize).
matcher: [
"/((?!login|api/auth|api/health|_next/static|_next/image|brand/|icons/|favicon.ico|icon.png|apple-icon.png|manifest.webmanifest|robots.txt).*)",
"/((?!login|api/auth|api/health|api/files|_next/static|_next/image|brand/|icons/|favicon.ico|icon.png|apple-icon.png|manifest.webmanifest|robots.txt).*)",
],
};
+20
View File
@@ -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";
+71
View File
@@ -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];
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import {
acceptAttribute,
allowedAttachmentKinds,
detectFileType,
formatFileSize,
kindOf,
} from "./attachments";
const bytes = (...parts: (number[] | string)[]) =>
new Uint8Array(
parts.flatMap((p) => (typeof p === "string" ? [...p].map((c) => c.charCodeAt(0)) : p)),
);
describe("detectFileType", () => {
it("imzalardan türü bulur", () => {
expect(detectFileType(bytes([0xff, 0xd8, 0xff, 0xe0]))).toBe("jpeg");
expect(detectFileType(bytes([0x89], "PNG", [0x0d, 0x0a, 0x1a, 0x0a]))).toBe("png");
expect(detectFileType(bytes("RIFF", [0, 0, 0, 0], "WEBPVP8 "))).toBe("webp");
expect(detectFileType(bytes("%PDF-1.7"))).toBe("pdf");
});
it("HEIC: ana veya uyumlu markadan", () => {
expect(detectFileType(bytes([0, 0, 0, 24], "ftypheic", [0, 0, 0, 0], "mif1heic"))).toBe("heic");
expect(detectFileType(bytes([0, 0, 0, 28], "ftypmif1", [0, 0, 0, 0], "mif1heichevc"))).toBe(
"heic",
);
// MP4 videosu HEIC değildir.
expect(detectFileType(bytes([0, 0, 0, 24], "ftypisom", [0, 0, 2, 0], "isomiso2"))).toBeNull();
});
it("uzantı/metin/kısa içerik reddedilir", () => {
expect(detectFileType(bytes("<svg xmlns="))).toBeNull();
expect(detectFileType(bytes("GIF89a"))).toBeNull();
expect(detectFileType(bytes([0xff, 0xd8]))).toBeNull();
expect(detectFileType(new Uint8Array())).toBeNull();
});
});
describe("tür kuralları", () => {
it("gider yalnızca görsel; gelir ve transfer görsel + PDF", () => {
expect(allowedAttachmentKinds("expense")).toEqual(["image"]);
expect(allowedAttachmentKinds("income")).toEqual(["image", "pdf"]);
expect(allowedAttachmentKinds("transfer")).toEqual(["image", "pdf"]);
expect(acceptAttribute(["image"])).not.toContain("pdf");
expect(acceptAttribute(["image", "pdf"])).toContain("application/pdf");
expect(kindOf("heic")).toBe("image");
expect(kindOf("pdf")).toBe("pdf");
});
it("boyut biçimi", () => {
expect(formatFileSize(900)).toBe("900 B");
expect(formatFileSize(2048)).toBe("2 KB");
expect(formatFileSize(1.5 * 1024 * 1024)).toBe("1,5 MB");
});
});
+78
View File
@@ -0,0 +1,78 @@
import type { TransactionType } from "./transactions";
/** Ek dosya kuralları (Bölüm 6.3, 7.4). Sunucu ve istemci aynı sabitleri kullanır. */
export const MAX_ATTACHMENTS_PER_RECORD = 10;
export const ATTACHMENT_KINDS = ["image", "pdf"] as const;
export type AttachmentKind = (typeof ATTACHMENT_KINDS)[number];
/** Dosya içeriğinden tespit edilen kaynak türler (uzantıya güvenilmez). */
export type DetectedType = "jpeg" | "png" | "webp" | "heic" | "pdf";
export function kindOf(type: DetectedType): AttachmentKind {
return type === "pdf" ? "pdf" : "image";
}
/**
* İşlem türüne göre izinli ek türleri: gider yalnızca görsel (fiş/fatura fotoğrafı);
* gelir görsel veya PDF (ör. bordro); transfer görsel veya PDF (dekont).
*/
export function allowedAttachmentKinds(type: TransactionType): readonly AttachmentKind[] {
return type === "expense" ? ["image"] : ["image", "pdf"];
}
/** `<input accept>` değeri (yalnızca seçici filtresi; asıl doğrulama sunucuda). */
export function acceptAttribute(kinds: readonly AttachmentKind[]): string {
const image = "image/jpeg,image/png,image/webp,image/heic,image/heif,.heic,.heif";
return kinds.includes("pdf") ? `${image},application/pdf,.pdf` : image;
}
/** Dosya içeriğinin ilk baytlarından türü bulur; desteklenmeyen içerikte null. */
export function detectFileType(bytes: Uint8Array): DetectedType | null {
const at = (offset: number, sig: number[]) =>
bytes.length >= offset + sig.length && sig.every((b, i) => bytes[offset + i] === b);
const ascii = (offset: number, text: string) =>
at(
offset,
[...text].map((c) => c.charCodeAt(0)),
);
if (at(0, [0xff, 0xd8, 0xff])) return "jpeg";
if (at(0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png";
if (ascii(0, "RIFF") && ascii(8, "WEBP")) return "webp";
if (ascii(0, "%PDF-")) return "pdf";
// ISO BMFF: [boyut][ftyp][ana marka][sürüm][uyumlu markalar…]
if (ascii(4, "ftyp")) {
const boxSize = Math.min(
bytes.length,
((bytes[0]! << 24) | (bytes[1]! << 16) | (bytes[2]! << 8) | bytes[3]!) >>> 0,
);
const brands: string[] = [];
const brandAt = (o: number) => String.fromCharCode(...bytes.subarray(o, o + 4));
brands.push(brandAt(8));
for (let o = 16; o + 4 <= boxSize && o < 64; o += 4) brands.push(brandAt(o));
if (brands.some((b) => HEIF_BRANDS.has(b))) return "heic";
}
return null;
}
const HEIF_BRANDS = new Set([
"heic",
"heix",
"heim",
"heis",
"hevc",
"hevx",
"hevm",
"hevs",
"mif1",
"msf1",
]);
/** "1,2 MB" gibi okunur boyut. */
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
const kb = bytes / 1024;
if (kb < 1024) return `${Math.round(kb)} KB`;
return `${(kb / 1024).toLocaleString("tr-TR", { maximumFractionDigits: 1 })} MB`;
}
+29
View File
@@ -0,0 +1,29 @@
/**
* CSV üretimi — Türkçe Excel ile uyumlu: noktalı virgül ayırıcı, ondalık virgül,
* UTF-8 BOM (Türkçe karakterler doğru açılır), CRLF satır sonu.
* Formül enjeksiyonuna karşı = + - @ ile başlayan metinler tek tırnakla etkisizleştirilir.
*/
export const CSV_SEPARATOR = ";";
const BOM = "";
export type CsvValue = string | number | null | undefined;
function escapeCell(value: CsvValue): string {
if (value === null || value === undefined) return "";
let s = typeof value === "number" ? String(value) : value;
// Sayısal görünen değerler (ör. "-1250,50") olduğu gibi kalır; diğerleri formül olarak çalışmasın.
if (typeof value === "string" && /^[=+\-@\t\r]/.test(s) && !/^-?\d+(,\d+)?$/.test(s)) s = `'${s}`;
return /[";\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export function toCsv(header: readonly string[], rows: readonly (readonly CsvValue[])[]): string {
const lines = [header, ...rows].map((r) => r.map(escapeCell).join(CSV_SEPARATOR));
return BOM + lines.join("\r\n") + "\r\n";
}
/** Kuruş → "1250,50" (CSV'de sayı olarak okunur; binlik ayırıcı yok). */
export function csvMoney(amountMinor: number): string {
const sign = amountMinor < 0 ? "-" : "";
const abs = Math.abs(amountMinor);
return `${sign}${Math.trunc(abs / 100)},${String(abs % 100).padStart(2, "0")}`;
}
+26
View File
@@ -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);
}
});
});
+51
View File
@@ -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);
}
+87
View File
@@ -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);
});
});
+119
View File
@@ -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),
);
}
+40
View File
@@ -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);
});
});
+51
View File
@@ -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);
}
+89
View File
@@ -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>;
+20
View File
@@ -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>;
+29
View File
@@ -0,0 +1,29 @@
import { z } from "zod";
import { tr } from "../../i18n/tr";
import { parseMoney } from "../money";
const v = tr.validation;
/**
* Mutabakat formu (web + mobil). `statementBalance` ekstredeki bakiye; kredi kartında
* ekstredeki BORÇ tutarı pozitif girilir (sunucu uygulamadaki eksi bakiyeye çevirir).
*/
export const reconcileSchema = z.object({
statementDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, v.date),
statementBalance: z
.string()
.trim()
.transform((s, ctx) => {
const minor = parseMoney(s);
if (minor === null) {
ctx.addIssue({ code: "custom", message: v.money });
return z.NEVER;
}
return minor;
}),
/** Fark varsa düzeltme işlemi oluşturulmasını onaylar. */
acceptAdjustment: z.boolean().default(false),
});
export type ReconcileInput = z.input<typeof reconcileSchema>;
export type ReconcileForm = z.output<typeof reconcileSchema>;
+126
View File
@@ -0,0 +1,126 @@
import { z } from "zod";
import { tr } from "../../i18n/tr";
import { parseMoney } from "../money";
import { MAX_ATTACHMENTS_PER_RECORD } from "../attachments";
import { MAX_SPLITS, normalizeTags, TRANSACTION_TYPES } from "../transactions";
const v = tr.validation;
const t = tr.transactions.validation;
const objectId = z.string().regex(/^[a-f0-9]{24}$/i, t.selectAccount);
const optionalId = z
.string()
.regex(/^([a-f0-9]{24})?$/i)
.nullable()
.optional()
.transform((s) => (s ? s : null));
/** Pozitif tutar ("1.250,50" → 125050). */
const positiveMoney = z
.string()
.trim()
.transform((s, ctx) => {
const minor = parseMoney(s);
if (minor === null || minor <= 0) {
ctx.addIssue({ code: "custom", message: minor === null ? v.money : t.amountPositive });
return z.NEVER;
}
return minor;
});
const splitSchema = z.object({
categoryId: objectId.refine(Boolean, t.selectCategory),
amount: positiveMoney,
note: z.string().trim().max(120).default(""),
});
/**
* İşlem formu (web + mobil). Kurallar:
* - transfer: hedef hesap zorunlu ve kaynaktan farklı; kategori/bölme yok.
* - gelir/gider: ya tek kategori ya da en az 2 kalemli bölme; kalemler toplamı = tutar.
*/
export const transactionFormSchema = z
.object({
type: z.enum(TRANSACTION_TYPES),
amount: positiveMoney,
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, v.date),
accountId: objectId,
toAccountId: optionalId,
categoryId: optionalId,
splits: z.array(splitSchema).max(MAX_SPLITS).default([]),
payee: z.string().trim().max(80).default(""),
description: z.string().trim().max(500).default(""),
tags: z
.union([z.string(), z.array(z.string())])
.default("")
.transform((x) => normalizeTags(x)),
/** Bağlı ek dosyalar (sıralı). Yeni ekler önce /api/files ile yüklenir. */
attachmentIds: z
.array(z.string().regex(/^[a-f0-9]{24}$/i))
.max(MAX_ATTACHMENTS_PER_RECORD, tr.attachments.errors.tooMany(MAX_ATTACHMENTS_PER_RECORD))
.default([]),
})
.superRefine((x, ctx) => {
if (x.type === "transfer") {
if (!x.toAccountId)
ctx.addIssue({ code: "custom", path: ["toAccountId"], message: t.selectToAccount });
else if (x.toAccountId === x.accountId)
ctx.addIssue({ code: "custom", path: ["toAccountId"], message: t.sameAccount });
return;
}
if (x.splits.length === 1) {
ctx.addIssue({ code: "custom", path: ["splits"], message: t.splitMin });
} else if (x.splits.length >= 2) {
const sum = x.splits.reduce((a, s) => a + s.amount, 0);
if (sum !== x.amount) ctx.addIssue({ code: "custom", path: ["splits"], message: t.splitSum });
} else if (!x.categoryId) {
ctx.addIssue({ code: "custom", path: ["categoryId"], message: t.selectCategory });
}
});
export type TransactionFormInput = z.input<typeof transactionFormSchema>;
export type TransactionForm = z.output<typeof transactionFormSchema>;
/** Liste filtreleri (URL arama parametrelerinden). Geçersiz değerler yok sayılır. */
export const transactionFilterSchema = z.object({
from: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional()
.catch(undefined),
to: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional()
.catch(undefined),
type: z.enum(TRANSACTION_TYPES).optional().catch(undefined),
hesap: z
.string()
.regex(/^[a-f0-9]{24}$/i)
.optional()
.catch(undefined),
kategori: z
.string()
.regex(/^[a-f0-9]{24}$/i)
.optional()
.catch(undefined),
kisi: z
.string()
.regex(/^[a-f0-9]{24}$/i)
.optional()
.catch(undefined),
durum: z.enum(["posted", "planned", "void"]).optional().catch(undefined),
min: z
.string()
.optional()
.catch(undefined)
.transform((s) => (s ? (parseMoney(s) ?? undefined) : undefined)),
max: z
.string()
.optional()
.catch(undefined)
.transform((s) => (s ? (parseMoney(s) ?? undefined) : undefined)),
etiket: z.string().trim().max(30).optional().catch(undefined),
q: z.string().trim().max(80).optional().catch(undefined),
sayfa: z.coerce.number().int().min(1).max(10_000).catch(1).default(1),
});
export type TransactionFilters = z.output<typeof transactionFilterSchema>;
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import {
accountEffect,
monthRange,
MONTH_PATTERN,
shiftMonth,
withRunningBalance,
} from "./statement";
describe("ay yardımcıları", () => {
it("monthRange ve shiftMonth yıl sınırını aşar", () => {
expect(monthRange("2026-12")).toEqual({ start: "2026-12-01", end: "2027-01-01" });
expect(shiftMonth("2026-01", -1)).toBe("2025-12");
expect(shiftMonth("2026-11", 14)).toBe("2028-01");
expect(MONTH_PATTERN.test("2026-13")).toBe(false);
expect(MONTH_PATTERN.test("2026-09")).toBe(true);
});
});
describe("accountEffect", () => {
const a = "A";
it("gelir +, gider −, transfer kaynak − / hedef +, ilgisiz 0", () => {
expect(accountEffect({ type: "income", amountMinor: 500, accountId: a }, a)).toBe(500);
expect(accountEffect({ type: "expense", amountMinor: 500, accountId: a }, a)).toBe(-500);
const tr = { type: "transfer" as const, amountMinor: 300, accountId: a, toAccountId: "B" };
expect(accountEffect(tr, a)).toBe(-300);
expect(accountEffect(tr, "B")).toBe(300);
expect(accountEffect(tr, "C")).toBe(0);
expect(accountEffect({ type: "expense", amountMinor: 1, accountId: "B" }, a)).toBe(0);
});
});
describe("withRunningBalance", () => {
it("açılıştan başlayarak biriktirir", () => {
expect(
withRunningBalance(1000, [{ deltaMinor: -200 }, { deltaMinor: 50 }]).map(
(r) => r.balanceMinor,
),
).toEqual([800, 850]);
expect(withRunningBalance(5, [])).toEqual([]);
});
});
+48
View File
@@ -0,0 +1,48 @@
import type { TransactionType } from "./transactions";
/** Hesap ekstresi yardımcıları (Bölüm 6.1). Saf fonksiyonlar; sunucu ve testler kullanır. */
export const MONTH_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/;
/** "2026-11" → { start: "2026-11-01", end: "2026-12-01" } (end hariç). */
export function monthRange(ym: string): { start: string; end: string } {
return { start: `${ym}-01`, end: `${shiftMonth(ym, 1)}-01` };
}
/** "2026-01", -1 → "2025-12". */
export function shiftMonth(ym: string, delta: number): string {
const [y, m] = ym.split("-").map(Number) as [number, number];
const index = y * 12 + (m - 1) + delta;
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, "0")}`;
}
/** Bir işlemin belirli bir hesaba etkisi (kuruş): gelir +, gider −, transfer kaynak − / hedef +. */
export function accountEffect(
tx: {
type: TransactionType;
amountMinor: number;
accountId: string;
toAccountId?: string | null;
},
accountId: string,
): number {
if (tx.type === "transfer") {
if (tx.accountId === accountId) return -tx.amountMinor;
if (tx.toAccountId === accountId) return tx.amountMinor;
return 0;
}
if (tx.accountId !== accountId) return 0;
return tx.type === "income" ? tx.amountMinor : -tx.amountMinor;
}
/** Kronolojik sıralı etkilere yürüyen bakiye ekler. */
export function withRunningBalance<T extends { deltaMinor: number }>(
openingMinor: number,
rows: readonly T[],
): (T & { balanceMinor: number })[] {
let balance = openingMinor;
return rows.map((r) => {
balance += r.deltaMinor;
return { ...r, balanceMinor: balance };
});
}
+132
View File
@@ -0,0 +1,132 @@
import { describe, expect, it } from "vitest";
import { toCsv, csvMoney } from "./csv";
import { transactionFormSchema } from "./schemas/transaction";
import { normalizeTags, transactionEffects } from "./transactions";
const A = "a".repeat(24);
const B = "b".repeat(24);
const C1 = "c".repeat(24);
const C2 = "d".repeat(24);
describe("transactionEffects", () => {
it("gelir +, gider −, transfer kaynaktan − hedefe +", () => {
expect(
transactionEffects({ type: "income", status: "posted", amountMinor: 500, accountId: A }),
).toEqual([{ accountId: A, deltaMinor: 500 }]);
expect(
transactionEffects({ type: "expense", status: "posted", amountMinor: 500, accountId: A }),
).toEqual([{ accountId: A, deltaMinor: -500 }]);
expect(
transactionEffects({
type: "transfer",
status: "posted",
amountMinor: 500,
accountId: A,
toAccountId: B,
}),
).toEqual([
{ accountId: A, deltaMinor: -500 },
{ accountId: B, deltaMinor: 500 },
]);
});
it("planlı, iptal ve silinmiş işlemler etkisizdir", () => {
for (const x of [
{ status: "planned" as const },
{ status: "void" as const },
{ status: "posted" as const, deleted: true },
]) {
expect(transactionEffects({ type: "expense", amountMinor: 1, accountId: A, ...x })).toEqual(
[],
);
}
});
});
describe("normalizeTags", () => {
it("küçük harf, kırpma, tekrar yok, en fazla 10", () => {
expect(normalizeTags(" Market, İNDİRİM ,market,,#tatil")).toEqual([
"market",
"indirim",
"tatil",
]);
expect(normalizeTags(Array.from({ length: 15 }, (_, i) => `e${i}`))).toHaveLength(10);
});
});
describe("transactionFormSchema", () => {
const base = { type: "expense", amount: "1.200,00", date: "2026-11-05", accountId: A };
it("tek kategorili gideri kabul eder ve tutarı kuruşa çevirir", () => {
const r = transactionFormSchema.parse({ ...base, categoryId: C1, tags: "ev, Ev" });
expect(r.amount).toBe(120000);
expect(r.categoryId).toBe(C1);
expect(r.tags).toEqual(["ev"]);
expect(r.splits).toEqual([]);
});
it("kategorisiz ve bölmesiz gideri reddeder", () => {
expect(transactionFormSchema.safeParse(base).success).toBe(false);
});
it("bölünmüş işlemde kalem toplamı tutara eşit olmalı", () => {
const ok = transactionFormSchema.safeParse({
...base,
splits: [
{ categoryId: C1, amount: "800" },
{ categoryId: C2, amount: "250" },
{ categoryId: C1, amount: "150,00" },
],
});
expect(ok.success).toBe(true);
const bad = transactionFormSchema.safeParse({
...base,
splits: [
{ categoryId: C1, amount: "800" },
{ categoryId: C2, amount: "250" },
],
});
expect(bad.success).toBe(false);
expect(bad.error?.issues[0]?.path).toEqual(["splits"]);
const single = transactionFormSchema.safeParse({
...base,
splits: [{ categoryId: C1, amount: "1200" }],
});
expect(single.success).toBe(false);
});
it("transfer: hedef zorunlu, kaynaktan farklı", () => {
expect(transactionFormSchema.safeParse({ ...base, type: "transfer" }).success).toBe(false);
expect(
transactionFormSchema.safeParse({ ...base, type: "transfer", toAccountId: A }).success,
).toBe(false);
expect(
transactionFormSchema.safeParse({ ...base, type: "transfer", toAccountId: B }).success,
).toBe(true);
});
it("sıfır, negatif ve geçersiz tutarı reddeder", () => {
for (const amount of ["0", "-5", "abc", ""]) {
expect(
transactionFormSchema.safeParse({ ...base, categoryId: C1, amount }).success,
amount,
).toBe(false);
}
});
});
describe("CSV", () => {
it("BOM, noktalı virgül, kaçış ve formül enjeksiyonu koruması", () => {
const csv = toCsv(
["A", "B"],
[
["x;y", '"tırnak"'],
["=HYPERLINK(1)", csvMoney(-125050)],
],
);
expect(csv.startsWith("")).toBe(true);
expect(csv).toContain('"x;y";"""tırnak"""');
expect(csv).toContain("'=HYPERLINK(1);-1250,50");
expect(csv.endsWith("\r\n")).toBe(true);
});
});
+53
View File
@@ -0,0 +1,53 @@
/** İşlem türleri ve durumları (Bölüm 6.3). */
export const TRANSACTION_TYPES = ["expense", "income", "transfer"] as const;
export type TransactionType = (typeof TRANSACTION_TYPES)[number];
/** planned: Faz 7 (planlı işlemler) · posted: gerçekleşti · void: iptal (bakiyeyi etkilemez). */
export const TRANSACTION_STATUSES = ["planned", "posted", "void"] as const;
export type TransactionStatus = (typeof TRANSACTION_STATUSES)[number];
export const MAX_SPLITS = 20;
export const MAX_TAGS = 10;
export type EffectInput = {
type: TransactionType;
status: TransactionStatus;
amountMinor: number;
accountId: string;
toAccountId?: string | null;
deleted?: boolean;
};
/**
* İşlemin hesap bakiyelerine etkisi (kuruş). Tutar her zaman pozitiftir; işaret türden gelir:
* gelir +, gider −, transfer kaynaktan −, hedefe +. Planlı, iptal ve silinmiş işlemler etkisizdir.
* Kredi kartında gider borcu artırır (bakiye daha negatif), karta transfer borcu azaltır.
*/
export function transactionEffects(t: EffectInput): { accountId: string; deltaMinor: number }[] {
if (t.status !== "posted" || t.deleted) return [];
switch (t.type) {
case "income":
return [{ accountId: t.accountId, deltaMinor: t.amountMinor }];
case "expense":
return [{ accountId: t.accountId, deltaMinor: -t.amountMinor }];
case "transfer":
return t.toAccountId
? [
{ accountId: t.accountId, deltaMinor: -t.amountMinor },
{ accountId: t.toAccountId, deltaMinor: t.amountMinor },
]
: [];
}
}
/** "market, İndirim ,market" → ["market", "indirim"] (küçük harf, tekrar yok, en fazla 10). */
export function normalizeTags(input: string | readonly string[]): string[] {
const parts = typeof input === "string" ? input.split(/[,#]/) : input;
const out: string[] = [];
for (const raw of parts) {
const tag = raw.trim().replace(/\s+/g, " ").toLocaleLowerCase("tr-TR").slice(0, 30);
if (tag && !out.includes(tag)) out.push(tag);
if (out.length >= MAX_TAGS) break;
}
return out;
}
+27
View File
@@ -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();
}
+5
View File
@@ -0,0 +1,5 @@
declare module "heic-decode" {
type Decoded = { width: number; height: number; data: Uint8ClampedArray };
function decode(input: { buffer: Uint8Array | ArrayBuffer }): Promise<Decoded>;
export default decode;
}
+4
View File
@@ -1,3 +1,5 @@
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadEnv } from "vite";
import { defineConfig } from "vitest/config";
@@ -35,6 +37,8 @@ export default defineConfig({
SEED_ADMIN_EMAIL: "admin@test.local",
SEED_ADMIN_PASSWORD: "Test-Admin-12345",
SEED_USER_PASSWORD: "Test-User-12345",
// Ek dosyalar geçici dizine (her çalıştırmada test dosyası temizler).
UPLOAD_DIR: path.join(tmpdir(), "butcem-test-uploads"),
},
},
});