feat: Faz 6c - ek dosyalar, carousel ve mutabakat
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+28
-1
@@ -6,7 +6,34 @@ Biçim [Keep a Changelog](https://keepachangelog.com/tr-TR/1.1.0/) esas alınır
|
|||||||
|
|
||||||
## [Yayınlanmamış]
|
## [Yayınlanmamış]
|
||||||
|
|
||||||
Faz 6 (alt fazlar halinde; `v0.6.0` Faz 6c sonunda).
|
## [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
|
### Eklendi — Faz 6b: işlemler
|
||||||
|
|
||||||
|
|||||||
@@ -52,16 +52,19 @@ Giriş kullanıcı adı **veya** e-posta ile yapılır. Kayıt kapalıdır; kull
|
|||||||
|
|
||||||
## Scriptler
|
## Scriptler
|
||||||
|
|
||||||
| Komut | Açıklama |
|
| Komut | Açıklama |
|
||||||
| ----------------------------- | -------------------------------- |
|
| ----------------------------- | --------------------------------- |
|
||||||
| `npm run dev` | Geliştirme sunucusu |
|
| `npm run dev` | Geliştirme sunucusu |
|
||||||
| `npm run build` / `start` | Üretim build'i / sunucusu |
|
| `npm run build` / `start` | Üretim build'i / sunucusu |
|
||||||
| `npm run lint` | ESLint |
|
| `npm run lint` | ESLint |
|
||||||
| `npm run typecheck` | `tsc --noEmit` |
|
| `npm run typecheck` | `tsc --noEmit` |
|
||||||
| `npm run test` | Vitest birim testleri |
|
| `npm run test` | Vitest birim testleri |
|
||||||
| `npm run format` | Prettier |
|
| `npm run format` | Prettier |
|
||||||
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
|
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
|
||||||
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
|
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
|
||||||
|
| `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
|
## Haneler ve yetki
|
||||||
|
|
||||||
|
|||||||
+24
-1
@@ -42,10 +42,24 @@ const securityHeaders = [
|
|||||||
[{ key: "Strict-Transport-Security", value: "max-age=31536000" }]),
|
[{ 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 = {
|
const nextConfig: NextConfig = {
|
||||||
// Docker imajı için yalnızca gerekli dosyaları .next/standalone altına kopyala.
|
// Docker imajı için yalnızca gerekli dosyaları .next/standalone altına kopyala.
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
poweredByHeader: false,
|
poweredByHeader: false,
|
||||||
|
// HEIC çözücü (libheif WASM) bundle'a girmesin; Node require ile yüklensin.
|
||||||
|
serverExternalPackages: ["heic-decode", "libheif-js"],
|
||||||
experimental: {
|
experimental: {
|
||||||
agentFeedback: true,
|
agentFeedback: true,
|
||||||
},
|
},
|
||||||
@@ -60,7 +74,16 @@ const nextConfig: NextConfig = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
async headers() {
|
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 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Generated
+53
-2
@@ -1,18 +1,20 @@
|
|||||||
{
|
{
|
||||||
"name": "butcem",
|
"name": "butcem",
|
||||||
"version": "0.1.0",
|
"version": "0.6.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "butcem",
|
"name": "butcem",
|
||||||
"version": "0.1.0",
|
"version": "0.6.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "^7.0.2",
|
"@hookform/resolvers": "^7.0.2",
|
||||||
"@tanstack/react-table": "^9.3.1",
|
"@tanstack/react-table": "^9.3.1",
|
||||||
"better-auth": "^1.7.17",
|
"better-auth": "^1.7.17",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"cn": "^0.5.2",
|
"cn": "^0.5.2",
|
||||||
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
"heic-decode": "^2.1.0",
|
||||||
"lucide-react": "^1.68.0",
|
"lucide-react": "^1.68.0",
|
||||||
"mongodb": "~7.7",
|
"mongodb": "~7.7",
|
||||||
"mongoose": "^9.11.4",
|
"mongoose": "^9.11.4",
|
||||||
@@ -6861,6 +6863,34 @@
|
|||||||
"integrity": "sha512-LnPnRZ0esKB9NjsSIaC+mffW+5dAtBui6kbK5f9Qykblj4Q33cn6yIhuCcTVjwpvL3YJPqqQ4IlsNyriGNpyFQ==",
|
"integrity": "sha512-LnPnRZ0esKB9NjsSIaC+mffW+5dAtBui6kbK5f9Qykblj4Q33cn6yIhuCcTVjwpvL3YJPqqQ4IlsNyriGNpyFQ==",
|
||||||
"license": "ISC"
|
"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": {
|
"node_modules/emoji-regex": {
|
||||||
"version": "9.2.2",
|
"version": "9.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
||||||
@@ -8205,6 +8235,18 @@
|
|||||||
"node": ">= 0.4"
|
"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": {
|
"node_modules/hermes-estree": {
|
||||||
"version": "0.25.1",
|
"version": "0.25.1",
|
||||||
"resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",
|
"resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",
|
||||||
@@ -9076,6 +9118,15 @@
|
|||||||
"node": ">= 0.8.0"
|
"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": {
|
"node_modules/lightningcss": {
|
||||||
"version": "1.33.0",
|
"version": "1.33.0",
|
||||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
|
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
|
||||||
|
|||||||
+5
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "butcem",
|
"name": "butcem",
|
||||||
"version": "0.5.0",
|
"version": "0.6.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
|
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -22,7 +22,8 @@
|
|||||||
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
|
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
|
||||||
"icons": "tsx scripts/generate-icons.ts",
|
"icons": "tsx scripts/generate-icons.ts",
|
||||||
"test:integration": "vitest run --config vitest.integration.config.mts",
|
"test:integration": "vitest run --config vitest.integration.config.mts",
|
||||||
"migrate": "tsx --conditions=react-server --env-file=.env.local scripts/migrate.ts"
|
"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": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "^7.0.2",
|
"@hookform/resolvers": "^7.0.2",
|
||||||
@@ -30,6 +31,8 @@
|
|||||||
"better-auth": "^1.7.17",
|
"better-auth": "^1.7.17",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"cn": "^0.5.2",
|
"cn": "^0.5.2",
|
||||||
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
"heic-decode": "^2.1.0",
|
||||||
"lucide-react": "^1.68.0",
|
"lucide-react": "^1.68.0",
|
||||||
"mongodb": "~7.7",
|
"mongodb": "~7.7",
|
||||||
"mongoose": "^9.11.4",
|
"mongoose": "^9.11.4",
|
||||||
|
|||||||
@@ -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,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 } });
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -3,10 +3,11 @@ import { connectMongoose } from "@/lib/db/mongoose";
|
|||||||
import { migration as m001 } from "./001-initial-indexes";
|
import { migration as m001 } from "./001-initial-indexes";
|
||||||
import { migration as m002 } from "./002-accounts-categories";
|
import { migration as m002 } from "./002-accounts-categories";
|
||||||
import { migration as m003 } from "./003-transactions";
|
import { migration as m003 } from "./003-transactions";
|
||||||
|
import { migration as m004 } from "./004-attachments-reconciliation";
|
||||||
import type { Migration } from "./types";
|
import type { Migration } from "./types";
|
||||||
|
|
||||||
/** Sıralı migration listesi. Yeni migration: dosyayı ekle ve buraya sırayla ekle. */
|
/** Sıralı migration listesi. Yeni migration: dosyayı ekle ve buraya sırayla ekle. */
|
||||||
export const MIGRATIONS: Migration[] = [m001, m002, m003];
|
export const MIGRATIONS: Migration[] = [m001, m002, m003, m004];
|
||||||
|
|
||||||
const COLLECTION = "migrations";
|
const COLLECTION = "migrations";
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { getAuth } from "@/lib/auth";
|
|||||||
import { getDb } from "@/lib/db/mongo";
|
import { getDb } from "@/lib/db/mongo";
|
||||||
import { connectMongoose } from "@/lib/db/mongoose";
|
import { connectMongoose } from "@/lib/db/mongoose";
|
||||||
import { env } from "@/lib/env";
|
import { env } from "@/lib/env";
|
||||||
|
import { getStorage } from "@/lib/storage";
|
||||||
import { installDefaultCategories } from "@/features/categories/service";
|
import { installDefaultCategories } from "@/features/categories/service";
|
||||||
import { AccountModel } from "@/models/account";
|
import { AccountModel } from "@/models/account";
|
||||||
import { HouseholdModel } from "@/models/household";
|
import { HouseholdModel } from "@/models/household";
|
||||||
@@ -53,6 +54,10 @@ const DOMAIN_COLLECTIONS = [
|
|||||||
"auditLogs",
|
"auditLogs",
|
||||||
"categories",
|
"categories",
|
||||||
"accounts",
|
"accounts",
|
||||||
|
"transactions",
|
||||||
|
"payees",
|
||||||
|
"attachments",
|
||||||
|
"reconciliations",
|
||||||
];
|
];
|
||||||
|
|
||||||
type AuthApi = ReturnType<typeof getAuth>["api"];
|
type AuthApi = ReturnType<typeof getAuth>["api"];
|
||||||
@@ -107,6 +112,14 @@ export async function runSeed({
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (reset) {
|
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]) {
|
for (const name of [...AUTH_COLLECTIONS, ...DOMAIN_COLLECTIONS]) {
|
||||||
await db.collection(name).deleteMany({});
|
await db.collection(name).deleteMany({});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ export type NavItem = {
|
|||||||
|
|
||||||
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
|
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
|
||||||
/** Alt fazlar ondalıkla: 6.1 = Faz 6a. */
|
/** Alt fazlar ondalıkla: 6.1 = Faz 6a. */
|
||||||
export const CURRENT_PHASE = 6.2;
|
export const CURRENT_PHASE = 6.3;
|
||||||
|
|
||||||
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
|
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
};
|
||||||
@@ -110,12 +110,14 @@ export function AccountsView({
|
|||||||
<li className={cn("flex items-center gap-3 p-3", a.archived && "opacity-60")}>
|
<li className={cn("flex items-center gap-3 p-3", a.archived && "opacity-60")}>
|
||||||
<IconBadge icon={a.icon} color={a.color} />
|
<IconBadge icon={a.icon} color={a.color} />
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<Link
|
{/* Gizli hesabın ekstresi yalnızca sahibine açılır. */}
|
||||||
href={`/islemler?hesap=${a.id}`}
|
{a.balanceMinor === null ? (
|
||||||
className="block truncate font-medium hover:underline"
|
<span className="block truncate font-medium">{a.name}</span>
|
||||||
>
|
) : (
|
||||||
{a.name}
|
<Link href={`/hesaplar/${a.id}`} className="block truncate font-medium hover:underline">
|
||||||
</Link>
|
{a.name}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||||
{a.type === "meal_card" && a.mealCardProvider ? (
|
{a.type === "meal_card" && a.mealCardProvider ? (
|
||||||
<span>{t.providers[a.mealCardProvider]}</span>
|
<span>{t.providers[a.mealCardProvider]}</span>
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { z } from "zod";
|
|||||||
import { tr } from "@/i18n/tr";
|
import { tr } from "@/i18n/tr";
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
import { getHouseholdActionContext } from "@/lib/dal";
|
import { getHouseholdActionContext } from "@/lib/dal";
|
||||||
|
import { reconcileSchema } from "@/shared/schemas/reconciliation";
|
||||||
import { transactionFormSchema } from "@/shared/schemas/transaction";
|
import { transactionFormSchema } from "@/shared/schemas/transaction";
|
||||||
import {
|
import {
|
||||||
createTransaction,
|
createTransaction,
|
||||||
@@ -17,6 +18,7 @@ import {
|
|||||||
type TransactionDetail,
|
type TransactionDetail,
|
||||||
type TransactionFormOptions,
|
type TransactionFormOptions,
|
||||||
} from "./service";
|
} from "./service";
|
||||||
|
import { previewReconciliation, reconcileAccount, type ReconcilePreview } from "./statement";
|
||||||
|
|
||||||
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
||||||
|
|
||||||
@@ -103,3 +105,32 @@ export async function searchPayeesAction(query: unknown): Promise<PayeeSuggestio
|
|||||||
if (!ctx || !q.success) return [];
|
if (!ctx || !q.success) return [];
|
||||||
return searchPayees(ctx.user.id, ctx.household.id, q.data);
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -27,6 +27,9 @@ import { cn } from "@/lib/utils";
|
|||||||
import { todayIstanbul } from "@/shared/dates";
|
import { todayIstanbul } from "@/shared/dates";
|
||||||
import { formatMoney } from "@/shared/format";
|
import { formatMoney } from "@/shared/format";
|
||||||
import { formatMoneyInput, parseMoney } from "@/shared/money";
|
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 { transactionFormSchema, type TransactionForm } from "@/shared/schemas/transaction";
|
||||||
import { MAX_SPLITS, TRANSACTION_TYPES, type TransactionType } from "@/shared/transactions";
|
import { MAX_SPLITS, TRANSACTION_TYPES, type TransactionType } from "@/shared/transactions";
|
||||||
import {
|
import {
|
||||||
@@ -57,6 +60,8 @@ type FormValues = {
|
|||||||
payee: string;
|
payee: string;
|
||||||
description: string;
|
description: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
|
/** Önizleme bilgisiyle ekler; sunucuya yalnızca kimlikleri gider. */
|
||||||
|
attachments: AttachmentInfo[];
|
||||||
};
|
};
|
||||||
|
|
||||||
function toValues(mode: TransactionFormMode, options: TransactionFormOptions | null): FormValues {
|
function toValues(mode: TransactionFormMode, options: TransactionFormOptions | null): FormValues {
|
||||||
@@ -72,6 +77,7 @@ function toValues(mode: TransactionFormMode, options: TransactionFormOptions | n
|
|||||||
payee: "",
|
payee: "",
|
||||||
description: "",
|
description: "",
|
||||||
tags: "",
|
tags: "",
|
||||||
|
attachments: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const x = mode.transaction;
|
const x = mode.transaction;
|
||||||
@@ -90,6 +96,8 @@ function toValues(mode: TransactionFormMode, options: TransactionFormOptions | n
|
|||||||
payee: x.payeeName,
|
payee: x.payeeName,
|
||||||
description: x.description,
|
description: x.description,
|
||||||
tags: x.tags.join(", "),
|
tags: x.tags.join(", "),
|
||||||
|
// Kopyada ekler taşınmaz (fiş o işleme aittir).
|
||||||
|
attachments: mode.kind === "edit" ? x.attachments : [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,6 +306,7 @@ export function TransactionFormDialog({
|
|||||||
const [loadError, setLoadError] = useState<string | null>(null);
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||||
const [suggested, setSuggested] = useState(false);
|
const [suggested, setSuggested] = useState(false);
|
||||||
|
const [uploadBusy, setUploadBusy] = useState(false);
|
||||||
const form = useForm<FormValues, unknown, TransactionForm>({
|
const form = useForm<FormValues, unknown, TransactionForm>({
|
||||||
// FormValues, şemanın giriş şekliyle birebir (tutarlar string; zod kuruşa çevirir).
|
// FormValues, şemanın giriş şekliyle birebir (tutarlar string; zod kuruşa çevirir).
|
||||||
resolver: zodResolver(transactionFormSchema) as unknown as Resolver<
|
resolver: zodResolver(transactionFormSchema) as unknown as Resolver<
|
||||||
@@ -332,6 +341,7 @@ export function TransactionFormDialog({
|
|||||||
const amount = useWatch({ control: form.control, name: "amount" });
|
const amount = useWatch({ control: form.control, name: "amount" });
|
||||||
const accountId = useWatch({ control: form.control, name: "accountId" });
|
const accountId = useWatch({ control: form.control, name: "accountId" });
|
||||||
const splitValues = useWatch({ control: form.control, name: "splits" });
|
const splitValues = useWatch({ control: form.control, name: "splits" });
|
||||||
|
const attachmentCount = useWatch({ control: form.control, name: "attachments" })?.length ?? 0;
|
||||||
const splitMode = splits.fields.length > 0;
|
const splitMode = splits.fields.length > 0;
|
||||||
|
|
||||||
// Düzenlemede arşivli/kapalı hesap veya kategori seçenek listesinde yoksa ekle (kaybolmasın).
|
// Düzenlemede arşivli/kapalı hesap veya kategori seçenek listesinde yoksa ekle (kaybolmasın).
|
||||||
@@ -431,9 +441,14 @@ export function TransactionFormDialog({
|
|||||||
|
|
||||||
async function onSubmit() {
|
async function onSubmit() {
|
||||||
if (!mode) return;
|
if (!mode) return;
|
||||||
const values = form.getValues();
|
if (uploadBusy) {
|
||||||
|
form.setError("root", { message: tr.attachments.waitForUploads });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { attachments, ...values } = form.getValues();
|
||||||
const payload = {
|
const payload = {
|
||||||
...values,
|
...values,
|
||||||
|
attachmentIds: attachments.map((a) => a.id),
|
||||||
toAccountId: values.type === "transfer" ? values.toAccountId : "",
|
toAccountId: values.type === "transfer" ? values.toAccountId : "",
|
||||||
categoryId: values.type === "transfer" || values.splits.length ? "" : values.categoryId,
|
categoryId: values.type === "transfer" || values.splits.length ? "" : values.categoryId,
|
||||||
splits: values.type === "transfer" ? [] : values.splits,
|
splits: values.type === "transfer" ? [] : values.splits,
|
||||||
@@ -479,7 +494,7 @@ export function TransactionFormDialog({
|
|||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
form="transaction-form"
|
form="transaction-form"
|
||||||
disabled={form.formState.isSubmitting || loading}
|
disabled={form.formState.isSubmitting || loading || uploadBusy}
|
||||||
>
|
>
|
||||||
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
|
||||||
{tr.common.save}
|
{tr.common.save}
|
||||||
@@ -674,10 +689,30 @@ export function TransactionFormDialog({
|
|||||||
· {t.list.split(splits.fields.length)}
|
· {t.list.split(splits.fields.length)}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
|
{attachmentCount ? (
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
· {tr.attachments.count(attachmentCount)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</Button>
|
</Button>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
<CollapsibleContent className="pt-3">
|
<CollapsibleContent className="pt-3">
|
||||||
<FieldGroup>
|
<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
|
<Controller
|
||||||
name="tags"
|
name="tags"
|
||||||
control={form.control}
|
control={form.control}
|
||||||
|
|||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -1,36 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import { ChevronLeft, ChevronRight, Download, Filter, Paperclip, Plus, X } from "lucide-react";
|
||||||
ArrowLeftRight,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
Copy,
|
|
||||||
Download,
|
|
||||||
Filter,
|
|
||||||
Paperclip,
|
|
||||||
Pencil,
|
|
||||||
Plus,
|
|
||||||
Split,
|
|
||||||
Trash2,
|
|
||||||
X,
|
|
||||||
} from "lucide-react";
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname, useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
import { useState, useTransition } from "react";
|
import { useState } from "react";
|
||||||
import { toast } from "sonner";
|
|
||||||
import { IconBadge } from "@/components/appearance/swatch";
|
|
||||||
import { useQuickAdd } from "@/components/layout/quick-add";
|
import { useQuickAdd } from "@/components/layout/quick-add";
|
||||||
import { MoneyInput } from "@/components/money-input";
|
import { MoneyInput } from "@/components/money-input";
|
||||||
import { ResponsiveDialog } from "@/components/responsive-dialog";
|
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 { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
@@ -43,103 +19,24 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
|
||||||
import { tr } from "@/i18n/tr";
|
import { tr } from "@/i18n/tr";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { formatDate, formatDateTime, formatMoney } from "@/shared/format";
|
import { formatMoney } from "@/shared/format";
|
||||||
import type { TransactionFilters } from "@/shared/schemas/transaction";
|
import type { TransactionFilters } from "@/shared/schemas/transaction";
|
||||||
|
import { TRANSACTION_STATUSES, TRANSACTION_TYPES } from "@/shared/transactions";
|
||||||
|
import type { TransactionFormOptions, TransactionListItem, TransactionPage } from "../service";
|
||||||
import {
|
import {
|
||||||
TRANSACTION_STATUSES,
|
Amount,
|
||||||
TRANSACTION_TYPES,
|
dayLabel,
|
||||||
type TransactionType,
|
RowIcon,
|
||||||
} from "@/shared/transactions";
|
rowSubtitle,
|
||||||
import { getTransactionAction, setTransactionDeletedAction } from "../actions";
|
rowTitle,
|
||||||
import type {
|
signed,
|
||||||
TransactionDetail,
|
useTransactionDetail,
|
||||||
TransactionFormOptions,
|
} from "./transaction-parts";
|
||||||
TransactionListItem,
|
|
||||||
TransactionPage,
|
|
||||||
} from "../service";
|
|
||||||
|
|
||||||
const t = tr.transactions;
|
const t = tr.transactions;
|
||||||
const ALL = "__all__";
|
const ALL = "__all__";
|
||||||
const weekday = new Intl.DateTimeFormat("tr-TR", { weekday: "long", timeZone: "Europe/Istanbul" });
|
|
||||||
|
|
||||||
/** "2026-11-05" → "05.11.2026 · Perşembe" */
|
|
||||||
function dayLabel(ymd: string) {
|
|
||||||
const d = new Date(`${ymd}T12:00:00+03:00`);
|
|
||||||
return `${formatDate(d)} · ${weekday.format(d)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function signed(type: TransactionType, amountMinor: number) {
|
|
||||||
return type === "income" ? amountMinor : type === "expense" ? -amountMinor : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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.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" />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function rowTitle(item: TransactionListItem) {
|
|
||||||
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];
|
|
||||||
}
|
|
||||||
|
|
||||||
function rowSubtitle(item: TransactionListItem) {
|
|
||||||
if (item.type === "transfer")
|
|
||||||
return t.list.transfer(item.account.name, item.toAccount?.name ?? "—");
|
|
||||||
const what = item.splitCount ? t.list.split(item.splitCount) : (item.category?.path ?? "—");
|
|
||||||
return `${what} · ${item.account.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Filtreler ---
|
// --- Filtreler ---
|
||||||
|
|
||||||
@@ -318,126 +215,6 @@ function FiltersDialog({
|
|||||||
|
|
||||||
// --- Ayrıntı ---
|
// --- Ayrıntı ---
|
||||||
|
|
||||||
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>
|
|
||||||
<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.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}
|
|
||||||
{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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Ana görünüm ---
|
// --- Ana görünüm ---
|
||||||
|
|
||||||
export function TransactionsView({
|
export function TransactionsView({
|
||||||
@@ -454,12 +231,9 @@ export function TransactionsView({
|
|||||||
canWrite: boolean;
|
canWrite: boolean;
|
||||||
}) {
|
}) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { openQuickAdd, openTransactionForm } = useQuickAdd();
|
const { openQuickAdd } = useQuickAdd();
|
||||||
const [filtersOpen, setFiltersOpen] = useState(false);
|
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||||
const [detail, setDetail] = useState<TransactionDetail | null>(null);
|
const { openDetail, element: detailElement } = useTransactionDetail(canWrite);
|
||||||
const [detailLoading, setDetailLoading] = useState(false);
|
|
||||||
const [deleting, setDeleting] = useState<TransactionDetail | null>(null);
|
|
||||||
const [, startTransition] = useTransition();
|
|
||||||
const active = countActive(filters);
|
const active = countActive(filters);
|
||||||
|
|
||||||
const pageHref = (page: number) => {
|
const pageHref = (page: number) => {
|
||||||
@@ -474,40 +248,6 @@ export function TransactionsView({
|
|||||||
return `/islemler/disa-aktar${params.size ? `?${params}` : ""}`;
|
return `/islemler/disa-aktar${params.size ? `?${params}` : ""}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function openDetail(id: string) {
|
|
||||||
setDetailLoading(true);
|
|
||||||
setDetail(null);
|
|
||||||
const res = await getTransactionAction(id);
|
|
||||||
setDetailLoading(false);
|
|
||||||
if (res.ok) setDetail(res.data);
|
|
||||||
else toast.error(res.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeDetail() {
|
|
||||||
setDetail(null);
|
|
||||||
setDetailLoading(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function remove(d: TransactionDetail) {
|
|
||||||
setDeleting(null);
|
|
||||||
closeDetail();
|
|
||||||
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);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sayfadaki işlemleri güne göre grupla (liste zaten tarihe göre sıralı).
|
// Sayfadaki işlemleri güne göre grupla (liste zaten tarihe göre sıralı).
|
||||||
const groups: { date: string; items: TransactionListItem[] }[] = [];
|
const groups: { date: string; items: TransactionListItem[] }[] = [];
|
||||||
for (const item of data.items) {
|
for (const item of data.items) {
|
||||||
@@ -679,35 +419,7 @@ export function TransactionsView({
|
|||||||
raw={raw}
|
raw={raw}
|
||||||
options={options}
|
options={options}
|
||||||
/>
|
/>
|
||||||
<DetailDialog
|
{detailElement}
|
||||||
detail={detail}
|
|
||||||
loading={detailLoading}
|
|
||||||
canWrite={canWrite}
|
|
||||||
onOpenChange={(o) => !o && closeDetail()}
|
|
||||||
onEdit={(d) => {
|
|
||||||
closeDetail();
|
|
||||||
openTransactionForm({ kind: "edit", transaction: d });
|
|
||||||
}}
|
|
||||||
onCopy={(d) => {
|
|
||||||
closeDetail();
|
|
||||||
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>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ function form(over: Partial<TransactionForm>): TransactionForm {
|
|||||||
payee: "",
|
payee: "",
|
||||||
description: "",
|
description: "",
|
||||||
tags: [],
|
tags: [],
|
||||||
|
attachmentIds: [],
|
||||||
...over,
|
...over,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import "server-only";
|
import "server-only";
|
||||||
import { Types, type PipelineStage } from "mongoose";
|
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 { resolveMembership } from "@/features/households/service";
|
||||||
import { buildTree, toOptions, type CategoryOption } from "@/features/categories/tree";
|
import { buildTree, toOptions, type CategoryOption } from "@/features/categories/tree";
|
||||||
import { tr } from "@/i18n/tr";
|
import { tr } from "@/i18n/tr";
|
||||||
@@ -12,6 +17,7 @@ import { CategoryModel } from "@/models/category";
|
|||||||
import { PayeeModel } from "@/models/payee";
|
import { PayeeModel } from "@/models/payee";
|
||||||
import { TransactionModel } from "@/models/transaction";
|
import { TransactionModel } from "@/models/transaction";
|
||||||
import type { AccountType } from "@/shared/accounts";
|
import type { AccountType } from "@/shared/accounts";
|
||||||
|
import { allowedAttachmentKinds } from "@/shared/attachments";
|
||||||
import type { IconKey, Swatch } from "@/shared/appearance";
|
import type { IconKey, Swatch } from "@/shared/appearance";
|
||||||
import { istanbulDayStart, toIstanbulYmd } from "@/shared/dates";
|
import { istanbulDayStart, toIstanbulYmd } from "@/shared/dates";
|
||||||
import type { CategoryKind } from "@/shared/schemas/category";
|
import type { CategoryKind } from "@/shared/schemas/category";
|
||||||
@@ -52,7 +58,12 @@ type CategoryInfo = {
|
|||||||
ancestors: string[];
|
ancestors: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
async function loadContext(userId: string, householdId: string, minRole: "viewer" | "member") {
|
/** 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);
|
const m = await resolveMembership(userId, householdId, minRole);
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
const [accounts, categories] = await Promise.all([
|
const [accounts, categories] = await Promise.all([
|
||||||
@@ -116,7 +127,7 @@ async function loadContext(userId: string, householdId: string, minRole: "viewer
|
|||||||
return { m, accountMap, categoryMap, hiddenAccountIds, flatCategories: flat };
|
return { m, accountMap, categoryMap, hiddenAccountIds, flatCategories: flat };
|
||||||
}
|
}
|
||||||
|
|
||||||
type Ctx = NonNullable<Awaited<ReturnType<typeof loadContext>>>;
|
export type Ctx = NonNullable<Awaited<ReturnType<typeof loadContext>>>;
|
||||||
|
|
||||||
/** Gizli hesaplara dokunan işlemleri dışlayan temel filtre. */
|
/** Gizli hesaplara dokunan işlemleri dışlayan temel filtre. */
|
||||||
function baseFilter(ctx: Ctx): Record<string, unknown> {
|
function baseFilter(ctx: Ctx): Record<string, unknown> {
|
||||||
@@ -316,15 +327,61 @@ export async function createTransaction(
|
|||||||
d.categoryId,
|
d.categoryId,
|
||||||
);
|
);
|
||||||
const actor = new Types.ObjectId(actorId);
|
const actor = new Types.ObjectId(actorId);
|
||||||
const doc = await TransactionModel.create({
|
try {
|
||||||
...built.data,
|
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,
|
householdId: ctx.m.householdId,
|
||||||
status: "posted",
|
actorId,
|
||||||
payeeId,
|
ownerType: "transaction",
|
||||||
createdBy: actor,
|
ownerId: transactionId,
|
||||||
updatedBy: actor,
|
ids: input.attachmentIds,
|
||||||
|
allowedKinds: allowedAttachmentKinds(input.type),
|
||||||
|
session,
|
||||||
});
|
});
|
||||||
return ok({ id: String(doc._id) });
|
if (!synced.ok) throw new AttachmentError(synced);
|
||||||
|
await TransactionModel.updateOne(
|
||||||
|
{ _id: transactionId, householdId: ctx.m.householdId },
|
||||||
|
{ $set: { attachmentCount: synced.data } },
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadOwnTransaction(
|
async function loadOwnTransaction(
|
||||||
@@ -349,9 +406,17 @@ export async function updateTransaction(
|
|||||||
if (!ctx) return fail(tr.common.unauthorized);
|
if (!ctx) return fail(tr.common.unauthorized);
|
||||||
const current = await loadOwnTransaction(ctx, transactionId);
|
const current = await loadOwnTransaction(ctx, transactionId);
|
||||||
if (!current) return fail(tr.common.notFound);
|
if (!current) return fail(tr.common.notFound);
|
||||||
|
if (current.isAdjustment) return fail(t.adjustmentReadOnly);
|
||||||
const built = buildDoc(ctx, input, current);
|
const built = buildDoc(ctx, input, current);
|
||||||
if (!built.ok) return built;
|
if (!built.ok) return built;
|
||||||
const d = built.data as { accountId: Types.ObjectId; categoryId: Types.ObjectId | null };
|
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(
|
const payeeId = await touchPayee(
|
||||||
ctx.m.householdId,
|
ctx.m.householdId,
|
||||||
input.payee,
|
input.payee,
|
||||||
@@ -359,10 +424,33 @@ export async function updateTransaction(
|
|||||||
d.accountId,
|
d.accountId,
|
||||||
d.categoryId,
|
d.categoryId,
|
||||||
);
|
);
|
||||||
await TransactionModel.updateOne(
|
// Bakiyeyi etkileyen bir alan değiştiyse mutabakat işareti geçersizleşir.
|
||||||
{ _id: current._id, householdId: ctx.m.householdId },
|
const balanceChanged =
|
||||||
{ $set: { ...built.data, payeeId, updatedBy: new Types.ObjectId(actorId) } },
|
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);
|
return ok(undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,6 +501,10 @@ export type TransactionListItem = {
|
|||||||
tags: string[];
|
tags: string[];
|
||||||
createdBy: { id: string; name: string };
|
createdBy: { id: string; name: string };
|
||||||
attachmentCount: number;
|
attachmentCount: number;
|
||||||
|
/** Mutabakat düzeltmesi (kategorisiz, düzenlenemez). */
|
||||||
|
isAdjustment: boolean;
|
||||||
|
/** Mutabakatı yapılmış hesaplar. */
|
||||||
|
reconciledAccountIds: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TransactionDetail = TransactionListItem & {
|
export type TransactionDetail = TransactionListItem & {
|
||||||
@@ -429,9 +521,10 @@ export type TransactionDetail = TransactionListItem & {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
/** Düzenleme formu için ham kimlikler. */
|
/** Düzenleme formu için ham kimlikler. */
|
||||||
categoryId: string | null;
|
categoryId: string | null;
|
||||||
|
attachments: AttachmentInfo[];
|
||||||
};
|
};
|
||||||
|
|
||||||
async function userNames(ids: Types.ObjectId[]): Promise<Map<string, string>> {
|
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 unique = [...new Set(ids.map(String))].map((id) => new Types.ObjectId(id));
|
||||||
const users = await getDb()
|
const users = await getDb()
|
||||||
.collection("user")
|
.collection("user")
|
||||||
@@ -440,13 +533,13 @@ async function userNames(ids: Types.ObjectId[]): Promise<Map<string, string>> {
|
|||||||
return new Map(users.map((u) => [String(u._id), String(u.name ?? "—")]));
|
return new Map(users.map((u) => [String(u._id), String(u.name ?? "—")]));
|
||||||
}
|
}
|
||||||
|
|
||||||
type LeanTx = Awaited<ReturnType<typeof TransactionModel.find>>[number] & {
|
export type LeanTx = Awaited<ReturnType<typeof TransactionModel.find>>[number] & {
|
||||||
_id: Types.ObjectId;
|
_id: Types.ObjectId;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
function toItem(ctx: Ctx, tx: LeanTx, names: Map<string, string>): TransactionListItem {
|
export function toItem(ctx: Ctx, tx: LeanTx, names: Map<string, string>): TransactionListItem {
|
||||||
const acc = (id: Types.ObjectId | null | undefined) => {
|
const acc = (id: Types.ObjectId | null | undefined) => {
|
||||||
if (!id) return null;
|
if (!id) return null;
|
||||||
const a = ctx.accountMap.get(String(id));
|
const a = ctx.accountMap.get(String(id));
|
||||||
@@ -470,6 +563,8 @@ function toItem(ctx: Ctx, tx: LeanTx, names: Map<string, string>): TransactionLi
|
|||||||
tags: tx.tags ?? [],
|
tags: tx.tags ?? [],
|
||||||
createdBy: { id: String(tx.createdBy), name: names.get(String(tx.createdBy)) ?? "—" },
|
createdBy: { id: String(tx.createdBy), name: names.get(String(tx.createdBy)) ?? "—" },
|
||||||
attachmentCount: tx.attachmentCount ?? 0,
|
attachmentCount: tx.attachmentCount ?? 0,
|
||||||
|
isAdjustment: Boolean(tx.isAdjustment),
|
||||||
|
reconciledAccountIds: (tx.reconciledAccountIds ?? []).map(String),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -571,8 +666,14 @@ export async function getTransaction(
|
|||||||
if (!ctx) return null;
|
if (!ctx) return null;
|
||||||
const tx = (await loadOwnTransaction(ctx, transactionId)) as unknown as LeanTx | null;
|
const tx = (await loadOwnTransaction(ctx, transactionId)) as unknown as LeanTx | null;
|
||||||
if (!tx) return null;
|
if (!tx) return null;
|
||||||
const names = await userNames([tx.createdBy as Types.ObjectId, tx.updatedBy as Types.ObjectId]);
|
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 {
|
return {
|
||||||
|
attachments,
|
||||||
...toItem(ctx, tx, names),
|
...toItem(ctx, tx, names),
|
||||||
categoryId: tx.categoryId ? String(tx.categoryId) : null,
|
categoryId: tx.categoryId ? String(tx.categoryId) : null,
|
||||||
splits: (tx.splits ?? []).map((s) => {
|
splits: (tx.splits ?? []).map((s) => {
|
||||||
@@ -650,7 +751,7 @@ export async function exportTransactions(
|
|||||||
} else {
|
} else {
|
||||||
out.push({
|
out.push({
|
||||||
...common,
|
...common,
|
||||||
category: categoryPath(r.categoryId),
|
category: r.isAdjustment ? t.adjustment : categoryPath(r.categoryId),
|
||||||
note: "",
|
note: "",
|
||||||
amountMinor: sign(r.type) * r.amountMinor,
|
amountMinor: sign(r.type) * r.amountMinor,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+87
-1
@@ -256,7 +256,7 @@ export const tr = {
|
|||||||
description: "Açıklama",
|
description: "Açıklama",
|
||||||
tags: "Etiketler",
|
tags: "Etiketler",
|
||||||
tagsHint: "Virgülle ayırın (ör. tatil, indirim)",
|
tagsHint: "Virgülle ayırın (ör. tatil, indirim)",
|
||||||
advanced: "Gelişmiş: etiket, bölme",
|
advanced: "Gelişmiş: ek, etiket, bölme",
|
||||||
split: "Bölünmüş işlem",
|
split: "Bölünmüş işlem",
|
||||||
splitHint: "Tutarı birden çok kategoriye bölün; kalemlerin toplamı tutara eşit olmalı.",
|
splitHint: "Tutarı birden çok kategoriye bölün; kalemlerin toplamı tutara eşit olmalı.",
|
||||||
addSplit: "Kalem ekle",
|
addSplit: "Kalem ekle",
|
||||||
@@ -344,10 +344,96 @@ export const tr = {
|
|||||||
],
|
],
|
||||||
filename: (date: string) => `butcem-islemler-${date}.csv`,
|
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.",
|
readOnly: "İzleyici rolündesiniz; işlem ekleyemezsiniz.",
|
||||||
noAccounts: "İşlem girmek için önce bir hesap gerekli.",
|
noAccounts: "İşlem girmek için önce bir hesap gerekli.",
|
||||||
noAccountsLink: "Hesaplara git",
|
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: {
|
categories: {
|
||||||
title: "Kategoriler",
|
title: "Kategoriler",
|
||||||
description: "Gelir ve gider kategorileri. Alt kategoriler raporlarda üst kategoriye toplanır.",
|
description: "Gelir ve gider kategorileri. Alt kategoriler raporlarda üst kategoriye toplanır.",
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -21,6 +21,7 @@ export const AUDIT_ACTIONS = [
|
|||||||
"account.update",
|
"account.update",
|
||||||
"account.archive",
|
"account.archive",
|
||||||
"account.unarchive",
|
"account.unarchive",
|
||||||
|
"account.reconcile",
|
||||||
"category.archive",
|
"category.archive",
|
||||||
"category.unarchive",
|
"category.unarchive",
|
||||||
"category.move",
|
"category.move",
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -35,6 +35,7 @@ const transactionSchema = new Schema(
|
|||||||
/** Arama için normalize metin (açıklama + satıcı + kalem notları). */
|
/** Arama için normalize metin (açıklama + satıcı + kalem notları). */
|
||||||
searchText: { type: String, default: "" },
|
searchText: { type: String, default: "" },
|
||||||
tags: { 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 },
|
attachmentCount: { type: Number, default: 0 },
|
||||||
// İleri fazlar: planlı işlem kuralı (7), taksit (7), kart dönemi (7), cari (8).
|
// İleri fazlar: planlı işlem kuralı (7), taksit (7), kart dönemi (7), cari (8).
|
||||||
recurringRuleId: { type: Schema.Types.ObjectId, default: null },
|
recurringRuleId: { type: Schema.Types.ObjectId, default: null },
|
||||||
@@ -47,7 +48,13 @@ const transactionSchema = new Schema(
|
|||||||
},
|
},
|
||||||
statementId: { type: Schema.Types.ObjectId, default: null },
|
statementId: { type: Schema.Types.ObjectId, default: null },
|
||||||
contactId: { type: Schema.Types.ObjectId, default: null },
|
contactId: { type: Schema.Types.ObjectId, default: null },
|
||||||
reconciledAt: { type: Date, 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 },
|
deletedAt: { type: Date, default: null },
|
||||||
/** Seed verisinin idempotent yüklenmesi için sabit anahtar. */
|
/** Seed verisinin idempotent yüklenmesi için sabit anahtar. */
|
||||||
seedRef: { type: String, default: null },
|
seedRef: { type: String, default: null },
|
||||||
|
|||||||
+3
-1
@@ -16,7 +16,9 @@ export function proxy(request: NextRequest) {
|
|||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
// Herkese açık yollar hariç: giriş, auth ve health API'leri, statik dosyalar, ikonlar, manifest.
|
// 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: [
|
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).*)",
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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`;
|
||||||
|
}
|
||||||
@@ -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>;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { tr } from "../../i18n/tr";
|
import { tr } from "../../i18n/tr";
|
||||||
import { parseMoney } from "../money";
|
import { parseMoney } from "../money";
|
||||||
|
import { MAX_ATTACHMENTS_PER_RECORD } from "../attachments";
|
||||||
import { MAX_SPLITS, normalizeTags, TRANSACTION_TYPES } from "../transactions";
|
import { MAX_SPLITS, normalizeTags, TRANSACTION_TYPES } from "../transactions";
|
||||||
|
|
||||||
const v = tr.validation;
|
const v = tr.validation;
|
||||||
@@ -52,6 +53,11 @@ export const transactionFormSchema = z
|
|||||||
.union([z.string(), z.array(z.string())])
|
.union([z.string(), z.array(z.string())])
|
||||||
.default("")
|
.default("")
|
||||||
.transform((x) => normalizeTags(x)),
|
.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) => {
|
.superRefine((x, ctx) => {
|
||||||
if (x.type === "transfer") {
|
if (x.type === "transfer") {
|
||||||
|
|||||||
@@ -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([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 };
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+5
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { loadEnv } from "vite";
|
import { loadEnv } from "vite";
|
||||||
import { defineConfig } from "vitest/config";
|
import { defineConfig } from "vitest/config";
|
||||||
@@ -35,6 +37,8 @@ export default defineConfig({
|
|||||||
SEED_ADMIN_EMAIL: "admin@test.local",
|
SEED_ADMIN_EMAIL: "admin@test.local",
|
||||||
SEED_ADMIN_PASSWORD: "Test-Admin-12345",
|
SEED_ADMIN_PASSWORD: "Test-Admin-12345",
|
||||||
SEED_USER_PASSWORD: "Test-User-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"),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user