18 Commits

Author SHA1 Message Date
suphicakir 291a117b4f feat: Faz 4 - örnek test verisi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:14:10 +03:00
suphicakir cd98694f0d docs: CHANGELOG ve README (0.4.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:14:10 +03:00
suphicakir 2b648975ae feat(seed): örnek aile kullanıcıları, haneler ve roller (idempotent)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:14:10 +03:00
suphicakir 38e2a7a26d feat(models): households ve householdMembers Mongoose modelleri
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:14:10 +03:00
suphicakir 3e11a34235 feat: Faz 3 - backend, kimlik doğrulama ve güvenlik
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:08 +03:00
suphicakir cdbd7a0446 docs: CHANGELOG ve README (0.3.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:00 +03:00
suphicakir fc3e0ae21b test: admin seed ve kimlik doğrulama entegrasyon testleri
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:00 +03:00
suphicakir 97e7ebe9aa feat(security): CSP ve güvenlik başlıkları, health DB ping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:00 +03:00
suphicakir 2035f73e7d feat(admin): Server Action'larla kullanıcı yönetimi ve gerçek oturumlu sayfalar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:00 +03:00
suphicakir 5191a5cce1 feat(auth): Better Auth, kullanıcı adı ile giriş, DAL ve proxy
- MongoDB/Mongoose bağlantıları, kayıt kapalı, admin + username plugin, rate limit
- DAL: getCurrentUser, requireSession, requireRole, getActionUser
- Kullanıcı adı normalizasyonu: İ/I/ı → i (tr-TR 'ADMIN' → 'admın' hatası)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:02:00 +03:00
suphicakir 381214c2cb feat(brand): BÜTÇEM logosu ve ikon seti
- public/brand: logo.svg, logo-dark.svg, icon.svg, icon-maskable.svg (yazı Noto Sans Bold yolları, OFL)
- npm run icons artık icon.svg / icon-maskable.svg'den üretir; maskable ve Apple ikonları köşesiz

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:44:59 +03:00
suphicakir e57e7b5517 feat: Faz 2 - frontend iskeleti
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:15 +03:00
suphicakir 9ae3eaf030 docs: CHANGELOG ve README (0.2.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
suphicakir 3b94bceaf0 feat(admin): kullanıcı yönetimi tablosu ve diyalogları (mock)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
suphicakir 1cf9fd9d8c feat(layout): login, uygulama kabuğu, alt menü, hızlı ekle ve dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
suphicakir 4dbd2eb441 feat(shared): zod şemaları, Türkçe arama ve TL/tarih biçimleri
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
suphicakir c875847b65 feat(brand): mavi/beyaz tema, yer tutucu logo, ikon üretimi ve PWA manifest
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
suphicakir 4f41c0f668 chore(ui): shadcn bileşenleri, use-mobile ve ESLint ayarı
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 01:35:10 +03:00
126 changed files with 7233 additions and 100 deletions
+2
View File
@@ -12,6 +12,8 @@ BETTER_AUTH_URL="http://localhost:3000"
# Faz 4 seed'i için ilk admin hesabı
SEED_ADMIN_EMAIL="admin@butcem.local"
SEED_ADMIN_PASSWORD=""
# Örnek aile kullanıcılarının ortak şifresi (yalnızca geliştirme; production'da örnek kullanıcı oluşturulmaz)
SEED_USER_PASSWORD=""
# Ek dosyalar (canlıda Docker volume: /app/uploads)
UPLOAD_DIR="./uploads"
+73 -1
View File
@@ -6,6 +6,75 @@ Biçim [Keep a Changelog](https://keepachangelog.com/tr-TR/1.1.0/) esas alınır
## [Yayınlanmamış]
## [0.4.0] - 2026-11-05
Faz 4: Örnek test verisi.
### Eklendi
- Seed (`npm run seed`): admin + 7 örnek kullanıcı (biri askıda, biri hanesi olmayan ikinci admin, ikisi e-postasız ve kullanıcı adıyla giriş yapan), 2 hane ("Çakır Ailesi", "Annemler") ve hane içi roller (owner / member / viewer; bir kullanıcı iki hanede farklı rollerle).
- Seed idempotenttir (kullanıcı adı, hane adı ve üyelik çiftine göre); kullanıcılar Better Auth API'siyle oluşturulur. Geliştirme hesapları konsolda tablo olarak gösterilir.
- `npm run seed:reset`: kimlik doğrulama ve hane koleksiyonlarını temizleyip yeniden doldurur; production'da reddedilir. Production'da seed yalnızca admini oluşturur.
- Mongoose modelleri: `households` (ayarlar: bütçe ayı başlangıcı, taksit ve günlük plan tercihleri, özel hesaplar, ek mağaza eşiği) ve `householdMembers` (benzersiz `{householdId, userId}` index'i).
- `SEED_USER_PASSWORD` ortam değişkeni (örnek kullanıcıların ortak geliştirme şifresi).
- Seed entegrasyon testleri (idempotentlik, roller, askı, e-postasız giriş, reset).
## [0.3.0] - 2026-11-05
Faz 3: Backend — kimlik doğrulama, yetki katmanı ve güvenlik.
### Eklendi
- Better Auth (MongoDB adaptörü, replica set transaction): e-posta veya **kullanıcı adı** ile giriş, kayıt (sign-up) kapalı, admin plugin, 30 günlük oturum, `HttpOnly`/`Secure`/`SameSite=Lax` cookie.
- Rate limit (veritabanında): genel 100 istek/dk, giriş denemeleri 5/dk.
- Data Access Layer (`lib/dal.ts`): `getCurrentUser` (istek başına tek okuma), `requireSession`, `requireRole`, `getActionUser`. Askıdaki kullanıcının oturumu reddedilir.
- `proxy.ts`: iyimser oturum cookie kontrolü (oturumsuz → `/login`); asıl kontrol DAL'da.
- Admin kullanıcı yönetimi Server Action'ları: oluşturma, düzenleme, rol, şifre sıfırlama (diğer oturumları kapatır), askıya alma/kaldırma, silme. Kendini silememe/askıya alamama ve son admini düşürememe sunucuda da uygulanır; Better Auth hataları Türkçe alan hatalarına çevrilir.
- E-postası olmayan kullanıcılar için `.invalid` yer tutucu adres (arayüzde gizlenir).
- MongoDB (`lib/db/mongo.ts`) ve Mongoose (`lib/db/mongoose.ts`) bağlantıları (HMR güvenli tekil örnek, tembel oluşturma).
- Güvenlik başlıkları: CSP (nonce'suz, Cache Components uyumlu), `X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`; production'da HSTS.
- `GET /api/health` veritabanı ping'i; erişilemezse 503.
- `npm run seed`: ilk admini (`SEED_ADMIN_*`, kullanıcı adı `admin`) idempotent olarak oluşturur.
- `npm run test:integration`: gerçek MongoDB'de (`butcem_test`) kimlik doğrulama sözleşmesi testleri (kayıt kapalı, giriş, askı, admin yetkisi, rate limit).
- BÜTÇEM logosu ve ikon seti (`logo.svg`, `logo-dark.svg`, `icon.svg`, `icon-maskable.svg`); `npm run icons` SVG kaynaktan üretir.
### Değişti
- Giriş, çıkış, dashboard ve admin sayfaları mock yerine gerçek oturum ve verilerle çalışır; oturuma bağlı kabuk Suspense içinde akış olarak gelir.
### Düzeltildi
- Kullanıcı adı normalizasyonu: `tr-TR` küçük harf dönüşümü "ADMIN"i "admın" yapıyordu; artık İ/I/ı → i ve ASCII küçük harf.
### Kaldırıldı
- Oturum ve admin kullanıcı listesi mock verileri (hane mock'u Faz 5'e kadar duruyor).
## [0.2.0] - 2026-11-05
Faz 2: Frontend iskeleti (veriler Faz 3'e kadar mock).
### Eklendi
- Marka paleti: mavi/beyaz oklch tema (açık), lacivert/açık mavi (koyu); anlamsal `--income`, `--expense`, `--budget`, `--warning` değişkenleri ve grafik renkleri.
- Açık / Koyu / Sistem tema (next-themes) ve her ekranda tema seçici.
- Giriş ekranı (`/login`): kullanıcı adı veya e-posta + şifre, zod doğrulama, şifre göster/gizle, yükleniyor durumu; kayıt bağlantısı yok. `/` her zaman `/login`'e yönlenir.
- Uygulama kabuğu: masaüstünde daraltılabilir yan menü, mobilde alt gezinme çubuğu (ortada Hızlı ekle, "Daha fazla" ile menü), üst bar (hane seçici, Hızlı ekle, tema, kullanıcı menüsü: ad, rol, sürüm, Çıkış yap). Henüz gelmeyen sayfalar "Yakında" olarak pasif.
- Hızlı ekle (gider / gelir / transfer) seçimi; mobilde alttan açılan Drawer, masaüstünde Dialog (`ResponsiveDialog`).
- Dashboard: karşılama ve özet kartları (Suspense + Skeleton).
- Admin kullanıcı yönetimi (`/admin/kullanicilar`): TanStack Table v9 ile Türkçe duyarlı arama, sıralama, sayfalama; oluşturma, düzenleme, rol değiştirme, şifre sıfırlama, askıya alma/kaldırma, silme (onaylı). Kendini silememe ve son admini düşürememe kuralları (`checkAdminAction`).
- Paylaşılan zod şemaları (`src/shared/schemas`: giriş, kullanıcı, şifre, askı), Türkçe arama/sıralama (`foldTr`, `compareTr`), TL ve İstanbul saatli tarih biçimleri (`formatMoney`, `formatDate`).
- PWA temeli: `manifest.webmanifest`, tema rengi, Apple web app meta, ikonlar.
- `npm run icons`: `public/brand/icon.png`'den favicon.ico, uygulama, Apple ve maskable PWA ikonları üretir (sharp).
- Yer tutucu marka dosyaları (`public/brand/logo.svg`, `logo-dark.svg`, `icon.png`).
- 404, hata (`retry`) ve global hata sayfaları; yükleniyor ekranları.
- `ActionResult` sonuç tipi (Faz 3 Server Action sözleşmesi).
### Değişti
- `use-mobile` hook'u `useSyncExternalStore` ile yeniden yazıldı (effect içinde setState yok, hydration güvenli).
- ESLint: `_` önekli bilinçli kullanılmayan değişkenlere izin.
## [0.1.0] - 2026-11-05
Faz 1: Framework, klasör yapısı ve altyapı.
@@ -25,5 +94,8 @@ Faz 1: Framework, klasör yapısı ve altyapı.
- `.nvmrc` (Node 26), `engines.node`, `typecheck`, `test`, `format`, `db:up`, `seed` scriptleri.
- `docs/PROMPT.md` (ana prompt ve Faz 0 kararları), `README.md`, `CHANGELOG.md`.
[Yayınlanmamış]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.1.0...HEAD
[Yayınlanmamış]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.4.0...HEAD
[0.4.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.3.0...v0.4.0
[0.3.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.2.0...v0.3.0
[0.2.0]: https://gitea.ta1sph.info/suphicakir/butcem/compare/v0.1.0...v0.2.0
[0.1.0]: https://gitea.ta1sph.info/suphicakir/butcem/releases/tag/v0.1.0
+26 -2
View File
@@ -26,10 +26,30 @@ cp .env.example .env.local
# 3) MongoDB (tek düğümlü replica set rs0, host portu 27019) — sağlıklı olana kadar bekler
npm run db:up
# 4) Uygulama
npm run dev # http://localhost:3000
# 4) Örnek veri: admin + aile kullanıcıları + 2 hane (tekrar çalıştırmak güvenli)
npm run seed
# 5) Uygulama
npm run dev # http://localhost:3000 → /login
```
### Geliştirme hesapları (`npm run seed`)
| Kullanıcı adı | Rol | Hane(ler) | Not |
| ------------- | ----- | --------------------------------------- | ------------------------------- |
| `admin` | admin | Çakır Ailesi (owner) | şifre `SEED_ADMIN_PASSWORD` |
| `ayse` | user | Çakır Ailesi (owner), Annemler (viewer) | |
| `emre` | user | Çakır Ailesi (member) | e-postasız |
| `zeynep` | user | Çakır Ailesi (viewer) | e-postasız |
| `fatma` | user | Annemler (owner) | |
| `mehmet` | user | Annemler (member) | |
| `burak` | admin | — | hanesi yok → hane verisi görmez |
| `ozan` | user | Çakır Ailesi (member) | askıda, giriş yapamaz |
Admin dışındaki hesapların şifresi `SEED_USER_PASSWORD` (`.env.local`). Production'da yalnızca admin oluşturulur.
Giriş kullanıcı adı **veya** e-posta ile yapılır. Kayıt kapalıdır; kullanıcıları admin `/admin/kullanicilar` sayfasından oluşturur.
## Scriptler
| Komut | Açıklama |
@@ -43,6 +63,10 @@ npm run dev # http://localhost:3000
| `npm run db:up` / `db:down` | Lokal MongoDB'yi başlat / durdur |
| `npm run seed` / `seed:reset` | Örnek veri (Faz 4) |
## Marka dosyaları
`public/brand/`: `logo.svg` (açık tema), `logo-dark.svg` (koyu tema), `icon.svg` (uygulama ikonu), `icon-maskable.svg` (Android/iOS, köşesiz). Yazı Noto Sans Bold (OFL) harf yollarıdır. İkonları değiştirdikten sonra `npm run icons` çalıştırın; favicon ve PWA ikonları bu kaynaklardan üretilir.
## Docker imajı
```bash
+9
View File
@@ -5,6 +5,15 @@ import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
{
rules: {
// "_" ile başlayan adlar bilinçli olarak kullanılmayan değişkenlerdir.
"@typescript-eslint/no-unused-vars": [
"warn",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_", destructuredArrayIgnorePattern: "^_" },
],
},
},
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
+45
View File
@@ -1,5 +1,47 @@
import type { NextConfig } from "next";
const isDev = process.env.NODE_ENV === "development";
/**
* Content-Security-Policy (nonce'suz): Cache Components'in statik kabuğu ile uyumlu.
* 'unsafe-inline' script: Next.js'in satır içi hydration verisi ve next-themes'in tema betiği için.
* Grafikler (Recharts, SVG) ve carousel (Embla) ek kaynak gerektirmez; ek dosyalar
* kendi origin'imizden (/api/files/...) ve blob: önizlemelerle servis edilir.
*/
const csp = [
"default-src 'self'",
`script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ""}`,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' blob: data:",
"font-src 'self'",
"connect-src 'self'",
"media-src 'self' blob:",
"worker-src 'self' blob:",
"manifest-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
...(isDev ? [] : ["upgrade-insecure-requests"]),
].join("; ");
const securityHeaders = [
{ key: "Content-Security-Policy", value: csp },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Cross-Origin-Opener-Policy", value: "same-origin" },
// Kamera: Faz 6'da fiş fotoğrafı için yalnızca kendi origin'imiz.
{
key: "Permissions-Policy",
value: "camera=(self), microphone=(), geolocation=(), payment=(), usb=()",
},
...(isDev
? []
: // includeSubDomains/preload bilinçli olarak yok: ta1sph.website'in diğer alt alanlarını bağlamasın.
[{ key: "Strict-Transport-Security", value: "max-age=31536000" }]),
];
const nextConfig: NextConfig = {
// Docker imajı için yalnızca gerekli dosyaları .next/standalone altına kopyala.
output: "standalone",
@@ -17,6 +59,9 @@ const nextConfig: NextConfig = {
},
},
},
async headers() {
return [{ source: "/:path*", headers: securityHeaders }];
},
};
export default nextConfig;
+18 -4
View File
@@ -24,8 +24,10 @@
"react-hook-form": "^7.91.0",
"server-only": "^0.0.1",
"shadcn": "^4.23.0",
"sharp": "^0.35.5",
"sonner": "^2.0.8",
"tw-animate-css": "^1.4.0",
"vaul": "^1.1.2",
"zod": "^4.6.7"
},
"devDependencies": {
@@ -42,6 +44,9 @@
"tsx": "^4.23.15",
"typescript": "^5",
"vitest": "^5.1.0"
},
"engines": {
"node": ">=26 <27"
}
},
"node_modules/@alloc/quick-lru": {
@@ -1650,7 +1655,6 @@
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=18"
}
@@ -6776,7 +6780,6 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"devOptional": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
@@ -11199,7 +11202,6 @@
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
"integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
@@ -11249,7 +11251,6 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"license": "ISC",
"optional": true,
"bin": {
"semver": "bin/semver.js"
},
@@ -12340,6 +12341,19 @@
"node": "^20.17.0 || >=22.9.0"
}
},
"node_modules/vaul": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
"integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-dialog": "^1.1.1"
},
"peerDependencies": {
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/vite": {
"version": "8.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz",
+7 -3
View File
@@ -1,6 +1,6 @@
{
"name": "butcem",
"version": "0.1.0",
"version": "0.4.0",
"private": true,
"description": "BÜTÇEM — aile bütçe, cari, birikim, ev stoğu ve akıllı alışveriş uygulaması",
"engines": {
@@ -18,8 +18,10 @@
"format:check": "prettier --check .",
"db:up": "docker compose up -d --wait",
"db:down": "docker compose down",
"seed": "tsx --env-file=.env.local scripts/seed.ts",
"seed:reset": "tsx --env-file=.env.local scripts/seed.ts --reset"
"seed": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts",
"seed:reset": "tsx --conditions=react-server --env-file=.env.local scripts/seed.ts --reset",
"icons": "tsx scripts/generate-icons.ts",
"test:integration": "vitest run --config vitest.integration.config.mts"
},
"dependencies": {
"@hookform/resolvers": "^7.0.2",
@@ -38,8 +40,10 @@
"react-hook-form": "^7.91.0",
"server-only": "^0.0.1",
"shadcn": "^4.23.0",
"sharp": "^0.35.5",
"sonner": "^2.0.8",
"tw-animate-css": "^1.4.0",
"vaul": "^1.1.2",
"zod": "^4.6.7"
},
"devDependencies": {
View File
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="BÜTÇEM">
<!-- BÜTÇEM maskable/Apple ikonu (köşesiz, tam zemin). Kaynak: npm run icons -->
<defs><linearGradient id="mg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#1d7cd5"/><stop offset="1" stop-color="#0e49a5"/></linearGradient></defs>
<rect width="512" height="512" fill="url(#mg)"/>
<path d="M108 240 256 124 404 240" fill="none" stroke="#ffffff" stroke-width="38" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="152" y="318" width="52" height="76" rx="13" fill="#ffffff"/>
<rect x="230" y="280" width="52" height="114" rx="13" fill="#ffffff"/>
<rect x="308" y="240" width="52" height="154" rx="13" fill="#8fd5fd"/>
</svg>

After

Width:  |  Height:  |  Size: 785 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="BÜTÇEM">
<!-- BÜTÇEM uygulama ikonu: hane (çatı) + yükselen bütçe/birikim sütunları. Kaynak: npm run icons -->
<defs><linearGradient id="ig" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#1d7cd5"/><stop offset="1" stop-color="#0e49a5"/></linearGradient></defs>
<rect width="512" height="512" rx="112" fill="url(#ig)"/>
<path d="M108 240 256 124 404 240" fill="none" stroke="#ffffff" stroke-width="38" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="152" y="318" width="52" height="76" rx="13" fill="#ffffff"/>
<rect x="230" y="280" width="52" height="114" rx="13" fill="#ffffff"/>
<rect x="308" y="240" width="52" height="154" rx="13" fill="#8fd5fd"/>
</svg>

After

Width:  |  Height:  |  Size: 820 B

+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 227 64" width="227" height="64" role="img" aria-label="BÜTÇEM">
<!-- BÜTÇEM logosu (koyu tema). Yazı Noto Sans Bold (OFL) yollarıdır; font gerektirmez. -->
<g transform="scale(0.125)">
<defs><linearGradient id="dg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#1d7cd5"/><stop offset="1" stop-color="#0e49a5"/></linearGradient></defs>
<rect width="512" height="512" rx="112" fill="url(#dg)"/>
<path d="M108 240 256 124 404 240" fill="none" stroke="#ffffff" stroke-width="38" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="152" y="318" width="52" height="76" rx="13" fill="#ffffff"/>
<rect x="230" y="280" width="52" height="114" rx="13" fill="#ffffff"/>
<rect x="308" y="240" width="52" height="154" rx="13" fill="#8fd5fd"/>
</g>
<path fill="#edf2f8" d="M88.744 19.863999999999997Q93.742 19.863999999999997 96.02000000000001 21.342999999999996Q98.298 22.822 98.298 25.916Q98.298 28.194 97.09100000000001 29.537Q95.884 30.88 94.184 31.253999999999998V31.424Q95.374 31.662 96.46199999999999 32.274Q97.55 32.885999999999996 98.22999999999999 34.042Q98.91 35.198 98.91 37.102000000000004Q98.91 40.434 96.513 42.287Q94.116 44.14 89.968 44.14H80.89V19.863999999999997ZM89.016 29.588Q91.226 29.588 92.093 28.772Q92.96000000000001 27.956 92.96000000000001 26.63Q92.96000000000001 25.236 91.94 24.573Q90.92 23.91 88.778 23.91H86.092V29.588ZM86.092 33.498V40.026H89.39Q91.702 40.026 92.60300000000001 39.091Q93.504 38.156 93.504 36.694Q93.504 35.368 92.58600000000001 34.433Q91.668 33.498 89.22 33.498Z M124.10400000000001 35.572Q124.10400000000001 38.088 122.99900000000001 40.111000000000004Q121.894 42.134 119.667 43.307Q117.44000000000001 44.480000000000004 114.04 44.480000000000004Q109.212 44.480000000000004 106.696 42.015Q104.18 39.55 104.18 35.504V19.863999999999997H109.31400000000001V34.722Q109.31400000000001 37.714 110.53800000000001 38.938Q111.762 40.162 114.176 40.162Q116.69200000000001 40.162 117.831 38.836Q118.97 37.51 118.97 34.688V19.863999999999997H124.10400000000001ZM108.05600000000001 15.103999999999996Q108.05600000000001 13.913999999999994 108.71900000000001 13.369999999999996Q109.382 12.825999999999997 110.40200000000002 12.825999999999997Q111.32000000000001 12.825999999999997 112.03400000000002 13.369999999999996Q112.74800000000002 13.913999999999994 112.74800000000002 15.103999999999996Q112.74800000000002 16.225999999999996 112.03400000000002 16.769999999999996Q111.32000000000001 17.313999999999997 110.40200000000002 17.313999999999997Q109.382 17.313999999999997 108.71900000000001 16.769999999999996Q108.05600000000001 16.225999999999996 108.05600000000001 15.103999999999996ZM115.4 15.103999999999996Q115.4 13.913999999999994 116.08000000000001 13.369999999999996Q116.76000000000002 12.825999999999997 117.74600000000001 12.825999999999997Q118.69800000000001 12.825999999999997 119.39500000000001 13.369999999999996Q120.09200000000001 13.913999999999994 120.09200000000001 15.103999999999996Q120.09200000000001 16.225999999999996 119.39500000000001 16.769999999999996Q118.69800000000001 17.313999999999997 117.74600000000001 17.313999999999997Q116.76000000000002 17.313999999999997 116.08000000000001 16.769999999999996Q115.4 16.225999999999996 115.4 15.103999999999996Z M140.084 44.14H134.882V24.182H128.32V19.863999999999997H146.64600000000002V24.182H140.084Z M161.50400000000002 23.842Q158.58 23.842 156.897 26.035Q155.214 28.228 155.214 32.07Q155.214 35.912 156.829 38.037Q158.44400000000002 40.162 161.708 40.162Q163.306 40.162 164.78500000000003 39.788Q166.264 39.414 167.76000000000002 38.836V43.256Q164.87 44.480000000000004 161.13 44.480000000000004Q157.25400000000002 44.480000000000004 154.755 42.93300000000001Q152.256 41.386 151.049 38.581Q149.842 35.775999999999996 149.842 32.036Q149.842 28.363999999999997 151.202 25.541999999999998Q152.562 22.72 155.18 21.122Q157.798 19.523999999999997 161.572 19.523999999999997Q163.37400000000002 19.523999999999997 165.22700000000003 19.915Q167.08 20.305999999999997 168.746 21.122L167.04600000000002 25.27Q165.822 24.692 164.445 24.267Q163.068 23.842 161.50400000000002 23.842ZM164.496 48.526Q164.496 50.26 163.238 51.28Q161.98000000000002 52.3 159.73600000000002 52.3Q158.818 52.3 158.07000000000002 52.181Q157.32200000000003 52.062 156.846 51.892V49.206Q157.83200000000002 49.512 158.88600000000002 49.512Q160.68800000000002 49.512 160.68800000000002 48.322Q160.68800000000002 47.642 160.00800000000004 47.268Q159.32800000000003 46.894 158.03600000000003 46.69L159.22600000000003 44.14H161.94600000000003L161.436 45.466Q162.15 45.636 162.86400000000003 45.976Q163.57800000000003 46.316 164.03700000000003 46.928Q164.496 47.54 164.496 48.526Z"/>
<path fill="#6bb9f8" d="M187.514 44.14H173.54000000000002V19.863999999999997H187.514V24.08H178.674V29.418H186.90200000000002V33.634H178.674V39.89H187.514Z M203.52800000000002 44.14 197.68 25.099999999999998H197.544Q197.57800000000003 25.779999999999998 197.64600000000002 27.14Q197.71400000000003 28.5 197.78200000000004 30.047Q197.85000000000002 31.594 197.85000000000002 32.852000000000004V44.14H193.26000000000002V19.863999999999997H200.264L206.01000000000002 38.428H206.11200000000002L212.198 19.863999999999997H219.20200000000003V44.14H214.40800000000002V32.647999999999996Q214.40800000000002 31.491999999999997 214.459 29.996Q214.51000000000002 28.5 214.56100000000004 27.157Q214.61200000000002 25.814 214.64600000000002 25.134H214.51000000000002L208.25400000000002 44.14Z"/>
</svg>

After

Width:  |  Height:  |  Size: 5.4 KiB

+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 227 64" width="227" height="64" role="img" aria-label="BÜTÇEM">
<!-- BÜTÇEM logosu (açık tema). Yazı Noto Sans Bold (OFL) yollarıdır; font gerektirmez. -->
<g transform="scale(0.125)">
<defs><linearGradient id="lg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#1d7cd5"/><stop offset="1" stop-color="#0e49a5"/></linearGradient></defs>
<rect width="512" height="512" rx="112" fill="url(#lg)"/>
<path d="M108 240 256 124 404 240" fill="none" stroke="#ffffff" stroke-width="38" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="152" y="318" width="52" height="76" rx="13" fill="#ffffff"/>
<rect x="230" y="280" width="52" height="114" rx="13" fill="#ffffff"/>
<rect x="308" y="240" width="52" height="154" rx="13" fill="#8fd5fd"/>
</g>
<path fill="#101a2d" d="M88.744 19.863999999999997Q93.742 19.863999999999997 96.02000000000001 21.342999999999996Q98.298 22.822 98.298 25.916Q98.298 28.194 97.09100000000001 29.537Q95.884 30.88 94.184 31.253999999999998V31.424Q95.374 31.662 96.46199999999999 32.274Q97.55 32.885999999999996 98.22999999999999 34.042Q98.91 35.198 98.91 37.102000000000004Q98.91 40.434 96.513 42.287Q94.116 44.14 89.968 44.14H80.89V19.863999999999997ZM89.016 29.588Q91.226 29.588 92.093 28.772Q92.96000000000001 27.956 92.96000000000001 26.63Q92.96000000000001 25.236 91.94 24.573Q90.92 23.91 88.778 23.91H86.092V29.588ZM86.092 33.498V40.026H89.39Q91.702 40.026 92.60300000000001 39.091Q93.504 38.156 93.504 36.694Q93.504 35.368 92.58600000000001 34.433Q91.668 33.498 89.22 33.498Z M124.10400000000001 35.572Q124.10400000000001 38.088 122.99900000000001 40.111000000000004Q121.894 42.134 119.667 43.307Q117.44000000000001 44.480000000000004 114.04 44.480000000000004Q109.212 44.480000000000004 106.696 42.015Q104.18 39.55 104.18 35.504V19.863999999999997H109.31400000000001V34.722Q109.31400000000001 37.714 110.53800000000001 38.938Q111.762 40.162 114.176 40.162Q116.69200000000001 40.162 117.831 38.836Q118.97 37.51 118.97 34.688V19.863999999999997H124.10400000000001ZM108.05600000000001 15.103999999999996Q108.05600000000001 13.913999999999994 108.71900000000001 13.369999999999996Q109.382 12.825999999999997 110.40200000000002 12.825999999999997Q111.32000000000001 12.825999999999997 112.03400000000002 13.369999999999996Q112.74800000000002 13.913999999999994 112.74800000000002 15.103999999999996Q112.74800000000002 16.225999999999996 112.03400000000002 16.769999999999996Q111.32000000000001 17.313999999999997 110.40200000000002 17.313999999999997Q109.382 17.313999999999997 108.71900000000001 16.769999999999996Q108.05600000000001 16.225999999999996 108.05600000000001 15.103999999999996ZM115.4 15.103999999999996Q115.4 13.913999999999994 116.08000000000001 13.369999999999996Q116.76000000000002 12.825999999999997 117.74600000000001 12.825999999999997Q118.69800000000001 12.825999999999997 119.39500000000001 13.369999999999996Q120.09200000000001 13.913999999999994 120.09200000000001 15.103999999999996Q120.09200000000001 16.225999999999996 119.39500000000001 16.769999999999996Q118.69800000000001 17.313999999999997 117.74600000000001 17.313999999999997Q116.76000000000002 17.313999999999997 116.08000000000001 16.769999999999996Q115.4 16.225999999999996 115.4 15.103999999999996Z M140.084 44.14H134.882V24.182H128.32V19.863999999999997H146.64600000000002V24.182H140.084Z M161.50400000000002 23.842Q158.58 23.842 156.897 26.035Q155.214 28.228 155.214 32.07Q155.214 35.912 156.829 38.037Q158.44400000000002 40.162 161.708 40.162Q163.306 40.162 164.78500000000003 39.788Q166.264 39.414 167.76000000000002 38.836V43.256Q164.87 44.480000000000004 161.13 44.480000000000004Q157.25400000000002 44.480000000000004 154.755 42.93300000000001Q152.256 41.386 151.049 38.581Q149.842 35.775999999999996 149.842 32.036Q149.842 28.363999999999997 151.202 25.541999999999998Q152.562 22.72 155.18 21.122Q157.798 19.523999999999997 161.572 19.523999999999997Q163.37400000000002 19.523999999999997 165.22700000000003 19.915Q167.08 20.305999999999997 168.746 21.122L167.04600000000002 25.27Q165.822 24.692 164.445 24.267Q163.068 23.842 161.50400000000002 23.842ZM164.496 48.526Q164.496 50.26 163.238 51.28Q161.98000000000002 52.3 159.73600000000002 52.3Q158.818 52.3 158.07000000000002 52.181Q157.32200000000003 52.062 156.846 51.892V49.206Q157.83200000000002 49.512 158.88600000000002 49.512Q160.68800000000002 49.512 160.68800000000002 48.322Q160.68800000000002 47.642 160.00800000000004 47.268Q159.32800000000003 46.894 158.03600000000003 46.69L159.22600000000003 44.14H161.94600000000003L161.436 45.466Q162.15 45.636 162.86400000000003 45.976Q163.57800000000003 46.316 164.03700000000003 46.928Q164.496 47.54 164.496 48.526Z"/>
<path fill="#105bbe" d="M187.514 44.14H173.54000000000002V19.863999999999997H187.514V24.08H178.674V29.418H186.90200000000002V33.634H178.674V39.89H187.514Z M203.52800000000002 44.14 197.68 25.099999999999998H197.544Q197.57800000000003 25.779999999999998 197.64600000000002 27.14Q197.71400000000003 28.5 197.78200000000004 30.047Q197.85000000000002 31.594 197.85000000000002 32.852000000000004V44.14H193.26000000000002V19.863999999999997H200.264L206.01000000000002 38.428H206.11200000000002L212.198 19.863999999999997H219.20200000000003V44.14H214.40800000000002V32.647999999999996Q214.40800000000002 31.491999999999997 214.459 29.996Q214.51000000000002 28.5 214.56100000000004 27.157Q214.61200000000002 25.814 214.64600000000002 25.134H214.51000000000002L208.25400000000002 44.14Z"/>
</svg>

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+125
View File
@@ -0,0 +1,125 @@
/**
* Uygulama ikonlarını logodan üretir: npm run icons
*
* Kaynak: public/brand/icon.svg (varsa; önce 512×512 icon.png olarak render edilir)
* veya doğrudan public/brand/icon.png (kare, en az 512×512).
* Çıktılar (commit edilir):
* public/brand/icon.png 512 px (icon.svg varsa ondan üretilir)
* src/app/favicon.ico 16/32/48 px (PNG gömülü ICO)
* src/app/icon.png 192 px → <link rel="icon">
* src/app/apple-icon.png 180 px, saydamsız → iOS ana ekran
* public/icons/icon-192.png PWA manifest
* public/icons/icon-512.png PWA manifest
* public/icons/maskable-512.png PWA manifest (purpose: maskable)
*
* public/brand/icon-maskable.svg (köşesiz, tam zemin) varsa maskable ve Apple ikonları ondan
* üretilir; yoksa icon.png marka mavisi zemine %80 güvenli alanla yerleştirilir.
*
* Logoyu değiştirdikten sonra bu betiği yeniden çalıştırın.
*/
import { access, mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
const ROOT = process.cwd();
const SOURCE = path.join(ROOT, "public/brand/icon.png");
const SOURCE_SVG = path.join(ROOT, "public/brand/icon.svg");
const MASKABLE_SVG = path.join(ROOT, "public/brand/icon-maskable.svg");
/** Saydamlık kabul etmeyen ikonlarda arka plan: marka mavisi (--primary, açık tema). */
const BRAND_BG = "#105bbe";
async function png(size: number, opts: { flatten?: boolean; padding?: number } = {}) {
const inner = Math.round(size * (1 - (opts.padding ?? 0) * 2));
const resized = await sharp(SOURCE).resize(inner, inner, { fit: "contain" }).png().toBuffer();
let img = sharp({
create: {
width: size,
height: size,
channels: 4,
background: opts.flatten || opts.padding ? BRAND_BG : { r: 0, g: 0, b: 0, alpha: 0 },
},
}).composite([{ input: resized, gravity: "center" }]);
if (opts.flatten) img = img.flatten({ background: BRAND_BG });
return img.png({ compressionLevel: 9 }).toBuffer();
}
/** PNG görüntülerinden ICO dosyası oluşturur (Vista+ tüm tarayıcılar PNG gömülü ICO destekler). */
function toIco(images: { size: number; data: Buffer }[]): Buffer {
const header = Buffer.alloc(6);
header.writeUInt16LE(0, 0); // reserved
header.writeUInt16LE(1, 2); // type: icon
header.writeUInt16LE(images.length, 4);
const entries: Buffer[] = [];
let offset = 6 + images.length * 16;
for (const { size, data } of images) {
const e = Buffer.alloc(16);
e.writeUInt8(size >= 256 ? 0 : size, 0);
e.writeUInt8(size >= 256 ? 0 : size, 1);
e.writeUInt8(0, 2); // palette
e.writeUInt8(0, 3); // reserved
e.writeUInt16LE(1, 4); // color planes
e.writeUInt16LE(32, 6); // bpp
e.writeUInt32LE(data.length, 8);
e.writeUInt32LE(offset, 12);
offset += data.length;
entries.push(e);
}
return Buffer.concat([header, ...entries, ...images.map((i) => i.data)]);
}
async function exists(file: string) {
return access(file).then(
() => true,
() => false,
);
}
async function main() {
if (await exists(SOURCE_SVG)) {
// Vektörden yüksek yoğunlukta render: küçük boyutlarda da keskin kenarlar.
const png512 = await sharp(SOURCE_SVG, { density: 288 }).resize(512, 512).png().toBuffer();
await writeFile(SOURCE, png512);
console.log(`✓ public/brand/icon.png ← icon.svg (${png512.length} bayt)`);
}
const meta = await sharp(SOURCE).metadata();
if (!meta.width || !meta.height || meta.width !== meta.height || meta.width < 512) {
throw new Error(`${SOURCE} kare ve en az 512×512 olmalı (şu an ${meta.width}×${meta.height}).`);
}
await mkdir(path.join(ROOT, "public/icons"), { recursive: true });
const fullBleed = (await exists(MASKABLE_SVG))
? (size: number) =>
sharp(MASKABLE_SVG, { density: 288 })
.resize(size, size)
.flatten({ background: BRAND_BG })
.png()
.toBuffer()
: null;
const out: [string, Buffer][] = [
["src/app/icon.png", await png(192)],
[
"src/app/apple-icon.png",
fullBleed ? await fullBleed(180) : await png(180, { flatten: true }),
],
["public/icons/icon-192.png", await png(192)],
["public/icons/icon-512.png", await png(512)],
[
"public/icons/maskable-512.png",
fullBleed ? await fullBleed(512) : await png(512, { padding: 0.1 }),
],
[
"src/app/favicon.ico",
toIco(await Promise.all([16, 32, 48].map(async (size) => ({ size, data: await png(size) })))),
],
];
for (const [file, data] of out) {
await writeFile(path.join(ROOT, file), data);
console.log(`✓ ${file} (${data.length} bayt)`);
}
}
main().catch((err: unknown) => {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
});
+30 -6
View File
@@ -1,10 +1,34 @@
/**
* Seed betiği — Faz 4'te doldurulacak (admin, örnek hane, aile üyeleri ve alan verisi).
* Çalıştırma: npm run seed | Sıfırlayıp doldurma: npm run seed:reset
* Seed: npm run seed | Sıfırlayıp doldurma: npm run seed:reset (production'da reddedilir)
*
* Oluşturulanlar: admin (SEED_ADMIN_*), 7 örnek kullanıcı (biri askıda, biri ikinci admin),
* 2 hane ve hane içi rolleri. Ayrıntı: scripts/seed/fixtures.ts
* `server-only` modülleri Next dışında yükleyebilmek için --conditions=react-server ile çalışır.
*/
if (process.env.NODE_ENV === "production" && process.argv.includes("--reset")) {
console.error("seed:reset production ortamında çalıştırılamaz.");
process.exit(1);
import { getMongoClient } from "@/lib/db/mongo";
import { env } from "@/lib/env";
import { closeSeedConnections, runSeed } from "./seed/run";
async function main() {
const summary = await runSeed({ reset: process.argv.includes("--reset") });
const { users, households, memberships } = summary.created;
console.log(`\nOluşturulan: ${users} kullanıcı, ${households} hane, ${memberships} üyelik.`);
// Hesap tablosu yalnızca geliştirme ortamında gösterilir.
if (env().NODE_ENV !== "production" && summary.accounts.length) {
console.log(
"\nGeliştirme hesapları (şifreler: admin → SEED_ADMIN_PASSWORD, diğerleri → SEED_USER_PASSWORD):",
);
console.table(summary.accounts);
}
}
console.log("Seed henüz uygulanmadı (Faz 4).");
main()
.catch((err: unknown) => {
console.error(err instanceof Error ? err.message : err);
process.exitCode = 1;
})
.finally(async () => {
await closeSeedConnections();
await getMongoClient().close();
});
+58
View File
@@ -0,0 +1,58 @@
import type { HouseholdRole } from "@/features/households/types";
import type { SystemRole } from "@/shared/schemas/common";
/** Örnek (geliştirme) kullanıcıları. E-postası olmayanlar kullanıcı adıyla giriş yapar. */
export type SeedUser = {
username: string;
name: string;
email?: string;
role: SystemRole;
banReason?: string;
};
export const SEED_USERS: SeedUser[] = [
{ username: "ayse", name: "Ayşe Çakır", email: "ayse@butcem.local", role: "user" },
{ username: "emre", name: "Emre Çakır", role: "user" },
{ username: "zeynep", name: "Zeynep Çakır", role: "user" },
{ username: "fatma", name: "Fatma Demir", email: "fatma@butcem.local", role: "user" },
{ username: "mehmet", name: "Mehmet Demir", email: "mehmet@butcem.local", role: "user" },
// İkinci admin: hiçbir haneye üye değil → hane verisini göremez (Faz 0 kararı).
{ username: "burak", name: "Burak Öztürk", email: "burak@butcem.local", role: "admin" },
{
username: "ozan",
name: "Ozan Kaya",
email: "ozan@butcem.local",
role: "user",
banReason: "Ev arkadaşlığı sona erdi; erişim kaldırıldı.",
},
];
/** Seed admin'in kullanıcı adı (SEED_ADMIN_EMAIL ile oluşturulur). */
export const ADMIN_USERNAME = "admin";
export type SeedHousehold = {
name: string;
members: { username: string; role: HouseholdRole }[];
};
export const SEED_HOUSEHOLDS: SeedHousehold[] = [
{
name: "Çakır Ailesi",
members: [
{ username: ADMIN_USERNAME, role: "owner" },
{ username: "ayse", role: "owner" },
{ username: "emre", role: "member" },
{ username: "zeynep", role: "viewer" },
{ username: "ozan", role: "member" },
],
},
{
name: "Annemler",
members: [
{ username: "fatma", role: "owner" },
{ username: "mehmet", role: "member" },
// Bir kullanıcı birden çok haneye üye olabilir.
{ username: "ayse", role: "viewer" },
],
},
];
+84
View File
@@ -0,0 +1,84 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getAuth } from "@/lib/auth";
import { authErrorCode } from "@/lib/auth-errors";
import { getDb, getMongoClient } from "@/lib/db/mongo";
import { HouseholdModel } from "@/models/household";
import { HouseholdMemberModel } from "@/models/household-member";
import { closeSeedConnections, runSeed } from "./run";
import { SEED_HOUSEHOLDS, SEED_USERS } from "./fixtures";
const silent = () => {};
beforeAll(async () => {
expect(getDb().databaseName).toBe("butcem_test");
await getDb().dropDatabase();
});
afterAll(async () => {
await getDb().dropDatabase();
await closeSeedConnections();
await getMongoClient().close();
});
describe("seed", () => {
it("ilk çalıştırmada admin, örnek kullanıcılar, haneler ve üyelikleri oluşturur", async () => {
const summary = await runSeed({ log: silent });
const memberCount = SEED_HOUSEHOLDS.reduce((n, h) => n + h.members.length, 0);
expect(summary.created).toEqual({
users: SEED_USERS.length + 1,
households: SEED_HOUSEHOLDS.length,
memberships: memberCount,
});
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
expect(await HouseholdMemberModel.countDocuments()).toBe(memberCount);
});
it("idempotenttir: ikinci çalıştırma kopya oluşturmaz", async () => {
const summary = await runSeed({ log: silent });
expect(summary.created).toEqual({ users: 0, households: 0, memberships: 0 });
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
expect(await HouseholdModel.countDocuments()).toBe(SEED_HOUSEHOLDS.length);
});
it("roller ve askı durumu doğru", async () => {
const users = await getDb()
.collection("user")
.find({}, { projection: { username: 1, role: 1, banned: 1 } })
.toArray();
const by = new Map(users.map((u) => [u.username as string, u]));
expect(by.get("admin")?.role).toBe("admin");
expect(by.get("burak")?.role).toBe("admin");
expect(by.get("ozan")?.banned).toBe(true);
expect(users.filter((u) => u.banned)).toHaveLength(1);
// Bir kullanıcı birden çok hanede, farklı rollerle.
const ayse = by.get("ayse")!;
const roles = await HouseholdMemberModel.find({ userId: ayse._id }).lean();
expect(roles.map((m) => m.role).sort()).toEqual(["owner", "viewer"]);
// Hanesi olmayan admin.
expect(await HouseholdMemberModel.countDocuments({ userId: by.get("burak")!._id })).toBe(0);
});
it("e-postası olmayan kullanıcı kullanıcı adıyla girer; askıdaki kullanıcı giremez", async () => {
const api = getAuth().api;
const emre = await api.signInUsername({
body: { username: "emre", password: "Test-User-12345" },
});
expect(emre.user.name).toBe("Emre Çakır");
const error = await api
.signInUsername({ body: { username: "ozan", password: "Test-User-12345" } })
.then(
() => null,
(e: unknown) => e,
);
expect(authErrorCode(error)).toBe("BANNED_USER");
});
it("reset koleksiyonları temizleyip yeniden doldurur", async () => {
const summary = await runSeed({ reset: true, log: silent });
expect(summary.created.users).toBe(SEED_USERS.length + 1);
expect(await getDb().collection("user").countDocuments()).toBe(SEED_USERS.length + 1);
});
});
+201
View File
@@ -0,0 +1,201 @@
import mongoose, { Types } from "mongoose";
import { getAuth } from "@/lib/auth";
import { getDb } from "@/lib/db/mongo";
import { connectMongoose } from "@/lib/db/mongoose";
import { env } from "@/lib/env";
import { HouseholdModel } from "@/models/household";
import { HouseholdMemberModel } from "@/models/household-member";
import { storedEmail } from "@/shared/account-email";
import { ADMIN_USERNAME, SEED_HOUSEHOLDS, SEED_USERS, type SeedUser } from "./fixtures";
/**
* İdempotent seed. Kullanıcılar Better Auth API'siyle oluşturulur (şifreler doğru hashlenir);
* tekrar çalıştırınca kopya oluşturmaz (kullanıcı adı / hane adı / üyelik çiftine göre).
* Production'da yalnızca admin oluşturulur; örnek kullanıcı ve hane oluşturulmaz.
*/
export type SeedOptions = { reset?: boolean; log?: (line: string) => void };
export type SeedAccountRow = {
rol: string;
kullaniciAdi: string;
eposta: string;
durum: string;
haneler: string;
};
export type SeedSummary = {
created: { users: number; households: number; memberships: number };
accounts: SeedAccountRow[];
};
const AUTH_COLLECTIONS = ["user", "account", "session", "verification", "rateLimit"];
const DOMAIN_COLLECTIONS = ["households", "householdMembers"];
type AuthApi = ReturnType<typeof getAuth>["api"];
async function findUserIdByUsername(username: string): Promise<string | null> {
const doc = await getDb()
.collection("user")
.findOne({ username }, { projection: { _id: 1 } });
return doc ? String(doc._id) : null;
}
/** Admin olarak giriş yapıp oturum başlıklarını döner (ban gibi oturum isteyen admin API'leri için). */
async function adminHeaders(api: AuthApi, password: string): Promise<Headers> {
const { headers } = await api.signInUsername({
body: { username: ADMIN_USERNAME, password },
returnHeaders: true,
});
const cookie = headers
.getSetCookie()
.map((c) => c.split(";")[0])
.join("; ");
return new Headers({ cookie });
}
export async function runSeed({
reset = false,
log = console.log,
}: SeedOptions = {}): Promise<SeedSummary> {
const e = env();
const isProd = e.NODE_ENV === "production";
if (reset && isProd) throw new Error("seed:reset production ortamında çalıştırılamaz.");
if (!e.SEED_ADMIN_EMAIL || !e.SEED_ADMIN_PASSWORD) {
throw new Error("SEED_ADMIN_EMAIL ve SEED_ADMIN_PASSWORD tanımlı olmalı.");
}
if (!isProd && !e.SEED_USER_PASSWORD) {
throw new Error("SEED_USER_PASSWORD tanımlı olmalı (örnek kullanıcıların ortak şifresi).");
}
const api = getAuth().api;
const db = getDb();
await connectMongoose();
const summary: SeedSummary = {
created: { users: 0, households: 0, memberships: 0 },
accounts: [],
};
if (reset) {
for (const name of [...AUTH_COLLECTIONS, ...DOMAIN_COLLECTIONS]) {
await db.collection(name).deleteMany({});
}
log("• Kimlik doğrulama ve hane koleksiyonları temizlendi.");
}
// Index'ler (production'da Mongoose autoIndex kapalı olduğu için açıkça oluşturulur).
await HouseholdModel.createIndexes();
await HouseholdMemberModel.createIndexes();
// 1) Admin
const adminEmail = e.SEED_ADMIN_EMAIL.toLowerCase();
let adminId = await findUserIdByUsername(ADMIN_USERNAME);
if (!adminId) {
const res = await api.createUser({
body: {
email: adminEmail,
password: e.SEED_ADMIN_PASSWORD,
name: "Yönetici",
role: "admin",
data: { username: ADMIN_USERNAME },
},
});
adminId = res.user.id;
summary.created.users++;
log(`✓ Admin oluşturuldu: ${adminEmail} (kullanıcı adı: ${ADMIN_USERNAME})`);
} else {
log(`• Admin zaten var: ${ADMIN_USERNAME}`);
}
if (isProd) {
log("• Production: örnek kullanıcı ve hane oluşturulmadı.");
return summary;
}
// 2) Örnek kullanıcılar
const ids = new Map<string, string>([[ADMIN_USERNAME, adminId]]);
const toBan: SeedUser[] = [];
for (const u of SEED_USERS) {
let id = await findUserIdByUsername(u.username);
if (!id) {
const res = await api.createUser({
body: {
email: storedEmail(u.username, u.email),
password: e.SEED_USER_PASSWORD!,
name: u.name,
role: u.role,
data: { username: u.username },
},
});
id = res.user.id;
summary.created.users++;
log(`✓ Kullanıcı: ${u.name} (@${u.username})`);
}
ids.set(u.username, id);
if (u.banReason) toBan.push(u);
}
// 3) Askıdaki kullanıcı(lar) — admin API'si oturum ister.
const pendingBans: { user: SeedUser; id: string }[] = [];
for (const u of toBan) {
const id = ids.get(u.username)!;
const doc = await db
.collection("user")
.findOne({ _id: new Types.ObjectId(id) }, { projection: { banned: 1 } });
if (!doc?.banned) pendingBans.push({ user: u, id });
}
if (pendingBans.length) {
const headers = await adminHeaders(api, e.SEED_ADMIN_PASSWORD);
for (const { user, id } of pendingBans) {
await api.banUser({ headers, body: { userId: id, banReason: user.banReason } });
log(`✓ Askıya alındı: @${user.username}`);
}
}
// 4) Haneler ve üyelikler
const memberships = new Map<string, string[]>();
const actor = new Types.ObjectId(adminId);
for (const h of SEED_HOUSEHOLDS) {
let household = await HouseholdModel.findOne({ name: h.name });
if (!household) {
household = await HouseholdModel.create({ name: h.name, createdBy: actor, updatedBy: actor });
summary.created.households++;
log(`✓ Hane: ${h.name}`);
}
for (const m of h.members) {
const userId = new Types.ObjectId(ids.get(m.username)!);
const result = await HouseholdMemberModel.updateOne(
{ householdId: household._id, userId },
{
$setOnInsert: { householdId: household._id, userId, createdBy: actor },
$set: { role: m.role, updatedBy: actor },
},
{ upsert: true },
);
if (result.upsertedCount) summary.created.memberships++;
memberships.set(m.username, [
...(memberships.get(m.username) ?? []),
`${h.name} (${m.role})`,
]);
}
}
// 5) Geliştirme hesapları tablosu
const all = [
{ username: ADMIN_USERNAME, name: "Yönetici", email: adminEmail, role: "admin" as const },
...SEED_USERS,
];
summary.accounts = all.map((u) => ({
rol: u.role,
kullaniciAdi: u.username,
eposta: u.email ?? "—",
durum: "banReason" in u && u.banReason ? "askıda" : "aktif",
haneler: (memberships.get(u.username) ?? ["—"]).join(", "),
}));
return summary;
}
/** Seed sonrası bağlantıları kapatır (CLI ve testler). */
export async function closeSeedConnections() {
await mongoose.disconnect();
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { PageHeader } from "@/components/page-header";
import { UsersTable } from "@/features/admin-users/components/users-table";
import { listAdminUsers } from "@/features/admin-users/queries";
import { tr } from "@/i18n/tr";
import { requireRole } from "@/lib/dal";
export const metadata: Metadata = { title: tr.adminUsers.title };
export default async function AdminUsersPage() {
const [admin, users] = await Promise.all([requireRole("admin"), listAdminUsers()]);
return (
<>
<PageHeader title={tr.adminUsers.title} description={tr.adminUsers.description} />
<UsersTable users={users} currentUserId={admin.id} />
</>
);
}
+7
View File
@@ -0,0 +1,7 @@
import { requireRole } from "@/lib/dal";
/** Yalnızca sistem admini; diğerlerine 404. Sayfalar ayrıca kendi kontrolünü yapar. */
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
await requireRole("admin");
return children;
}
+14
View File
@@ -0,0 +1,14 @@
import { Skeleton } from "@/components/ui/skeleton";
import { SummaryCardsSkeleton } from "@/features/dashboard/components/summary-cards-skeleton";
export default function DashboardLoading() {
return (
<>
<div className="space-y-2">
<Skeleton className="h-8 w-56" />
<Skeleton className="h-4 w-80 max-w-full" />
</div>
<SummaryCardsSkeleton />
</>
);
}
+67
View File
@@ -0,0 +1,67 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import { PageHeader } from "@/components/page-header";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { SummaryCardsSkeleton } from "@/features/dashboard/components/summary-cards-skeleton";
import { tr } from "@/i18n/tr";
import { requireSession } from "@/lib/dal";
import { cn } from "@/lib/utils";
import { formatMoney } from "@/shared/format";
export const metadata: Metadata = { title: tr.dashboard.title };
type SummaryCard = {
key: keyof typeof tr.dashboard.cards;
tone?: string;
amountMinor: number | null;
};
/** FAZ 14: gerçek özet verisi (gelir, gider, bakiye, kart borcu, net varlık). */
async function getSummary(): Promise<SummaryCard[]> {
return [
{ key: "monthIncome", tone: "text-income", amountMinor: null },
{ key: "monthExpense", tone: "text-expense", amountMinor: null },
{ key: "monthRemaining", tone: "text-budget", amountMinor: null },
{ key: "totalBalance", amountMinor: null },
{ key: "cardDebt", tone: "text-expense", amountMinor: null },
{ key: "netWorth", amountMinor: null },
];
}
async function SummaryCards() {
const cards = await getSummary();
return (
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
{cards.map((c) => (
<Card key={c.key} size="sm">
<CardHeader>
<CardDescription>{tr.dashboard.cards[c.key]}</CardDescription>
<CardTitle className={cn("text-lg tabular-nums", c.tone)}>
{c.amountMinor === null ? "—" : formatMoney(c.amountMinor)}
</CardTitle>
</CardHeader>
{c.amountMinor === null ? (
<CardContent className="text-xs text-muted-foreground">
{tr.dashboard.noData}
</CardContent>
) : null}
</Card>
))}
</div>
);
}
export default async function DashboardPage() {
const user = await requireSession();
return (
<>
<PageHeader
title={tr.dashboard.welcome(user.name.split(" ")[0] ?? user.name)}
description={tr.dashboard.welcomeDescription}
/>
<Suspense fallback={<SummaryCardsSkeleton />}>
<SummaryCards />
</Suspense>
</>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { Suspense } from "react";
import { AppHeader } from "@/components/layout/app-header";
import { AppShellFallback } from "@/components/layout/app-shell-fallback";
import { AppSidebar } from "@/components/layout/app-sidebar";
import { BottomNav } from "@/components/layout/bottom-nav";
import { QuickAddProvider } from "@/components/layout/quick-add";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { MOCK_HOUSEHOLDS } from "@/features/households/mock";
import { requireSession } from "@/lib/dal";
import { APP_VERSION } from "@/lib/version";
/**
* Oturum gerektiren alan. Oturum okuması istek anında yapılır (Cache Components), bu yüzden
* kullanıcıya bağlı kabuk Suspense içinde render edilir. Her sayfa ayrıca kendi yetkisini
* DAL üzerinden kontrol eder (layout istemci gezinmesinde yeniden çalışmaz).
*/
export default function AppLayout({ children }: { children: React.ReactNode }) {
return (
<Suspense fallback={<AppShellFallback />}>
<AuthenticatedShell>{children}</AuthenticatedShell>
</Suspense>
);
}
async function AuthenticatedShell({ children }: { children: React.ReactNode }) {
const user = await requireSession();
return (
<SidebarProvider>
<QuickAddProvider>
<AppSidebar isAdmin={user.role === "admin"} version={APP_VERSION} />
<SidebarInset>
{/* FAZ 5: kullanıcının üye olduğu haneler */}
<AppHeader user={user} households={MOCK_HOUSEHOLDS} version={APP_VERSION} />
{/* Mobilde alt menü yüksekliği kadar boşluk */}
<div className="flex flex-1 flex-col gap-4 p-4 pb-24 md:p-6 md:pb-6">{children}</div>
</SidebarInset>
<BottomNav />
</QuickAddProvider>
</SidebarProvider>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { ThemeToggle } from "@/components/layout/theme-toggle";
/** Oturum gerektirmeyen ekranlar (yalnızca giriş). */
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<div className="relative flex min-h-dvh flex-1 flex-col items-center justify-center bg-gradient-to-b from-primary/5 via-background to-background px-4 py-10">
<div className="absolute top-3 right-3">
<ThemeToggle />
</div>
{children}
</div>
);
}
+95
View File
@@ -0,0 +1,95 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { PasswordInput } from "@/components/password-input";
import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { tr } from "@/i18n/tr";
import { authClient } from "@/lib/auth-client";
import { looksLikeEmail, normalizeUsername } from "@/shared/schemas/common";
import { loginSchema, type LoginInput } from "@/shared/schemas/auth";
export function LoginForm() {
const router = useRouter();
const [formError, setFormError] = useState<string | null>(null);
const form = useForm<LoginInput>({
resolver: zodResolver(loginSchema),
defaultValues: { identifier: "", password: "" },
});
async function onSubmit({ identifier, password }: LoginInput) {
setFormError(null);
const value = identifier.trim();
const { error } = looksLikeEmail(value)
? await authClient.signIn.email({ email: value.toLowerCase(), password })
: await authClient.signIn.username({ username: normalizeUsername(value), password });
if (error) {
// Hangi bilginin yanlış olduğu söylenmez (hesap tahmini zorlaşır).
if (error.status === 429) setFormError(tr.auth.tooManyAttempts);
else if (error.code === "BANNED_USER") setFormError(tr.auth.banned);
else setFormError(tr.auth.invalidCredentials);
form.setValue("password", "");
return;
}
router.replace("/dashboard");
router.refresh();
}
const submitting = form.formState.isSubmitting;
return (
<form onSubmit={form.handleSubmit(onSubmit)} noValidate aria-busy={submitting}>
<FieldGroup>
<Controller
name="identifier"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="identifier">{tr.auth.identifier}</FieldLabel>
<Input
{...field}
id="identifier"
autoComplete="username"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
inputMode="email"
placeholder={tr.auth.identifierPlaceholder}
aria-invalid={fieldState.invalid}
autoFocus
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Controller
name="password"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="password">{tr.auth.password}</FieldLabel>
<PasswordInput
{...field}
id="password"
autoComplete="current-password"
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
{formError ? <FieldError>{formError}</FieldError> : null}
<Button type="submit" size="lg" disabled={submitting} className="w-full">
{submitting ? <Loader2 className="animate-spin" /> : null}
{submitting ? tr.auth.submitting : tr.auth.submit}
</Button>
</FieldGroup>
</form>
);
}
+38
View File
@@ -0,0 +1,38 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { Logo } from "@/components/brand/logo";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { tr } from "@/i18n/tr";
import { getCurrentUser } from "@/lib/dal";
import { LoginForm } from "./login-form";
export const metadata: Metadata = { title: tr.auth.loginTitle };
/** Oturum açıksa dashboard'a yönlendirir (istek anında, Suspense içinde). */
async function RedirectIfSignedIn() {
const user = await getCurrentUser();
if (user) redirect("/dashboard");
return null;
}
export default function LoginPage() {
return (
<main className="flex w-full max-w-sm flex-col items-center gap-6">
<Suspense fallback={null}>
<RedirectIfSignedIn />
</Suspense>
<Logo priority className="scale-125" />
<Card className="w-full">
<CardHeader>
<CardTitle className="text-xl">{tr.auth.loginTitle}</CardTitle>
<CardDescription>{tr.auth.loginDescription}</CardDescription>
</CardHeader>
<CardContent>
<LoginForm />
</CardContent>
</Card>
<p className="text-center text-xs text-muted-foreground">{tr.auth.noSignUp}</p>
</main>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { toNextJsHandler } from "better-auth/next-js";
import { getAuth } from "@/lib/auth";
/** Better Auth uç noktaları (/api/auth/*). Kayıt (sign-up) yapılandırmada kapalıdır. */
export function GET(request: Request) {
return toNextJsHandler(getAuth()).GET(request);
}
export function POST(request: Request) {
return toNextJsHandler(getAuth()).POST(request);
}
+7 -4
View File
@@ -1,20 +1,23 @@
import { connection } from "next/server";
import { pingDb } from "@/lib/db/mongo";
import { APP_COMMIT, APP_VERSION } from "@/lib/version";
/**
* Sağlık kontrolü (Dokploy / Docker HEALTHCHECK).
* Faz 3'te veritabanı ping'i eklenecek; DB erişilemezse 503 dönecek.
* Sağlık kontrolü (Dokploy / Docker HEALTHCHECK). Veritabanına erişilemezse 503.
* İç hata detayı döndürülmez.
*/
export async function GET() {
// Cache Components açıkken GET handler'ı build'de prerender edilmesin.
await connection();
const dbOk = await pingDb();
return Response.json(
{
status: "ok",
status: dbOk ? "ok" : "degraded",
db: dbOk ? "ok" : "unreachable",
version: APP_VERSION,
commit: APP_COMMIT,
time: new Date().toISOString(),
},
{ headers: { "Cache-Control": "no-store" } },
{ status: dbOk ? 200 : 503, headers: { "Cache-Control": "no-store" } },
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

+27
View File
@@ -0,0 +1,27 @@
"use client";
import { useEffect } from "react";
import { Button } from "@/components/ui/button";
import { tr } from "@/i18n/tr";
/** Rota hata sınırı. İç detay gösterilmez; yalnızca sunucu loglarıyla eşleşen hata kodu (digest). */
export default function ErrorPage({ error, retry }: { error: unknown; retry: () => void }) {
useEffect(() => {
console.error(error);
}, [error]);
const digest = error instanceof Error && "digest" in error ? String(error.digest) : undefined;
return (
<main className="flex flex-1 flex-col items-center justify-center gap-4 p-8 text-center">
<h1 className="text-2xl font-semibold tracking-tight">{tr.errors.errorTitle}</h1>
<p className="max-w-md text-muted-foreground">{tr.errors.errorDescription}</p>
{digest ? (
<p className="text-xs text-muted-foreground">
{tr.errors.reference}: <code>{digest}</code>
</p>
) : null}
<Button onClick={() => retry()}>{tr.errors.retry}</Button>
</main>
);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

+23
View File
@@ -0,0 +1,23 @@
"use client";
import { tr } from "@/i18n/tr";
import "./globals.css";
/** Kök layout hataları için son çare sınırı (kendi <html>/<body> etiketini render eder). */
export default function GlobalError({ retry }: { error: unknown; retry: () => void }) {
return (
<html lang="tr">
<body className="flex min-h-dvh flex-col items-center justify-center gap-4 p-8 text-center">
<h1 className="text-2xl font-semibold tracking-tight">{tr.errors.errorTitle}</h1>
<p className="max-w-md text-muted-foreground">{tr.errors.errorDescription}</p>
<button
type="button"
onClick={() => retry()}
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
>
{tr.errors.retry}
</button>
</body>
</html>
);
}
+98 -60
View File
@@ -18,6 +18,14 @@
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-income: var(--income);
--color-income-foreground: var(--income-foreground);
--color-expense: var(--expense);
--color-expense-foreground: var(--expense-foreground);
--color-budget: var(--budget);
--color-budget-foreground: var(--budget-foreground);
--color-warning: var(--warning);
--color-warning-foreground: var(--warning-foreground);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
@@ -48,73 +56,98 @@
--radius-4xl: calc(var(--radius) * 2.6);
}
/*
* BÜTÇEM marka paleti — mavi ve beyaz tonları (oklch). Sabit renk kodu yalnızca burada.
* Anlamsal renkler: --income (gelir/yeşil), --expense (gider/kırmızı),
* --budget (bütçe-plan/mavi), --warning (uyarı/turuncu). Grafikler de bunları kullanır.
*/
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--background: oklch(0.99 0.004 250);
--foreground: oklch(0.22 0.04 262);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--card-foreground: oklch(0.22 0.04 262);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--popover-foreground: oklch(0.22 0.04 262);
--primary: oklch(0.49 0.17 258);
--primary-foreground: oklch(0.99 0.004 250);
--secondary: oklch(0.955 0.016 250);
--secondary-foreground: oklch(0.3 0.06 260);
--muted: oklch(0.955 0.012 250);
--muted-foreground: oklch(0.5 0.03 258);
--accent: oklch(0.935 0.03 250);
--accent-foreground: oklch(0.3 0.08 260);
--destructive: oklch(0.56 0.21 25);
--border: oklch(0.905 0.016 252);
--input: oklch(0.89 0.018 252);
--ring: oklch(0.6 0.15 258);
--income: oklch(0.58 0.15 152);
--income-foreground: oklch(0.99 0.004 250);
--expense: oklch(0.56 0.21 25);
--expense-foreground: oklch(0.99 0.004 250);
--budget: oklch(0.55 0.17 258);
--budget-foreground: oklch(0.99 0.004 250);
--warning: oklch(0.68 0.17 55);
--warning-foreground: oklch(0.22 0.04 262);
--chart-1: var(--income);
--chart-2: var(--budget);
--chart-3: var(--expense);
--chart-4: var(--warning);
--chart-5: oklch(0.65 0.08 230);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--sidebar: oklch(0.975 0.008 250);
--sidebar-foreground: oklch(0.22 0.04 262);
--sidebar-primary: oklch(0.49 0.17 258);
--sidebar-primary-foreground: oklch(0.99 0.004 250);
--sidebar-accent: oklch(0.935 0.03 250);
--sidebar-accent-foreground: oklch(0.3 0.08 260);
--sidebar-border: oklch(0.905 0.016 252);
--sidebar-ring: oklch(0.6 0.15 258);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
--background: oklch(0.18 0.04 264);
--foreground: oklch(0.96 0.01 250);
--card: oklch(0.22 0.045 264);
--card-foreground: oklch(0.96 0.01 250);
--popover: oklch(0.22 0.045 264);
--popover-foreground: oklch(0.96 0.01 250);
--primary: oklch(0.76 0.12 245);
--primary-foreground: oklch(0.18 0.04 264);
--secondary: oklch(0.27 0.045 264);
--secondary-foreground: oklch(0.96 0.01 250);
--muted: oklch(0.26 0.04 264);
--muted-foreground: oklch(0.73 0.03 250);
--accent: oklch(0.3 0.06 262);
--accent-foreground: oklch(0.96 0.01 250);
--destructive: oklch(0.7 0.18 22);
--border: oklch(1 0 0 / 11%);
--input: oklch(1 0 0 / 16%);
--ring: oklch(0.7 0.12 245);
--income: oklch(0.75 0.16 152);
--income-foreground: oklch(0.18 0.04 264);
--expense: oklch(0.7 0.18 22);
--expense-foreground: oklch(0.18 0.04 264);
--budget: oklch(0.73 0.13 245);
--budget-foreground: oklch(0.18 0.04 264);
--warning: oklch(0.79 0.15 62);
--warning-foreground: oklch(0.18 0.04 264);
--chart-1: var(--income);
--chart-2: var(--budget);
--chart-3: var(--expense);
--chart-4: var(--warning);
--chart-5: oklch(0.7 0.07 230);
--sidebar: oklch(0.2 0.045 264);
--sidebar-foreground: oklch(0.96 0.01 250);
--sidebar-primary: oklch(0.76 0.12 245);
--sidebar-primary-foreground: oklch(0.18 0.04 264);
--sidebar-accent: oklch(0.28 0.055 262);
--sidebar-accent-foreground: oklch(0.96 0.01 250);
--sidebar-border: oklch(1 0 0 / 11%);
--sidebar-ring: oklch(0.7 0.12 245);
}
@layer base {
@@ -128,3 +161,8 @@
@apply font-sans;
}
}
/* Mobil alt menü + iOS ana ekran çentiği için güvenli alan */
@utility pb-safe {
padding-bottom: env(safe-area-inset-bottom);
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+17 -2
View File
@@ -1,5 +1,6 @@
import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Providers } from "@/components/providers";
import { tr } from "@/i18n/tr";
import "./globals.css";
@@ -18,17 +19,31 @@ export const metadata: Metadata = {
title: { default: tr.app.name, template: `%s · ${tr.app.name}` },
description: tr.app.tagline,
applicationName: tr.app.name,
appleWebApp: { capable: true, title: tr.app.name, statusBarStyle: "default" },
formatDetection: { telephone: false },
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover",
// Manifest/tarayıcı çubuğu rengi CSS değişkeni okuyamaz; --background değerlerinin hex karşılığı.
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "#fafcfe" },
{ media: "(prefers-color-scheme: dark)", color: "#081123" },
],
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="tr" className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}>
<body className="flex min-h-full flex-col">{children}</body>
<html
lang="tr"
suppressHydrationWarning
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="flex min-h-full flex-col">
<Providers>{children}</Providers>
</body>
</html>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { Loader2 } from "lucide-react";
import { tr } from "@/i18n/tr";
export default function Loading() {
return (
<div
role="status"
className="flex flex-1 items-center justify-center gap-2 p-8 text-muted-foreground"
>
<Loader2 className="size-5 animate-spin" />
<span>{tr.common.loading}</span>
</div>
);
}
+26
View File
@@ -0,0 +1,26 @@
import type { MetadataRoute } from "next";
import { tr } from "@/i18n/tr";
/** PWA manifest: "Ana ekrana ekle" ile kurulabilir. İkonlar: npm run icons. */
export default function manifest(): MetadataRoute.Manifest {
return {
id: "/",
name: tr.app.name,
short_name: tr.app.name,
description: tr.app.tagline,
lang: "tr-TR",
dir: "ltr",
start_url: "/dashboard",
scope: "/",
display: "standalone",
orientation: "portrait",
background_color: "#fafcfe",
theme_color: "#105bbe",
categories: ["finance", "productivity"],
icons: [
{ src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
{ src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
{ src: "/icons/maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
],
};
}
+16
View File
@@ -0,0 +1,16 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { tr } from "@/i18n/tr";
export default function NotFound() {
return (
<main className="flex flex-1 flex-col items-center justify-center gap-4 p-8 text-center">
<p className="text-6xl font-semibold text-primary tabular-nums">404</p>
<h1 className="text-2xl font-semibold tracking-tight">{tr.errors.notFoundTitle}</h1>
<p className="max-w-md text-muted-foreground">{tr.errors.notFoundDescription}</p>
<Button asChild>
<Link href="/">{tr.errors.backHome}</Link>
</Button>
</main>
);
}
+3 -12
View File
@@ -1,15 +1,6 @@
import { tr } from "@/i18n/tr";
import { APP_VERSION } from "@/lib/version";
import { redirect } from "next/navigation";
/** Geçici açılış sayfası — Faz 2'de /login'e yönlendirme ile değişecek. */
/** Oturum yoksa proxy zaten /login'e yönlendirir; varsa dashboard. */
export default function Home() {
return (
<main className="flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center">
<h1 className="text-3xl font-semibold tracking-tight">{tr.app.name}</h1>
<p className="max-w-md text-muted-foreground">{tr.app.setupDescription}</p>
<p className="text-sm text-muted-foreground">
{tr.app.version} {APP_VERSION}
</p>
</main>
);
redirect("/dashboard");
}
View File
+27
View File
@@ -0,0 +1,27 @@
import Image from "next/image";
import { cn } from "@/lib/utils";
import { tr } from "@/i18n/tr";
/**
* Marka logosu: açık temada logo.svg, koyu temada logo-dark.svg (CSS ile seçilir,
* hydration uyumsuzluğu olmaz). Dosyalar public/brand/ altında.
*/
export function Logo({ className, priority }: { className?: string; priority?: boolean }) {
const common = { width: 114, height: 32, priority, unoptimized: true } as const;
return (
<span className={cn("inline-flex items-center", className)}>
<Image
src="/brand/logo.svg"
alt={tr.app.name}
className="h-8 w-auto dark:hidden"
{...common}
/>
<Image
src="/brand/logo-dark.svg"
alt=""
className="hidden h-8 w-auto dark:block"
{...common}
/>
</span>
);
}
View File
+31
View File
@@ -0,0 +1,31 @@
import { SidebarTrigger } from "@/components/ui/sidebar";
import type { SessionUser } from "@/features/auth/types";
import type { HouseholdSummary } from "@/features/households/types";
import { tr } from "@/i18n/tr";
import { HouseholdSwitcher } from "./household-switcher";
import { QuickAddButton } from "./quick-add";
import { ThemeToggle } from "./theme-toggle";
import { UserMenu } from "./user-menu";
/** Üst bar: menü düğmesi (masaüstü), hane seçici, hızlı ekle, tema ve kullanıcı menüsü. */
export function AppHeader({
user,
households,
version,
}: {
user: SessionUser;
households: HouseholdSummary[];
version: string;
}) {
return (
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-background/95 px-3 backdrop-blur supports-backdrop-filter:bg-background/80 md:px-4">
<SidebarTrigger className="hidden md:inline-flex" aria-label={tr.nav.toggleSidebar} />
<HouseholdSwitcher households={households} />
<div className="ml-auto flex items-center gap-1">
<QuickAddButton className="hidden md:inline-flex" />
<ThemeToggle />
<UserMenu user={user} version={version} />
</div>
</header>
);
}
@@ -0,0 +1,26 @@
import { Skeleton } from "@/components/ui/skeleton";
import { tr } from "@/i18n/tr";
/** Oturum okunurken gösterilen kabuk iskeleti (yan menü + üst bar + içerik). */
export function AppShellFallback() {
return (
<div role="status" aria-label={tr.common.loading} className="flex min-h-dvh w-full">
<div className="hidden w-64 shrink-0 flex-col gap-3 border-r bg-sidebar p-3 md:flex">
<Skeleton className="h-8 w-28" />
{Array.from({ length: 8 }, (_, i) => (
<Skeleton key={i} className="h-7 w-full" />
))}
</div>
<div className="flex flex-1 flex-col">
<div className="flex h-14 items-center gap-2 border-b px-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="ml-auto size-8 rounded-full" />
</div>
<div className="flex flex-col gap-4 p-4 md:p-6">
<Skeleton className="h-8 w-56" />
<Skeleton className="h-24 w-full" />
</div>
</div>
</div>
);
}
+103
View File
@@ -0,0 +1,103 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Logo } from "@/components/brand/logo";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
useSidebar,
} from "@/components/ui/sidebar";
import { tr } from "@/i18n/tr";
import { ADMIN_NAV, MAIN_NAV, isActivePath, isAvailable, type NavItem } from "./nav-config";
function NavList({ items, pathname }: { items: NavItem[]; pathname: string }) {
const { setOpenMobile } = useSidebar();
return (
<SidebarMenu>
{items.map((item) => {
const Icon = item.icon;
if (!isAvailable(item)) {
return (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
aria-disabled
disabled
tooltip={`${item.label} · ${tr.common.comingSoon}`}
>
<Icon />
<span>{item.label}</span>
</SidebarMenuButton>
<SidebarMenuBadge className="text-[0.65rem] opacity-70">
{tr.common.comingSoon}
</SidebarMenuBadge>
</SidebarMenuItem>
);
}
const active = isActivePath(pathname, item.href);
return (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton asChild isActive={active} tooltip={item.label}>
<Link
href={item.href}
aria-current={active ? "page" : undefined}
onClick={() => setOpenMobile(false)}
>
<Icon />
<span>{item.label}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
);
}
/** Masaüstünde sabit yan menü; mobilde "Daha fazla" ile açılan Sheet. */
export function AppSidebar({ isAdmin, version }: { isAdmin: boolean; version: string }) {
const pathname = usePathname();
return (
<Sidebar collapsible="icon">
<SidebarHeader className="h-14 justify-center px-3">
<Link
href="/dashboard"
aria-label={tr.nav.dashboard}
className="group-data-[collapsible=icon]:hidden"
>
<Logo />
</Link>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>{tr.nav.main}</SidebarGroupLabel>
<SidebarGroupContent>
<NavList items={MAIN_NAV} pathname={pathname} />
</SidebarGroupContent>
</SidebarGroup>
{isAdmin ? (
<SidebarGroup>
<SidebarGroupLabel>{tr.nav.admin}</SidebarGroupLabel>
<SidebarGroupContent>
<NavList items={ADMIN_NAV} pathname={pathname} />
</SidebarGroupContent>
</SidebarGroup>
) : null}
</SidebarContent>
<SidebarFooter className="px-4 pb-3 text-xs text-muted-foreground group-data-[collapsible=icon]:hidden">
{tr.app.name} · {tr.app.version} {version}
</SidebarFooter>
<SidebarRail />
</Sidebar>
);
}
+80
View File
@@ -0,0 +1,80 @@
"use client";
import { Menu, Plus } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useSidebar } from "@/components/ui/sidebar";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
import { BOTTOM_NAV, isActivePath, isAvailable, type NavItem } from "./nav-config";
import { useQuickAdd } from "./quick-add";
const itemClass =
"flex min-h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[0.7rem] font-medium outline-none focus-visible:bg-muted";
function BottomNavLink({ item, pathname }: { item: NavItem; pathname: string }) {
const Icon = item.icon;
if (!isAvailable(item)) {
return (
<span
aria-disabled
className={cn(itemClass, "text-muted-foreground/50")}
title={tr.common.comingSoon}
>
<Icon className="size-5" />
{item.label}
</span>
);
}
const active = isActivePath(pathname, item.href);
return (
<Link
href={item.href}
aria-current={active ? "page" : undefined}
className={cn(itemClass, active ? "text-primary" : "text-muted-foreground")}
>
<Icon className="size-5" />
{item.label}
</Link>
);
}
/** Mobil alt gezinme çubuğu (md altı). */
export function BottomNav() {
const pathname = usePathname();
const { openQuickAdd } = useQuickAdd();
const { setOpenMobile } = useSidebar();
return (
<nav
aria-label={tr.nav.main}
className="fixed inset-x-0 bottom-0 z-40 border-t bg-background/95 pb-safe backdrop-blur supports-backdrop-filter:bg-background/80 md:hidden"
>
<div className="flex items-stretch">
{BOTTOM_NAV.left.map((item) => (
<BottomNavLink key={item.href} item={item} pathname={pathname} />
))}
<div className="flex flex-1 items-center justify-center">
<button
type="button"
onClick={openQuickAdd}
aria-label={tr.quickAdd.button}
className="-mt-5 flex size-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg outline-none focus-visible:ring-4 focus-visible:ring-ring/50"
>
<Plus className="size-6" />
</button>
</div>
{BOTTOM_NAV.right.map((item) => (
<BottomNavLink key={item.href} item={item} pathname={pathname} />
))}
<button
type="button"
onClick={() => setOpenMobile(true)}
className={cn(itemClass, "text-muted-foreground")}
>
<Menu className="size-5" />
{tr.nav.more}
</button>
</div>
</nav>
);
}
@@ -0,0 +1,37 @@
"use client";
import { House } from "lucide-react";
import { useState } from "react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { HouseholdSummary } from "@/features/households/types";
import { tr } from "@/i18n/tr";
/** Üst bar aktif hane seçici. FAZ 5: seçim sunucuda (cookie) saklanacak. */
export function HouseholdSwitcher({ households }: { households: HouseholdSummary[] }) {
const [value, setValue] = useState(households[0]?.id);
const current = households.find((h) => h.id === value);
if (households.length === 0) return null;
return (
<Select value={value} onValueChange={setValue}>
<SelectTrigger aria-label={tr.household.label} className="w-[min(46vw,13rem)]">
<House className="text-muted-foreground" />
{/* Etiket children ile verilir: Radix aksi halde hydration'a kadar boş gösterir. */}
<SelectValue placeholder={tr.household.select}>{current?.name}</SelectValue>
</SelectTrigger>
<SelectContent>
{households.map((h) => (
<SelectItem key={h.id} value={h.id}>
{h.name}
<span className="text-xs text-muted-foreground">· {tr.household.roles[h.role]}</span>
</SelectItem>
))}
</SelectContent>
</Select>
);
}
+59
View File
@@ -0,0 +1,59 @@
import {
ArrowLeftRight,
CalendarClock,
ChartColumn,
Coins,
House,
LayoutDashboard,
Package,
Settings,
ShoppingCart,
Target,
UserCog,
Users,
Wallet,
type LucideIcon,
} from "lucide-react";
import { tr } from "@/i18n/tr";
export type NavItem = {
href: string;
label: string;
icon: LucideIcon;
/** Sayfanın ekleneceği faz; mevcut fazdan büyükse "Yakında" olarak pasif gösterilir. */
phase: number;
};
/** Şu an tamamlanmış en yüksek faz — sayfalar eklendikçe artar. */
export const CURRENT_PHASE = 2;
export const isAvailable = (item: NavItem) => item.phase <= CURRENT_PHASE;
export const MAIN_NAV: NavItem[] = [
{ href: "/dashboard", label: tr.nav.dashboard, icon: LayoutDashboard, phase: 2 },
{ href: "/islemler", label: tr.nav.transactions, icon: ArrowLeftRight, phase: 6 },
{ href: "/hesaplar", label: tr.nav.accounts, icon: Wallet, phase: 6 },
{ href: "/planli", label: tr.nav.planned, icon: CalendarClock, phase: 7 },
{ href: "/cari", label: tr.nav.contacts, icon: Users, phase: 8 },
{ href: "/birikim", label: tr.nav.savings, icon: Coins, phase: 9 },
{ href: "/butce", label: tr.nav.budget, icon: Target, phase: 10 },
{ href: "/stok", label: tr.nav.stock, icon: Package, phase: 11 },
{ href: "/alisveris", label: tr.nav.shopping, icon: ShoppingCart, phase: 13 },
{ href: "/raporlar", label: tr.nav.reports, icon: ChartColumn, phase: 14 },
{ href: "/ayarlar", label: tr.nav.settings, icon: Settings, phase: 5 },
];
export const ADMIN_NAV: NavItem[] = [
{ href: "/admin/kullanicilar", label: tr.nav.adminUsers, icon: UserCog, phase: 2 },
{ href: "/admin/haneler", label: tr.nav.adminHouseholds, icon: House, phase: 5 },
];
/** Mobil alt menü: ortada Hızlı ekle, sağda "Daha fazla" (yan menüyü açar). */
export const BOTTOM_NAV = {
left: [MAIN_NAV[0]!, MAIN_NAV[1]!],
right: [MAIN_NAV[6]!],
};
export function isActivePath(pathname: string, href: string) {
return pathname === href || pathname.startsWith(`${href}/`);
}
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { ArrowDownLeft, ArrowLeftRight, ArrowUpRight, Plus } from "lucide-react";
import { createContext, use, useState } from "react";
import { toast } from "sonner";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Button } from "@/components/ui/button";
import { tr } from "@/i18n/tr";
import { cn } from "@/lib/utils";
type QuickAddKind = "expense" | "income" | "transfer";
const QuickAddContext = createContext<{ openQuickAdd: () => void } | null>(null);
export function useQuickAdd() {
const ctx = use(QuickAddContext);
if (!ctx) throw new Error("useQuickAdd, QuickAddProvider içinde kullanılmalı");
return ctx;
}
const CHOICES: {
kind: QuickAddKind;
label: string;
hint: string;
icon: typeof Plus;
tone: string;
}[] = [
{
kind: "expense",
label: tr.quickAdd.expense,
hint: tr.quickAdd.expenseHint,
icon: ArrowUpRight,
tone: "text-expense bg-expense/10",
},
{
kind: "income",
label: tr.quickAdd.income,
hint: tr.quickAdd.incomeHint,
icon: ArrowDownLeft,
tone: "text-income bg-income/10",
},
{
kind: "transfer",
label: tr.quickAdd.transfer,
hint: tr.quickAdd.transferHint,
icon: ArrowLeftRight,
tone: "text-budget bg-budget/10",
},
];
/** Hızlı ekle (gider / gelir / transfer) — her ekrandan açılabilir. */
export function QuickAddProvider({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
function choose(kind: QuickAddKind) {
setOpen(false);
// FAZ 6: ilgili işlem formu açılacak.
toast.info(`${CHOICES.find((c) => c.kind === kind)?.label}: ${tr.quickAdd.notYet}`);
}
return (
<QuickAddContext value={{ openQuickAdd: () => setOpen(true) }}>
{children}
<ResponsiveDialog
open={open}
onOpenChange={setOpen}
title={tr.quickAdd.title}
description={tr.quickAdd.description}
>
<div className="grid gap-2 pb-2 sm:grid-cols-3">
{CHOICES.map(({ kind, label, hint, icon: Icon, tone }) => (
<button
key={kind}
type="button"
onClick={() => choose(kind)}
className="flex items-center gap-3 rounded-xl border p-4 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 sm:flex-col sm:text-center"
>
<span className={cn("flex size-10 items-center justify-center rounded-full", tone)}>
<Icon className="size-5" />
</span>
<span className="flex flex-col">
<span className="font-medium">{label}</span>
<span className="text-xs text-muted-foreground">{hint}</span>
</span>
</button>
))}
</div>
</ResponsiveDialog>
</QuickAddContext>
);
}
/** Masaüstü üst bar düğmesi. */
export function QuickAddButton({ className }: { className?: string }) {
const { openQuickAdd } = useQuickAdd();
return (
<Button onClick={openQuickAdd} className={className}>
<Plus />
{tr.quickAdd.button}
</Button>
);
}
+46
View File
@@ -0,0 +1,46 @@
"use client";
import { Monitor, Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { tr } from "@/i18n/tr";
const OPTIONS = [
{ value: "light", label: tr.theme.light, icon: Sun },
{ value: "dark", label: tr.theme.dark, icon: Moon },
{ value: "system", label: tr.theme.system, icon: Monitor },
] as const;
/** Açık / Koyu / Sistem tema seçici. İkon CSS ile değişir (hydration güvenli). */
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label={tr.theme.label}>
<Sun className="scale-100 rotate-0 transition-transform dark:scale-0 dark:-rotate-90" />
<Moon className="absolute scale-0 rotate-90 transition-transform dark:scale-100 dark:rotate-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-36">
<DropdownMenuLabel>{tr.theme.label}</DropdownMenuLabel>
<DropdownMenuRadioGroup value={theme ?? "system"} onValueChange={setTheme}>
{OPTIONS.map(({ value, label, icon: Icon }) => (
<DropdownMenuRadioItem key={value} value={value}>
<Icon />
{label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
+81
View File
@@ -0,0 +1,81 @@
"use client";
import { LogOut } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { SessionUser } from "@/features/auth/types";
import { authClient } from "@/lib/auth-client";
import { tr } from "@/i18n/tr";
export function initials(name: string) {
return name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((p) => p.charAt(0).toLocaleUpperCase("tr-TR"))
.join("");
}
/** Kullanıcı menüsü: ad, rol, sürüm ve Çıkış yap. */
export function UserMenu({ user, version }: { user: SessionUser; version: string }) {
const router = useRouter();
async function logout() {
const { error } = await authClient.signOut();
if (error) {
toast.error(tr.common.genericError);
return;
}
toast.success(tr.userMenu.loggedOut);
router.replace("/login");
router.refresh();
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-lg"
className="rounded-full"
aria-label={tr.userMenu.open}
>
<Avatar>
<AvatarFallback className="bg-primary/10 font-medium text-primary">
{initials(user.name)}
</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-60">
<DropdownMenuLabel className="flex flex-col gap-1 font-normal">
<span className="truncate font-medium text-foreground">{user.name}</span>
<span className="truncate text-xs text-muted-foreground">@{user.username}</span>
<Badge variant={user.role === "admin" ? "default" : "secondary"} className="mt-1">
{tr.roles[user.role]}
</Badge>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={() => void logout()}>
<LogOut />
{tr.userMenu.logout}
</DropdownMenuItem>
<DropdownMenuSeparator />
<div className="px-2 py-1.5 text-xs text-muted-foreground">
{tr.app.name} · {tr.app.version} {version}
</div>
</DropdownMenuContent>
</DropdownMenu>
);
}
+20
View File
@@ -0,0 +1,20 @@
/** Sayfa başlığı + açıklama + sağda isteğe bağlı aksiyonlar. */
export function PageHeader({
title,
description,
actions,
}: {
title: string;
description?: string;
actions?: React.ReactNode;
}) {
return (
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="min-w-0">
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
{description ? <p className="mt-1 text-sm text-muted-foreground">{description}</p> : null}
</div>
{actions ? <div className="flex items-center gap-2">{actions}</div> : null}
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { Eye, EyeOff } from "lucide-react";
import { useState } from "react";
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from "@/components/ui/input-group";
import { tr } from "@/i18n/tr";
/** Göster/gizle düğmeli şifre alanı. */
export function PasswordInput(props: Omit<React.ComponentProps<typeof InputGroupInput>, "type">) {
const [visible, setVisible] = useState(false);
const label = visible ? tr.common.hidePassword : tr.common.showPassword;
return (
<InputGroup>
<InputGroupInput type={visible ? "text" : "password"} {...props} />
<InputGroupAddon align="inline-end">
<InputGroupButton
size="icon-xs"
aria-label={label}
title={label}
aria-pressed={visible}
onClick={() => setVisible((v) => !v)}
>
{visible ? <EyeOff /> : <Eye />}
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
);
}
+17
View File
@@ -0,0 +1,17 @@
"use client";
import { ThemeProvider } from "next-themes";
import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
/** Kök istemci sağlayıcıları: tema (açık/koyu/sistem), tooltip ve bildirimler. */
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
<TooltipProvider delayDuration={300}>
{children}
<Toaster position="top-center" richColors closeButton />
</TooltipProvider>
</ThemeProvider>
);
}
+74
View File
@@ -0,0 +1,74 @@
"use client";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
title: React.ReactNode;
description?: React.ReactNode;
children: React.ReactNode;
footer?: React.ReactNode;
className?: string;
};
/**
* Masaüstünde Dialog, mobilde (neredeyse) tam ekran alttan açılan Drawer.
* Formlar bu bileşenle açılır (Bölüm 4: "formlar mobilde tam ekran Sheet/Drawer").
*/
export function ResponsiveDialog({
open,
onOpenChange,
title,
description,
children,
footer,
className,
}: Props) {
const isMobile = useIsMobile();
if (isMobile) {
return (
<Drawer open={open} onOpenChange={onOpenChange}>
<DrawerContent className="max-h-[96dvh]">
<DrawerHeader className="text-left">
<DrawerTitle>{title}</DrawerTitle>
{description ? <DrawerDescription>{description}</DrawerDescription> : null}
</DrawerHeader>
<div className={cn("overflow-y-auto px-4 pb-2", className)}>{children}</div>
{footer ? <DrawerFooter className="pb-safe">{footer}</DrawerFooter> : null}
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
</DialogHeader>
<div className={className}>{children}</div>
{footer ? <DialogFooter>{footer}</DialogFooter> : null}
</DialogContent>
</Dialog>
);
}
+182
View File
@@ -0,0 +1,182 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
import { Button } from "@/components/ui/button";
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
}
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm";
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className,
)}
{...props}
/>
);
}
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogMedia({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className,
)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn(
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className,
)}
{...props}
/>
);
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
);
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
);
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
};
+95
View File
@@ -0,0 +1,95 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Avatar as AvatarPrimitive } from "radix-ui";
function Avatar({
className,
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: "default" | "sm" | "lg";
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className,
)}
{...props}
/>
);
}
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full rounded-full object-cover", className)}
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className,
)}
{...props}
/>
);
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className,
)}
{...props}
/>
);
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className,
)}
{...props}
/>
);
}
function AvatarGroupCount({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className,
)}
{...props}
/>
);
}
export { Avatar, AvatarImage, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarBadge };
+44
View File
@@ -0,0 +1,44 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import { Slot } from "radix-ui";
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };
+87
View File
@@ -0,0 +1,87 @@
import * as React from "react";
import { cn } from "cn";
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className,
)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="card-content" className={cn("px-(--card-spacing)", className)} {...props} />
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
className,
)}
{...props}
/>
);
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
+28
View File
@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Checkbox as CheckboxPrimitive } from "radix-ui";
import { CheckIcon } from "lucide-react";
function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
>
<CheckIcon />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
}
export { Checkbox };
+21
View File
@@ -0,0 +1,21 @@
"use client";
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />;
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />;
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
+145
View File
@@ -0,0 +1,145 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Dialog as DialogPrimitive } from "radix-ui";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="dialog-header" className={cn("flex flex-col gap-2", className)} {...props} />
);
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
);
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("font-heading text-base leading-none font-medium", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className,
)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};
+119
View File
@@ -0,0 +1,119 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Drawer as DrawerPrimitive } from "vaul";
function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
}
function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
}
function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
}
function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className,
)}
{...props}
/>
);
}
function DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content fixed z-50 flex h-auto flex-col bg-popover text-sm text-popover-foreground data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-xl data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:rounded-r-xl data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:rounded-l-xl data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-xl data-[vaul-drawer-direction=top]:border-b data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm",
className,
)}
{...props}
>
<div className="mx-auto mt-4 hidden h-1 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
);
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn(
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-0.5 md:text-left",
className,
)}
{...props}
/>
);
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("font-heading text-base font-medium text-foreground", className)}
{...props}
/>
);
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};
+249
View File
@@ -0,0 +1,249 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import { CheckIcon, ChevronRightIcon } from "lucide-react";
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
className,
align = "start",
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
align={align}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className,
)}
{...props}
/>
);
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className,
)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
);
}
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className,
)}
{...props}
/>
);
}
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
);
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};
+224
View File
@@ -0,0 +1,224 @@
"use client";
import { useMemo } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className,
)}
{...props}
/>
);
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
className,
)}
{...props}
/>
);
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className,
)}
{...props}
/>
);
}
const fieldVariants = cva("group/field flex w-full gap-2 data-[invalid=true]:text-destructive", {
variants: {
orientation: {
vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
horizontal:
"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
responsive:
"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
},
},
defaultVariants: {
orientation: "vertical",
},
});
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
);
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn("group/field-content flex flex-1 flex-col gap-0.5 leading-snug", className)}
{...props}
/>
);
}
function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
className,
)}
{...props}
/>
);
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
className,
)}
{...props}
/>
);
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
"last:mt-0 nth-last-2:-mt-1",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className,
)}
{...props}
/>
);
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode;
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className,
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
);
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>;
}) {
const content = useMemo(() => {
if (children) {
return children;
}
if (!errors?.length) {
return null;
}
const uniqueErrors = [...new Map(errors.map((error) => [error?.message, error])).values()];
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message;
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map((error, index) => error?.message && <li key={index}>{error.message}</li>)}
</ul>
);
}, [children, errors]);
if (!content) {
return null;
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
);
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
};
+144
View File
@@ -0,0 +1,144 @@
"use client";
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
"group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
className,
)}
{...props}
/>
);
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
"inline-start": "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
"inline-end": "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
"block-start":
"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
"block-end":
"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
},
},
defaultVariants: {
align: "inline-start",
},
},
);
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return;
}
e.currentTarget.parentElement?.querySelector("input")?.focus();
}}
{...props}
/>
);
}
const inputGroupButtonVariants = cva("flex items-center gap-2 text-sm shadow-none", {
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
sm: "",
"icon-xs": "size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
});
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size"> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
);
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function InputGroupInput({ className, ...props }: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className,
)}
{...props}
/>
);
}
function InputGroupTextarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className,
)}
{...props}
/>
);
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
};
+18
View File
@@ -0,0 +1,18 @@
import * as React from "react";
import { cn } from "cn";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className,
)}
{...props}
/>
);
}
export { Input };
+20
View File
@@ -0,0 +1,20 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Label as LabelPrimitive } from "radix-ui";
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className,
)}
{...props}
/>
);
}
export { Label };
+184
View File
@@ -0,0 +1,184 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Select as SelectPrimitive } from "radix-ui";
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react";
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
);
}
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
data-align-trigger={position === "item-aligned"}
className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
data-position={position}
className={cn(
"data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",
position === "popper" && "",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};
+27
View File
@@ -0,0 +1,27 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Separator as SeparatorPrimitive } from "radix-ui";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className,
)}
{...props}
/>
);
}
export { Separator };
+130
View File
@@ -0,0 +1,130 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Dialog as SheetPrimitive } from "radix-ui";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = "right",
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
showCloseButton?: boolean;
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
data-side={side}
className={cn(
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close data-slot="sheet-close" asChild>
<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-0.5 p-4", className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("font-heading text-base font-medium text-foreground", className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
+671
View File
@@ -0,0 +1,671 @@
"use client";
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import { Slot } from "radix-ui";
import { useIsMobile } from "@/hooks/use-mobile";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { PanelLeftIcon } from "lucide-react";
const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
className,
)}
{...props}
>
{children}
</div>
</SidebarContext.Provider>
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
dir,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
className,
)}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
dir={dir}
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
className="group peer hidden text-sidebar-foreground md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)}
/>
<div
data-slot="sidebar-container"
data-side={side}
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className,
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"
>
{children}
</div>
</div>
</div>
);
}
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon-sm"
className={cn(className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar();
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className,
)}
{...props}
/>
);
}
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("h-8 w-full bg-background shadow-none", className)}
{...props}
/>
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div";
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
className,
)}
{...props}
/>
);
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "button";
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
className,
)}
{...props}
/>
);
}
function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-0", className)}
{...props}
/>
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot.Root : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
);
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}) {
const Comp = asChild ? Slot.Root : "button";
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",
className,
)}
{...props}
/>
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const [width] = React.useState(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
});
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
);
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}) {
const Comp = asChild ? Slot.Root : "a";
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
className,
)}
{...props}
/>
);
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};
+13
View File
@@ -0,0 +1,13 @@
import { cn } from "cn";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
);
}
export { Skeleton };
+45
View File
@@ -0,0 +1,45 @@
"use client";
import { useTheme } from "next-themes";
import { Toaster as Sonner, type ToasterProps } from "sonner";
import {
CircleCheckIcon,
InfoIcon,
TriangleAlertIcon,
OctagonXIcon,
Loader2Icon,
} from "lucide-react";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
toastOptions={{
classNames: {
toast: "cn-toast",
},
}}
{...props}
/>
);
};
export { Toaster };
+88
View File
@@ -0,0 +1,88 @@
"use client";
import * as React from "react";
import { cn } from "cn";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div data-slot="table-container" className="relative w-full overflow-x-auto">
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return <thead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} />;
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
);
}
function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
+79
View File
@@ -0,0 +1,79 @@
"use client";
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import { Tabs as TabsPrimitive } from "radix-ui";
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
className={cn("group/tabs flex gap-2 data-horizontal:flex-col", className)}
{...props}
/>
);
}
const tabsListVariants = cva(
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
},
);
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
);
}
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
"data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
className,
)}
{...props}
/>
);
}
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 text-sm outline-none", className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react";
import { cn } from "cn";
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className,
)}
{...props}
/>
);
}
export { Textarea };
+52
View File
@@ -0,0 +1,52 @@
"use client";
import * as React from "react";
import { cn } from "cn";
import { Tooltip as TooltipPrimitive } from "radix-ui";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
}
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
View File
+250
View File
@@ -0,0 +1,250 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { z } from "zod";
import { tr } from "@/i18n/tr";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { getAuth } from "@/lib/auth";
import { authErrorCode } from "@/lib/auth-errors";
import { getActionUser } from "@/lib/dal";
import { storedEmail } from "@/shared/account-email";
import { systemRoleSchema, type SystemRole } from "@/shared/schemas/common";
import {
banUserSchema,
setPasswordSchema,
userCreateSchema,
userUpdateSchema,
} from "@/shared/schemas/user";
import { checkAdminAction, type AdminAction, type GuardViolation } from "./guards";
/**
* Admin kullanıcı yönetimi Server Action'ları.
* Sıra: yetki (sunucuda) → zod doğrulama → iş kuralları (guards) → Better Auth admin API → revalidate.
*/
const t = tr.adminUsers;
const PATH = "/admin/kullanicilar";
const userIdSchema = z.string().min(1).max(64);
const guardMessage = (v: GuardViolation) => (v === "self" ? t.guards.self : t.guards.lastAdmin);
/** Bilinen Better Auth hata kodlarını kullanıcıya gösterilecek alan hatalarına çevirir. */
function mapAuthError(error: unknown): ActionResult<never> {
const code = authErrorCode(error);
switch (code) {
case "USERNAME_IS_ALREADY_TAKEN":
return fail(t.errors.checkFields, { username: t.errors.usernameTaken });
case "USER_ALREADY_EXISTS":
case "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL":
return fail(t.errors.checkFields, { email: t.errors.emailTaken });
case "INVALID_USERNAME":
case "USERNAME_TOO_SHORT":
case "USERNAME_TOO_LONG":
return fail(t.errors.checkFields, { username: tr.validation.usernameFormat });
case "INVALID_EMAIL":
return fail(t.errors.checkFields, { email: tr.validation.email });
case "PASSWORD_TOO_SHORT":
case "PASSWORD_TOO_LONG":
return fail(t.errors.checkFields, { password: tr.validation.passwordMin });
case "YOU_CANNOT_BAN_YOURSELF":
case "YOU_CANNOT_REMOVE_YOURSELF":
return fail(t.guards.self);
default:
// İç detay kullanıcıya sızdırılmaz; sunucuda loglanır.
console.error("[admin-users] beklenmeyen hata", code ?? error);
return fail(tr.common.genericError);
}
}
/** Fiziksel kontrol: oturumdaki kullanıcı admin mi? Değilse işlem yapılmaz. */
async function adminContext() {
const actor = await getActionUser("admin");
if (!actor) return null;
return { actor, headers: await headers(), api: getAuth().api };
}
type Ctx = NonNullable<Awaited<ReturnType<typeof adminContext>>>;
async function loadTarget(ctx: Ctx, userId: string) {
try {
const user = await ctx.api.getUser({ headers: ctx.headers, query: { id: userId } });
return user
? {
id: user.id,
role: (user.role === "admin" ? "admin" : "user") as SystemRole,
name: user.name,
}
: null;
} catch {
return null;
}
}
async function countAdmins(ctx: Ctx): Promise<number> {
const result = await ctx.api.listUsers({
headers: ctx.headers,
query: { filterField: "role", filterOperator: "eq", filterValue: "admin", limit: 1 },
});
return result.total;
}
async function guard(ctx: Ctx, action: AdminAction, target: { id: string; role: SystemRole }) {
const adminCount = target.role === "admin" ? await countAdmins(ctx) : Number.POSITIVE_INFINITY;
return checkAdminAction(action, { actorId: ctx.actor.id, target, adminCount });
}
// --- Action'lar ---
export async function createUserAction(input: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const parsed = userCreateSchema.safeParse(input);
if (!parsed.success) return fail(t.errors.checkFields);
const v = parsed.data;
try {
await ctx.api.createUser({
headers: ctx.headers,
body: {
name: v.name,
email: storedEmail(v.username, v.email),
password: v.password,
role: v.role,
data: { username: v.username },
},
});
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
export async function updateUserAction(userId: unknown, input: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
const parsed = userUpdateSchema.safeParse(input);
if (!id.success || !parsed.success) return fail(t.errors.checkFields);
const target = await loadTarget(ctx, id.data);
if (!target) return fail(tr.common.notFound);
const v = parsed.data;
if (v.role !== target.role) {
const violation = await guard(ctx, { type: "setRole", role: v.role }, target);
if (violation) return fail(guardMessage(violation), { role: guardMessage(violation) });
}
try {
await ctx.api.adminUpdateUser({
headers: ctx.headers,
body: {
userId: target.id,
data: { name: v.name, username: v.username, email: storedEmail(v.username, v.email) },
},
});
if (v.role !== target.role) {
await ctx.api.setRole({ headers: ctx.headers, body: { userId: target.id, role: v.role } });
}
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
export async function setRoleAction(userId: unknown, role: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
const r = systemRoleSchema.safeParse(role);
if (!id.success || !r.success) return fail(tr.common.genericError);
const target = await loadTarget(ctx, id.data);
if (!target) return fail(tr.common.notFound);
const violation = await guard(ctx, { type: "setRole", role: r.data }, target);
if (violation) return fail(guardMessage(violation));
try {
await ctx.api.setRole({ headers: ctx.headers, body: { userId: target.id, role: r.data } });
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
export async function setPasswordAction(userId: unknown, input: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
const parsed = setPasswordSchema.safeParse(input);
if (!id.success || !parsed.success) return fail(t.errors.checkFields);
const target = await loadTarget(ctx, id.data);
if (!target) return fail(tr.common.notFound);
try {
await ctx.api.setUserPassword({
headers: ctx.headers,
body: { userId: target.id, newPassword: parsed.data.password },
});
// Başka bir kullanıcının şifresi sıfırlandıysa açık oturumlarını kapat.
if (target.id !== ctx.actor.id) {
await ctx.api.revokeUserSessions({ headers: ctx.headers, body: { userId: target.id } });
}
} catch (error) {
return mapAuthError(error);
}
return ok(undefined);
}
export async function banUserAction(userId: unknown, input: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
const parsed = banUserSchema.safeParse(input);
if (!id.success || !parsed.success) return fail(t.errors.checkFields);
const target = await loadTarget(ctx, id.data);
if (!target) return fail(tr.common.notFound);
const violation = await guard(ctx, { type: "ban" }, target);
if (violation) return fail(guardMessage(violation));
try {
// banUser açık oturumları da sonlandırır.
await ctx.api.banUser({
headers: ctx.headers,
body: { userId: target.id, banReason: parsed.data.reason },
});
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
export async function unbanUserAction(userId: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
if (!id.success) return fail(tr.common.genericError);
try {
await ctx.api.unbanUser({ headers: ctx.headers, body: { userId: id.data } });
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
export async function removeUserAction(userId: unknown): Promise<ActionResult> {
const ctx = await adminContext();
if (!ctx) return fail(tr.common.unauthorized);
const id = userIdSchema.safeParse(userId);
if (!id.success) return fail(tr.common.genericError);
const target = await loadTarget(ctx, id.data);
if (!target) return fail(tr.common.notFound);
const violation = await guard(ctx, { type: "delete" }, target);
if (violation) return fail(guardMessage(violation));
try {
await ctx.api.removeUser({ headers: ctx.headers, body: { userId: target.id } });
} catch (error) {
return mapAuthError(error);
}
revalidatePath(PATH);
return ok(undefined);
}
@@ -0,0 +1,219 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { PasswordInput } from "@/components/password-input";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Textarea } from "@/components/ui/textarea";
import { tr } from "@/i18n/tr";
import type { ActionResult } from "@/lib/action-result";
import {
banUserSchema,
setPasswordSchema,
type BanUserInput,
type SetPasswordInput,
} from "@/shared/schemas/user";
import type { AdminUser } from "../types";
const t = tr.adminUsers;
type DialogProps<T> = {
user: AdminUser | undefined;
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: (user: AdminUser, values: T) => Promise<ActionResult>;
};
export function SetPasswordDialog({
user,
open,
onOpenChange,
onConfirm,
}: DialogProps<{ password: string }>) {
const form = useForm<SetPasswordInput>({
resolver: zodResolver(setPasswordSchema),
defaultValues: { password: "" },
});
useEffect(() => {
if (open) form.reset({ password: "" });
}, [open, form]);
async function onSubmit(values: SetPasswordInput) {
if (!user) return;
const result = await onConfirm(user, values);
if (result.ok) onOpenChange(false);
else form.setError("root", { message: result.error });
}
return (
<ResponsiveDialog
open={open}
onOpenChange={onOpenChange}
title={t.password.title}
description={user ? t.password.description(user.name) : undefined}
footer={
<>
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
{tr.common.cancel}
</Button>
<Button type="submit" form="password-form" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
{t.password.confirm}
</Button>
</>
}
>
<form id="password-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
<FieldGroup>
<Controller
name="password"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="new-password">{t.password.newPassword}</FieldLabel>
<PasswordInput
{...field}
id="new-password"
autoComplete="new-password"
aria-invalid={fieldState.invalid}
aria-describedby="new-password-hint"
/>
<FieldDescription id="new-password-hint">{t.form.passwordHint}</FieldDescription>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
{form.formState.errors.root ? (
<FieldError>{form.formState.errors.root.message}</FieldError>
) : null}
</FieldGroup>
</form>
</ResponsiveDialog>
);
}
export function BanUserDialog({
user,
open,
onOpenChange,
onConfirm,
}: DialogProps<{ reason?: string }>) {
const form = useForm<BanUserInput, unknown, { reason?: string }>({
resolver: zodResolver(banUserSchema),
defaultValues: { reason: "" },
});
useEffect(() => {
if (open) form.reset({ reason: "" });
}, [open, form]);
async function onSubmit(values: { reason?: string }) {
if (!user) return;
const result = await onConfirm(user, values);
if (result.ok) onOpenChange(false);
else form.setError("root", { message: result.error });
}
return (
<ResponsiveDialog
open={open}
onOpenChange={onOpenChange}
title={t.ban.title}
description={user ? t.ban.description(user.name) : undefined}
footer={
<>
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
{tr.common.cancel}
</Button>
<Button
type="submit"
form="ban-form"
variant="destructive"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? <Loader2 className="animate-spin" /> : null}
{t.ban.confirm}
</Button>
</>
}
>
<form id="ban-form" onSubmit={form.handleSubmit(onSubmit)} noValidate>
<FieldGroup>
<Controller
name="reason"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="ban-reason">{t.ban.reason}</FieldLabel>
<Textarea
{...field}
value={field.value ?? ""}
id="ban-reason"
rows={3}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
{form.formState.errors.root ? (
<FieldError>{form.formState.errors.root.message}</FieldError>
) : null}
</FieldGroup>
</form>
</ResponsiveDialog>
);
}
export function DeleteUserDialog({ user, open, onOpenChange, onConfirm }: DialogProps<void>) {
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
function handleOpenChange(next: boolean) {
if (!next) setError(null);
onOpenChange(next);
}
async function confirm() {
if (!user) return;
setPending(true);
const result = await onConfirm(user, undefined);
setPending(false);
if (result.ok) handleOpenChange(false);
else setError(result.error);
}
return (
<AlertDialog open={open} onOpenChange={handleOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t.remove.title}</AlertDialogTitle>
<AlertDialogDescription>
{user ? t.remove.description(user.name) : null}
</AlertDialogDescription>
</AlertDialogHeader>
{error ? <FieldError>{error}</FieldError> : null}
<AlertDialogFooter>
<AlertDialogCancel disabled={pending}>{tr.common.cancel}</AlertDialogCancel>
{/* AlertDialogAction otomatik kapanır; sonuç beklenmesi için normal düğme. */}
<Button variant="destructive" onClick={confirm} disabled={pending}>
{pending ? <Loader2 className="animate-spin" /> : null}
{t.remove.confirm}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -0,0 +1,226 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useEffect } from "react";
import { Controller, useForm, type Resolver } from "react-hook-form";
import { PasswordInput } from "@/components/password-input";
import { ResponsiveDialog } from "@/components/responsive-dialog";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { tr } from "@/i18n/tr";
import type { ActionResult } from "@/lib/action-result";
import { SYSTEM_ROLES } from "@/shared/schemas/common";
import {
userCreateSchema,
userUpdateSchema,
type UserCreate,
type UserCreateInput,
type UserUpdate,
} from "@/shared/schemas/user";
import type { AdminUser } from "../types";
const t = tr.adminUsers.form;
const FORM_ID = "user-form";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
/** Verilirse düzenleme modu. */
user?: AdminUser;
onCreate: (values: UserCreate) => Promise<ActionResult>;
onUpdate: (id: string, values: UserUpdate) => Promise<ActionResult>;
};
type FormOutput = UserCreate | UserUpdate;
const createResolver: Resolver<UserCreateInput, unknown, FormOutput> =
zodResolver(userCreateSchema);
/**
* Düzenleme şeması şifre alanını içermez; zod nesnesi bilinmeyen alanı (boş "password") atar.
* Form değer şekli aynı kaldığı için tip dönüşümü güvenlidir.
*/
const updateResolver = zodResolver(userUpdateSchema) as unknown as Resolver<
UserCreateInput,
unknown,
FormOutput
>;
const empty: UserCreateInput = { name: "", username: "", email: "", role: "user", password: "" };
export function UserFormDialog({ open, onOpenChange, user, onCreate, onUpdate }: Props) {
const isEdit = Boolean(user);
const form = useForm<UserCreateInput, unknown, FormOutput>({
resolver: isEdit ? updateResolver : createResolver,
defaultValues: empty,
});
useEffect(() => {
if (open) {
form.reset(
user
? {
name: user.name,
username: user.username,
email: user.email ?? "",
role: user.role,
password: "",
}
: empty,
);
}
}, [open, user, form]);
async function onSubmit(values: FormOutput) {
const result = user ? await onUpdate(user.id, values) : await onCreate(values as UserCreate);
if (result.ok) {
onOpenChange(false);
return;
}
for (const [name, message] of Object.entries(result.fieldErrors ?? {})) {
if (message) form.setError(name as keyof UserCreateInput, { message });
}
if (!result.fieldErrors) form.setError("root", { message: result.error });
}
const submitting = form.formState.isSubmitting;
return (
<ResponsiveDialog
open={open}
onOpenChange={onOpenChange}
title={isEdit ? t.editTitle : t.createTitle}
description={isEdit ? t.editDescription : t.createDescription}
footer={
<>
<Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
{tr.common.cancel}
</Button>
<Button type="submit" form={FORM_ID} disabled={submitting}>
{submitting ? <Loader2 className="animate-spin" /> : null}
{isEdit ? tr.common.save : tr.common.create}
</Button>
</>
}
>
<form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)} noValidate>
<FieldGroup>
<Controller
name="name"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="user-name">{t.name}</FieldLabel>
<Input
{...field}
id="user-name"
autoComplete="off"
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Controller
name="username"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="user-username">{t.username}</FieldLabel>
<Input
{...field}
id="user-username"
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby="user-username-hint"
/>
<FieldDescription id="user-username-hint">{t.usernameHint}</FieldDescription>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Controller
name="email"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="user-email">{t.email}</FieldLabel>
<Input
{...field}
value={field.value ?? ""}
id="user-email"
type="email"
inputMode="email"
autoComplete="off"
aria-invalid={fieldState.invalid}
aria-describedby="user-email-hint"
/>
<FieldDescription id="user-email-hint">{t.emailHint}</FieldDescription>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
<Controller
name="role"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="user-role">{t.role}</FieldLabel>
<Select name={field.name} value={field.value} onValueChange={field.onChange}>
<SelectTrigger
id="user-role"
aria-invalid={fieldState.invalid}
onBlur={field.onBlur}
>
<SelectValue>{tr.roles[field.value]}</SelectValue>
</SelectTrigger>
<SelectContent>
{SYSTEM_ROLES.map((r) => (
<SelectItem key={r} value={r}>
{tr.roles[r]}
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
{!isEdit ? (
<Controller
name="password"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="user-password">{t.password}</FieldLabel>
<PasswordInput
{...field}
id="user-password"
autoComplete="new-password"
aria-invalid={fieldState.invalid}
aria-describedby="user-password-hint"
/>
<FieldDescription id="user-password-hint">{t.passwordHint}</FieldDescription>
{fieldState.invalid ? <FieldError errors={[fieldState.error]} /> : null}
</Field>
)}
/>
) : null}
{form.formState.errors.root ? (
<FieldError>{form.formState.errors.root.message}</FieldError>
) : null}
</FieldGroup>
</form>
</ResponsiveDialog>
);
}
@@ -0,0 +1,532 @@
"use client";
import {
ArrowDown,
ArrowUp,
ArrowUpDown,
Ban,
ChevronLeft,
ChevronRight,
KeyRound,
MoreHorizontal,
Pencil,
Plus,
Search,
ShieldCheck,
ShieldOff,
Trash2,
UserCheck,
} from "lucide-react";
import { createContext, use, useState } from "react";
import { toast } from "sonner";
import {
columnFilteringFeature,
createColumnHelper,
createFilteredRowModel,
createPaginatedRowModel,
createSortedRowModel,
globalFilteringFeature,
rowPaginationFeature,
rowSortingFeature,
tableFeatures,
useTable,
type SortFn,
} from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { tr } from "@/i18n/tr";
import { fail, type ActionResult } from "@/lib/action-result";
import { cn } from "@/lib/utils";
import { formatDate } from "@/shared/format";
import type { SystemRole } from "@/shared/schemas/common";
import type { UserCreate, UserUpdate } from "@/shared/schemas/user";
import { compareTr, includesTr } from "@/shared/search";
import {
banUserAction,
createUserAction,
removeUserAction,
setPasswordAction,
setRoleAction,
unbanUserAction,
updateUserAction,
} from "../actions";
import { checkAdminAction, type AdminAction, type GuardViolation } from "../guards";
import type { AdminUser } from "../types";
import { BanUserDialog, DeleteUserDialog, SetPasswordDialog } from "./user-action-dialogs";
import { UserFormDialog } from "./user-form-dialog";
const t = tr.adminUsers;
// --- Tablo yapılandırması (modül seviyesinde sabit: v9 kararlı girdi ister) ---
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
columnFilteringFeature,
globalFilteringFeature,
filteredRowModel: createFilteredRowModel(),
rowPaginationFeature,
paginatedRowModel: createPaginatedRowModel(),
});
const byTr: SortFn<typeof features, AdminUser> = (a, b, id) =>
compareTr(String(a.getValue(id) ?? ""), String(b.getValue(id) ?? ""));
const helper = createColumnHelper<typeof features, AdminUser>();
/** Mobilde gizlenen sütunlar. */
const COLUMN_CLASS: Partial<Record<string, string>> = {
username: "hidden sm:table-cell",
email: "hidden lg:table-cell",
createdAt: "hidden md:table-cell",
actions: "w-12 text-right",
};
const PAGE_SIZES = [10, 20, 50] as const;
type DialogState =
{ kind: "create" } | { kind: "edit" | "password" | "ban" | "delete"; user: AdminUser } | null;
function SortableHeader({
label,
sorted,
onToggle,
}: {
label: string;
sorted: false | "asc" | "desc";
onToggle: ((event: unknown) => void) | undefined;
}) {
const Icon = sorted === "asc" ? ArrowUp : sorted === "desc" ? ArrowDown : ArrowUpDown;
return (
<Button
variant="ghost"
size="sm"
className="-ml-2.5"
onClick={onToggle}
aria-label={`${label} — sırala`}
>
{label}
<Icon className={cn("size-3.5", !sorted && "opacity-40")} />
</Button>
);
}
type RowActionsApi = {
currentUserId: string;
guard: (action: AdminAction, target: AdminUser) => GuardViolation | null;
guardMessage: (v: GuardViolation) => string;
setDialog: (d: DialogState) => void;
setRole: (user: AdminUser, role: SystemRole) => void;
unbanUser: (user: AdminUser) => void;
};
/** Satır aksiyonları güncel durumu context'ten okur; sütunlar modül seviyesinde sabit kalır. */
const RowActionsContext = createContext<RowActionsApi | null>(null);
function useRowActions() {
const ctx = use(RowActionsContext);
if (!ctx) throw new Error("RowActionsContext eksik");
return ctx;
}
function NameCell({ user }: { user: AdminUser }) {
const { currentUserId } = useRowActions();
return (
<div className="flex min-w-0 flex-col">
<span className="truncate font-medium">
{user.name}
{user.id === currentUserId ? (
<span className="ml-1.5 text-xs font-normal text-muted-foreground">({t.you})</span>
) : null}
</span>
<span className="truncate text-xs text-muted-foreground sm:hidden">@{user.username}</span>
</div>
);
}
function RowActions({ user }: { user: AdminUser }) {
const { guard, guardMessage, setDialog, setRole, unbanUser } = useRowActions();
const del = guard({ type: "delete" }, user);
const ban = guard({ type: "ban" }, user);
const toggleRole: SystemRole = user.role === "admin" ? "user" : "admin";
const role = guard({ type: "setRole", role: toggleRole }, user);
const blocked = del ?? role;
return (
// modal={false}: menüden açılan Dialog kapandıktan sonra sayfanın kilitli kalmasını önler.
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label={`${user.name} — ${tr.common.actions}`}>
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="truncate">{user.name}</DropdownMenuLabel>
<DropdownMenuItem onSelect={() => setDialog({ kind: "edit", user })}>
<Pencil />
{t.actions.edit}
</DropdownMenuItem>
<DropdownMenuItem disabled={Boolean(role)} onSelect={() => setRole(user, toggleRole)}>
{toggleRole === "admin" ? <ShieldCheck /> : <ShieldOff />}
{toggleRole === "admin" ? t.actions.makeAdmin : t.actions.makeUser}
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setDialog({ kind: "password", user })}>
<KeyRound />
{t.actions.resetPassword}
</DropdownMenuItem>
{user.banned ? (
<DropdownMenuItem onSelect={() => unbanUser(user)}>
<UserCheck />
{t.actions.unban}
</DropdownMenuItem>
) : (
<DropdownMenuItem
disabled={Boolean(ban)}
onSelect={() => setDialog({ kind: "ban", user })}
>
<Ban />
{t.actions.ban}
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
disabled={Boolean(del)}
onSelect={() => setDialog({ kind: "delete", user })}
>
<Trash2 />
{t.actions.delete}
</DropdownMenuItem>
{blocked ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground">{guardMessage(blocked)}</p>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
const columns = helper.columns([
helper.accessor("name", {
header: ({ column }) => (
<SortableHeader
label={t.columns.name}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
sortFn: byTr,
cell: ({ row }) => <NameCell user={row.original} />,
}),
helper.accessor("username", {
header: ({ column }) => (
<SortableHeader
label={t.columns.username}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
sortFn: byTr,
cell: ({ getValue }) => <span className="text-muted-foreground">@{getValue()}</span>,
}),
helper.accessor((u) => u.email ?? "", {
id: "email",
header: ({ column }) => (
<SortableHeader
label={t.columns.email}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
sortFn: byTr,
cell: ({ getValue }) =>
getValue() || <span className="text-muted-foreground">{t.noEmail}</span>,
}),
helper.accessor("role", {
header: ({ column }) => (
<SortableHeader
label={t.columns.role}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
cell: ({ getValue }) => (
<Badge variant={getValue() === "admin" ? "default" : "secondary"}>
{tr.roles[getValue()]}
</Badge>
),
}),
helper.accessor("banned", {
header: ({ column }) => (
<SortableHeader
label={t.columns.status}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
cell: ({ row }) =>
row.original.banned ? (
<Badge variant="destructive" title={row.original.banReason}>
{t.status.banned}
</Badge>
) : (
<Badge variant="outline" className="border-income/30 text-income">
{t.status.active}
</Badge>
),
}),
helper.accessor("createdAt", {
header: ({ column }) => (
<SortableHeader
label={t.columns.createdAt}
sorted={column.getIsSorted()}
onToggle={column.getToggleSortingHandler()}
/>
),
cell: ({ getValue }) => <span className="tabular-nums">{formatDate(getValue())}</span>,
}),
helper.display({
id: "actions",
header: () => <span className="sr-only">{tr.common.actions}</span>,
cell: ({ row }) => <RowActions user={row.original} />,
}),
]);
export function UsersTable({
users,
currentUserId,
}: {
users: AdminUser[];
currentUserId: string;
}) {
const [dialog, setDialog] = useState<DialogState>(null);
// Arayüzdeki kural kontrolü yalnızca erken geri bildirim içindir; asıl kontrol sunucuda.
const adminCount = users.filter((u) => u.role === "admin").length;
const guard = (action: AdminAction, target: AdminUser): GuardViolation | null =>
checkAdminAction(action, { actorId: currentUserId, target, adminCount });
const guardMessage = (v: GuardViolation) => (v === "self" ? t.guards.self : t.guards.lastAdmin);
/** Server Action'ı çağırır; başarıda bildirim gösterir. Sayfa revalidatePath ile tazelenir. */
async function run(promise: Promise<ActionResult>, success: string): Promise<ActionResult> {
try {
const result = await promise;
if (result.ok) toast.success(success);
return result;
} catch {
return fail(tr.common.genericError);
}
}
const createUser = (values: UserCreate) =>
run(createUserAction(values), t.toast.created(values.name));
const updateUser = (id: string, values: UserUpdate) =>
run(updateUserAction(id, values), t.toast.updated(values.name));
async function setRole(user: AdminUser, role: SystemRole) {
const result = await run(setRoleAction(user.id, role), t.toast.roleChanged(user.name));
if (!result.ok) toast.error(result.error);
}
const setPassword = (user: AdminUser, values: { password: string }) =>
run(setPasswordAction(user.id, values), t.toast.passwordSet(user.name));
const banUser = (user: AdminUser, values: { reason?: string }) =>
run(banUserAction(user.id, values), t.toast.banned(user.name));
async function unbanUser(user: AdminUser) {
const result = await run(unbanUserAction(user.id), t.toast.unbanned(user.name));
if (!result.ok) toast.error(result.error);
}
const removeUser = (user: AdminUser) =>
run(removeUserAction(user.id), t.toast.removed(user.name));
const table = useTable({
features,
columns,
data: users,
// Türkçe, büyük/küçük harf ve aksan duyarsız arama (ad, kullanıcı adı, e-posta).
globalFilterFn: (row, _columnId, filterValue) => {
const q = String(filterValue ?? "");
const u = row.original;
return includesTr(u.name, q) || includesTr(u.username, q) || includesTr(u.email, q);
},
getColumnCanGlobalFilter: (column) => column.id !== "actions",
initialState: {
sorting: [{ id: "createdAt", desc: true }],
pagination: { pageIndex: 0, pageSize: 10 },
},
});
const globalFilter = String(table.state.globalFilter ?? "");
const pageCount = Math.max(table.getPageCount(), 1);
const filteredCount = table.getFilteredRowModel().rows.length;
const selected = dialog && dialog.kind !== "create" ? dialog.user : undefined;
const close = (open: boolean) => !open && setDialog(null);
const rowActions: RowActionsApi = {
currentUserId,
guard,
guardMessage,
setDialog,
setRole,
unbanUser,
};
return (
<RowActionsContext value={rowActions}>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<InputGroup className="max-w-sm flex-1">
<InputGroupAddon>
<Search />
</InputGroupAddon>
<InputGroupInput
type="search"
value={globalFilter}
onChange={(e) => table.setGlobalFilter(e.target.value)}
placeholder={t.searchPlaceholder}
aria-label={tr.common.search}
/>
</InputGroup>
<Button className="ml-auto" onClick={() => setDialog({ kind: "create" })}>
<Plus />
{t.newUser}
</Button>
</div>
<div className="overflow-hidden rounded-xl border bg-card">
<Table>
<TableHeader>
{table.getHeaderGroups().map((group) => (
<TableRow key={group.id}>
{group.headers.map((header) => (
<TableHead key={header.id} className={COLUMN_CLASS[header.column.id]}>
{header.isPlaceholder ? null : <table.FlexRender header={header} />}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} className={cn(row.original.banned && "opacity-70")}>
{row.getAllCells().map((cell) => (
<TableCell key={cell.id} className={COLUMN_CLASS[cell.column.id]}>
<table.FlexRender cell={cell} />
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center text-muted-foreground"
>
{tr.common.noResults}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
<span>{tr.common.totalRows(filteredCount)}</span>
<div className="flex items-center gap-2">
<span className="hidden sm:inline">{tr.common.rowsPerPage}</span>
<Select
value={String(table.state.pagination.pageSize)}
onValueChange={(v) => table.setPageSize(Number(v))}
>
<SelectTrigger size="sm" aria-label={tr.common.rowsPerPage} className="w-18">
<SelectValue>{table.state.pagination.pageSize}</SelectValue>
</SelectTrigger>
<SelectContent>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="tabular-nums">
{tr.common.page(table.state.pagination.pageIndex + 1, pageCount)}
</span>
<Button
variant="outline"
size="icon-sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
aria-label={tr.common.previous}
>
<ChevronLeft />
</Button>
<Button
variant="outline"
size="icon-sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
aria-label={tr.common.next}
>
<ChevronRight />
</Button>
</div>
</div>
<UserFormDialog
open={dialog?.kind === "create" || dialog?.kind === "edit"}
onOpenChange={close}
user={dialog?.kind === "edit" ? dialog.user : undefined}
onCreate={createUser}
onUpdate={updateUser}
/>
<SetPasswordDialog
user={selected}
open={dialog?.kind === "password"}
onOpenChange={close}
onConfirm={setPassword}
/>
<BanUserDialog
user={selected}
open={dialog?.kind === "ban"}
onOpenChange={close}
onConfirm={banUser}
/>
<DeleteUserDialog
user={selected}
open={dialog?.kind === "delete"}
onOpenChange={close}
onConfirm={removeUser}
/>
</div>
</RowActionsContext>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { checkAdminAction } from "./guards";
const admin = { id: "a1", role: "admin" as const };
const user = { id: "u1", role: "user" as const };
describe("checkAdminAction", () => {
it("admin kendini silemez, askıya alamaz, rolünü düşüremez", () => {
const ctx = { actorId: "a1", target: admin, adminCount: 3 };
expect(checkAdminAction({ type: "delete" }, ctx)).toBe("self");
expect(checkAdminAction({ type: "ban" }, ctx)).toBe("self");
expect(checkAdminAction({ type: "setRole", role: "user" }, ctx)).toBe("self");
});
it("admin kendi bilgisini ve şifresini değiştirebilir", () => {
const ctx = { actorId: "a1", target: admin, adminCount: 1 };
expect(checkAdminAction({ type: "edit" }, ctx)).toBeNull();
expect(checkAdminAction({ type: "setPassword" }, ctx)).toBeNull();
expect(checkAdminAction({ type: "setRole", role: "admin" }, ctx)).toBeNull();
});
it("son admin silinemez, askıya alınamaz, düşürülemez", () => {
const ctx = { actorId: "x", target: admin, adminCount: 1 };
expect(checkAdminAction({ type: "delete" }, ctx)).toBe("lastAdmin");
expect(checkAdminAction({ type: "ban" }, ctx)).toBe("lastAdmin");
expect(checkAdminAction({ type: "setRole", role: "user" }, ctx)).toBe("lastAdmin");
});
it("birden çok admin varken başka bir admin düşürülebilir", () => {
const ctx = { actorId: "x", target: admin, adminCount: 2 };
expect(checkAdminAction({ type: "setRole", role: "user" }, ctx)).toBeNull();
expect(checkAdminAction({ type: "delete" }, ctx)).toBeNull();
});
it("normal kullanıcıya her işlem yapılabilir", () => {
const ctx = { actorId: "a1", target: user, adminCount: 1 };
for (const t of ["delete", "ban", "edit", "setPassword"] as const) {
expect(checkAdminAction({ type: t }, ctx)).toBeNull();
}
expect(checkAdminAction({ type: "setRole", role: "admin" }, ctx)).toBeNull();
});
});
+37
View File
@@ -0,0 +1,37 @@
import type { SystemRole } from "@/shared/schemas/common";
export type AdminAction =
| { type: "delete" }
| { type: "ban" }
| { type: "setRole"; role: SystemRole }
| { type: "edit" }
| { type: "setPassword" };
export type GuardContext = {
actorId: string;
target: { id: string; role: SystemRole };
/** Sistemdeki toplam admin sayısı (hedef dahil). */
adminCount: number;
};
export type GuardViolation = "self" | "lastAdmin";
/**
* Admin işlem kuralları (arayüz ve sunucu aynı fonksiyonu kullanır):
* - Admin kendini silemez, askıya alamaz ve kendi admin rolünü kaldıramaz.
* - Sistemdeki son admin silinemez, askıya alınamaz veya rolü düşürülemez.
*/
export function checkAdminAction(action: AdminAction, ctx: GuardContext): GuardViolation | null {
const isSelf = ctx.actorId === ctx.target.id;
const removesAdmin =
ctx.target.role === "admin" &&
(action.type === "delete" ||
action.type === "ban" ||
(action.type === "setRole" && action.role !== "admin"));
if (isSelf && (action.type === "delete" || action.type === "ban" || removesAdmin)) {
return "self";
}
if (removesAdmin && ctx.adminCount <= 1) return "lastAdmin";
return null;
}
+27
View File
@@ -0,0 +1,27 @@
import { visibleEmail } from "@/shared/account-email";
import type { AdminUser } from "./types";
type RawAdminUser = {
id: string;
name: string;
email: string;
username?: string | null;
role?: string | null;
banned?: boolean | null;
banReason?: string | null;
createdAt: Date | string;
};
/** Better Auth kullanıcı kaydını arayüz satırına çevirir (yer tutucu e-posta gizlenir). */
export function toAdminUser(u: RawAdminUser): AdminUser {
return {
id: u.id,
name: u.name,
username: u.username ?? "",
email: visibleEmail(u.email),
role: u.role === "admin" ? "admin" : "user",
banned: Boolean(u.banned),
banReason: u.banReason ?? undefined,
createdAt: new Date(u.createdAt).toISOString(),
};
}
+16
View File
@@ -0,0 +1,16 @@
import "server-only";
import { headers } from "next/headers";
import { getAuth } from "@/lib/auth";
import { requireRole } from "@/lib/dal";
import { toAdminUser } from "./mapper";
import type { AdminUser } from "./types";
/** Admin: tüm kullanıcılar (en yeni önce). Kişisel kullanım ölçeğinde tek sayfa yeterli. */
export async function listAdminUsers(): Promise<AdminUser[]> {
await requireRole("admin");
const result = await getAuth().api.listUsers({
headers: await headers(),
query: { limit: 1000, sortBy: "createdAt", sortDirection: "desc" },
});
return result.users.map(toAdminUser);
}
+14
View File
@@ -0,0 +1,14 @@
import type { SystemRole } from "@/shared/schemas/common";
/** Admin kullanıcı listesindeki satır (Better Auth user kaydının arayüz özeti). */
export type AdminUser = {
id: string;
name: string;
username: string;
email?: string;
role: SystemRole;
banned: boolean;
banReason?: string;
/** ISO tarih (UTC) */
createdAt: string;
};
+11
View File
@@ -0,0 +1,11 @@
import type { SystemRole } from "@/shared/schemas/common";
/** Oturumdaki kullanıcının arayüzde ihtiyaç duyulan özeti. */
export type SessionUser = {
id: string;
name: string;
username: string;
email?: string;
role: SystemRole;
image?: string;
};
@@ -0,0 +1,16 @@
import { Skeleton } from "@/components/ui/skeleton";
import { tr } from "@/i18n/tr";
export function SummaryCardsSkeleton() {
return (
<div
role="status"
aria-label={tr.common.loading}
className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6"
>
{Array.from({ length: 6 }, (_, i) => (
<Skeleton key={i} className="h-24 rounded-xl" />
))}
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
import type { HouseholdSummary } from "./types";
/** FAZ 2 GEÇİCİ: Faz 5'te kullanıcının üye olduğu hanelerle değiştirilecek. */
export const MOCK_HOUSEHOLDS: HouseholdSummary[] = [
{ id: "h_cakir", name: "Çakır Ailesi", role: "owner" },
{ id: "h_anne", name: "Annemler", role: "viewer" },
];
+8
View File
@@ -0,0 +1,8 @@
export const HOUSEHOLD_ROLES = ["owner", "member", "viewer"] as const;
export type HouseholdRole = (typeof HOUSEHOLD_ROLES)[number];
export type HouseholdSummary = {
id: string;
name: string;
role: HouseholdRole;
};
+22
View File
@@ -0,0 +1,22 @@
import { useSyncExternalStore } from "react";
const MOBILE_BREAKPOINT = 768;
const QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
function subscribe(onChange: () => void) {
const mql = window.matchMedia(QUERY);
mql.addEventListener("change", onChange);
return () => mql.removeEventListener("change", onChange);
}
/**
* Ekran mobil genişlikte mi (< 768px)? Sunucuda ve hydration sırasında `false` döner,
* ardından tarayıcı değerine geçer (effect içinde setState yok).
*/
export function useIsMobile() {
return useSyncExternalStore(
subscribe,
() => window.matchMedia(QUERY).matches,
() => false,
);
}
+199 -3
View File
@@ -1,15 +1,211 @@
/**
* Arayüz metinleri (tr-TR). Tüm kullanıcıya görünen metinler burada toplanır.
* Arayüz metinleri (tr-TR). Kullanıcıya görünen tüm metinler burada toplanır.
* Şimdilik tek dil; ileride çok dil gerekirse bu nesnenin şekli sözleşme olur.
*/
export const tr = {
app: {
name: "BÜTÇEM",
tagline: "Aile bütçesi, birikim, ev stoğu ve akıllı alışveriş",
setupInProgress: "Kurulum sürüyor",
setupDescription: "Altyapı hazır. Giriş ekranı ve arayüz bir sonraki fazda eklenecek.",
version: "Sürüm",
},
common: {
save: "Kaydet",
cancel: "Vazgeç",
close: "Kapat",
delete: "Sil",
edit: "Düzenle",
create: "Oluştur",
search: "Ara",
actions: "İşlemler",
loading: "Yükleniyor…",
comingSoon: "Yakında",
required: "Bu alan zorunlu",
yes: "Evet",
no: "Hayır",
previous: "Önceki",
next: "Sonraki",
noResults: "Sonuç bulunamadı.",
page: (current: number, total: number) => `Sayfa ${current} / ${total}`,
rowsPerPage: "Sayfa başına",
totalRows: (n: number) => `Toplam ${n} kayıt`,
showPassword: "Şifreyi göster",
hidePassword: "Şifreyi gizle",
genericError: "Beklenmeyen bir hata oluştu. Lütfen tekrar deneyin.",
unauthorized: "Bu işlem için yetkiniz yok.",
notFound: "Kayıt bulunamadı.",
},
theme: {
label: "Tema",
light: "Açık",
dark: "Koyu",
system: "Sistem",
},
nav: {
main: "Menü",
dashboard: "Ana sayfa",
transactions: "İşlemler",
accounts: "Hesaplar",
budget: "Bütçe",
planned: "Planlı işlemler",
contacts: "Cari hesaplar",
savings: "Birikim",
stock: "Ev stoğu",
shopping: "Alışveriş",
reports: "Raporlar",
settings: "Ayarlar",
more: "Daha fazla",
admin: "Yönetim",
adminUsers: "Kullanıcılar",
adminHouseholds: "Haneler",
toggleSidebar: "Menüyü aç/kapat",
},
household: {
label: "Aktif hane",
select: "Hane seçin",
roles: { owner: "Sahip", member: "Üye", viewer: "İzleyici" },
},
userMenu: {
open: "Kullanıcı menüsü",
profile: "Profil",
logout: "Çıkış yap",
loggedOut: "Çıkış yapıldı.",
},
roles: { admin: "Yönetici", user: "Kullanıcı" },
quickAdd: {
button: "Hızlı ekle",
title: "Hızlı ekle",
description: "Ne eklemek istiyorsunuz?",
expense: "Gider",
income: "Gelir",
transfer: "Transfer",
expenseHint: "Harcama, fatura, alışveriş",
incomeHint: "Maaş, ek gelir, iade",
transferHint: "Hesaplar ve cariler arası",
notYet: "İşlem formu Faz 6'da eklenecek.",
},
auth: {
loginTitle: "Giriş yap",
loginDescription: "Hesabınıza kullanıcı adı veya e-posta ile giriş yapın.",
identifier: "Kullanıcı adı veya e-posta",
identifierPlaceholder: "ornek veya ornek@eposta.com",
password: "Şifre",
submit: "Giriş yap",
submitting: "Giriş yapılıyor…",
invalidCredentials: "Kullanıcı adı/e-posta veya şifre hatalı.",
banned: "Hesabınız askıya alınmış. Lütfen yöneticiyle iletişime geçin.",
tooManyAttempts: "Çok fazla deneme yapıldı. Lütfen bir dakika sonra tekrar deneyin.",
noSignUp: "Hesaplar yalnızca yönetici tarafından açılır.",
identifierRequired: "Kullanıcı adı veya e-posta girin",
passwordRequired: "Şifre girin",
},
dashboard: {
title: "Ana sayfa",
welcome: (name: string) => `Hoş geldin, ${name}`,
welcomeDescription: "Bu ayın özetini burada göreceksin. Veriler sonraki fazlarda bağlanacak.",
cards: {
monthIncome: "Bu ay gelir",
monthExpense: "Bu ay gider",
monthRemaining: "Kalan",
totalBalance: "Toplam hesap bakiyesi",
cardDebt: "Kart borçları",
netWorth: "Net varlık",
},
noData: "Henüz veri yok",
},
adminUsers: {
title: "Kullanıcılar",
description: "Kullanıcı oluşturma, rol, şifre ve erişim yönetimi.",
newUser: "Yeni kullanıcı",
searchPlaceholder: "Ad, kullanıcı adı veya e-posta ara…",
columns: {
name: "Ad soyad",
username: "Kullanıcı adı",
email: "E-posta",
role: "Rol",
status: "Durum",
createdAt: "Oluşturulma",
},
status: { active: "Aktif", banned: "Askıda" },
actions: {
edit: "Düzenle",
changeRole: "Rolü değiştir",
makeAdmin: "Yönetici yap",
makeUser: "Kullanıcı yap",
resetPassword: "Şifre sıfırla",
ban: "Askıya al",
unban: "Askıyı kaldır",
delete: "Sil",
},
form: {
createTitle: "Yeni kullanıcı",
createDescription: "Kullanıcı kendi hesabını açamaz; hesapları buradan oluşturun.",
editTitle: "Kullanıcıyı düzenle",
editDescription: "Ad, kullanıcı adı, e-posta ve rol bilgilerini güncelleyin.",
name: "Ad soyad",
username: "Kullanıcı adı",
usernameHint: "Küçük harf, rakam, nokta, alt çizgi; 3–30 karakter.",
email: "E-posta",
emailHint: "İsteğe bağlı. Boş bırakılırsa giriş kullanıcı adıyla yapılır.",
role: "Sistem rolü",
password: "Geçici şifre",
passwordHint: "En az 8 karakter. Kullanıcıya güvenli bir kanaldan iletin.",
},
password: {
title: "Şifre sıfırla",
description: (name: string) => `${name} için yeni bir şifre belirleyin.`,
newPassword: "Yeni şifre",
confirm: "Şifreyi belirle",
},
ban: {
title: "Kullanıcıyı askıya al",
description: (name: string) => `${name} giriş yapamayacak ve açık oturumları kapatılacak.`,
reason: "Neden (isteğe bağlı)",
confirm: "Askıya al",
},
remove: {
title: "Kullanıcı silinsin mi?",
description: (name: string) => `${name} kalıcı olarak silinecek. Bu işlem geri alınamaz.`,
confirm: "Kalıcı olarak sil",
},
toast: {
created: (name: string) => `${name} oluşturuldu.`,
updated: (name: string) => `${name} güncellendi.`,
roleChanged: (name: string) => `${name} için rol değiştirildi.`,
passwordSet: (name: string) => `${name} için şifre güncellendi.`,
banned: (name: string) => `${name} askıya alındı.`,
unbanned: (name: string) => `${name} için askı kaldırıldı.`,
removed: (name: string) => `${name} silindi.`,
},
guards: {
self: "Kendi hesabınız için bu işlem yapılamaz.",
lastAdmin: "Sistemdeki son yönetici silinemez veya rolü düşürülemez.",
},
errors: {
usernameTaken: "Bu kullanıcı adı kullanılıyor.",
emailTaken: "Bu e-posta adresi kullanılıyor.",
checkFields: "Lütfen işaretli alanları düzeltin.",
},
you: "Siz",
noEmail: "—",
},
validation: {
nameMin: "Ad en az 2 karakter olmalı",
nameMax: "Ad en fazla 80 karakter olabilir",
usernameFormat: "Yalnızca küçük harf, rakam, nokta ve alt çizgi; 3–30 karakter",
email: "Geçerli bir e-posta adresi girin",
passwordMin: "Şifre en az 8 karakter olmalı",
passwordMax: "Şifre en fazla 128 karakter olabilir",
banReasonMax: "Neden en fazla 200 karakter olabilir",
},
errors: {
notFoundTitle: "Sayfa bulunamadı",
notFoundDescription: "Aradığınız sayfa taşınmış veya hiç var olmamış olabilir.",
backHome: "Ana sayfaya dön",
errorTitle: "Bir şeyler ters gitti",
errorDescription: "Sayfa yüklenirken bir hata oluştu. Tekrar deneyebilirsiniz.",
retry: "Tekrar dene",
reference: "Hata kodu",
},
} as const;
export type Messages = typeof tr;
+17
View File
@@ -0,0 +1,17 @@
/**
* Server Action ve servis dönüş tipi (Faz 3+). Hata durumunda kullanıcıya gösterilecek
* genel mesaj ve isteğe bağlı alan bazlı hatalar döner; iç detay asla sızdırılmaz.
*/
export type ActionResult<T = void> =
| { ok: true; data: T }
| { ok: false; error: string; fieldErrors?: Partial<Record<string, string>> };
export const ok = <T>(data: T): ActionResult<T> => ({ ok: true, data });
export const fail = (
error: string,
fieldErrors?: Partial<Record<string, string>>,
): ActionResult<never> => ({
ok: false,
error,
fieldErrors,
});
+9
View File
@@ -0,0 +1,9 @@
"use client";
import { adminClient, usernameClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
/** Tarayıcı tarafı Better Auth istemcisi (aynı origin: /api/auth). */
export const authClient = createAuthClient({
plugins: [usernameClient(), adminClient()],
});
+8
View File
@@ -0,0 +1,8 @@
import { isAPIError } from "better-auth/api";
/** Better Auth hatasından makine okunur kodu çıkarır (ör. "USERNAME_IS_ALREADY_TAKEN"). */
export function authErrorCode(error: unknown): string | undefined {
if (!isAPIError(error)) return undefined;
const body = error.body as { code?: unknown } | undefined;
return typeof body?.code === "string" ? body.code : undefined;
}

Some files were not shown because too many files have changed in this diff Show More