Compare commits

...

2 Commits

Author SHA1 Message Date
suphicakir 440523b176 feat(arayüz): Tailwind + shadcn/ui tasarım sistemi, tema ve biçimlendirme
- Tailwind v4 + shadcn/ui (Radix), Inter yazı tipi (yerel)
- Tasarım token'ları: 4 ana grup (renk körlüğüne uygun) ve durum renkleri, WCAG AA
- Aydınlık / Karanlık / Sistem teması (ilk açılışta parlama yok)
- lib/format.ts: para (1.250,00 ₺), miktar, yüzde, tarih (GG.AA.YYYY), tutar ayrıştırma
- Vitest: 22 biçimlendirme testi; npm test artık frontend'i de çalıştırır
- Butonlar mobil dokunma alanına (≥44 px) göre büyütüldü

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 00:06:27 +03:00
suphicakir 6eb5440d4d feat(katalog): kategori ve ödeme türü uç noktaları, hane izolasyonu entegrasyon testleri
- /api/categories ve /api/payment-methods: listele, ekle, düzenle, sırala, pasife al
- Sürüm kontrolü ile eşzamanlı düzenleme çakışması (409)
- Backend lib + bin yapısına ayrıldı (entegrasyon testleri için)
- tests/: hane izolasyonu (3) ve katalog (4) entegrasyon testleri
- db:reset artık artık test veritabanlarını da siler
- api.http tamamlandı; Faz 1 tamamlandı

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:54:16 +03:00
39 changed files with 7306 additions and 157 deletions
+8 -3
View File
@@ -53,14 +53,19 @@ npm run dev # frontend (5173) + backend (8080) birlikte, hot reload
npm run dev:host # telefondan test için ağa aç
npm run db:up # yerel MongoDB (Docker)
npm run db:down
npm run db:seed / db:reset
npm test # backend testleri
npm run db:seed
npm run db:reset # kakeibo_dev + artık kakeibo_test_* veritabanlarını siler
npm test # backend (cargo test, MongoDB açık olmalı) + frontend (vitest)
npm run lint # clippy + oxlint
```
- `npm run dev` öncesinde DB otomatik başlar (`predev`).
- Yerel MongoDB host portu **27020** (27017 sistem mongod, 27018/27019 diğer projeler).
- Frontend lint: **oxlint** (Vite şablonu varsayılanı; ESLint yerine).
- Frontend lint: **oxlint** (Vite şablonu varsayılanı; ESLint yerine). `components/ui/**` shadcn dosyaları.
- Frontend: Tailwind v4 (`src/index.css` token'ları), shadcn/ui (style `radix-nova`, `cn` paketi), `@/` → `src/`. Renkler: `bg-needs`/`text-needs-fg`/`bg-needs-soft` (wants, culture, unexpected aynı), `text-income`/`text-expense`/`text-warning`. Tutarlarda `money` sınıfı. Butonlar ≥44 px (shadcn boyutları büyütüldü).
- Grup tanımları: `lib/groups.ts`; tema: `lib/theme.tsx` (+ `index.html` içindeki ilk-boya betiği); biçimlendirme: `lib/format.ts`.
- API örnekleri: `backend/api.http`
- Backend = lib (`src/lib.rs`) + bin (`src/main.rs`). Entegrasyon testleri `backend/tests/` (her test geçici `kakeibo_test_<uuid>` DB, `tests/common` yardımcıları).
- Hane izolasyonu: hane kimliği yalnızca `AuthUser.household_id`'den; sorgular `scope(hid)` ile başlar; başka hane → 404.
## Ortam
- Geliştirme makinesi: CachyOS (Arch), fish kabuğu, VS Code
+2
View File
@@ -1287,6 +1287,7 @@ dependencies = [
"axum",
"axum-extra",
"dotenvy",
"http-body-util",
"jsonwebtoken",
"mongodb",
"serde",
@@ -1294,6 +1295,7 @@ dependencies = [
"thiserror",
"time",
"tokio",
"tower",
"tracing",
"tracing-subscriber",
"uuid",
+4
View File
@@ -19,3 +19,7 @@ tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
uuid = { version = "1.29.2", features = ["v4", "v7"] }
validator = { version = "0.21.0", features = ["derive"] }
[dev-dependencies]
http-body-util = "0.1.5"
tower = { version = "0.5.3", features = ["util"] }
+66
View File
@@ -61,3 +61,69 @@ GET {{baseUrl}}/household/invites
### Daveti iptal et (yalnızca hane sahibi) — id'yi yukarıdaki listeden alın
DELETE {{baseUrl}}/household/invites/BURAYA-ID
# ─────────────────────────── Kategoriler ───────────────────────────
# Gruplar: needs (Zorunlu) · wants (İstek) · culture (Kültürel) · unexpected (Beklenmeyen)
# Silme yok; "is_active": false ile pasife alınır.
### Kategoriler (aktif olanlar; pasifler için ?include_inactive=true)
GET {{baseUrl}}/categories
### Kategori ekle (grubun sonuna eklenir)
POST {{baseUrl}}/categories
Content-Type: application/json
{
"group": "needs",
"name": "Aidat",
"emoji": "🏢"
}
### Kategori düzenle / pasife al — "version": listede gördüğünüz sürüm (başkası değiştirdiyse 409)
PATCH {{baseUrl}}/categories/BURAYA-ID
Content-Type: application/json
{
"name": "Site Aidatı",
"is_active": true,
"version": 1
}
### Grup içi sıralama — gruptaki TÜM kimlikler (pasifler dahil), istenen sırada
PUT {{baseUrl}}/categories/order
Content-Type: application/json
{
"group": "culture",
"ids": ["ID-1", "ID-2", "ID-3"]
}
# ─────────────────────────── Ödeme türleri ───────────────────────────
### Ödeme türleri
GET {{baseUrl}}/payment-methods
### Ödeme türü ekle
POST {{baseUrl}}/payment-methods
Content-Type: application/json
{
"name": "Yemek Kartı",
"emoji": "🍽️"
}
### Ödeme türü düzenle / pasife al
PATCH {{baseUrl}}/payment-methods/BURAYA-ID
Content-Type: application/json
{
"is_active": false
}
### Ödeme türü sıralama — TÜM kimlikler
PUT {{baseUrl}}/payment-methods/order
Content-Type: application/json
{
"ids": ["ID-1", "ID-2", "ID-3", "ID-4"]
}
-1
View File
@@ -55,7 +55,6 @@ pub async fn prepare(db: &Database) -> mongodb::error::Result<()> {
}
/// Koleksiyon adları (DATA_MODEL.md §3). Yazım hatasını derleyici yakalasın diye sabit.
#[allow(dead_code)] // Bazıları sonraki fazlarda kullanılacak
pub mod col {
pub const USERS: &str = "users";
pub const HOUSEHOLDS: &str = "households";
+13
View File
@@ -0,0 +1,13 @@
//! Kakeibo backend kütüphanesi.
//!
//! `main.rs` (çalıştırılabilir sunucu) ve `tests/` (entegrasyon testleri) bu modülleri kullanır.
pub mod auth;
pub mod config;
pub mod db;
pub mod error;
pub mod extract;
pub mod models;
pub mod routes;
pub mod services;
pub mod state;
+3 -24
View File
@@ -1,23 +1,8 @@
mod auth;
mod config;
mod db;
mod error;
mod extract;
mod models;
mod routes;
mod services;
mod state;
use std::{net::SocketAddr, process::ExitCode, sync::Arc, time::Duration};
use std::{net::SocketAddr, process::ExitCode};
use kakeibo::{config::Config, db, routes, state::AppState};
use tracing_subscriber::EnvFilter;
use crate::{
auth::{jwt::Jwt, limiter::LoginLimiter},
config::Config,
state::AppState,
};
#[tokio::main]
async fn main() -> ExitCode {
// .env dosyasını yükle (proje kökünde; üst klasörler de aranır). Yoksa sorun değil.
@@ -57,13 +42,7 @@ async fn main() -> ExitCode {
}
let port = config.port;
let state = AppState {
db,
jwt: Arc::new(Jwt::new(&config.jwt_secret)),
// Aynı e-postaya 15 dakikada en fazla 5 hatalı giriş denemesi
login_limiter: Arc::new(LoginLimiter::new(5, Duration::from_secs(15 * 60))),
config: Arc::new(config),
};
let state = AppState::new(db, config);
let app = routes::router(state);
let addr = SocketAddr::from(([0, 0, 0, 0], port));
-9
View File
@@ -36,15 +36,6 @@ pub fn scope(household_id: Uuid) -> Document {
doc! { "household_id": household_id, "deleted_at": null }
}
#[allow(dead_code)] // Faz 1 – Adım 5'te (kategori güncelleme) kullanılacak
/// Güncellemelerde eklenecek ortak kısım: `updated_at` yenilenir, `version` +1.
pub fn touch() -> Document {
doc! {
"$set": { "updated_at": now() },
"$inc": { "version": 1_i32 },
}
}
#[cfg(test)]
mod tests {
use super::*;
+39
View File
@@ -0,0 +1,39 @@
//! 4 sabit ana grup (DATA_MODEL.md §2). Değiştirilemez, silinemez; veritabanında değil kodda.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Group {
/// 🏠 Zorunlu
Needs,
/// 🛍️ İstek
Wants,
/// 📚 Kültürel
Culture,
/// ⚡ Beklenmeyen
Unexpected,
}
impl Group {
pub const ALL: [Group; 4] = [
Group::Needs,
Group::Wants,
Group::Culture,
Group::Unexpected,
];
pub fn as_str(self) -> &'static str {
match self {
Group::Needs => "needs",
Group::Wants => "wants",
Group::Culture => "culture",
Group::Unexpected => "unexpected",
}
}
/// Ekranda gösterim sırası
pub fn order(self) -> usize {
Self::ALL.iter().position(|g| *g == self).unwrap_or(0)
}
}
+1
View File
@@ -2,6 +2,7 @@
//! Şema: `docs/DATA_MODEL.md`
pub mod common;
pub mod group;
pub mod household;
pub mod invite;
pub mod user;
+230
View File
@@ -0,0 +1,230 @@
//! Kategori ve ödeme türü uç noktaları (hanenin tüm üyeleri kullanabilir):
//!
//! | Yöntem | Yol | İş |
//! |---|---|---|
//! | GET | `/api/categories?include_inactive=true` | listele |
//! | POST | `/api/categories` | ekle |
//! | PATCH | `/api/categories/{id}` | ad / emoji / aktiflik değiştir |
//! | PUT | `/api/categories/order` | sırala |
//!
//! `/api/payment-methods` aynı yapıdadır (yalnızca `group` alanı yoktur).
use axum::{
Json,
extract::{Path, Query, State},
http::StatusCode,
};
use mongodb::bson::Uuid;
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::{
auth::AuthUser,
error::{AppError, AppResult},
extract::ValidJson,
models::group::Group,
services::catalog::{self, Catalog, Changes, Item},
state::AppState,
};
// ---------- İstek / yanıt ----------
#[derive(Deserialize, Default)]
pub struct ListQuery {
#[serde(default)]
include_inactive: bool,
}
#[derive(Deserialize, Validate)]
pub struct CreateRequest {
group: Option<Group>,
#[validate(length(max = 40, message = "Ad en fazla 40 karakter olabilir"))]
name: String,
#[validate(length(max = 16, message = "Emoji çok uzun"))]
emoji: Option<String>,
}
#[derive(Deserialize, Validate)]
pub struct UpdateRequest {
#[validate(length(max = 40, message = "Ad en fazla 40 karakter olabilir"))]
name: Option<String>,
#[validate(length(max = 16, message = "Emoji çok uzun"))]
emoji: Option<String>,
is_active: Option<bool>,
version: Option<i32>,
}
#[derive(Deserialize, Validate)]
pub struct OrderRequest {
group: Option<Group>,
#[validate(length(max = 200, message = "Liste çok uzun"))]
ids: Vec<String>,
}
#[derive(Serialize)]
pub struct ItemDto {
id: String,
#[serde(skip_serializing_if = "Option::is_none")]
group: Option<Group>,
name: String,
emoji: Option<String>,
sort_order: i32,
is_active: bool,
version: i32,
}
impl From<Item> for ItemDto {
fn from(i: Item) -> Self {
Self {
id: i.id.to_string(),
group: i.group,
name: i.name,
emoji: i.emoji,
sort_order: i.sort_order,
is_active: i.is_active,
version: i.version,
}
}
}
fn dtos(items: Vec<Item>) -> Json<Vec<ItemDto>> {
Json(items.into_iter().map(ItemDto::from).collect())
}
/// URL'deki kimlik bozuksa "bulunamadı" (başka hanenin kaydıyla aynı yanıt).
fn parse_id(id: &str) -> AppResult<Uuid> {
Uuid::parse_str(id).map_err(|_| AppError::NotFound)
}
// ---------- Ortak işleyiciler ----------
async fn list(
c: Catalog,
state: AppState,
auth: AuthUser,
q: ListQuery,
) -> AppResult<Json<Vec<ItemDto>>> {
let items = catalog::list(&state.db, c, auth.household_id, q.include_inactive).await?;
Ok(dtos(items))
}
async fn create(
c: Catalog,
state: AppState,
auth: AuthUser,
req: CreateRequest,
) -> AppResult<(StatusCode, Json<ItemDto>)> {
let item = catalog::create(
&state.db,
c,
auth.household_id,
req.group,
req.name,
req.emoji,
)
.await?;
Ok((StatusCode::CREATED, Json(item.into())))
}
async fn update(
c: Catalog,
state: AppState,
auth: AuthUser,
id: String,
req: UpdateRequest,
) -> AppResult<Json<ItemDto>> {
let changes = Changes {
name: req.name,
emoji: req.emoji,
is_active: req.is_active,
version: req.version,
};
let item = catalog::update(&state.db, c, auth.household_id, parse_id(&id)?, changes).await?;
Ok(Json(item.into()))
}
async fn reorder(
c: Catalog,
state: AppState,
auth: AuthUser,
req: OrderRequest,
) -> AppResult<Json<Vec<ItemDto>>> {
let ids = req
.ids
.iter()
.map(Uuid::parse_str)
.collect::<Result<Vec<_>, _>>()
.map_err(|_| AppError::BadRequest("Sıralama listesinde geçersiz kimlik var".into()))?;
let items = catalog::reorder(&state.db, c, auth.household_id, req.group, ids).await?;
Ok(dtos(items))
}
// ---------- Kategoriler ----------
pub async fn list_categories(
State(s): State<AppState>,
auth: AuthUser,
Query(q): Query<ListQuery>,
) -> AppResult<Json<Vec<ItemDto>>> {
list(Catalog::Categories, s, auth, q).await
}
pub async fn create_category(
State(s): State<AppState>,
auth: AuthUser,
ValidJson(req): ValidJson<CreateRequest>,
) -> AppResult<(StatusCode, Json<ItemDto>)> {
create(Catalog::Categories, s, auth, req).await
}
pub async fn update_category(
State(s): State<AppState>,
auth: AuthUser,
Path(id): Path<String>,
ValidJson(req): ValidJson<UpdateRequest>,
) -> AppResult<Json<ItemDto>> {
update(Catalog::Categories, s, auth, id, req).await
}
pub async fn reorder_categories(
State(s): State<AppState>,
auth: AuthUser,
ValidJson(req): ValidJson<OrderRequest>,
) -> AppResult<Json<Vec<ItemDto>>> {
reorder(Catalog::Categories, s, auth, req).await
}
// ---------- Ödeme türleri ----------
pub async fn list_payment_methods(
State(s): State<AppState>,
auth: AuthUser,
Query(q): Query<ListQuery>,
) -> AppResult<Json<Vec<ItemDto>>> {
list(Catalog::PaymentMethods, s, auth, q).await
}
pub async fn create_payment_method(
State(s): State<AppState>,
auth: AuthUser,
ValidJson(req): ValidJson<CreateRequest>,
) -> AppResult<(StatusCode, Json<ItemDto>)> {
create(Catalog::PaymentMethods, s, auth, req).await
}
pub async fn update_payment_method(
State(s): State<AppState>,
auth: AuthUser,
Path(id): Path<String>,
ValidJson(req): ValidJson<UpdateRequest>,
) -> AppResult<Json<ItemDto>> {
update(Catalog::PaymentMethods, s, auth, id, req).await
}
pub async fn reorder_payment_methods(
State(s): State<AppState>,
auth: AuthUser,
ValidJson(req): ValidJson<OrderRequest>,
) -> AppResult<Json<Vec<ItemDto>>> {
reorder(Catalog::PaymentMethods, s, auth, req).await
}
+22 -2
View File
@@ -1,16 +1,18 @@
//! API route'larının tek giriş noktası. Tüm uç noktalar `/api` altında.
mod auth;
mod catalog;
mod health;
mod household;
use axum::{
Router,
routing::{delete, get, post},
routing::{delete, get, patch, post, put},
};
use crate::state::AppState;
/// Tüm API route'ları. Testler de bu fonksiyonu kullanır.
pub fn router(state: AppState) -> Router {
let api = Router::new()
.route("/health", get(health::health))
@@ -23,7 +25,25 @@ pub fn router(state: AppState) -> Router {
"/household/invites",
get(household::list_invites).post(household::create_invite),
)
.route("/household/invites/{id}", delete(household::revoke_invite));
.route("/household/invites/{id}", delete(household::revoke_invite))
.route(
"/categories",
get(catalog::list_categories).post(catalog::create_category),
)
.route("/categories/order", put(catalog::reorder_categories))
.route("/categories/{id}", patch(catalog::update_category))
.route(
"/payment-methods",
get(catalog::list_payment_methods).post(catalog::create_payment_method),
)
.route(
"/payment-methods/order",
put(catalog::reorder_payment_methods),
)
.route(
"/payment-methods/{id}",
patch(catalog::update_payment_method),
);
Router::new().nest("/api", api).with_state(state)
}
+318
View File
@@ -0,0 +1,318 @@
//! Kategoriler ve ödeme türleri için ortak iş mantığı (DATA_MODEL.md §3.5, §3.6).
//!
//! İkisi de aynı şekilde çalışır: listele, ekle, düzenle, sırala, pasife al.
//! Tek fark: kategoriler bir ana gruba (`group`) bağlıdır, ödeme türleri değil.
//! **Silme yoktur** — geçmiş harcama kayıtları bozulmasın diye yalnızca pasife alınır.
use mongodb::{
Database,
bson::{Bson, Document, Uuid, doc},
options::ReturnDocument,
};
use serde::Deserialize;
use crate::{
error::{AppError, AppResult},
models::{
common::{new_meta, now, scope},
group::Group,
},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Catalog {
Categories,
PaymentMethods,
}
impl Catalog {
fn collection(self) -> &'static str {
match self {
Catalog::Categories => crate::db::col::CATEGORIES,
Catalog::PaymentMethods => crate::db::col::PAYMENT_METHODS,
}
}
fn has_group(self) -> bool {
self == Catalog::Categories
}
fn noun(self) -> &'static str {
match self {
Catalog::Categories => "kategori",
Catalog::PaymentMethods => "ödeme türü",
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Item {
#[serde(rename = "_id")]
pub id: Uuid,
#[serde(default)]
pub group: Option<Group>,
pub name: String,
#[serde(default)]
pub emoji: Option<String>,
pub sort_order: i32,
pub is_active: bool,
pub version: i32,
}
#[derive(Debug, Default)]
pub struct Changes {
pub name: Option<String>,
/// `Some("")` → emoji kaldırılır
pub emoji: Option<String>,
pub is_active: Option<bool>,
/// İstemcinin gördüğü sürüm; farklıysa başkası değiştirmiş demektir → 409
pub version: Option<i32>,
}
fn coll(db: &Database, c: Catalog) -> mongodb::Collection<Item> {
db.collection(c.collection())
}
/// Hanenin kayıtları. Kategoriler grup sırasına, sonra `sort_order`'a göre sıralanır.
pub async fn list(
db: &Database,
c: Catalog,
household_id: Uuid,
include_inactive: bool,
) -> AppResult<Vec<Item>> {
let mut filter = scope(household_id);
if !include_inactive {
filter.insert("is_active", true);
}
let mut items = collect(coll(db, c).find(filter).await?).await?;
items.sort_by_key(|i| (i.group.map(Group::order), i.sort_order));
Ok(items)
}
pub async fn create(
db: &Database,
c: Catalog,
household_id: Uuid,
group: Option<Group>,
name: String,
emoji: Option<String>,
) -> AppResult<Item> {
let group = check_group(c, group)?;
let name = clean_name(&name)?;
ensure_unique_name(db, c, household_id, group, &name, None).await?;
// Grubun (veya listenin) en sonuna ekle
let mut last_filter = scope(household_id);
if let Some(g) = group {
last_filter.insert("group", g.as_str());
}
let last = coll(db, c)
.find_one(last_filter)
.sort(doc! { "sort_order": -1 })
.await?;
let sort_order = last.map_or(10, |i| i.sort_order + 10);
let mut d = new_meta(household_id);
let id = d.get("_id").cloned().unwrap_or(Bson::Null);
if let Some(g) = group {
d.insert("group", g.as_str());
}
d.insert("name", name);
d.insert("emoji", clean_emoji(emoji));
d.insert("sort_order", sort_order);
d.insert("is_active", true);
db.collection::<Document>(c.collection())
.insert_one(d)
.await?;
coll(db, c)
.find_one(doc! { "_id": id })
.await?
.ok_or_else(|| AppError::Internal("eklenen kayıt okunamadı".into()))
}
pub async fn update(
db: &Database,
c: Catalog,
household_id: Uuid,
id: Uuid,
changes: Changes,
) -> AppResult<Item> {
let mut filter = scope(household_id);
filter.insert("_id", id);
let current = coll(db, c)
.find_one(filter.clone())
.await?
.ok_or(AppError::NotFound)?;
if changes.version.is_some_and(|v| v != current.version) {
return Err(stale());
}
let mut set = doc! { "updated_at": now() };
if let Some(name) = changes.name {
let name = clean_name(&name)?;
if name != current.name {
ensure_unique_name(db, c, household_id, current.group, &name, Some(id)).await?;
}
set.insert("name", name);
}
if let Some(emoji) = changes.emoji {
set.insert("emoji", clean_emoji(Some(emoji)));
}
if let Some(active) = changes.is_active {
set.insert("is_active", active);
}
// Sürüm filtresi: okuma ile yazma arasında başkası değiştirdiyse güncelleme olmaz
filter.insert("version", current.version);
coll(db, c)
.find_one_and_update(filter, doc! { "$set": set, "$inc": { "version": 1 } })
.return_document(ReturnDocument::After)
.await?
.ok_or_else(stale)
}
/// Sıralamayı verilen kimlik listesine göre yeniden yazar.
/// Liste, (kategorilerde ilgili gruptaki) **tüm** kayıtları içermelidir — pasifler dahil.
pub async fn reorder(
db: &Database,
c: Catalog,
household_id: Uuid,
group: Option<Group>,
ids: Vec<Uuid>,
) -> AppResult<Vec<Item>> {
let group = check_group(c, group)?;
let mut filter = scope(household_id);
if let Some(g) = group {
filter.insert("group", g.as_str());
}
let existing = collect(coll(db, c).find(filter).await?).await?;
let mut want: Vec<Uuid> = ids.clone();
let mut have: Vec<Uuid> = existing.iter().map(|i| i.id).collect();
want.sort_by_key(|u| u.bytes());
have.sort_by_key(|u| u.bytes());
if want != have {
return Err(AppError::BadRequest(
"Sıralama listesi eksik veya hatalı, sayfayı yenileyip tekrar deneyin".into(),
));
}
let mut session = db.client().start_session().await?;
session.start_transaction().await?;
let ts = now();
for (i, id) in ids.iter().enumerate() {
let r = db
.collection::<Document>(c.collection())
.update_one(
doc! { "_id": id, "household_id": household_id },
doc! {
"$set": { "sort_order": (i as i32 + 1) * 10, "updated_at": ts },
"$inc": { "version": 1 },
},
)
.session(&mut session)
.await;
if let Err(e) = r {
let _ = session.abort_transaction().await;
return Err(e.into());
}
}
session.commit_transaction().await?;
let all = list(db, c, household_id, true).await?;
Ok(all.into_iter().filter(|i| i.group == group).collect())
}
// ---------- yardımcılar ----------
fn check_group(c: Catalog, group: Option<Group>) -> AppResult<Option<Group>> {
match (c.has_group(), group) {
(true, None) => Err(AppError::BadRequest("Ana grup seçilmeli".into())),
(true, g) => Ok(g),
(false, _) => Ok(None), // ödeme türlerinde grup yok sayılır
}
}
fn clean_name(name: &str) -> AppResult<String> {
let name = name.trim();
match name.chars().count() {
0 => Err(AppError::BadRequest("Ad boş olamaz".into())),
1..=40 => Ok(name.to_string()),
_ => Err(AppError::BadRequest(
"Ad en fazla 40 karakter olabilir".into(),
)),
}
}
fn clean_emoji(emoji: Option<String>) -> Bson {
match emoji.map(|e| e.trim().to_string()) {
Some(e) if !e.is_empty() => Bson::String(e),
_ => Bson::Null,
}
}
/// Aynı grupta (pasifler dahil) aynı adda kayıt olmasın. Büyük/küçük harf duyarsız.
async fn ensure_unique_name(
db: &Database,
c: Catalog,
household_id: Uuid,
group: Option<Group>,
name: &str,
exclude: Option<Uuid>,
) -> AppResult<()> {
let mut filter = scope(household_id);
if let Some(g) = group {
filter.insert("group", g.as_str());
}
let wanted = name.to_lowercase();
let items = collect(coll(db, c).find(filter).await?).await?;
let clash = items
.iter()
.any(|i| Some(i.id) != exclude && i.name.to_lowercase() == wanted);
if clash {
return Err(AppError::Conflict(format!(
"Bu adla bir {} zaten var (pasif olabilir)",
c.noun()
)));
}
Ok(())
}
fn stale() -> AppError {
AppError::Conflict("Bu kayıt başka biri tarafından değiştirildi, sayfayı yenileyin".into())
}
async fn collect(mut cursor: mongodb::Cursor<Item>) -> AppResult<Vec<Item>> {
let mut v = Vec::new();
while cursor.advance().await? {
v.push(cursor.deserialize_current()?);
}
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_rules() {
assert_eq!(clean_name(" Market ").unwrap(), "Market");
assert!(clean_name(" ").is_err());
assert!(
clean_name(&"ş".repeat(40)).is_ok(),
"Türkçe karakterler tek sayılmalı"
);
assert!(clean_name(&"a".repeat(41)).is_err());
}
#[test]
fn group_required_only_for_categories() {
assert!(check_group(Catalog::Categories, None).is_err());
assert_eq!(
check_group(Catalog::PaymentMethods, Some(Group::Needs)).unwrap(),
None
);
}
}
+1
View File
@@ -1,5 +1,6 @@
//! İş mantığı. Route'lar ince kalır; asıl işi buradaki fonksiyonlar yapar.
pub mod account;
pub mod catalog;
pub mod invite;
pub mod seed;
+13 -1
View File
@@ -1,6 +1,6 @@
//! Tüm route'ların paylaştığı uygulama durumu.
use std::sync::Arc;
use std::{sync::Arc, time::Duration};
use mongodb::Database;
@@ -17,3 +17,15 @@ pub struct AppState {
pub jwt: Arc<Jwt>,
pub login_limiter: Arc<LoginLimiter>,
}
impl AppState {
pub fn new(db: Database, config: Config) -> Self {
Self {
db,
jwt: Arc::new(Jwt::new(&config.jwt_secret)),
// Aynı e-postaya 15 dakikada en fazla 5 hatalı giriş denemesi
login_limiter: Arc::new(LoginLimiter::new(5, Duration::from_secs(15 * 60))),
config: Arc::new(config),
}
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Kategori ve ödeme türü davranış testleri.
mod common;
use axum::http::StatusCode;
use common::TestApp;
use serde_json::{Value, json};
fn names(list: &Value) -> Vec<&str> {
list.as_array()
.unwrap()
.iter()
.map(|i| i["name"].as_str().unwrap())
.collect()
}
#[tokio::test]
async fn new_household_gets_default_categories_and_payment_methods() {
let app = TestApp::new().await;
let s = app.register("Yeni", None).await;
let (_, cats) = app.get("/categories", &s).await;
assert_eq!(cats.as_array().unwrap().len(), 13);
// Grup sırası: needs → wants → culture → unexpected
let groups: Vec<&str> = cats
.as_array()
.unwrap()
.iter()
.map(|c| c["group"].as_str().unwrap())
.collect();
assert_eq!(groups.first(), Some(&"needs"));
assert_eq!(groups.last(), Some(&"unexpected"));
let (_, pms) = app.get("/payment-methods", &s).await;
assert_eq!(
names(&pms),
vec!["Nakit", "Kredi Kartı", "Banka Kartı", "Havale/EFT"]
);
assert!(
pms[0].get("group").is_none(),
"ödeme türünde group alanı olmamalı"
);
app.cleanup().await;
}
#[tokio::test]
async fn create_validates_and_appends_to_end_of_group() {
let app = TestApp::new().await;
let s = app.register("Test", None).await;
// Grup zorunlu
let (st, _) = app
.post("/categories", &s, json!({ "name": "Grupsuz" }))
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
// Boş ad
let (st, _) = app
.post(
"/categories",
&s,
json!({ "group": "needs", "name": " " }),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
// Geçersiz grup
let (st, _) = app
.post("/categories", &s, json!({ "group": "luks", "name": "X" }))
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
// Aynı ad (büyük/küçük harf duyarsız) → 409
let (st, body) = app
.post(
"/categories",
&s,
json!({ "group": "needs", "name": "MARKET" }),
)
.await;
assert_eq!(st, StatusCode::CONFLICT, "{body}");
// Aynı ad başka grupta serbest
let (st, _) = app
.post(
"/categories",
&s,
json!({ "group": "wants", "name": "Market" }),
)
.await;
assert_eq!(st, StatusCode::CREATED);
// Yeni kayıt grubun sonuna eklenir
let (st, cat) = app
.post(
"/categories",
&s,
json!({ "group": "needs", "name": " Aidat ", "emoji": "🏢" }),
)
.await;
assert_eq!(st, StatusCode::CREATED);
assert_eq!(cat["name"], "Aidat");
let (_, cats) = app.get("/categories", &s).await;
let needs: Vec<&str> = cats
.as_array()
.unwrap()
.iter()
.filter(|c| c["group"] == "needs")
.map(|c| c["name"].as_str().unwrap())
.collect();
assert_eq!(needs.last(), Some(&"Aidat"));
app.cleanup().await;
}
#[tokio::test]
async fn update_deactivate_and_version_conflict() {
let app = TestApp::new().await;
let s = app.register("Test", None).await;
let (_, pm) = app
.post(
"/payment-methods",
&s,
json!({ "name": "Yemek Kartı", "emoji": "🍽️" }),
)
.await;
let path = format!("/payment-methods/{}", pm["id"].as_str().unwrap());
assert_eq!(pm["version"], 1);
// Ad + emoji kaldırma, doğru sürümle
let (st, upd) = app
.patch(
&path,
&s,
json!({ "name": "Multinet", "emoji": "", "version": 1 }),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(upd["name"], "Multinet");
assert_eq!(upd["emoji"], Value::Null);
assert_eq!(upd["version"], 2);
// Eski sürümle güncelleme → 409 (başkası değiştirmiş)
let (st, _) = app
.patch(&path, &s, json!({ "name": "Sodexo", "version": 1 }))
.await;
assert_eq!(st, StatusCode::CONFLICT);
// Pasife al: varsayılan listede görünmez, include_inactive ile görünür
let (st, _) = app.patch(&path, &s, json!({ "is_active": false })).await;
assert_eq!(st, StatusCode::OK);
let (_, active) = app.get("/payment-methods", &s).await;
assert!(!names(&active).contains(&"Multinet"));
let (_, all) = app.get("/payment-methods?include_inactive=true", &s).await;
assert!(names(&all).contains(&"Multinet"));
// Pasif kayıtla aynı adda yeni kayıt açılamaz
let (st, _) = app
.post("/payment-methods", &s, json!({ "name": "multinet" }))
.await;
assert_eq!(st, StatusCode::CONFLICT);
// Olmayan / bozuk kimlik → 404
let (st, _) = app
.patch(
"/payment-methods/01a1cc59-0000-7000-8000-000000000000",
&s,
json!({ "name": "X" }),
)
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
let (st, _) = app
.patch("/payment-methods/bozuk", &s, json!({ "name": "X" }))
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
app.cleanup().await;
}
#[tokio::test]
async fn reorder_requires_complete_list() {
let app = TestApp::new().await;
let s = app.register("Test", None).await;
let (_, cats) = app.get("/categories", &s).await;
let mut culture: Vec<String> = cats
.as_array()
.unwrap()
.iter()
.filter(|c| c["group"] == "culture")
.map(|c| c["id"].as_str().unwrap().to_string())
.collect();
assert_eq!(culture.len(), 3);
// Eksik liste → 400
let (st, _) = app
.put(
"/categories/order",
&s,
json!({ "group": "culture", "ids": &culture[..2] }),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
// Ters çevir → yeni sıra
culture.reverse();
let (st, ordered) = app
.put(
"/categories/order",
&s,
json!({ "group": "culture", "ids": culture }),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(names(&ordered), vec!["Sinema/Konser", "Eğitim", "Kitap"]);
assert_eq!(ordered[0]["sort_order"], 10);
app.cleanup().await;
}
+149
View File
@@ -0,0 +1,149 @@
//! Entegrasyon testleri için yardımcılar.
//!
//! Her test kendi geçici veritabanını (`kakeibo_test_<uuid>`) kullanır ve sonunda siler.
//! Gereken: yerel MongoDB çalışıyor olmalı (`npm run db:up`), `.env` içinde `MONGODB_URI`.
#![allow(dead_code)] // her test dosyası tüm yardımcıları kullanmaz
use axum::{
Router,
body::Body,
http::{Method, Request, StatusCode, header},
};
use http_body_util::BodyExt;
use kakeibo::{config::Config, db, routes, state::AppState};
use mongodb::Database;
use serde_json::{Value, json};
use tower::ServiceExt;
pub struct TestApp {
router: Router,
pub db: Database,
}
/// Oturum açmış bir test kullanıcısı
#[derive(Clone)]
pub struct Session {
pub cookie: String,
pub household_id: String,
}
impl TestApp {
pub async fn new() -> Self {
dotenvy::dotenv().ok();
let uri = std::env::var("MONGODB_URI")
.expect("MONGODB_URI tanımlı değil (.env dosyasını kontrol edin)");
let base = db::connect(&uri)
.await
.expect("MongoDB'ye bağlanılamadı — `npm run db:up` çalıştırın");
let name = format!("kakeibo_test_{}", uuid::Uuid::new_v4().simple());
let db = base.client().database(&name);
db::prepare(&db).await.expect("test DB hazırlanamadı");
let config = Config {
mongodb_uri: uri,
jwt_secret: "test-jwt-secret-en-az-32-karakter-olmali!!".into(),
app_url: "http://localhost".into(),
port: 0,
};
let router = routes::router(AppState::new(db.clone(), config));
Self { router, db }
}
/// Test sonunda geçici veritabanını siler.
pub async fn cleanup(self) {
self.db.drop().await.ok();
}
/// İstek gönderir; (durum kodu, JSON gövde, set-cookie) döner.
pub async fn send(
&self,
method: Method,
path: &str,
cookie: Option<&str>,
body: Option<Value>,
) -> (StatusCode, Value, Option<String>) {
let mut req = Request::builder().method(method).uri(format!("/api{path}"));
if let Some(c) = cookie {
req = req.header(header::COOKIE, c);
}
let req = match body {
Some(b) => req
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(b.to_string())),
None => req.body(Body::empty()),
}
.unwrap();
let res = self.router.clone().oneshot(req).await.unwrap();
let status = res.status();
let set_cookie = res
.headers()
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(';').next())
.map(String::from);
let bytes = res.into_body().collect().await.unwrap().to_bytes();
let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
(status, json, set_cookie)
}
pub async fn get(&self, path: &str, s: &Session) -> (StatusCode, Value) {
let (st, v, _) = self.send(Method::GET, path, Some(&s.cookie), None).await;
(st, v)
}
pub async fn post(&self, path: &str, s: &Session, body: Value) -> (StatusCode, Value) {
let (st, v, _) = self
.send(Method::POST, path, Some(&s.cookie), Some(body))
.await;
(st, v)
}
pub async fn patch(&self, path: &str, s: &Session, body: Value) -> (StatusCode, Value) {
let (st, v, _) = self
.send(Method::PATCH, path, Some(&s.cookie), Some(body))
.await;
(st, v)
}
pub async fn put(&self, path: &str, s: &Session, body: Value) -> (StatusCode, Value) {
let (st, v, _) = self
.send(Method::PUT, path, Some(&s.cookie), Some(body))
.await;
(st, v)
}
pub async fn delete(&self, path: &str, s: &Session) -> (StatusCode, Value) {
let (st, v, _) = self.send(Method::DELETE, path, Some(&s.cookie), None).await;
(st, v)
}
/// Yeni kullanıcı kaydeder (davet koduyla veya yeni hane olarak) ve oturumunu döner.
pub async fn register(&self, name: &str, invite_code: Option<&str>) -> Session {
let email = format!(
"{}-{}@test.com",
name.to_lowercase(),
uuid::Uuid::new_v4().simple()
);
let (status, body, cookie) = self
.send(
Method::POST,
"/auth/register",
None,
Some(json!({
"name": name,
"email": email,
"password": "test-sifre-123",
"invite_code": invite_code,
})),
)
.await;
assert_eq!(status, StatusCode::CREATED, "kayıt başarısız: {body}");
Session {
cookie: cookie.expect("kayıtta cookie dönmedi"),
household_id: body["household"]["id"].as_str().unwrap().to_string(),
}
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Hane izolasyonu testleri: bir hane, başka hanenin verisini göremez ve değiştiremez.
//! (KAKEIBO_PROMPT.md §11 — "başka hanenin verisine erişim imkânsız olmalı")
mod common;
use axum::http::{Method, StatusCode};
use common::TestApp;
use serde_json::{Value, json};
fn ids(list: &Value) -> Vec<String> {
list.as_array()
.unwrap()
.iter()
.map(|i| i["id"].as_str().unwrap().to_string())
.collect()
}
#[tokio::test]
async fn households_cannot_see_or_touch_each_other() {
let app = TestApp::new().await;
let a = app.register("Ayse", None).await;
let b = app.register("Burak", None).await;
assert_ne!(a.household_id, b.household_id);
// A'ya özel kategori ve ödeme türü
let (st, cat) = app
.post(
"/categories",
&a,
json!({ "group": "wants", "name": "A'nın gizli kategorisi" }),
)
.await;
assert_eq!(st, StatusCode::CREATED);
let cat_id = cat["id"].as_str().unwrap();
let (_, pm) = app
.post("/payment-methods", &a, json!({ "name": "A'nın kartı" }))
.await;
let pm_id = pm["id"].as_str().unwrap();
let (_, invite) = app.post("/household/invites", &a, json!({})).await;
let invite_id = invite["id"].as_str().unwrap();
// --- Okuma: B, A'nın kayıtlarını görmez ---
let (_, b_cats) = app.get("/categories?include_inactive=true", &b).await;
assert!(!ids(&b_cats).contains(&cat_id.to_string()));
let (_, b_pms) = app.get("/payment-methods?include_inactive=true", &b).await;
assert!(!ids(&b_pms).contains(&pm_id.to_string()));
let (_, b_hh) = app.get("/household", &b).await;
assert_eq!(b_hh["id"], b.household_id.as_str());
assert_eq!(b_hh["members"].as_array().unwrap().len(), 1);
let (_, b_invites) = app.get("/household/invites", &b).await;
assert_eq!(b_invites, json!([]));
// --- Yazma: B, A'nın kayıtlarını değiştiremez (404: varlığı bile sızmaz) ---
let (st, _) = app
.patch(
&format!("/categories/{cat_id}"),
&b,
json!({ "name": "ele geçirildi" }),
)
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
let (st, _) = app
.patch(
&format!("/payment-methods/{pm_id}"),
&b,
json!({ "is_active": false }),
)
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
let (st, _) = app
.delete(&format!("/household/invites/{invite_id}"), &b)
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
// B, kendi sıralama listesine A'nın kaydını sokamaz
let mut b_wants: Vec<String> = b_cats
.as_array()
.unwrap()
.iter()
.filter(|c| c["group"] == "wants")
.map(|c| c["id"].as_str().unwrap().to_string())
.collect();
b_wants.push(cat_id.to_string());
let (st, _) = app
.put(
"/categories/order",
&b,
json!({ "group": "wants", "ids": b_wants }),
)
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
// --- A'nın verisi hiç değişmedi ---
let (_, a_cats) = app.get("/categories", &a).await;
let mine = a_cats
.as_array()
.unwrap()
.iter()
.find(|c| c["id"] == cat_id)
.unwrap();
assert_eq!(mine["name"], "A'nın gizli kategorisi");
assert_eq!(mine["version"], 1);
let (_, a_invites) = app.get("/household/invites", &a).await;
assert_eq!(ids(&a_invites), vec![invite_id.to_string()]);
app.cleanup().await;
}
#[tokio::test]
async fn member_joins_via_invite_and_shares_household_data() {
let app = TestApp::new().await;
let owner = app.register("Sahip", None).await;
let (_, inv) = app.post("/household/invites", &owner, json!({})).await;
let member = app
.register("Uye", Some(inv["code"].as_str().unwrap()))
.await;
assert_eq!(member.household_id, owner.household_id);
// Üye, sahibin eklediği kategoriyi görür ve düzenleyebilir (ortak defter)
let (_, cat) = app
.post(
"/categories",
&owner,
json!({ "group": "needs", "name": "Ortak" }),
)
.await;
let (st, _) = app
.patch(
&format!("/categories/{}", cat["id"].as_str().unwrap()),
&member,
json!({ "emoji": "🤝" }),
)
.await;
assert_eq!(st, StatusCode::OK);
// Ama davet oluşturamaz
let (st, _) = app.post("/household/invites", &member, json!({})).await;
assert_eq!(st, StatusCode::FORBIDDEN);
app.cleanup().await;
}
#[tokio::test]
async fn protected_endpoints_require_session() {
let app = TestApp::new().await;
let endpoints = [
(Method::GET, "/auth/me"),
(Method::GET, "/household"),
(Method::GET, "/household/invites"),
(Method::POST, "/household/invites"),
(Method::GET, "/categories"),
(Method::POST, "/categories"),
(Method::PUT, "/categories/order"),
(Method::GET, "/payment-methods"),
(Method::POST, "/payment-methods"),
];
for (method, path) in endpoints {
// Oturumsuz ve sahte cookie ile
for cookie in [None, Some("kakeibo_session=sahte.token.degeri")] {
let (st, _, _) = app
.send(method.clone(), path, cookie, Some(json!({})))
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED, "{method} {path} korumasız!");
}
}
app.cleanup().await;
}
+10 -2
View File
@@ -1,7 +1,7 @@
# 🧠 Proje Hafızası
## ▶️ Sıradaki Adım
**Faz 1 – Adım 5:** Kategori (`/api/categories`) ve ödeme türü (`/api/payment-methods`) uç noktaları: listele, ekle, düzenle, sırala, pasife al (silme yok). Otomatik hane izolasyonu entegrasyon testleri (gerçek DB, ayrı test veritabanı). `api.http` tamamlanır → Faz 1 kapanır.
**Faz 2 – Adım 2:** Logo + uygulama ikonu (SVG, defter + yen/para teması), favicon, PWA ikonları (192/512, maskable), Apple touch icon. PNG üretimi için araç seçimi (rsvg-convert / sharp).
## 📌 Alınan Kararlar
- Sürüm kontrolü: Gitea (`https://gitea.ta1sph.info/suphicakir/kakeibo.git`), dal `main`.
@@ -18,7 +18,11 @@
- Hane izolasyonu kuralı: hane kimliği **her zaman** `AuthUser.household_id`'den alınır, asla URL/gövdeden. Başka hanenin kaydı → 404 (403 değil; varlığı sızdırılmaz).
- `AuthUser` her istekte DB'den kullanıcıyı doğrular (silinen kullanıcı → 401, rol DB'den). Owner-only işlemler: `auth.require_owner()?`.
- Davet: 8 karakter (31 harflik okunaklı alfabe), 7 gün, tek kullanım; `find_one_and_update` ile atomik claim, kayıt transaction'ı içinde.
- Sürümler: Rust 1.99.1 (edition 2024), Axum 0.8, React 19, Vite 8, TypeScript 7.
- Kategoriler/ödeme türleri: tüm üyeler yönetir; silme yok (pasife alma); grup sonradan değişmez; ad grup içinde benzersiz (büyük/küçük harf duyarsız, pasifler dahil); PATCH'te `version` → iyimser kilit (409); sıralama tam liste ister.
- Tasarım: ana renk indigo (`oklch(0.42 0.13 268)`), grup renkleri Okabe-Ito (needs #0072b2, wants #cc79a7, culture #009e73, unexpected #d55e00), *-fg tonları AA (açık ≥5.0, koyu ≥9) hesaplanarak doğrulandı. Gelir #15803d, gider #c62828, uyarı #b45309.
- Tema seçimi localStorage (`kakeibo-theme`), yalnızca cihaz kolaylığı; ileride `users.preferences.theme` ile senkron olabilir.
- `parseMoney`: virgül varsa ondalık; virgül yoksa son noktadan sonra 1–2 rakam → ondalık ("1.25" = 1,25 ₺; "1.250" = 1250 ₺).
- Sürümler: Rust 1.99.1 (edition 2024), Axum 0.8, React 19, Vite 8, TypeScript 7, Tailwind 4.3, shadcn 4.23, Vitest 5.
## ❓ Açık Konular
- Üye çıkarma / rol değiştirme / sahipliği devretme henüz yok (Ayarlar ekranıyla birlikte, Faz 2+).
@@ -41,3 +45,7 @@
- **Adım 2:** `db/` modülü: `col` sabitleri, `migrations.rs` (`schema_migrations`, v1 = koleksiyonları oluştur), `indexes.rs` (DATA_MODEL §4 + tüm hane koleksiyonlarına `(household_id, updated_at)`). `models/common.rs`: UUID v7, `new_meta`, `scope`, `touch`. Açılışta `db::prepare`. 4 birim testi; idempotency ve tek açık dönem indeksi elle doğrulandı. `uuid` (v7) eklendi.
- **Adım 3:** Kimlik doğrulama: `auth/` (password argon2id + spawn_blocking, jwt, limiter, session cookie + `AuthUser` extractor), `extract.rs` (`ValidJson` = JSON + validator, Türkçe 400), `services/account.rs` (kayıt tek transaction: hane + owner + 13 kategori + 4 ödeme türü), `services/seed.rs`, `routes/auth.rs` (register/login/logout/me). Yeni crate'ler: argon2, jsonwebtoken, axum-extra(cookie), validator, time. 11 birim testi; 13 senaryo curl ile, rollback DB'de doğrulandı.
- **Adım 4:** `AuthUser` DB doğrulaması + `require_owner`, `services/invite.rs` (create/list_active/revoke/claim), kayıt davet koduyla `member` olarak katılma (`services/account.rs` yeniden düzenlendi), `routes/household.rs` (GET /household, invites GET/POST/DELETE). 13 birim testi; 15 senaryo e2e (izolasyon 404, member 403, kod tekrar kullanımı, rollback) geçti.
- **Adım 5:** `models/group.rs`, `services/catalog.rs` (kategori + ödeme türü ortak: list/create/update/reorder), `routes/catalog.rs`. Backend lib+bin'e ayrıldı (`AppState::new`). Entegrasyon testleri: `tests/isolation.rs` (3), `tests/catalog.rs` (4) — toplam 22 test. İzolasyon testi, kasıtlı açık eklenerek doğrulandı (yakaladı). `db:reset` artık test DB'lerini de siler. Dev-deps: tower, http-body-util. **Faz 1 tamamlandı.**
### 2026-11-12 — Faz 2
- **Adım 1:** Tailwind v4 (@tailwindcss/vite), shadcn init (radix, preset nova; `cn` paketi = shadcn'in clsx+tailwind-merge yerine geçeni, incelendi), Inter (@fontsource-variable, çevrimdışı). `index.css`: grup + durum token'ları, odak halkası, `money` utility, reduced-motion. `lib/format.ts` (+22 vitest), `lib/theme.tsx`, `lib/groups.ts`, `components/theme-toggle.tsx`. Butonlar 44/48 px'e büyütüldü. Geçici önizleme ekranı (App.tsx), 375 px headless ekran görüntüsüyle iki temada kontrol edildi.
+10 -3
View File
@@ -5,8 +5,8 @@
| Faz | Kapsam | Çıktı | Durum |
|---|---|---|---|
| **Faz 0** | Ortam kurulumu, VS Code yapılandırması, monorepo iskeleti, hafıza dosyaları, yerel MongoDB, veri modeli onayı | `npm run dev` ile boş uygulama tarayıcıda açılıyor | ✅ |
| **Faz 1** | Backend temeli: config, DB bağlantısı, kimlik doğrulama, hane, kategoriler, ödeme türleri, health check | API `.http` dosyasıyla test edilebiliyor | 🔄 |
| **Faz 2** | Frontend temeli: tasarım sistemi, tema, logo/ikonlar, layout, navigasyon, giriş/kayıt | Giriş yapılabilen, temalı iskelet uygulama | ⏳ |
| **Faz 1** | Backend temeli: config, DB bağlantısı, kimlik doğrulama, hane, kategoriler, ödeme türleri, health check | API `.http` dosyasıyla test edilebiliyor | ✅ |
| **Faz 2** | Frontend temeli: tasarım sistemi, tema, logo/ikonlar, layout, navigasyon, giriş/kayıt | Giriş yapılabilen, temalı iskelet uygulama | 🔄 |
| **Faz 3** | 🚀 İlk canlıya alma: Dockerfile, Dokploy, canlı MongoDB, domain + HTTPS, yedekleme | Giriş ekranı canlıda çalışıyor | ⏳ |
| **Faz 4** | Dönem açma + aylık planlama + notlar | Plan ekranı | ⏳ |
| **Faz 5** | Günlük defter | Harcama girişi | ⏳ |
@@ -29,4 +29,11 @@
- ✅ 2. Modeller, migration mekanizması ve indeksler
- ✅ 3. Kimlik doğrulama: kayıt (+ hane + örnek kategori/ödeme türü), giriş, çıkış, `me`; argon2 + JWT cookie + rate limit
- ✅ 4. Hane izolasyonu (middleware), üye davet kodu
- 🔄 5. Kategori ve ödeme türü uç noktaları + hane izolasyonu testleri, `api.http`
- ✅ 5. Kategori ve ödeme türü uç noktaları + hane izolasyonu testleri, `api.http`
## Faz 2 Adımları
- ✅ 1. Tailwind v4 + shadcn/ui (radix, nova), tasarım token'ları (4 grup + durum renkleri, AA doğrulandı), Inter, tema (aydınlık/karanlık/sistem), `lib/format.ts` + Vitest
- ⏳ 2. Logo ve uygulama ikonu (SVG), favicon, PWA/Apple ikonları
- ⏳ 3. `lib/api.ts`, TanStack Query, ts-rs tip üretimi, oturum durumu
- ⏳ 4. Router (react-router), korumalı sayfalar, layout: mobil alt menü / masaüstü sol menü
- ⏳ 5. Giriş / kayıt ekranları (react-hook-form + zod, beni hatırla, davet kodu), arayüz metinleri tek dosyada
+22 -3
View File
@@ -1,8 +1,27 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"plugins": [
"react",
"typescript",
"oxc"
],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
"react/only-export-components": [
"warn",
{
"allowConstantExport": true
}
]
},
"overrides": [
{
"files": [
"src/components/ui/**"
],
"rules": {
"react/only-export-components": "off"
}
}
]
}
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
+10 -2
View File
@@ -2,9 +2,17 @@
<html lang="tr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="color-scheme" content="light dark" />
<title>Kakeibo</title>
<!-- Tema: React yüklenmeden önce uygulanır → ilk açılışta "beyaz parlama" olmaz (lib/theme.tsx ile aynı mantık) -->
<script>
try {
var t = localStorage.getItem('kakeibo-theme')
if (t === 'dark' || ((!t || t === 'system') && matchMedia('(prefers-color-scheme: dark)').matches))
document.documentElement.classList.add('dark')
} catch (e) {}
</script>
</head>
<body>
<div id="root"></div>
+5236 -60
View File
File diff suppressed because it is too large Load Diff
+15 -3
View File
@@ -7,11 +7,22 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@tailwindcss/vite": "^4.3.5",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.2",
"lucide-react": "^1.72.0",
"radix-ui": "^1.8.1",
"react": "^19.3.1",
"react-dom": "^19.3.1"
"react-dom": "^19.3.1",
"shadcn": "^4.23.0",
"tailwindcss": "^4.3.5",
"tw-animate-css": "^1.4.0"
},
"devDependencies": {
"@types/node": "^24.19.2",
@@ -20,6 +31,7 @@
"@vitejs/plugin-react": "^6.1.2",
"oxlint": "^1.90.0",
"typescript": "~7.0.2",
"vite": "^8.3.6"
"vite": "^8.3.6",
"vitest": "^5.1.0"
}
}
+82 -10
View File
@@ -1,12 +1,18 @@
import { useEffect, useState } from 'react'
import { Plus } from 'lucide-react'
import { ThemeToggle } from '@/components/theme-toggle'
import { Button } from '@/components/ui/button'
import { formatDate, formatMoney, formatQuantity, toIsoDate } from '@/lib/format'
import { GROUPS } from '@/lib/groups'
type Health = { status: string; version: string }
type Health = { status: string; db: string; version: string }
// Faz 0 geçici ekranı: frontend ↔ backend bağlantısını doğrular.
// Faz 2'de gerçek tasarım sistemi ve layout ile değiştirilecek.
// Faz 2 – Adım 1 geçici ekranı: tasarım sistemi önizlemesi.
// Adım 4'te gerçek layout ve sayfalarla değiştirilecek.
export default function App() {
const [health, setHealth] = useState<Health | null>(null)
const [error, setError] = useState(false)
const [today] = useState(() => toIsoDate(new Date()))
useEffect(() => {
fetch('/api/health')
@@ -16,14 +22,80 @@ export default function App() {
}, [])
return (
<main className="placeholder">
<h1>📒 Kakeibo</h1>
<p>Kişisel Ev Finans Defteri</p>
<p className="status">
{error && '🔴 Backend\'e ulaşılamadı'}
{!error && !health && '⏳ Backend kontrol ediliyor…'}
{health && `🟢 Backend çalışıyor (v${health.version})`}
<main className="mx-auto flex max-w-3xl flex-col gap-8 px-4 py-8">
<header className="flex flex-wrap items-center justify-between gap-4">
<div>
<h1 className="text-3xl font-bold tracking-tight">📒 Kakeibo</h1>
<p className="text-muted-foreground">Tasarım sistemi önizlemesi</p>
</div>
<ThemeToggle />
</header>
<p className="text-sm">
{error && <span className="text-expense">● Backend'e ulaşılamadı</span>}
{!error && !health && <span className="text-muted-foreground">● Backend kontrol ediliyor…</span>}
{health && (
<span className="text-income">
● Backend çalışıyor (v{health.version}, DB: {health.db})
</span>
)}
</p>
<section className="space-y-3">
<h2 className="text-xl font-semibold">Ana gruplar</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{GROUPS.map((g) => (
<div key={g.code} className={`rounded-xl p-4 ${g.className.soft}`}>
<div className={`flex items-center gap-2 font-semibold ${g.className.text}`}>
<span aria-hidden>{g.emoji}</span>
{g.label}
</div>
<div className="mt-3 h-2 overflow-hidden rounded-full bg-background/60">
<div className={`h-full w-2/3 rounded-full ${g.className.fill}`} />
</div>
<p className="mt-2 text-xs text-muted-foreground">{g.description}</p>
</div>
))}
</div>
</section>
<section className="space-y-3">
<h2 className="text-xl font-semibold">Tutarlar ve durum renkleri</h2>
<div className="divide-y rounded-xl border bg-card">
{[
['Gelir', formatMoney(4_500_000, 'TRY', { signed: true }), 'text-income'],
['Gider', formatMoney(-125_000), 'text-expense'],
['Bütçenin %85\'i kullanıldı', formatMoney(85_000), 'text-warning'],
['Euro', formatMoney(30_000, 'EUR'), ''],
['Dolar', formatMoney(15_000, 'USD'), ''],
['Gram altın', formatQuantity(12_500_000, 'gr'), ''],
['Bugün', formatDate(today), ''],
].map(([label, value, color]) => (
<div key={label} className="flex items-center justify-between px-4 py-3">
<span>{label}</span>
<span className={`money font-medium ${color}`}>{value}</span>
</div>
))}
</div>
</section>
<section className="space-y-3">
<h2 className="text-xl font-semibold">Butonlar</h2>
<div className="flex flex-wrap gap-3">
<Button size="lg">
<Plus /> Harcama Ekle
</Button>
<Button size="lg" variant="secondary">
İkincil
</Button>
<Button size="lg" variant="outline">
Çerçeveli
</Button>
<Button size="lg" variant="destructive">
Sil
</Button>
</div>
</section>
</main>
)
}
+38
View File
@@ -0,0 +1,38 @@
import { Monitor, Moon, Sun } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useTheme, type Theme } from '@/lib/theme'
const OPTIONS: { value: Theme; label: string; icon: typeof Sun }[] = [
{ value: 'light', label: 'Aydınlık', icon: Sun },
{ value: 'dark', label: 'Karanlık', icon: Moon },
{ value: 'system', label: 'Sistem', icon: Monitor },
]
/** Aydınlık / Karanlık / Sistem seçici (radyo grubu gibi davranır, klavyeyle gezilebilir). */
export function ThemeToggle({ className }: { className?: string }) {
const { theme, setTheme } = useTheme()
return (
<div
role="radiogroup"
aria-label="Tema"
className={cn('inline-flex rounded-lg border bg-muted p-1', className)}
>
{OPTIONS.map(({ value, label, icon: Icon }) => (
<button
key={value}
type="button"
role="radio"
aria-checked={theme === value}
onClick={() => setTheme(value)}
className={cn(
'inline-flex min-h-11 min-w-11 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium text-muted-foreground transition-colors',
theme === value && 'bg-background text-foreground shadow-sm',
)}
>
<Icon className="size-4" aria-hidden />
<span>{label}</span>
</button>
))}
</div>
)
}
+67
View File
@@ -0,0 +1,67 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Slot } from "radix-ui"
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 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",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
// Kakeibo: mobile-first — dokunma alanı en az 44×44 px (KAKEIBO_PROMPT §9)
default:
"h-11 gap-2 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-9 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-12 gap-2 px-5 text-base has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4",
icon: "size-11",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-9 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-12",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+202 -30
View File
@@ -1,37 +1,209 @@
/* Faz 0 geçici stil. Faz 2'de TailwindCSS ile değiştirilecek. */
:root {
font-family: Inter, system-ui, sans-serif;
color-scheme: light dark;
background: #fafaf9;
color: #1c1917;
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/inter";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-heading: var(--font-sans);
--font-sans: 'Inter Variable', system-ui, sans-serif;
/* Kakeibo: 4 ana grup + durum renkleri (aşağıdaki :root / .dark değişkenlerinden) */
--color-needs: var(--needs);
--color-needs-fg: var(--needs-fg);
--color-needs-soft: var(--needs-soft);
--color-wants: var(--wants);
--color-wants-fg: var(--wants-fg);
--color-wants-soft: var(--wants-soft);
--color-culture: var(--culture);
--color-culture-fg: var(--culture-fg);
--color-culture-soft: var(--culture-soft);
--color-unexpected: var(--unexpected);
--color-unexpected-fg: var(--unexpected-fg);
--color-unexpected-soft: var(--unexpected-soft);
--color-income: var(--income);
--color-expense: var(--expense);
--color-warning: var(--warning);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
@media (prefers-color-scheme: dark) {
:root {
background: #1c1917;
color: #f5f5f4;
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.42 0.13 268); /* ai-iro: Japon indigosu */
--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.55 0.13 268);
--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);
--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);
/* 4 ana grup — Okabe-Ito (renk körlüğüne uygun) paletinden.
*: çubuk/dolgu · *-fg: yazı (WCAG AA ≥ 4.5:1) · *-soft: zemin */
--needs: #0072b2;
--needs-fg: #005a8c;
--needs-soft: #e6f1f8;
--wants: #cc79a7;
--wants-fg: #9c3f72;
--wants-soft: #f9eef4;
--culture: #009e73;
--culture-fg: #00714f;
--culture-soft: #e5f5f0;
--unexpected: #d55e00;
--unexpected-fg: #a84a00;
--unexpected-soft: #fbefe5;
/* Durum: gelir/olumlu · gider/aşım · uyarı (yazı olarak AA uyumlu) */
--income: #15803d;
--expense: #c62828;
--warning: #b45309;
}
.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.72 0.12 268);
--primary-foreground: oklch(0.18 0.03 268);
--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.62 0.12 268);
--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);
/* Koyu zeminde daha açık tonlar (kontrast için) */
--needs: #3a9fdb;
--needs-fg: #7cc3f0;
--needs-soft: #10283a;
--wants: #d98fb8;
--wants-fg: #ecb6d4;
--wants-soft: #35202c;
--culture: #1fbf8f;
--culture-fg: #6fdcb9;
--culture-soft: #0c2e25;
--unexpected: #f07a24;
--unexpected-fg: #f8a96b;
--unexpected-soft: #3a2010;
--income: #4ade80;
--expense: #f87171;
--warning: #fbbf24;
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
font-size: 16px;
-webkit-tap-highlight-color: transparent;
}
/* Görünür odak halkası (klavye ile gezinme) */
:focus-visible {
@apply outline-2 outline-offset-2 outline-ring;
}
}
body {
margin: 0;
}
.placeholder {
min-height: 100dvh;
display: grid;
place-content: center;
text-align: center;
gap: 0.25rem;
padding: 1rem;
}
.placeholder h1 {
margin: 0;
font-size: 2.5rem;
}
.status {
margin-top: 1.5rem;
/* Tutarlar: rakamlar alt alta hizalı */
@utility money {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
/* Hareket azaltma tercihine saygı */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest'
import {
formatDate,
formatMoney,
formatNumber,
formatPercent,
formatQuantity,
parseMoney,
toIsoDate,
} from './format'
describe('formatMoney', () => {
it('kuruşu Türkçe biçimde, para birimi sağda ve boşluklu yazar', () => {
expect(formatMoney(125000)).toBe('1.250,00 ₺')
expect(formatMoney(30000, 'EUR')).toBe('300,00 €')
expect(formatMoney(15000, 'USD')).toBe('150,00 $')
expect(formatMoney(0)).toBe('0,00 ₺')
expect(formatMoney(5)).toBe('0,05 ₺')
expect(formatMoney(123456789)).toBe('1.234.567,89 ₺')
})
it('negatif ve işaretli', () => {
expect(formatMoney(-125000)).toBe('-1.250,00 ₺')
expect(formatMoney(125000, 'TRY', { signed: true })).toBe('+1.250,00 ₺')
expect(formatMoney(-500, 'TRY', { signed: true })).toBe('-5,00 ₺')
})
})
describe('diğer biçimler', () => {
it('miktar, sayı, yüzde', () => {
expect(formatQuantity(12_500_000, 'gr')).toBe('12,50 gr')
expect(formatQuantity(1_234_567, 'gr', 3)).toBe('1,235 gr')
expect(formatNumber(1250.5)).toBe('1.250,50')
expect(formatPercent(0.123)).toBe('%12,3')
})
it('tarih GG.AA.YYYY', () => {
expect(formatDate('2026-12-09')).toBe('09.12.2026')
expect(formatDate(new Date(2027, 0, 1))).toBe('01.01.2027')
expect(toIsoDate(new Date(2026, 11, 9))).toBe('2026-12-09')
})
})
describe('parseMoney', () => {
it.each([
['1250', 125000],
['1.250', 125000],
['1250,5', 125050],
['1.250,50', 125050],
['1250.50', 125050], // telefon klavyesindeki nokta
['1250.5', 125050],
[' 1.250,00 ₺ ', 125000],
[',99', 99],
['0,1', 10],
['1.234.567,89', 123456789],
['-45,5', -4550],
])('%s → %i kuruş', (input, expected) => {
expect(parseMoney(input)).toBe(expected)
})
it.each(['', 'abc', '1,2,3', '12,345', '1.250,5.0', '₺'])('geçersiz: "%s"', (input) => {
expect(parseMoney(input)).toBeNull()
})
it('kayan nokta hatası yok (0,1 + 0,2 gibi değerler tam)', () => {
expect(parseMoney('0,29')).toBe(29)
expect(parseMoney('19,99')).toBe(1999)
})
})
+117
View File
@@ -0,0 +1,117 @@
/**
* Tüm sayı / para / tarih biçimlendirmesi buradan yapılır (KAKEIBO_PROMPT §9).
*
* - Para: backend'den **kuruş cinsinden tamsayı** gelir → `1.250,00 ₺`
* (para birimi rakamın sağında, arada bir boşluk)
* - Miktar (altın, döviz): milyonda bir birim (`_e6`) → `12,50 gr`
* - Tarih: `GG.AA.YYYY`
*/
export type CurrencyCode = 'TRY' | 'USD' | 'EUR' | 'XAU_GRAM'
const CURRENCY_SUFFIX: Record<CurrencyCode, string> = {
TRY: '₺',
USD: '$',
EUR: '€',
XAU_GRAM: 'gr',
}
const numberFormats = new Map<number, Intl.NumberFormat>()
function numberFormat(decimals: number): Intl.NumberFormat {
let f = numberFormats.get(decimals)
if (!f) {
f = new Intl.NumberFormat('tr-TR', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
})
numberFormats.set(decimals, f)
}
return f
}
/** Ondalıklı sayıyı Türkçe biçimler: `1250.5` → `1.250,50` */
export function formatNumber(value: number, decimals = 2): string {
return numberFormat(decimals).format(value)
}
/** Kuruş → `1.250,00 ₺`. `signed: true` ise pozitiflere `+` eklenir. */
export function formatMoney(
kurus: number,
currency: CurrencyCode = 'TRY',
options: { signed?: boolean } = {},
): string {
const text = `${formatNumber(kurus / 100)} ${CURRENCY_SUFFIX[currency]}`
return options.signed && kurus > 0 ? `+${text}` : text
}
/** Milyonda bir birim → `12,50 gr` (altın, döviz miktarı) */
export function formatQuantity(e6: number, unit: string, decimals = 2): string {
return `${formatNumber(e6 / 1_000_000, decimals)} ${unit}`
}
/** Yüzde: `0.123` → `%12,3` (Türkçede % işareti başta) */
export function formatPercent(ratio: number, decimals = 1): string {
return `%${formatNumber(ratio * 100, decimals)}`
}
/**
* Kullanıcının yazdığı tutarı kuruşa çevirir. Geçersizse `null`.
*
* Kabul edilenler: `1250` · `1.250` · `1250,5` · `1.250,50` · `1250.50` (telefon klavyesi)
* Kural: virgül varsa ondalık ayırıcıdır, noktalar binliktir.
* Virgül yoksa ve son noktadan sonra 1–2 rakam varsa o nokta ondalıktır.
* Float hatası olmasın diye hesap metin üzerinden yapılır.
*/
export function parseMoney(input: string): number | null {
let s = input.replace(/[\s₺]/g, '')
if (!s) return null
let negative = false
if (s.startsWith('-')) {
negative = true
s = s.slice(1)
}
let intPart: string
let fracPart = ''
if (s.includes(',')) {
const parts = s.split(',')
if (parts.length !== 2) return null
intPart = parts[0].replace(/\./g, '')
fracPart = parts[1]
} else {
const m = /^(.*)\.(\d{1,2})$/.exec(s)
if (m && !m[1].includes('.')) {
intPart = m[1]
fracPart = m[2]
} else {
intPart = s.replace(/\./g, '')
}
}
if (intPart === '') intPart = '0'
if (!/^\d+$/.test(intPart) || !/^\d{0,2}$/.test(fracPart)) return null
const kurus = Number(intPart) * 100 + Number(fracPart.padEnd(2, '0'))
if (!Number.isSafeInteger(kurus)) return null
return negative ? -kurus : kurus
}
/** `"2026-12-09"` veya ISO zaman damgası → `09.12.2026` */
export function formatDate(value: string | Date): string {
if (typeof value === 'string') {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
if (m) return `${m[3]}.${m[2]}.${m[1]}`
value = new Date(value)
}
const dd = String(value.getDate()).padStart(2, '0')
const mm = String(value.getMonth() + 1).padStart(2, '0')
return `${dd}.${mm}.${value.getFullYear()}`
}
/** Yerel tarih → `"2026-12-09"` (backend'in takvim tarihi biçimi) */
export function toIsoDate(date: Date): string {
const mm = String(date.getMonth() + 1).padStart(2, '0')
const dd = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${mm}-${dd}`
}
+67
View File
@@ -0,0 +1,67 @@
/**
* 4 sabit ana grup (backend `models/group.rs` ile aynı kodlar).
* Renk asla tek başına anlam taşımaz: her zaman emoji/ikon + etiketle birlikte kullanılır.
*/
import { BookOpen, House, ShoppingBag, Zap, type LucideIcon } from 'lucide-react'
export type GroupCode = 'needs' | 'wants' | 'culture' | 'unexpected'
export type GroupMeta = {
code: GroupCode
label: string
emoji: string
icon: LucideIcon
description: string
/** Tailwind sınıfları (index.css'teki token'lardan) */
className: {
/** dolgu: çubuk, nokta */
fill: string
/** yazı (AA kontrast) */
text: string
/** yumuşak zemin */
soft: string
}
}
export const GROUPS: readonly GroupMeta[] = [
{
code: 'needs',
label: 'Zorunlu',
emoji: '🏠',
icon: House,
description: 'Temel ihtiyaçlar: market, fatura, ulaşım',
className: { fill: 'bg-needs', text: 'text-needs-fg', soft: 'bg-needs-soft' },
},
{
code: 'wants',
label: 'İstek',
emoji: '🛍️',
icon: ShoppingBag,
description: 'Arzular: dışarıda yemek, alışveriş',
className: { fill: 'bg-wants', text: 'text-wants-fg', soft: 'bg-wants-soft' },
},
{
code: 'culture',
label: 'Kültürel',
emoji: '📚',
icon: BookOpen,
description: 'Kitap, eğitim, sinema, konser',
className: { fill: 'bg-culture', text: 'text-culture-fg', soft: 'bg-culture-soft' },
},
{
code: 'unexpected',
label: 'Beklenmeyen',
emoji: '⚡',
icon: Zap,
description: 'Öngörülmeyen: tamir, sağlık, hediye',
className: {
fill: 'bg-unexpected',
text: 'text-unexpected-fg',
soft: 'bg-unexpected-soft',
},
},
]
export function group(code: GroupCode): GroupMeta {
return GROUPS.find((g) => g.code === code)!
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Aydınlık / Karanlık / Sistem teması.
*
* Seçim tarayıcıda saklanır (yalnızca bu cihaz için bir kolaylık).
* İlk boyamada "beyaz parlama" olmasın diye aynı mantık `index.html` içinde de çalışır.
*/
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react'
export type Theme = 'light' | 'dark' | 'system'
const STORAGE_KEY = 'kakeibo-theme'
const media = () => window.matchMedia('(prefers-color-scheme: dark)')
function readStored(): Theme {
try {
const v = localStorage.getItem(STORAGE_KEY)
if (v === 'light' || v === 'dark' || v === 'system') return v
} catch {
/* gizli sekme vb. — varsayılan kullanılır */
}
return 'system'
}
function apply(theme: Theme) {
const dark = theme === 'dark' || (theme === 'system' && media().matches)
document.documentElement.classList.toggle('dark', dark)
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
}
type ThemeContextValue = { theme: Theme; setTheme: (t: Theme) => void }
const ThemeContext = createContext<ThemeContextValue | null>(null)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(readStored)
useEffect(() => {
apply(theme)
if (theme !== 'system') return
// Sistem teması değişirse (ör. akşam otomatik koyu mod) anında uygula
const m = media()
const onChange = () => apply('system')
m.addEventListener('change', onChange)
return () => m.removeEventListener('change', onChange)
}, [theme])
const setTheme = useCallback((t: Theme) => {
try {
localStorage.setItem(STORAGE_KEY, t)
} catch {
/* saklanamazsa yalnızca bu oturumda geçerli olur */
}
setThemeState(t)
}, [])
return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>
}
// oxlint-disable-next-line react/only-export-components -- hook, provider ile aynı dosyada
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext)
if (!ctx) throw new Error('useTheme, ThemeProvider içinde kullanılmalı')
return ctx
}
+1
View File
@@ -0,0 +1 @@
export { cn } from "cn"
+4 -1
View File
@@ -2,9 +2,12 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { ThemeProvider } from '@/lib/theme'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
<ThemeProvider>
<App />
</ThemeProvider>
</StrictMode>,
)
+3
View File
@@ -16,6 +16,9 @@
"noEmit": true,
"jsx": "react-jsx",
/* "@/..." → src/... */
"paths": { "@/*": ["./src/*"] },
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
+3
View File
@@ -1,5 +1,8 @@
{
"files": [],
"compilerOptions": {
"paths": { "@/*": ["./src/*"] }
},
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
+7 -1
View File
@@ -1,9 +1,15 @@
import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
plugins: [react(), tailwindcss()],
resolve: {
// "@/lib/format" → src/lib/format
alias: { '@': path.resolve(import.meta.dirname, './src') },
},
server: {
port: 5173,
strictPort: true,
+2 -2
View File
@@ -13,8 +13,8 @@
"db:up": "docker compose -f docker-compose.dev.yml up -d --wait",
"db:down": "docker compose -f docker-compose.dev.yml stop",
"db:seed": "echo 'Seed betiği Faz 1-4 arasında eklenecek.'",
"db:reset": "docker exec kakeibo-mongo mongosh --quiet kakeibo_dev --eval 'db.dropDatabase()' && echo 'kakeibo_dev veritabanı sıfırlandı.'",
"test": "cd backend && cargo test",
"db:reset": "docker exec kakeibo-mongo mongosh --quiet --eval \"db.getSiblingDB('kakeibo_dev').dropDatabase(); db.adminCommand({listDatabases:1}).databases.filter(d => d.name.startsWith('kakeibo_test_')).forEach(d => db.getSiblingDB(d.name).dropDatabase()); print('kakeibo_dev ve test veritabanları sıfırlandı.')\"",
"test": "cd backend && cargo test && cd .. && npm --prefix frontend test",
"lint": "cd backend && cargo clippy && cd .. && npm --prefix frontend run lint"
},
"devDependencies": {