diff --git a/app/api/router.py b/app/api/router.py
index 09c39c7f8f7eff537a8c6e21d5f661089126354b..1859db017e51d18ea8c06da9ae63b99aaa1e6a26 100644
--- a/app/api/router.py
+++ b/app/api/router.py
@@ -7,13 +7,11 @@ Yeni bir endpoint modülü eklendiğinde yalnızca bu dosya güncellenir.
from fastapi import FastAPI
from app.api.routes.auth import router as auth_router
-from app.api.routes.companies import router as companies_router
from app.api.routes.expenses import product_costs_router, router as expenses_router
from app.api.routes.exports import router as exports_router
from app.api.routes.lumber import router as lumber_router
from app.api.routes.orders import router as orders_router
from app.api.routes.reports import router as reports_router
-from app.api.routes.talash import router as talash_router
def include_api_routers(application: FastAPI) -> None:
@@ -25,5 +23,3 @@ def include_api_routers(application: FastAPI) -> None:
application.include_router(reports_router)
application.include_router(exports_router)
application.include_router(lumber_router)
- application.include_router(companies_router)
- application.include_router(talash_router)
diff --git a/app/api/routes/companies.py b/app/api/routes/companies.py
deleted file mode 100644
index a2d783d6a501c2e5344676cdac6c97da27ac4cca..0000000000000000000000000000000000000000
--- a/app/api/routes/companies.py
+++ /dev/null
@@ -1,234 +0,0 @@
-"""Firma katalog endpoint'leri."""
-
-from typing import Optional
-
-from fastapi import APIRouter, Depends, HTTPException
-
-from app.auth import get_active_user
-from app.infrastructure.database import get_db
-from app.schemas import CompanyPayload
-
-router = APIRouter(
- prefix="/api/companies",
- tags=["companies"],
- dependencies=[Depends(get_active_user)],
-)
-
-_COMPANY_SELECT = (
- "SELECT id, name, address, tax_number, notes, created_at, is_active FROM companies"
-)
-
-
-def _norm_name(name: str) -> str:
- return " ".join(name.strip().split()).casefold()
-
-
-def _norm_tax(tax: str) -> str:
- return "".join(ch for ch in (tax or "").strip() if ch.isdigit())
-
-
-def _archived_display_name(name: str, company_id: int) -> str:
- """Pasif kayitlarin adini degistirir; ayni isimle yeni aktif firma acilabilsin."""
- suffix = f" (pasif #{company_id})"
- base = " ".join(name.strip().split())
- max_base = max(1, 240 - len(suffix))
- if len(base) > max_base:
- base = base[:max_base].rstrip()
- return f"{base}{suffix}"
-
-
-def _is_archived_name(name: str, company_id: int) -> bool:
- return name.endswith(f" (pasif #{company_id})")
-
-
-def _release_inactive_name_collisions(cur, key: str) -> None:
- """Eski pasif kayitlar ayni ismi tutuyorsa adlarini arsivler."""
- rows = cur.execute(
- """
- SELECT id, name FROM companies
- WHERE COALESCE(is_active, 1) = 0
- """
- ).fetchall()
- for row in rows:
- cid = int(row["id"])
- if _norm_name(row["name"]) != key:
- continue
- if _is_archived_name(row["name"], cid):
- continue
- cur.execute(
- "UPDATE companies SET name = ? WHERE id = ?",
- (_archived_display_name(row["name"], cid), cid),
- )
-
-
-def _duplicate_active_id(cur, key: str, exclude_id: Optional[int] = None) -> Optional[int]:
- rows = cur.execute(
- """
- SELECT id, name FROM companies
- WHERE COALESCE(is_active, 1) = 1
- """
- ).fetchall()
- for row in rows:
- if exclude_id is not None and int(row["id"]) == exclude_id:
- continue
- if _norm_name(row["name"]) == key:
- return int(row["id"])
- return None
-
-
-def _duplicate_active_tax_id(
- cur, tax_key: str, exclude_id: Optional[int] = None
-) -> Optional[int]:
- if not tax_key:
- return None
- rows = cur.execute(
- """
- SELECT id, tax_number FROM companies
- WHERE COALESCE(is_active, 1) = 1
- """
- ).fetchall()
- for row in rows:
- if exclude_id is not None and int(row["id"]) == exclude_id:
- continue
- if _norm_tax(row["tax_number"]) == tax_key:
- return int(row["id"])
- return None
-
-
-def _row_to_dict(row) -> dict:
- keys = row.keys()
- is_active = bool(row["is_active"]) if "is_active" in keys else True
- return {
- "id": row["id"],
- "name": row["name"],
- "address": row["address"] or "",
- "tax_number": row["tax_number"] or "",
- "notes": row["notes"] or "",
- "created_at": row["created_at"],
- "is_active": is_active,
- }
-
-
-def _payload_fields(payload: CompanyPayload) -> tuple[str, str, str, str]:
- name = " ".join(payload.name.strip().split())
- address = (payload.address or "").strip()
- tax_number = (payload.tax_number or "").strip()
- notes = (payload.notes or "").strip()
- return name, address, tax_number, notes
-
-
-@router.get("")
-def list_companies():
- """Yalnizca aktif (listedeki) firmalari listeler."""
- conn = get_db()
- rows = conn.execute(
- f"""
- {_COMPANY_SELECT}
- WHERE COALESCE(is_active, 1) = 1
- ORDER BY name COLLATE NOCASE ASC, id ASC
- """
- ).fetchall()
- conn.close()
- return {"companies": [_row_to_dict(row) for row in rows]}
-
-
-@router.post("")
-def create_company(payload: CompanyPayload):
- """Yeni firma kaydi olusturur."""
- name, address, tax_number, notes = _payload_fields(payload)
- if not name:
- raise HTTPException(status_code=400, detail="Firma adi bos olamaz")
-
- conn = get_db()
- cur = conn.cursor()
- key = _norm_name(name)
- if _duplicate_active_id(cur, key):
- conn.close()
- raise HTTPException(status_code=400, detail="Bu firma adi zaten kayitli")
-
- tax_key = _norm_tax(tax_number)
- if tax_key and _duplicate_active_tax_id(cur, tax_key):
- conn.close()
- raise HTTPException(status_code=400, detail="Bu vergi numarasi zaten kayitli")
-
- _release_inactive_name_collisions(cur, key)
-
- cur.execute(
- "INSERT INTO companies (name, address, tax_number, notes) VALUES (?, ?, ?, ?)",
- (name, address, tax_number, notes),
- )
- cid = cur.lastrowid
- conn.commit()
- row = conn.execute(f"{_COMPANY_SELECT} WHERE id = ?", (cid,)).fetchone()
- conn.close()
- return {"company": _row_to_dict(row)}
-
-
-@router.patch("/{company_id}")
-def update_company(company_id: int, payload: CompanyPayload):
- """Firma kaydini gunceller."""
- name, address, tax_number, notes = _payload_fields(payload)
- if not name:
- raise HTTPException(status_code=400, detail="Firma adi bos olamaz")
-
- conn = get_db()
- cur = conn.cursor()
- exists = cur.execute("SELECT id FROM companies WHERE id = ?", (company_id,)).fetchone()
- if not exists:
- conn.close()
- raise HTTPException(status_code=404, detail="Kayit bulunamadi")
-
- key = _norm_name(name)
- if _duplicate_active_id(cur, key, exclude_id=company_id):
- conn.close()
- raise HTTPException(status_code=400, detail="Bu firma adi baska kayitta kullaniliyor")
-
- tax_key = _norm_tax(tax_number)
- if tax_key and _duplicate_active_tax_id(cur, tax_key, exclude_id=company_id):
- conn.close()
- raise HTTPException(status_code=400, detail="Bu vergi numarasi baska kayitta kullaniliyor")
-
- cur.execute(
- """
- UPDATE companies SET name = ?, address = ?, tax_number = ?, notes = ?
- WHERE id = ?
- """,
- (name, address, tax_number, notes, company_id),
- )
- conn.commit()
- row = conn.execute(f"{_COMPANY_SELECT} WHERE id = ?", (company_id,)).fetchone()
- conn.close()
- return {"company": _row_to_dict(row)}
-
-
-@router.delete("/{company_id}")
-def delete_company(company_id: int):
- """Firmayi pasife alir; talaş fiyat ve satis kayitlari silinmez."""
- conn = get_db()
- cur = conn.cursor()
- row = cur.execute(
- f"{_COMPANY_SELECT} WHERE id = ?", (company_id,)
- ).fetchone()
- if not row:
- conn.close()
- raise HTTPException(status_code=404, detail="Kayit bulunamadi")
- keys = row.keys()
- if "is_active" in keys and not row["is_active"]:
- conn.close()
- return {"deleted": False, "archived": True}
-
- if "is_active" not in keys:
- conn.close()
- raise HTTPException(
- status_code=503,
- detail="Veritabani guncellemesi bekleniyor; Space'i bir kez yeniden baslatin",
- )
-
- archived_name = _archived_display_name(row["name"], company_id)
- cur.execute(
- "UPDATE companies SET is_active = 0, name = ? WHERE id = ?",
- (archived_name, company_id),
- )
- conn.commit()
- conn.close()
- return {"deleted": True, "archived": True}
diff --git a/app/api/routes/talash.py b/app/api/routes/talash.py
deleted file mode 100644
index a5ac622f6cbdf80ef1a127b36bf614ab895bbe37..0000000000000000000000000000000000000000
--- a/app/api/routes/talash.py
+++ /dev/null
@@ -1,882 +0,0 @@
-"""Talas cuval fiyat tarifesi ve firma satis kayitlari."""
-
-from datetime import date
-from typing import Optional
-
-from fastapi import APIRouter, Depends, HTTPException, Query
-from fastapi.responses import Response
-
-from app.auth import get_active_user
-from app.infrastructure.database import get_db
-from app.schemas import (
- TalashBulkCollectionPayload,
- TalashCollectionPayload,
- TalashCompanyPaymentPayload,
- TalashExpensePayload,
- TalashPricePayload,
- TalashSalePayload,
- TalashUnitCostPayload,
-)
-from app.services.talash_costs import resolve_unit_cost
-from app.services.talash_collection import (
- allocate_company_payment,
- apply_collected_update,
- enrich_sale_row,
- slip_line_from_sale,
- summarize_sales,
- sync_collection_status,
-)
-from app.services.talash_pricing import resolve_unit_price, sale_total
-from app.services.talash_dashboard import build_talash_dashboard
-from app.services.talash_slip_pdf import build_collection_slip_pdf
-
-_SALE_SELECT = """
-SELECT s.id, s.company_id, c.name AS company_name, s.sale_date,
- s.bag_count, s.unit_price, s.total_amount, s.notes, s.created_at,
- s.collection_status, s.collected_at, s.collected_amount
-FROM company_talash_sales s
-JOIN companies c ON c.id = s.company_id
-"""
-
-_OPEN_BALANCE_SQL = (
- "COALESCE(s.collected_amount, 0) + 0.005 < s.total_amount"
-)
-_CLOSED_BALANCE_SQL = (
- "COALESCE(s.collected_amount, 0) + 0.005 >= s.total_amount"
-)
-_PARTIAL_BALANCE_SQL = (
- "COALESCE(s.collected_amount, 0) > 0.005 AND COALESCE(s.collected_amount, 0) + 0.005 < s.total_amount"
-)
-
-router = APIRouter(
- prefix="/api/talash",
- tags=["talash"],
- dependencies=[Depends(get_active_user)],
-)
-
-
-def _company_exists(cur, company_id: int) -> bool:
- return cur.execute("SELECT 1 FROM companies WHERE id = ?", (company_id,)).fetchone() is not None
-
-
-def _company_active(cur, company_id: int) -> bool:
- row = cur.execute(
- "SELECT is_active FROM companies WHERE id = ?", (company_id,)
- ).fetchone()
- return row is not None and bool(row["is_active"])
-
-
-def _company_writable(cur, company_id: int, prior_company_id: Optional[int] = None) -> bool:
- """Yeni kayit icin aktif firma; duzenlemede pasif firma ayni kalabilir."""
- if _company_active(cur, company_id):
- return True
- if prior_company_id is not None and int(prior_company_id) == int(company_id):
- return _company_exists(cur, company_id)
- return False
-
-
-def _price_row_to_dict(row, company_name: str = "") -> dict:
- return {
- "id": row["id"],
- "company_id": row["company_id"],
- "company_name": company_name or row["company_name"],
- "effective_date": row["effective_date"],
- "unit_price": round(float(row["unit_price"]), 2),
- "notes": row["notes"] or "",
- "created_at": row["created_at"],
- }
-
-
-def _sale_row_to_dict(row) -> dict:
- keys = row.keys()
- collected_raw = row["collected_amount"] if "collected_amount" in keys else 0
- collected_at = row["collected_at"] if "collected_at" in keys else None
- payload = {
- "id": row["id"],
- "company_id": row["company_id"],
- "company_name": row["company_name"],
- "sale_date": row["sale_date"],
- "bag_count": round(float(row["bag_count"]), 2),
- "unit_price": round(float(row["unit_price"]), 2),
- "total_amount": round(float(row["total_amount"]), 2),
- "notes": row["notes"] or "",
- "created_at": row["created_at"],
- "collected_amount": round(float(collected_raw or 0), 2),
- "collected_at": collected_at or "",
- }
- return enrich_sale_row(payload)
-
-
-def _sales_summary(sales: list[dict]) -> dict:
- return summarize_sales(sales)
-
-
-def _collection_status_clause(collection_status: Optional[str]) -> tuple[str, list]:
- if collection_status in ("pending", "open"):
- return f"({_OPEN_BALANCE_SQL})", []
- if collection_status == "partial":
- return f"({_PARTIAL_BALANCE_SQL})", []
- if collection_status == "collected":
- return f"({_CLOSED_BALANCE_SQL})", []
- return "", []
-
-
-def _persist_sale_collection(cur, sale_id: int, total: float, collected: float, collected_at: Optional[str]):
- status = sync_collection_status(total, collected)
- cur.execute(
- """
- UPDATE company_talash_sales
- SET collected_amount = ?, collection_status = ?, collected_at = ?
- WHERE id = ?
- """,
- (collected, status, collected_at, sale_id),
- )
-
-
-@router.get("/prices")
-def list_talash_prices(company_id: Optional[int] = Query(None)):
- conn = get_db()
- if company_id is not None:
- rows = conn.execute(
- """
- SELECT p.id, p.company_id, c.name AS company_name, p.effective_date,
- p.unit_price, p.notes, p.created_at
- FROM company_talash_prices p
- JOIN companies c ON c.id = p.company_id
- WHERE p.company_id = ?
- ORDER BY p.effective_date DESC, p.id DESC
- """,
- (company_id,),
- ).fetchall()
- else:
- rows = conn.execute(
- """
- SELECT p.id, p.company_id, c.name AS company_name, p.effective_date,
- p.unit_price, p.notes, p.created_at
- FROM company_talash_prices p
- JOIN companies c ON c.id = p.company_id
- ORDER BY c.name COLLATE NOCASE ASC, p.effective_date DESC, p.id DESC
- """
- ).fetchall()
- conn.close()
- return {"prices": [_price_row_to_dict(r) for r in rows]}
-
-
-@router.get("/quote")
-def talash_price_quote(
- company_id: int = Query(...),
- sale_date: str = Query(...),
-):
- conn = get_db()
- cur = conn.cursor()
- if not _company_active(cur, company_id):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi veya pasif")
- quote = resolve_unit_price(cur, company_id, sale_date)
- conn.close()
- return {"quote": quote}
-
-
-@router.post("/prices")
-def create_talash_price(payload: TalashPricePayload):
- if float(payload.unit_price) <= 0:
- raise HTTPException(status_code=400, detail="Birim fiyat sifirdan buyuk olmali")
-
- conn = get_db()
- cur = conn.cursor()
- if not _company_active(cur, payload.company_id):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi veya pasif")
-
- dup = cur.execute(
- """
- SELECT id FROM company_talash_prices
- WHERE company_id = ? AND effective_date = ?
- """,
- (payload.company_id, payload.effective_date),
- ).fetchone()
- if dup:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu firma icin ayni gecerlilik tarihinde zaten fiyat var",
- )
-
- cur.execute(
- """
- INSERT INTO company_talash_prices (company_id, effective_date, unit_price, notes)
- VALUES (?, ?, ?, ?)
- """,
- (
- payload.company_id,
- payload.effective_date,
- float(payload.unit_price),
- (payload.notes or "").strip(),
- ),
- )
- pid = cur.lastrowid
- conn.commit()
- row = conn.execute(
- """
- SELECT p.id, p.company_id, c.name AS company_name, p.effective_date,
- p.unit_price, p.notes, p.created_at
- FROM company_talash_prices p
- JOIN companies c ON c.id = p.company_id
- WHERE p.id = ?
- """,
- (pid,),
- ).fetchone()
- conn.close()
- return {"price": _price_row_to_dict(row)}
-
-
-@router.patch("/prices/{price_id}")
-def update_talash_price(price_id: int, payload: TalashPricePayload):
- if float(payload.unit_price) <= 0:
- raise HTTPException(status_code=400, detail="Birim fiyat sifirdan buyuk olmali")
-
- conn = get_db()
- cur = conn.cursor()
- existing = cur.execute(
- "SELECT id, company_id FROM company_talash_prices WHERE id = ?", (price_id,)
- ).fetchone()
- if not existing:
- conn.close()
- raise HTTPException(status_code=404, detail="Fiyat kaydi bulunamadi")
- if not _company_writable(cur, payload.company_id, int(existing["company_id"])):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi veya pasif")
-
- dup = cur.execute(
- """
- SELECT id FROM company_talash_prices
- WHERE company_id = ? AND effective_date = ? AND id != ?
- """,
- (payload.company_id, payload.effective_date, price_id),
- ).fetchone()
- if dup:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu firma icin ayni gecerlilik tarihinde baska fiyat var",
- )
-
- cur.execute(
- """
- UPDATE company_talash_prices
- SET company_id = ?, effective_date = ?, unit_price = ?, notes = ?
- WHERE id = ?
- """,
- (
- payload.company_id,
- payload.effective_date,
- float(payload.unit_price),
- (payload.notes or "").strip(),
- price_id,
- ),
- )
- conn.commit()
- row = conn.execute(
- """
- SELECT p.id, p.company_id, c.name AS company_name, p.effective_date,
- p.unit_price, p.notes, p.created_at
- FROM company_talash_prices p
- JOIN companies c ON c.id = p.company_id
- WHERE p.id = ?
- """,
- (price_id,),
- ).fetchone()
- conn.close()
- return {"price": _price_row_to_dict(row)}
-
-
-@router.delete("/prices/{price_id}")
-def delete_talash_price(price_id: int):
- conn = get_db()
- cur = conn.cursor()
- cur.execute("DELETE FROM company_talash_prices WHERE id = ?", (price_id,))
- conn.commit()
- deleted = cur.rowcount
- conn.close()
- return {"deleted": deleted > 0}
-
-
-@router.get("/sales")
-def list_talash_sales(
- company_id: Optional[int] = Query(None),
- collection_status: Optional[str] = Query(None),
-):
- conn = get_db()
- clauses: list[str] = []
- params: list = []
- if company_id is not None:
- clauses.append("s.company_id = ?")
- params.append(company_id)
- status_sql, status_params = _collection_status_clause(collection_status)
- if status_sql:
- clauses.append(status_sql)
- params.extend(status_params)
- where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
- rows = conn.execute(
- f"""
- {_SALE_SELECT}
- {where}
- ORDER BY s.sale_date DESC, s.id DESC
- """,
- params,
- ).fetchall()
- conn.close()
- sales = [_sale_row_to_dict(r) for r in rows]
- return {"sales": sales, "summary": _sales_summary(sales)}
-
-
-def _collection_slip_payload(company_id: int) -> dict:
- """Tahsilat irsaliyesi verisi; yalnizca bekleyen satislar."""
- conn = get_db()
- company = conn.execute(
- """
- SELECT id, name, address, tax_number
- FROM companies WHERE id = ?
- """,
- (company_id,),
- ).fetchone()
- if not company:
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi")
-
- rows = conn.execute(
- f"""
- {_SALE_SELECT}
- WHERE s.company_id = ?
- AND {_OPEN_BALANCE_SQL}
- ORDER BY s.sale_date ASC, s.id ASC
- """,
- (company_id,),
- ).fetchall()
- conn.close()
- sales = [_sale_row_to_dict(r) for r in rows]
- slip_lines = [line for line in (slip_line_from_sale(s) for s in sales) if line]
- total_remaining = round(sum(line["remaining_amount"] for line in slip_lines), 2)
- total_bags = round(sum(line["bag_count"] for line in slip_lines), 2)
- return {
- "issued_date": date.today().isoformat(),
- "company": {
- "id": company["id"],
- "name": company["name"],
- "address": company["address"] or "",
- "tax_number": company["tax_number"] or "",
- },
- "lines": slip_lines,
- "total_bags": total_bags,
- "total_amount": total_remaining,
- "total_remaining": total_remaining,
- "line_count": len(slip_lines),
- }
-
-
-@router.get("/collection-slip")
-def talash_collection_slip(company_id: int = Query(...)):
- return {"slip": _collection_slip_payload(company_id)}
-
-
-@router.get("/collection-slip.pdf")
-def talash_collection_slip_pdf(company_id: int = Query(...)):
- """Yazdirma: tarayici HTML altbilgisi yerine salt PDF."""
- slip = _collection_slip_payload(company_id)
- if slip["line_count"] == 0:
- raise HTTPException(status_code=404, detail="Bekleyen satis yok")
- pdf_bytes = build_collection_slip_pdf(slip)
- doc_id = f"TI-{int(slip['company']['id']):04d}-{(slip['issued_date'] or '').replace('-', '')}"
- return Response(
- content=pdf_bytes,
- media_type="application/pdf",
- headers={
- "Content-Disposition": f'inline; filename="tahsilat-{doc_id}.pdf"',
- },
- )
-
-
-def _unit_cost_row_to_dict(row) -> dict:
- return {
- "id": row["id"],
- "effective_date": row["effective_date"],
- "cost_per_bag": round(float(row["cost_per_bag"]), 2),
- "notes": row["notes"] or "",
- "created_at": row["created_at"],
- }
-
-
-def _expense_row_to_dict(row) -> dict:
- return {
- "id": row["id"],
- "expense_date": row["expense_date"],
- "category": row["category"] or "",
- "amount": round(float(row["amount"]), 2),
- "notes": row["notes"] or "",
- "created_at": row["created_at"],
- }
-
-
-@router.get("/unit-costs")
-def list_talash_unit_costs():
- conn = get_db()
- rows = conn.execute(
- """
- SELECT id, effective_date, cost_per_bag, notes, created_at
- FROM talash_unit_costs
- ORDER BY effective_date DESC, id DESC
- """
- ).fetchall()
- conn.close()
- return {"unit_costs": [_unit_cost_row_to_dict(r) for r in rows]}
-
-
-@router.post("/unit-costs")
-def create_talash_unit_cost(payload: TalashUnitCostPayload):
- if float(payload.cost_per_bag) <= 0:
- raise HTTPException(status_code=400, detail="Maliyet sifirdan buyuk olmali")
- conn = get_db()
- cur = conn.cursor()
- dup = cur.execute(
- "SELECT id FROM talash_unit_costs WHERE effective_date = ?",
- (payload.effective_date,),
- ).fetchone()
- if dup:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu gecerlilik tarihinde zaten tedarik maliyeti var",
- )
- cur.execute(
- """
- INSERT INTO talash_unit_costs (effective_date, cost_per_bag, notes)
- VALUES (?, ?, ?)
- """,
- (
- payload.effective_date,
- float(payload.cost_per_bag),
- (payload.notes or "").strip(),
- ),
- )
- rid = cur.lastrowid
- conn.commit()
- row = conn.execute(
- "SELECT id, effective_date, cost_per_bag, notes, created_at FROM talash_unit_costs WHERE id = ?",
- (rid,),
- ).fetchone()
- conn.close()
- return {"unit_cost": _unit_cost_row_to_dict(row)}
-
-
-@router.get("/unit-costs/quote")
-def talash_unit_cost_quote(sale_date: str = Query(...)):
- conn = get_db()
- cur = conn.cursor()
- quote = resolve_unit_cost(cur, sale_date)
- conn.close()
- return {"quote": quote}
-
-
-@router.patch("/unit-costs/{cost_id}")
-def update_talash_unit_cost(cost_id: int, payload: TalashUnitCostPayload):
- if float(payload.cost_per_bag) <= 0:
- raise HTTPException(status_code=400, detail="Maliyet sifirdan buyuk olmali")
- conn = get_db()
- cur = conn.cursor()
- existing = cur.execute(
- "SELECT id FROM talash_unit_costs WHERE id = ?", (cost_id,)
- ).fetchone()
- if not existing:
- conn.close()
- raise HTTPException(status_code=404, detail="Maliyet kaydi bulunamadi")
- dup = cur.execute(
- """
- SELECT id FROM talash_unit_costs
- WHERE effective_date = ? AND id != ?
- """,
- (payload.effective_date, cost_id),
- ).fetchone()
- if dup:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu gecerlilik tarihinde baska maliyet kaydi var",
- )
- cur.execute(
- """
- UPDATE talash_unit_costs
- SET effective_date = ?, cost_per_bag = ?, notes = ?
- WHERE id = ?
- """,
- (
- payload.effective_date,
- float(payload.cost_per_bag),
- (payload.notes or "").strip(),
- cost_id,
- ),
- )
- conn.commit()
- row = conn.execute(
- "SELECT id, effective_date, cost_per_bag, notes, created_at FROM talash_unit_costs WHERE id = ?",
- (cost_id,),
- ).fetchone()
- conn.close()
- return {"unit_cost": _unit_cost_row_to_dict(row)}
-
-
-@router.delete("/unit-costs/{cost_id}")
-def delete_talash_unit_cost(cost_id: int):
- conn = get_db()
- cur = conn.cursor()
- cur.execute("DELETE FROM talash_unit_costs WHERE id = ?", (cost_id,))
- conn.commit()
- deleted = cur.rowcount
- conn.close()
- return {"deleted": deleted > 0}
-
-
-@router.get("/expenses")
-def list_talash_expenses():
- conn = get_db()
- rows = conn.execute(
- """
- SELECT id, expense_date, category, amount, notes, created_at
- FROM talash_expenses
- ORDER BY expense_date DESC, id DESC
- """
- ).fetchall()
- conn.close()
- return {"expenses": [_expense_row_to_dict(r) for r in rows]}
-
-
-@router.post("/expenses")
-def create_talash_expense(payload: TalashExpensePayload):
- if float(payload.amount) <= 0:
- raise HTTPException(status_code=400, detail="Tutar sifirdan buyuk olmali")
- conn = get_db()
- cur = conn.cursor()
- cur.execute(
- """
- INSERT INTO talash_expenses (expense_date, category, amount, notes)
- VALUES (?, ?, ?, ?)
- """,
- (
- payload.expense_date,
- (payload.category or "").strip(),
- float(payload.amount),
- (payload.notes or "").strip(),
- ),
- )
- eid = cur.lastrowid
- conn.commit()
- row = conn.execute(
- """
- SELECT id, expense_date, category, amount, notes, created_at
- FROM talash_expenses WHERE id = ?
- """,
- (eid,),
- ).fetchone()
- conn.close()
- return {"expense": _expense_row_to_dict(row)}
-
-
-@router.patch("/expenses/{expense_id}")
-def update_talash_expense(expense_id: int, payload: TalashExpensePayload):
- if float(payload.amount) <= 0:
- raise HTTPException(status_code=400, detail="Tutar sifirdan buyuk olmali")
- conn = get_db()
- cur = conn.cursor()
- existing = cur.execute(
- "SELECT id FROM talash_expenses WHERE id = ?", (expense_id,)
- ).fetchone()
- if not existing:
- conn.close()
- raise HTTPException(status_code=404, detail="Gider kaydi bulunamadi")
- cur.execute(
- """
- UPDATE talash_expenses
- SET expense_date = ?, category = ?, amount = ?, notes = ?
- WHERE id = ?
- """,
- (
- payload.expense_date,
- (payload.category or "").strip(),
- float(payload.amount),
- (payload.notes or "").strip(),
- expense_id,
- ),
- )
- conn.commit()
- row = conn.execute(
- """
- SELECT id, expense_date, category, amount, notes, created_at
- FROM talash_expenses WHERE id = ?
- """,
- (expense_id,),
- ).fetchone()
- conn.close()
- return {"expense": _expense_row_to_dict(row)}
-
-
-@router.delete("/expenses/{expense_id}")
-def delete_talash_expense(expense_id: int):
- conn = get_db()
- cur = conn.cursor()
- cur.execute("DELETE FROM talash_expenses WHERE id = ?", (expense_id,))
- conn.commit()
- deleted = cur.rowcount
- conn.close()
- return {"deleted": deleted > 0}
-
-
-@router.get("/dashboard")
-def talash_financial_dashboard(
- month: str = Query(..., description="YYYY-MM"),
- company_id: Optional[int] = Query(None),
-):
- """Firma bazli aylik satis, tahsilat ve acik alacak ozeti."""
- try:
- conn = get_db()
- payload = build_talash_dashboard(conn, month, company_id)
- conn.close()
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
- return {"dashboard": payload}
-
-
-@router.patch("/sales/{sale_id}/collection")
-def update_talash_sale_collection(sale_id: int, payload: TalashCollectionPayload):
- conn = get_db()
- cur = conn.cursor()
- row = cur.execute(
- """
- SELECT id, total_amount, COALESCE(collected_amount, 0) AS collected_amount
- FROM company_talash_sales WHERE id = ?
- """,
- (sale_id,),
- ).fetchone()
- if not row:
- conn.close()
- raise HTTPException(status_code=404, detail="Satis kaydi bulunamadi")
-
- status = (payload.status or "").strip().lower() or None
- if status and status not in ("pending", "collected", "partial"):
- conn.close()
- raise HTTPException(status_code=400, detail="Gecersiz tahsilat durumu")
-
- new_collected, _, auto_at = apply_collected_update(
- float(row["total_amount"]),
- float(row["collected_amount"]),
- collected_amount=payload.collected_amount,
- add_collected_amount=payload.add_collected_amount,
- status=status,
- )
- collected_at = (payload.collected_at or "").strip() or auto_at
- _persist_sale_collection(cur, sale_id, float(row["total_amount"]), new_collected, collected_at)
- conn.commit()
- out = conn.execute(f"{_SALE_SELECT} WHERE s.id = ?", (sale_id,)).fetchone()
- conn.close()
- return {"sale": _sale_row_to_dict(out)}
-
-
-@router.post("/sales/bulk-collection")
-def bulk_update_talash_collection(payload: TalashBulkCollectionPayload):
- if not payload.sale_ids:
- raise HTTPException(status_code=400, detail="En az bir satis secilmeli")
-
- status = (payload.status or "collected").strip().lower()
- if status not in ("pending", "collected"):
- raise HTTPException(status_code=400, detail="Gecersiz tahsilat durumu")
-
- collected_at = (payload.collected_at or "").strip()
- if status == "collected" and not collected_at:
- collected_at = date.today().isoformat()
-
- conn = get_db()
- cur = conn.cursor()
- updated = 0
- for sid in payload.sale_ids:
- row = cur.execute(
- """
- SELECT id, total_amount, COALESCE(collected_amount, 0) AS collected_amount
- FROM company_talash_sales WHERE id = ?
- """,
- (int(sid),),
- ).fetchone()
- if not row:
- continue
- if status == "pending":
- new_collected = 0.0
- at = None
- else:
- new_collected = float(row["total_amount"])
- at = collected_at or date.today().isoformat()
- _persist_sale_collection(cur, int(sid), float(row["total_amount"]), new_collected, at)
- updated += 1
- conn.commit()
- conn.close()
- return {"updated": updated, "status": status}
-
-
-@router.post("/companies/{company_id}/collect-payment")
-def collect_talash_company_payment(company_id: int, payload: TalashCompanyPaymentPayload):
- """Firmadan alinan odemeyi acik satislara eski->yeni sirasiyla uygular."""
- amount = float(payload.amount)
- if amount <= 0:
- raise HTTPException(status_code=400, detail="Tutar sifirdan buyuk olmali")
-
- conn = get_db()
- cur = conn.cursor()
- if not _company_exists(cur, company_id):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi")
-
- rows = cur.execute(
- f"""
- {_SALE_SELECT}
- WHERE s.company_id = ?
- AND {_OPEN_BALANCE_SQL}
- ORDER BY s.sale_date ASC, s.id ASC
- """,
- (company_id,),
- ).fetchall()
- sales = [_sale_row_to_dict(r) for r in rows]
- updates = allocate_company_payment(sales, amount)
- if not updates:
- conn.close()
- raise HTTPException(status_code=400, detail="Acik bakiye yok")
-
- pay_at = (payload.collected_at or "").strip() or date.today().isoformat()
- applied = 0.0
- for sale_id, new_collected, add_amount in updates:
- row = next(s for s in sales if int(s["id"]) == sale_id)
- _persist_sale_collection(cur, sale_id, float(row["total_amount"]), new_collected, pay_at)
- applied += add_amount
-
- conn.commit()
- conn.close()
- return {
- "company_id": company_id,
- "requested_amount": round(amount, 2),
- "applied_amount": round(applied, 2),
- "updated_sales": len(updates),
- }
-
-
-@router.post("/sales")
-def create_talash_sale(payload: TalashSalePayload):
- if float(payload.bag_count) <= 0:
- raise HTTPException(status_code=400, detail="Cuval adedi sifirdan buyuk olmali")
-
- conn = get_db()
- cur = conn.cursor()
- if not _company_active(cur, payload.company_id):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi veya pasif")
-
- unit_price = payload.unit_price
- if unit_price is None:
- quote = resolve_unit_price(cur, payload.company_id, payload.sale_date)
- if not quote:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu tarih icin tanimli fiyat yok; birim fiyat girin veya once fiyat tanimlayin",
- )
- unit_price = quote["unit_price"]
- elif float(unit_price) <= 0:
- conn.close()
- raise HTTPException(status_code=400, detail="Birim fiyat sifirdan buyuk olmali")
-
- total = sale_total(payload.bag_count, float(unit_price))
- cur.execute(
- """
- INSERT INTO company_talash_sales
- (company_id, sale_date, bag_count, unit_price, total_amount, notes)
- VALUES (?, ?, ?, ?, ?, ?)
- """,
- (
- payload.company_id,
- payload.sale_date,
- float(payload.bag_count),
- float(unit_price),
- total,
- (payload.notes or "").strip(),
- ),
- )
- sid = cur.lastrowid
- conn.commit()
- row = conn.execute(f"{_SALE_SELECT} WHERE s.id = ?", (sid,)).fetchone()
- conn.close()
- return {"sale": _sale_row_to_dict(row)}
-
-
-@router.patch("/sales/{sale_id}")
-def update_talash_sale(sale_id: int, payload: TalashSalePayload):
- if float(payload.bag_count) <= 0:
- raise HTTPException(status_code=400, detail="Cuval adedi sifirdan buyuk olmali")
-
- conn = get_db()
- cur = conn.cursor()
- exists = cur.execute(
- "SELECT id FROM company_talash_sales WHERE id = ?", (sale_id,)
- ).fetchone()
- if not exists:
- conn.close()
- raise HTTPException(status_code=404, detail="Satis kaydi bulunamadi")
- existing_sale = cur.execute(
- "SELECT company_id FROM company_talash_sales WHERE id = ?", (sale_id,)
- ).fetchone()
- if not _company_writable(
- cur, payload.company_id, int(existing_sale["company_id"]) if existing_sale else None
- ):
- conn.close()
- raise HTTPException(status_code=404, detail="Firma bulunamadi veya pasif")
-
- unit_price = payload.unit_price
- if unit_price is None:
- quote = resolve_unit_price(cur, payload.company_id, payload.sale_date)
- if not quote:
- conn.close()
- raise HTTPException(
- status_code=400,
- detail="Bu tarih icin tanimli fiyat yok; birim fiyat girin",
- )
- unit_price = quote["unit_price"]
- elif float(unit_price) <= 0:
- conn.close()
- raise HTTPException(status_code=400, detail="Birim fiyat sifirdan buyuk olmali")
-
- total = sale_total(payload.bag_count, float(unit_price))
- cur.execute(
- """
- UPDATE company_talash_sales
- SET company_id = ?, sale_date = ?, bag_count = ?, unit_price = ?,
- total_amount = ?, notes = ?
- WHERE id = ?
- """,
- (
- payload.company_id,
- payload.sale_date,
- float(payload.bag_count),
- float(unit_price),
- total,
- (payload.notes or "").strip(),
- sale_id,
- ),
- )
- conn.commit()
- row = conn.execute(f"{_SALE_SELECT} WHERE s.id = ?", (sale_id,)).fetchone()
- conn.close()
- return {"sale": _sale_row_to_dict(row)}
-
-
-@router.delete("/sales/{sale_id}")
-def delete_talash_sale(sale_id: int):
- conn = get_db()
- cur = conn.cursor()
- cur.execute("DELETE FROM company_talash_sales WHERE id = ?", (sale_id,))
- conn.commit()
- deleted = cur.rowcount
- conn.close()
- return {"deleted": deleted > 0}
diff --git a/app/infrastructure/database.py b/app/infrastructure/database.py
index 94a9572cd958cd5f91841481d69c9ea40d1757e8..fb5db6301a080c60b76e3fbdc5d2b4364c69705f 100644
--- a/app/infrastructure/database.py
+++ b/app/infrastructure/database.py
@@ -113,93 +113,6 @@ def init_db():
_ensure_product_costs_schema(cur)
cur.execute("CREATE INDEX IF NOT EXISTS idx_product_costs_name ON product_costs(product_name)")
- cur.execute(
- """
- CREATE TABLE IF NOT EXISTS companies (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT UNIQUE NOT NULL,
- address TEXT DEFAULT '',
- tax_number TEXT DEFAULT '',
- notes TEXT DEFAULT '',
- is_active INTEGER NOT NULL DEFAULT 1,
- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
- )
- """
- )
- _ensure_companies_schema(cur)
- cur.execute("CREATE INDEX IF NOT EXISTS idx_companies_name ON companies(name)")
-
- cur.execute(
- """
- CREATE TABLE IF NOT EXISTS company_talash_prices (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- company_id INTEGER NOT NULL,
- effective_date TEXT NOT NULL,
- unit_price REAL NOT NULL,
- notes TEXT DEFAULT '',
- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY(company_id) REFERENCES companies(id),
- UNIQUE(company_id, effective_date)
- )
- """
- )
- cur.execute(
- """
- CREATE TABLE IF NOT EXISTS company_talash_sales (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- company_id INTEGER NOT NULL,
- sale_date TEXT NOT NULL,
- bag_count REAL NOT NULL,
- unit_price REAL NOT NULL,
- total_amount REAL NOT NULL,
- notes TEXT DEFAULT '',
- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY(company_id) REFERENCES companies(id)
- )
- """
- )
- cur.execute(
- "CREATE INDEX IF NOT EXISTS idx_talash_prices_company_date "
- "ON company_talash_prices(company_id, effective_date)"
- )
- cur.execute(
- "CREATE INDEX IF NOT EXISTS idx_talash_sales_company_date "
- "ON company_talash_sales(company_id, sale_date)"
- )
- _ensure_talash_sales_schema(cur)
-
- cur.execute(
- """
- CREATE TABLE IF NOT EXISTS talash_unit_costs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- effective_date TEXT NOT NULL UNIQUE,
- cost_per_bag REAL NOT NULL,
- notes TEXT DEFAULT '',
- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
- )
- """
- )
- cur.execute(
- """
- CREATE TABLE IF NOT EXISTS talash_expenses (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- expense_date TEXT NOT NULL,
- category TEXT NOT NULL DEFAULT '',
- amount REAL NOT NULL,
- notes TEXT DEFAULT '',
- created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
- )
- """
- )
- cur.execute(
- "CREATE INDEX IF NOT EXISTS idx_talash_unit_costs_date "
- "ON talash_unit_costs(effective_date)"
- )
- cur.execute(
- "CREATE INDEX IF NOT EXISTS idx_talash_expenses_date "
- "ON talash_expenses(expense_date)"
- )
-
cur.execute("CREATE INDEX IF NOT EXISTS idx_orders_order_date ON orders(order_date)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_orders_order_no ON orders(order_no)")
cur.execute(
@@ -295,70 +208,6 @@ def _ensure_users_schema(cur):
)
-def _ensure_companies_schema(cur):
- columns = {
- row["name"] for row in cur.execute("PRAGMA table_info(companies)").fetchall()
- }
- if "address" not in columns:
- cur.execute("ALTER TABLE companies ADD COLUMN address TEXT DEFAULT ''")
- if "tax_number" not in columns:
- cur.execute("ALTER TABLE companies ADD COLUMN tax_number TEXT DEFAULT ''")
- if "is_active" not in columns:
- cur.execute(
- "ALTER TABLE companies ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1"
- )
- _rename_legacy_inactive_company_names(cur)
-
-
-def _ensure_talash_sales_schema(cur) -> None:
- columns = {
- row["name"] for row in cur.execute("PRAGMA table_info(company_talash_sales)").fetchall()
- }
- if "collection_status" not in columns:
- cur.execute(
- "ALTER TABLE company_talash_sales "
- "ADD COLUMN collection_status TEXT NOT NULL DEFAULT 'pending'"
- )
- if "collected_at" not in columns:
- cur.execute("ALTER TABLE company_talash_sales ADD COLUMN collected_at TEXT")
- if "collected_amount" not in columns:
- cur.execute(
- "ALTER TABLE company_talash_sales "
- "ADD COLUMN collected_amount REAL NOT NULL DEFAULT 0"
- )
- cur.execute(
- """
- UPDATE company_talash_sales
- SET collected_amount = total_amount
- WHERE COALESCE(collection_status, 'pending') = 'collected'
- """
- )
-
-
-def _rename_legacy_inactive_company_names(cur) -> None:
- """Pasif firmalar eski isimle duruyorsa adini arsivler (aynı isimle yeni kayit icin)."""
- rows = cur.execute(
- """
- SELECT id, name FROM companies
- WHERE COALESCE(is_active, 1) = 0
- """
- ).fetchall()
- for row in rows:
- cid = int(row["id"])
- name = row["name"] or ""
- suffix = f" (pasif #{cid})"
- if name.endswith(suffix):
- continue
- base = " ".join(name.strip().split())
- max_base = max(1, 240 - len(suffix))
- if len(base) > max_base:
- base = base[:max_base].rstrip()
- cur.execute(
- "UPDATE companies SET name = ? WHERE id = ?",
- (f"{base}{suffix}", cid),
- )
-
-
def _ensure_product_costs_schema(cur):
columns = {
row["name"] for row in cur.execute("PRAGMA table_info(product_costs)").fetchall()
diff --git a/app/main.py b/app/main.py
index f77bd8d78facd9f7af3a88de4a4f5ed0c7d46804..908bbb39239056bc1506425ac1522ae271bcd9dd 100644
--- a/app/main.py
+++ b/app/main.py
@@ -6,129 +6,16 @@ FastAPI uygulama fabrikası ve statik dosya sunumu.
from __future__ import annotations
-import re
from contextlib import asynccontextmanager
-from fastapi import FastAPI, HTTPException
-from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
+from fastapi import FastAPI
+from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
-from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
-from starlette.requests import Request
-from starlette.responses import Response
from app.api.router import include_api_routers
from app.core.config import SESSION_SECRET, STATIC_DIR
from app.infrastructure.database import init_db
-from app.static_assets import asset_build_token, resolve_entry_css, resolve_entry_js
-
-_HTML_NO_CACHE = "no-cache, no-store, must-revalidate"
-_ASSETS_CACHE = "public, max-age=31536000, immutable"
-_LEGACY_ASSET_CACHE = "no-cache, must-revalidate"
-
-_LEGACY_ENTRY_JS = re.compile(r"^/assets/index-.+\.js$")
-_LEGACY_ENTRY_CSS = re.compile(r"^/assets/index-.+\.css$")
-
-
-def _entry_js_file_response() -> FileResponse:
- path = resolve_entry_js()
- if path is None:
- raise HTTPException(status_code=404, detail="JS bundle bulunamadi")
- return FileResponse(
- path,
- media_type="application/javascript",
- headers={"Cache-Control": _ASSETS_CACHE},
- )
-
-
-def _entry_css_file_response() -> FileResponse:
- path = resolve_entry_css()
- if path is None:
- raise HTTPException(status_code=404, detail="CSS bundle bulunamadi")
- return FileResponse(
- path,
- media_type="text/css",
- headers={"Cache-Control": _ASSETS_CACHE},
- )
-
-
-def _spa_index_html() -> str:
- """Her istekte guncel asset yollarini garanti eder (eski onbellekli index.html icin)."""
- version = asset_build_token()
- return f"""
-
-
-
-
-
- Muhasebe App
-
-
-
-
-
-
-"""
-
-
-def _spa_index_response() -> HTMLResponse:
- return HTMLResponse(
- _spa_index_html(),
- headers={
- "Cache-Control": _HTML_NO_CACHE,
- "Pragma": "no-cache",
- "Expires": "0",
- },
- )
-
-
-def _legacy_js_redirect() -> RedirectResponse:
- version = asset_build_token()
- return RedirectResponse(
- url=f"/assets/index.js?v={version}",
- status_code=302,
- headers={"Cache-Control": _LEGACY_ASSET_CACHE},
- )
-
-
-def _legacy_css_redirect() -> RedirectResponse:
- version = asset_build_token()
- return RedirectResponse(
- url=f"/assets/index.css?v={version}",
- status_code=302,
- headers={"Cache-Control": _LEGACY_ASSET_CACHE},
- )
-
-
-class SpaAssetFallbackMiddleware(BaseHTTPMiddleware):
- """Eski tarayici onbellegindeki dev ve hash'li asset URL'lerini kurtarir."""
-
- async def dispatch(self, request: Request, call_next) -> Response:
- path = request.url.path
- if path == "/src/main.jsx" or _LEGACY_ENTRY_JS.match(path):
- return _legacy_js_redirect()
- if _LEGACY_ENTRY_CSS.match(path):
- return _legacy_css_redirect()
- return await call_next(request)
-
-
-class StaticCacheControlMiddleware(BaseHTTPMiddleware):
- """Deploy sonrasi eski index.html onbellegi yanlis asset hash'lerine yol acmasin."""
-
- async def dispatch(self, request: Request, call_next) -> Response:
- response = await call_next(request)
- path = request.url.path
- if path.startswith("/assets/") and not (
- _LEGACY_ENTRY_JS.match(path) or _LEGACY_ENTRY_CSS.match(path)
- ):
- response.headers["Cache-Control"] = _ASSETS_CACHE
- elif path == "/" or path.endswith(".html"):
- response.headers["Cache-Control"] = _HTML_NO_CACHE
- response.headers["Pragma"] = "no-cache"
- elif response.headers.get("content-type", "").startswith("text/html"):
- response.headers["Cache-Control"] = _HTML_NO_CACHE
- response.headers["Pragma"] = "no-cache"
- return response
@asynccontextmanager
@@ -141,8 +28,6 @@ async def lifespan(app: FastAPI):
def create_app() -> FastAPI:
"""FastAPI uygulamasını middleware ve route'larla oluşturur."""
application = FastAPI(title="Muhasebe App", lifespan=lifespan)
- application.add_middleware(StaticCacheControlMiddleware)
- application.add_middleware(SpaAssetFallbackMiddleware)
application.add_middleware(
SessionMiddleware,
secret_key=SESSION_SECRET,
@@ -155,18 +40,9 @@ def create_app() -> FastAPI:
include_api_routers(application)
@application.get("/")
- @application.get("/index.html")
def serve_index():
"""React giriş dosyasını döndürür."""
- return _spa_index_response()
-
- @application.get("/assets/index.js")
- def serve_entry_js():
- return _entry_js_file_response()
-
- @application.get("/assets/index.css")
- def serve_entry_css():
- return _entry_css_file_response()
+ return FileResponse(STATIC_DIR / "index.html")
application.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")
diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py
index 2aed854fc7474b1b617c202117d95ad293a5fccf..c50b717cbec882a6075dde81c396426b094e601d 100644
--- a/app/schemas/__init__.py
+++ b/app/schemas/__init__.py
@@ -5,22 +5,11 @@ Alt modüllerde domain bazlı ayrım; `from app.schemas import X` ile geriye uyu
"""
from app.schemas.auth import LoginPayload
-from app.schemas.companies import CompanyPayload
from app.schemas.expenses import ExpensePayload, ProductCostPayload
from app.schemas.lumber import LumberTierCreatePayload, LumberTierPutPayload, LumberTransactionPayload
from app.schemas.orders import OrderPayload
-from app.schemas.talash import (
- TalashBulkCollectionPayload,
- TalashCollectionPayload,
- TalashCompanyPaymentPayload,
- TalashExpensePayload,
- TalashPricePayload,
- TalashSalePayload,
- TalashUnitCostPayload,
-)
__all__ = [
- "CompanyPayload",
"ExpensePayload",
"LoginPayload",
"LumberTierCreatePayload",
@@ -28,11 +17,4 @@ __all__ = [
"LumberTransactionPayload",
"OrderPayload",
"ProductCostPayload",
- "TalashBulkCollectionPayload",
- "TalashCollectionPayload",
- "TalashCompanyPaymentPayload",
- "TalashExpensePayload",
- "TalashPricePayload",
- "TalashSalePayload",
- "TalashUnitCostPayload",
]
diff --git a/app/schemas/companies.py b/app/schemas/companies.py
deleted file mode 100644
index b1ab4fa32f488a92e08a7b2553372daaed999d6e..0000000000000000000000000000000000000000
--- a/app/schemas/companies.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Firma kayitlari icin istek semalari."""
-
-from pydantic import BaseModel
-
-
-class CompanyPayload(BaseModel):
- """Firma olusturma/guncelleme govdesi."""
-
- name: str
- address: str = ""
- tax_number: str = ""
- notes: str = ""
diff --git a/app/schemas/talash.py b/app/schemas/talash.py
deleted file mode 100644
index 5cbe3966de794518398c86a291f633f5a7f205e6..0000000000000000000000000000000000000000
--- a/app/schemas/talash.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Talas fiyat ve satis istek semalari."""
-
-from typing import Optional
-
-from pydantic import BaseModel
-
-
-class TalashPricePayload(BaseModel):
- company_id: int
- effective_date: str
- unit_price: float
- notes: str = ""
-
-
-class TalashSalePayload(BaseModel):
- company_id: int
- sale_date: str
- bag_count: float
- unit_price: Optional[float] = None
- notes: str = ""
-
-
-class TalashCollectionPayload(BaseModel):
- """Kismi veya tam tahsilat: collected_amount mutlak, add_collected_amount ekleme."""
-
- status: Optional[str] = None
- collected_amount: Optional[float] = None
- add_collected_amount: Optional[float] = None
- collected_at: Optional[str] = None
-
-
-class TalashBulkCollectionPayload(BaseModel):
- sale_ids: list[int]
- status: str = "collected"
- collected_at: Optional[str] = None
-
-
-class TalashCompanyPaymentPayload(BaseModel):
- """Firmaya gelen odemeyi acik satislara (FIFO) dagitir."""
-
- amount: float
- collected_at: Optional[str] = None
-
-
-class TalashUnitCostPayload(BaseModel):
- effective_date: str
- cost_per_bag: float
- notes: str = ""
-
-
-class TalashExpensePayload(BaseModel):
- expense_date: str
- category: str = ""
- amount: float
- notes: str = ""
diff --git a/app/services/talash_collection.py b/app/services/talash_collection.py
deleted file mode 100644
index 9d4968c97e7cd238b3075f3f7cd7203dd78b3b7e..0000000000000000000000000000000000000000
--- a/app/services/talash_collection.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""Talaş satış tahsilatı: kismi odeme, kalan bakiye, durum senkronu."""
-
-from __future__ import annotations
-
-from datetime import date
-from typing import Any, Optional
-
-_AMOUNT_EPS = 0.005
-
-
-def _round_money(value: float) -> float:
- return round(float(value or 0), 2)
-
-
-def remaining_amount(total_amount: float, collected_amount: float) -> float:
- return _round_money(max(0.0, float(total_amount or 0) - float(collected_amount or 0)))
-
-
-def sync_collection_status(total_amount: float, collected_amount: float) -> str:
- total = float(total_amount or 0)
- collected = float(collected_amount or 0)
- if collected <= _AMOUNT_EPS:
- return "pending"
- if collected + _AMOUNT_EPS >= total:
- return "collected"
- return "partial"
-
-
-def enrich_sale_row(row_dict: dict[str, Any]) -> dict[str, Any]:
- total = _round_money(row_dict.get("total_amount"))
- collected = _round_money(row_dict.get("collected_amount", 0))
- remaining = remaining_amount(total, collected)
- status = sync_collection_status(total, collected)
- row_dict["total_amount"] = total
- row_dict["collected_amount"] = collected
- row_dict["remaining_amount"] = remaining
- row_dict["collection_status"] = status
- return row_dict
-
-
-def summarize_sales(sales: list[dict[str, Any]]) -> dict[str, float | int]:
- total_bags = 0.0
- open_bags = 0.0
- total_amount = 0.0
- collected_amount = 0.0
- remaining_amount_sum = 0.0
- open_count = 0
- partial_count = 0
- closed_count = 0
-
- for sale in sales:
- bags = float(sale.get("bag_count") or 0)
- total_bags += bags
- total = float(sale.get("total_amount") or 0)
- collected = float(sale.get("collected_amount") or 0)
- remaining = remaining_amount(total, collected)
- total_amount += total
- collected_amount += collected
- remaining_amount_sum += remaining
- status = sync_collection_status(total, collected)
- if status == "collected":
- closed_count += 1
- elif status == "partial":
- partial_count += 1
- open_count += 1
- open_bags += bags
- else:
- open_count += 1
- open_bags += bags
-
- return {
- "sale_count": len(sales),
- "total_bags": _round_money(total_bags),
- "total_amount": _round_money(total_amount),
- "collected_amount": _round_money(collected_amount),
- "remaining_amount": _round_money(remaining_amount_sum),
- "open_count": open_count,
- "partial_count": partial_count,
- "closed_count": closed_count,
- "pending_count": open_count,
- "pending_bags": _round_money(open_bags),
- "pending_amount": _round_money(remaining_amount_sum),
- "collected_count": closed_count,
- "collected_bags": _round_money(total_bags - open_bags),
- }
-
-
-def clamp_collected(total_amount: float, collected_amount: float) -> float:
- total = float(total_amount or 0)
- return _round_money(min(max(0.0, float(collected_amount or 0)), total))
-
-
-def apply_collected_update(
- total_amount: float,
- current_collected: float,
- *,
- collected_amount: Optional[float] = None,
- add_collected_amount: Optional[float] = None,
- status: Optional[str] = None,
-) -> tuple[float, str, Optional[str]]:
- """Yeni tahsil tutari ve durum; collected_at icin collected ise bugun."""
- total = float(total_amount or 0)
- current = float(current_collected or 0)
-
- if status == "pending":
- new_collected = 0.0
- elif status == "collected" and collected_amount is None and add_collected_amount is None:
- new_collected = total
- elif collected_amount is not None:
- new_collected = clamp_collected(total, collected_amount)
- elif add_collected_amount is not None:
- new_collected = clamp_collected(total, current + float(add_collected_amount))
- else:
- new_collected = current
-
- new_status = sync_collection_status(total, new_collected)
- collected_at: Optional[str] = None
- if new_status == "collected":
- collected_at = date.today().isoformat()
- elif new_status == "partial" and new_collected > current + _AMOUNT_EPS:
- collected_at = date.today().isoformat()
- elif new_status == "pending":
- collected_at = None
-
- return new_collected, new_status, collected_at
-
-
-def slip_line_from_sale(sale: dict[str, Any]) -> Optional[dict[str, Any]]:
- remaining = float(sale.get("remaining_amount") or 0)
- if remaining <= _AMOUNT_EPS:
- return None
- return {
- "id": sale["id"],
- "sale_date": sale["sale_date"],
- "bag_count": sale["bag_count"],
- "unit_price": sale["unit_price"],
- "total_amount": sale["total_amount"],
- "collected_amount": sale.get("collected_amount", 0),
- "remaining_amount": remaining,
- "notes": sale.get("notes") or "",
- }
-
-
-def allocate_company_payment(
- sales: list[dict[str, Any]], payment_amount: float
-) -> list[tuple[int, float, float]]:
- """
- Odeme tutarini satirlara (id, yeni_collected, add_amount) FIFO dagitir.
- sales: sale_date/id sirali, acik bakiyeli kayitlar.
- """
- left = _round_money(payment_amount)
- if left <= 0:
- return []
-
- updates: list[tuple[int, float, float]] = []
- for sale in sales:
- if left <= _AMOUNT_EPS:
- break
- total = float(sale["total_amount"])
- current = float(sale.get("collected_amount") or 0)
- rem = remaining_amount(total, current)
- if rem <= _AMOUNT_EPS:
- continue
- pay = min(rem, left)
- new_collected = clamp_collected(total, current + pay)
- updates.append((int(sale["id"]), new_collected, pay))
- left = _round_money(left - pay)
- return updates
diff --git a/app/services/talash_costs.py b/app/services/talash_costs.py
deleted file mode 100644
index c6159d4deea86580788b402009f50d074ae077df..0000000000000000000000000000000000000000
--- a/app/services/talash_costs.py
+++ /dev/null
@@ -1,84 +0,0 @@
-"""Talaş tedarik birim maliyeti ve dönem maliyet hesapları."""
-
-from __future__ import annotations
-
-from typing import Any, Optional
-
-
-def resolve_unit_cost(cur, as_of_date: str) -> Optional[dict[str, Any]]:
- """effective_date <= as_of_date olan en güncel çuval tedarik maliyeti."""
- row = cur.execute(
- """
- SELECT id, effective_date, cost_per_bag, notes
- FROM talash_unit_costs
- WHERE effective_date <= ?
- ORDER BY effective_date DESC, id DESC
- LIMIT 1
- """,
- (as_of_date,),
- ).fetchone()
- if not row:
- return None
- return {
- "cost_id": row["id"],
- "effective_date": row["effective_date"],
- "cost_per_bag": round(float(row["cost_per_bag"]), 2),
- "notes": row["notes"] or "",
- }
-
-
-def sale_procurement_cost(cur, sale_date: str, bag_count: float) -> tuple[float, bool]:
- """Satır tedarik maliyeti ve maliyet tarifesi bulundu mu."""
- quote = resolve_unit_cost(cur, sale_date)
- if not quote:
- return 0.0, False
- total = round(float(bag_count) * quote["cost_per_bag"], 2)
- return total, True
-
-
-def sum_period_procurement_cost(
- cur,
- start: str,
- end: str,
- company_id: Optional[int] = None,
-) -> dict[str, float | int]:
- extra_sql = ""
- params: list = [start, end]
- if company_id is not None:
- extra_sql = " AND s.company_id = ?"
- params.append(company_id)
-
- rows = cur.execute(
- f"""
- SELECT s.sale_date, s.bag_count
- FROM company_talash_sales s
- WHERE s.sale_date >= ? AND s.sale_date < ?
- {extra_sql}
- """,
- params,
- ).fetchall()
-
- total = 0.0
- missing = 0
- for row in rows:
- line_cost, found = sale_procurement_cost(cur, row["sale_date"], float(row["bag_count"]))
- total += line_cost
- if not found:
- missing += 1
-
- return {
- "procurement_cost": round(total, 2),
- "missing_cost_sale_count": missing,
- }
-
-
-def sum_period_operating_expenses(cur, start: str, end: str) -> float:
- row = cur.execute(
- """
- SELECT COALESCE(SUM(amount), 0) AS total
- FROM talash_expenses
- WHERE expense_date >= ? AND expense_date < ?
- """,
- (start, end),
- ).fetchone()
- return round(float(row["total"]), 2)
diff --git a/app/services/talash_dashboard.py b/app/services/talash_dashboard.py
deleted file mode 100644
index 72aeed25336c24ec4c8aafcc2c4670ff2add1c8f..0000000000000000000000000000000000000000
--- a/app/services/talash_dashboard.py
+++ /dev/null
@@ -1,261 +0,0 @@
-"""Talaş satış / tahsilat finansal özet sorguları."""
-
-from __future__ import annotations
-
-import re
-from datetime import date
-from typing import Any, Optional
-
-from app.services.talash_costs import (
- sum_period_operating_expenses,
- sum_period_procurement_cost,
-)
-
-_MONTH_RE = re.compile(r"^\d{4}-\d{2}$")
-
-_REMAINING_EXPR = "(s.total_amount - COALESCE(s.collected_amount, 0))"
-_OPEN_WHERE = "COALESCE(s.collected_amount, 0) + 0.005 < s.total_amount"
-
-
-def _parse_month(month: str) -> str:
- if not _MONTH_RE.match(month):
- raise ValueError("month YYYY-MM olmali")
- y, m = month.split("-")
- if not (1 <= int(m) <= 12):
- raise ValueError("month gecersiz")
- return month
-
-
-def _month_bounds(month: str) -> tuple[str, str]:
- y, m = map(int, month.split("-"))
- start = f"{y:04d}-{m:02d}-01"
- if m == 12:
- end = f"{y + 1:04d}-01-01"
- else:
- end = f"{y:04d}-{m + 1:02d}-01"
- return start, end
-
-
-def _shift_month(month: str, delta: int) -> str:
- y, m = map(int, month.split("-"))
- m += delta
- while m < 1:
- m += 12
- y -= 1
- while m > 12:
- m -= 12
- y += 1
- return f"{y:04d}-{m:02d}"
-
-
-def _company_clause(company_id: Optional[int]) -> tuple[str, list]:
- if company_id is None:
- return "", []
- return " AND s.company_id = ?", [company_id]
-
-
-def build_talash_dashboard(
- conn,
- month: str,
- company_id: Optional[int] = None,
- series_months: int = 6,
-) -> dict[str, Any]:
- month = _parse_month(month)
- start, end = _month_bounds(month)
- extra_sql, extra_params = _company_clause(company_id)
-
- period = conn.execute(
- f"""
- SELECT
- COUNT(*) AS sale_count,
- COALESCE(SUM(s.bag_count), 0) AS total_bags,
- COALESCE(SUM(s.total_amount), 0) AS sales_amount,
- COALESCE(SUM(COALESCE(s.collected_amount, 0)), 0) AS collected_on_sales,
- COALESCE(SUM({_REMAINING_EXPR}), 0) AS pending_on_sales
- FROM company_talash_sales s
- WHERE s.sale_date >= ? AND s.sale_date < ?
- {extra_sql}
- """,
- [start, end, *extra_params],
- ).fetchone()
-
- collected_cash = conn.execute(
- f"""
- SELECT COALESCE(SUM(COALESCE(s.collected_amount, 0)), 0) AS amount
- FROM company_talash_sales s
- WHERE COALESCE(s.collected_amount, 0) > 0.005
- AND s.collected_at >= ? AND s.collected_at < ?
- {extra_sql}
- """,
- [start, end, *extra_params],
- ).fetchone()
-
- open_receivable = conn.execute(
- f"""
- SELECT
- COUNT(*) AS sale_count,
- COALESCE(SUM({_REMAINING_EXPR}), 0) AS amount
- FROM company_talash_sales s
- WHERE {_OPEN_WHERE}
- {extra_sql}
- """,
- extra_params,
- ).fetchone()
-
- series_start = _shift_month(month, -(series_months - 1))
- series_start_date = f"{series_start}-01"
- series_rows = conn.execute(
- f"""
- SELECT
- substr(s.sale_date, 1, 7) AS ym,
- COALESCE(SUM(s.total_amount), 0) AS sales_amount,
- COALESCE(SUM(s.bag_count), 0) AS bags
- FROM company_talash_sales s
- WHERE s.sale_date >= ?
- {extra_sql}
- GROUP BY ym
- ORDER BY ym ASC
- """,
- [series_start_date, *extra_params],
- ).fetchall()
-
- collection_rows = conn.execute(
- f"""
- SELECT
- substr(s.collected_at, 1, 7) AS ym,
- COALESCE(SUM(COALESCE(s.collected_amount, 0)), 0) AS collected_amount
- FROM company_talash_sales s
- WHERE COALESCE(s.collected_amount, 0) > 0.005
- AND s.collected_at >= ?
- AND length(trim(s.collected_at)) >= 7
- {extra_sql}
- GROUP BY ym
- ORDER BY ym ASC
- """,
- [series_start_date, *extra_params],
- ).fetchall()
-
- sales_by_ym = {r["ym"]: float(r["sales_amount"]) for r in series_rows}
- bags_by_ym = {r["ym"]: float(r["bags"]) for r in series_rows}
- collected_by_ym = {r["ym"]: float(r["collected_amount"]) for r in collection_rows}
-
- monthly_series = []
- cursor = series_start
- for _ in range(series_months):
- monthly_series.append(
- {
- "month": cursor,
- "sales_amount": round(sales_by_ym.get(cursor, 0.0), 2),
- "collected_amount": round(collected_by_ym.get(cursor, 0.0), 2),
- "bags": round(bags_by_ym.get(cursor, 0.0), 2),
- }
- )
- cursor = _shift_month(cursor, 1)
-
- company_rows = conn.execute(
- f"""
- SELECT
- c.id AS company_id,
- c.name AS company_name,
- COUNT(s.id) AS sale_count,
- COALESCE(SUM(s.bag_count), 0) AS total_bags,
- COALESCE(SUM(s.total_amount), 0) AS sales_amount,
- COALESCE(SUM(COALESCE(s.collected_amount, 0)), 0) AS collected_amount,
- COALESCE(SUM({_REMAINING_EXPR}), 0) AS pending_amount
- FROM company_talash_sales s
- JOIN companies c ON c.id = s.company_id
- WHERE s.sale_date >= ? AND s.sale_date < ?
- {extra_sql}
- GROUP BY c.id, c.name
- ORDER BY sales_amount DESC, c.name COLLATE NOCASE ASC
- """,
- [start, end, *extra_params],
- ).fetchall()
-
- by_company = []
- for row in company_rows:
- sales_amt = round(float(row["sales_amount"]), 2)
- coll = round(float(row["collected_amount"]), 2)
- rate = round((coll / sales_amt) * 100, 1) if sales_amt > 0 else 0.0
- by_company.append(
- {
- "company_id": row["company_id"],
- "company_name": row["company_name"],
- "sale_count": row["sale_count"],
- "total_bags": round(float(row["total_bags"]), 2),
- "sales_amount": sales_amt,
- "collected_amount": coll,
- "pending_amount": round(float(row["pending_amount"]), 2),
- "collection_rate": rate,
- }
- )
-
- open_by_company_rows = conn.execute(
- f"""
- SELECT
- c.id AS company_id,
- c.name AS company_name,
- COALESCE(SUM({_REMAINING_EXPR}), 0) AS open_amount
- FROM company_talash_sales s
- JOIN companies c ON c.id = s.company_id
- WHERE {_OPEN_WHERE}
- GROUP BY c.id, c.name
- HAVING open_amount > 0.005
- ORDER BY open_amount DESC, c.name COLLATE NOCASE ASC
- LIMIT 12
- """
- ).fetchall()
-
- open_by_company = [
- {
- "company_id": r["company_id"],
- "company_name": r["company_name"],
- "open_amount": round(float(r["open_amount"]), 2),
- }
- for r in open_by_company_rows
- ]
-
- sales_amount = round(float(period["sales_amount"]), 2)
- collected_cash_amount = round(float(collected_cash["amount"]), 2)
-
- cur = conn.cursor()
- cogs = sum_period_procurement_cost(cur, start, end, company_id)
- procurement_cost = float(cogs["procurement_cost"])
- missing_cost_sale_count = int(cogs["missing_cost_sale_count"])
- operating_expenses = sum_period_operating_expenses(cur, start, end)
- gross_profit = round(sales_amount - procurement_cost, 2)
- net_profit = round(gross_profit - operating_expenses, 2)
- margin_rate = round((net_profit / sales_amount) * 100, 1) if sales_amount > 0 else 0.0
-
- return {
- "filters": {"month": month, "company_id": company_id},
- "period": {
- "month": month,
- "sale_count": period["sale_count"],
- "total_bags": round(float(period["total_bags"]), 2),
- "sales_amount": sales_amount,
- "collected_on_sales": round(float(period["collected_on_sales"]), 2),
- "pending_on_sales": round(float(period["pending_on_sales"]), 2),
- "collected_cash_amount": collected_cash_amount,
- "collection_rate": round((collected_cash_amount / sales_amount) * 100, 1)
- if sales_amount > 0
- else 0.0,
- },
- "open_receivable": {
- "sale_count": open_receivable["sale_count"],
- "amount": round(float(open_receivable["amount"]), 2),
- },
- "monthly_series": monthly_series,
- "by_company": by_company,
- "open_by_company": open_by_company,
- "profitability": {
- "sales_revenue": sales_amount,
- "procurement_cost": procurement_cost,
- "gross_profit": gross_profit,
- "operating_expenses": operating_expenses,
- "net_profit": net_profit,
- "margin_rate": margin_rate,
- "missing_cost_sale_count": missing_cost_sale_count,
- },
- "generated_on": date.today().isoformat(),
- }
diff --git a/app/services/talash_pricing.py b/app/services/talash_pricing.py
deleted file mode 100644
index 9a262803ac565f96ce23b1aefdc999f10b1e2fe3..0000000000000000000000000000000000000000
--- a/app/services/talash_pricing.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""Firma bazli talas (cuval) birim fiyat cozumlemesi."""
-
-from __future__ import annotations
-
-from typing import Any, Optional
-
-
-def resolve_unit_price(cur, company_id: int, as_of_date: str) -> Optional[dict[str, Any]]:
- """
- Verilen tarihte gecerli birim fiyat: effective_date <= as_of_date olan
- en guncel tarife satiri.
- """
- row = cur.execute(
- """
- SELECT id, company_id, effective_date, unit_price, notes
- FROM company_talash_prices
- WHERE company_id = ? AND effective_date <= ?
- ORDER BY effective_date DESC, id DESC
- LIMIT 1
- """,
- (company_id, as_of_date),
- ).fetchone()
- if not row:
- return None
- return {
- "price_id": row["id"],
- "company_id": row["company_id"],
- "effective_date": row["effective_date"],
- "unit_price": round(float(row["unit_price"]), 2),
- "notes": row["notes"] or "",
- }
-
-
-def sale_total(bag_count: float, unit_price: float) -> float:
- return round(float(bag_count) * float(unit_price), 2)
diff --git a/app/services/talash_slip_pdf.py b/app/services/talash_slip_pdf.py
deleted file mode 100644
index 32486becac2309f563323566e81c94a93c73824a..0000000000000000000000000000000000000000
--- a/app/services/talash_slip_pdf.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""Tahsilat irsaliyesi PDF (reportlab)."""
-
-from __future__ import annotations
-
-import io
-from typing import Any
-
-from reportlab.lib import colors
-from reportlab.lib.pagesizes import A4
-from reportlab.lib.units import mm
-from reportlab.pdfgen import canvas
-
-
-def _format_date_tr(iso: str) -> str:
- if not iso or len(iso) < 10:
- return iso or "—"
- parts = iso[:10].split("-")
- if len(parts) != 3:
- return iso
- y, m, d = parts
- return f"{d}.{m}.{y}"
-
-
-def _document_no(company_id: int, issued_date: str) -> str:
- day = (issued_date or "").replace("-", "") or "00000000"
- return f"TI-{int(company_id):04d}-{day}"
-
-
-def _money(value: float | int) -> str:
- return f"{float(value or 0):.2f} TL"
-
-
-def build_collection_slip_pdf(slip: dict[str, Any]) -> bytes:
- """Slip JSON yapisindan tek sayfalik PDF uretir."""
- stream = io.BytesIO()
- width, height = A4
- pdf = canvas.Canvas(stream, pagesize=A4)
- margin_x = 14 * mm
- content_w = width - 2 * margin_x
- y = height - 12 * mm
-
- company = slip.get("company") or {}
- issued = str(slip.get("issued_date") or "")
- doc_no = _document_no(int(company.get("id") or 0), issued)
- lines = slip.get("lines") or []
-
- header_h = 32 * mm
- y_top = y
- y_bottom = y - header_h
- pdf.setFillColor(colors.HexColor("#4338ca"))
- pdf.roundRect(margin_x, y_bottom, content_w, header_h, 6, fill=1, stroke=0)
-
- pdf.setFillColor(colors.white)
- pdf.setFont("Helvetica-Bold", 8)
- pdf.drawString(margin_x + 5 * mm, y_top - 7 * mm, "MUHASEBE · TALAS")
- pdf.setFont("Helvetica-Bold", 16)
- pdf.drawString(margin_x + 5 * mm, y_top - 16 * mm, "Tahsilat irsaliyesi")
-
- pdf.setFont("Helvetica", 9)
- meta_x = margin_x + content_w - 58 * mm
- pdf.drawString(meta_x, y_top - 8 * mm, f"Belge no: {doc_no}")
- pdf.drawString(meta_x, y_top - 14 * mm, f"Duzenleme: {_format_date_tr(issued)}")
-
- y = y_bottom - 8 * mm
- pdf.setFillColor(colors.HexColor("#4338ca"))
- pdf.setFont("Helvetica-Bold", 8)
- pdf.drawString(margin_x, y, "TAHSILAT YAPILACAK FIRMA")
- y -= 5 * mm
- pdf.setFillColor(colors.black)
- pdf.setFont("Helvetica-Bold", 13)
- pdf.drawString(margin_x, y, str(company.get("name") or ""))
- y -= 6 * mm
- pdf.setFont("Helvetica", 10)
- tax = company.get("tax_number") or ""
- if tax:
- pdf.drawString(margin_x, y, f"VKN / TCKN: {tax}")
- y -= 5 * mm
- address = company.get("address") or ""
- if address:
- for chunk in _wrap_text(str(address), 95):
- pdf.drawString(margin_x, y, chunk)
- y -= 4.5 * mm
-
- y -= 4 * mm
- pdf.setStrokeColor(colors.HexColor("#c7d2fe"))
- pdf.setFillColor(colors.HexColor("#eef2ff"))
- box_h = 14 * mm
- box_w = (content_w - 8 * mm) / 3
- labels = [
- ("Kalem sayisi", str(slip.get("line_count") or 0)),
- ("Toplam cuval", str(slip.get("total_bags") or 0)),
- ("Tahsil edilecek", _money(slip.get("total_amount") or 0)),
- ]
- for i, (label, value) in enumerate(labels):
- x = margin_x + i * (box_w + 4 * mm)
- fill = colors.HexColor("#eef2ff") if i < 2 else colors.HexColor("#e0e7ff")
- pdf.setFillColor(fill)
- pdf.roundRect(x, y - box_h, box_w, box_h, 4, fill=1, stroke=1)
- pdf.setFillColor(colors.HexColor("#64748b"))
- pdf.setFont("Helvetica", 7)
- pdf.drawString(x + 3 * mm, y - 5 * mm, label.upper())
- pdf.setFillColor(colors.HexColor("#312e81") if i == 2 else colors.black)
- pdf.setFont("Helvetica-Bold", 11 if i < 2 else 12)
- pdf.drawString(x + 3 * mm, y - 11 * mm, value)
-
- y -= box_h + 10 * mm
- col_w = [8 * mm, 24 * mm, 16 * mm, 24 * mm, 24 * mm, 26 * mm]
- headers = ["#", "Tarih", "Cuval", "Satis", "Tahsil", "Kalan"]
- pdf.setFillColor(colors.HexColor("#f1f5f9"))
- pdf.rect(margin_x, y - 7 * mm, content_w, 7 * mm, fill=1, stroke=0)
- pdf.setFillColor(colors.HexColor("#334155"))
- pdf.setFont("Helvetica-Bold", 8)
- x = margin_x + 2 * mm
- for header, w in zip(headers, col_w):
- pdf.drawString(x, y - 5 * mm, header)
- x += w
-
- y -= 7 * mm
- pdf.setFont("Helvetica", 9)
- pdf.setFillColor(colors.black)
- row_h = 6.5 * mm
- for idx, line in enumerate(lines, start=1):
- if y < 45 * mm:
- pdf.showPage()
- y = height - 15 * mm
- if idx % 2 == 0:
- pdf.setFillColor(colors.HexColor("#f8fafc"))
- pdf.rect(margin_x, y - row_h, content_w, row_h, fill=1, stroke=0)
- pdf.setFillColor(colors.black)
- cells = [
- str(idx),
- _format_date_tr(str(line.get("sale_date") or "")),
- str(line.get("bag_count") or 0),
- _money(line.get("total_amount") or 0),
- _money(line.get("collected_amount") or 0),
- _money(line.get("remaining_amount") or line.get("total_amount") or 0),
- ]
- x = margin_x + 2 * mm
- for cell, w in zip(cells, col_w):
- pdf.drawString(x, y - 4.5 * mm, cell)
- x += w
- y -= row_h
-
- y -= 2 * mm
- pdf.setStrokeColor(colors.HexColor("#6366f1"))
- pdf.setLineWidth(1.2)
- pdf.line(margin_x, y, margin_x + content_w, y)
- y -= 6 * mm
- pdf.setFont("Helvetica-Bold", 10)
- pdf.drawString(margin_x + 2 * mm, y, "Genel toplam")
- pdf.drawString(margin_x + col_w[0] + col_w[1] + col_w[2] + 2 * mm, y, str(slip.get("total_bags") or 0))
- pdf.drawString(
- margin_x + col_w[0] + col_w[1] + col_w[2] + col_w[3] + col_w[4] + 2 * mm,
- y,
- _money(slip.get("total_remaining") or slip.get("total_amount") or 0),
- )
-
- y -= 18 * mm
- sign_w = (content_w - 10 * mm) / 2
- pdf.setFont("Helvetica-Bold", 8)
- pdf.setFillColor(colors.HexColor("#475569"))
- pdf.drawString(margin_x, y, "TESLIM EDEN (PERSONEL)")
- pdf.drawString(margin_x + sign_w + 10 * mm, y, "TESLIM ALAN (FIRMA)")
- y -= 14 * mm
- pdf.setStrokeColor(colors.HexColor("#334155"))
- pdf.setLineWidth(0.8)
- pdf.line(margin_x, y, margin_x + sign_w, y)
- pdf.line(margin_x + sign_w + 10 * mm, y, margin_x + content_w, y)
-
- pdf.save()
- stream.seek(0)
- return stream.getvalue()
-
-
-def _wrap_text(text: str, max_chars: int) -> list[str]:
- words = text.split()
- if not words:
- return []
- lines: list[str] = []
- current = words[0]
- for word in words[1:]:
- candidate = f"{current} {word}"
- if len(candidate) <= max_chars:
- current = candidate
- else:
- lines.append(current)
- current = word
- lines.append(current)
- return lines
diff --git a/app/static_assets.py b/app/static_assets.py
deleted file mode 100644
index 2334b4640bb3abf1860f6e2025805c4926cb4c21..0000000000000000000000000000000000000000
--- a/app/static_assets.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""Vite dist icindeki guncel giris JS/CSS dosyalarini cozer."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from app.core.config import STATIC_DIR
-
-
-def _assets_dir() -> Path:
- return STATIC_DIR / "assets"
-
-
-def resolve_entry_js() -> Path | None:
- assets = _assets_dir()
- stable = assets / "index.js"
- if stable.is_file():
- return stable
- candidates = list(assets.glob("index-*.js"))
- if not candidates:
- return None
- return max(candidates, key=lambda path: path.stat().st_size)
-
-
-def resolve_entry_css() -> Path | None:
- assets = _assets_dir()
- stable = assets / "index.css"
- if stable.is_file():
- return stable
- candidates = list(assets.glob("index-*.css"))
- if not candidates:
- return None
- return max(candidates, key=lambda path: path.stat().st_size)
-
-
-def asset_build_token() -> str:
- """Deploy sonrasi HTML'deki ?v= ile tarayici onbellegini kirar."""
- tokens: list[str] = []
- for path in (resolve_entry_js(), resolve_entry_css()):
- if path is not None and path.is_file():
- tokens.append(str(int(path.stat().st_mtime)))
- return tokens[0] if len(tokens) == 1 else "-".join(tokens) if tokens else "0"
diff --git a/frontend/index.html b/frontend/index.html
index 05e9e518b69d9d7b84d77881f33d340b683b4214..a4627f0a74c006560c49ea828821f7fd4a6c0fcf 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -2,7 +2,6 @@
-
Muhasebe App
diff --git a/frontend/src/components/CompanySelect.jsx b/frontend/src/components/CompanySelect.jsx
deleted file mode 100644
index a3b7f90008645077363e06c25576e092b043213a..0000000000000000000000000000000000000000
--- a/frontend/src/components/CompanySelect.jsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { isCompanyActive } from "../features/firma/companyActive.js";
-
-function optionsForSelect(companies, value, activeOnly, fallbackCompany) {
- let list = activeOnly ? companies.filter(isCompanyActive) : companies;
- const id = value ? String(value) : "";
- if (activeOnly && id && !list.some((c) => String(c.id) === id)) {
- const selected = companies.find((c) => String(c.id) === id);
- if (selected) {
- list = [...list, selected];
- } else if (fallbackCompany && String(fallbackCompany.id) === id) {
- list = [...list, fallbackCompany];
- }
- }
- return list;
-}
-
-/** Firma secimi — companies listesinden dropdown. */
-export function CompanySelect({
- companies,
- value,
- onChange,
- required = false,
- allowAll = false,
- activeOnly = true,
- fallbackCompany = null,
- allLabel = "Tum firmalar",
- id = "company-select",
- placeholder = "Firma secin",
-}) {
- const options = optionsForSelect(companies, value, activeOnly, fallbackCompany);
-
- return (
-
- );
-}
diff --git a/frontend/src/constants/nav.js b/frontend/src/constants/nav.js
index e56ab9727fa489fb7d203cd0d7f05da9f600d1f6..782169b7932a78416162dcaf2c4bbe639384aad6 100644
--- a/frontend/src/constants/nav.js
+++ b/frontend/src/constants/nav.js
@@ -1,12 +1,8 @@
/**
* Kenar çubuğu sayfa anahtarları ve etiketleri.
* Tek kaynak: rota adları hem navigasyonda hem olası ilerideki yönlendirmede kullanılır.
- * Ust blok: e-ticaret · orta: TALAŞ · alt: Kereste
*/
-/** Pazaryeri siparis, gider ve kar/zarar modulu. */
-export const SIDEBAR_ECOMMERCE_KICKER = "E-Ticaret";
-
export const SIDEBAR_MAIN_NAV = [
["dashboard", "Dashboard"],
["order-entry", "Siparis Girisi"],
@@ -25,24 +21,6 @@ export const SIDEBAR_LUMBER_NAV = [
["lumber-charts", "Kereste grafikler"],
];
-/** Kenar cubugu modul basligi (CSS uppercase kullanilmaz; dogrudan TALAŞ). */
-export const SIDEBAR_TALASH_KICKER = "TALAŞ";
-
-/** Talas modulu (firma kayitlari + cuval fiyat/satis). */
-export const SIDEBAR_FIRMA_NAV = [
- ["talash-dashboard", "Talas finans ozeti"],
- ["talash-cost-entry", "Talas maliyet / gider"],
- ["talash-costs", "Maliyet & gider listesi"],
- ["company-entry", "Firma girisi"],
- ["companies", "Firma listesi"],
- ["talash-price-entry", "Talas fiyat girisi"],
- ["talash-prices", "Talas fiyat listesi"],
- ["talash-sale-entry", "Talas satis girisi"],
- ["talash-sales", "Talas satis listesi"],
- ["talash-collection-slip", "Tahsilat irsaliyesi"],
-];
-
-/** E-ticaret altindaki urun maliyeti sayfalari (ayri vurgu istenirse). */
export function isCatalogNavKey(key) {
return key === "product-cost-entry" || key === "product-costs";
}
diff --git a/frontend/src/features/app/ActivePageSwitch.jsx b/frontend/src/features/app/ActivePageSwitch.jsx
index 5d9ed9e9b881451aa8031e21049d4c44e8276bc5..7dc8396631056599479b850a0b754aa1383410ab 100644
--- a/frontend/src/features/app/ActivePageSwitch.jsx
+++ b/frontend/src/features/app/ActivePageSwitch.jsx
@@ -10,16 +10,6 @@ import { LumberCalcPage } from "./pages/LumberCalcPage.jsx";
import { LumberTransactionsPage } from "./pages/LumberTransactionsPage.jsx";
import { LumberChartsPage } from "./pages/LumberChartsPage.jsx";
import { ReportsPage } from "./pages/ReportsPage.jsx";
-import { CompanyEntryPage } from "./pages/CompanyEntryPage.jsx";
-import { CompaniesListPage } from "./pages/CompaniesListPage.jsx";
-import { TalashPriceEntryPage } from "./pages/TalashPriceEntryPage.jsx";
-import { TalashPricesListPage } from "./pages/TalashPricesListPage.jsx";
-import { TalashSaleEntryPage } from "./pages/TalashSaleEntryPage.jsx";
-import { TalashSalesListPage } from "./pages/TalashSalesListPage.jsx";
-import { TalashCollectionSlipPage } from "./pages/TalashCollectionSlipPage.jsx";
-import { TalashDashboardPage } from "./pages/TalashDashboardPage.jsx";
-import { TalashCostEntryPage } from "./pages/TalashCostEntryPage.jsx";
-import { TalashCostsListPage } from "./pages/TalashCostsListPage.jsx";
/** `activePage` anahtarına göre tek tam ekran gövdesi. */
export function ActivePageSwitch({ app }) {
@@ -100,124 +90,6 @@ export function ActivePageSwitch({ app }) {
handleDeleteProductCost={app.handleDeleteProductCost}
/>
);
- case "talash-dashboard":
- return (
-
- );
- case "talash-cost-entry":
- return (
-
- );
- case "talash-costs":
- return (
-
- );
- case "company-entry":
- return (
-
- );
- case "companies":
- return (
-
- );
- case "talash-price-entry":
- return (
-
- );
- case "talash-prices":
- return (
-
- );
- case "talash-sale-entry":
- return (
-
- );
- case "talash-sales":
- return (
-
- );
- case "talash-collection-slip":
- return (
-
- );
case "lumber-rules":
return (
-
-
-
-
-
{
- if (e.target === e.currentTarget) closeEditCompany();
- }}
- >
- e.stopPropagation()}>
-
-
Firmayi duzenle
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/modals/TalashExpenseEditModal.jsx b/frontend/src/features/app/modals/TalashExpenseEditModal.jsx
deleted file mode 100644
index c0478de74776f3256fa05baf0b0fe4d7b7d0615b..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/modals/TalashExpenseEditModal.jsx
+++ /dev/null
@@ -1,87 +0,0 @@
-const EXPENSE_CATEGORIES = ["Tedarik", "Nakliye", "Iscilik", "Yakit", "Diger"];
-
-export function TalashExpenseEditModal({
- editingTalashExpense,
- editTalashExpenseForm,
- setEditTalashExpenseForm,
- closeEditTalashExpense,
- handleUpdateTalashExpense,
-}) {
- if (!editTalashExpenseForm || !editingTalashExpense) return null;
- return (
- {
- if (e.target === e.currentTarget) closeEditTalashExpense();
- }}
- >
-
e.stopPropagation()}>
-
-
Gideri duzenle
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/modals/TalashPaymentModal.jsx b/frontend/src/features/app/modals/TalashPaymentModal.jsx
deleted file mode 100644
index fcfcb5d12fa2aec2a74cd9efa903deaa322a2db1..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/modals/TalashPaymentModal.jsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { useEffect, useState } from "react";
-
-/** Kismi veya tam tahsilat tutari girisi. */
-export function TalashPaymentModal({
- open,
- title,
- subtitle,
- defaultAmount,
- maxAmount,
- onClose,
- onSubmit,
-}) {
- const [amount, setAmount] = useState("");
-
- useEffect(() => {
- if (!open) return;
- const d = Number(defaultAmount);
- setAmount(Number.isFinite(d) && d > 0 ? String(d) : "");
- }, [open, defaultAmount]);
-
- if (!open) return null;
-
- function handleSubmit(event) {
- event.preventDefault();
- const value = Number(amount);
- if (!Number.isFinite(value) || value <= 0) return;
- onSubmit(value);
- }
-
- return (
-
-
e.stopPropagation()}
- >
-
{title}
- {subtitle ?
{subtitle}
: null}
-
-
-
- );
-}
diff --git a/frontend/src/features/app/modals/TalashPriceEditModal.jsx b/frontend/src/features/app/modals/TalashPriceEditModal.jsx
deleted file mode 100644
index 421c8987c0f4944883e68b5b8a7beb5f2bf4514b..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/modals/TalashPriceEditModal.jsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-
-export function TalashPriceEditModal({
- companies,
- editingTalashPrice,
- editTalashPriceForm,
- setEditTalashPriceForm,
- closeEditTalashPrice,
- handleUpdateTalashPrice,
-}) {
- if (!editTalashPriceForm || !editingTalashPrice) return null;
- return (
- {
- if (e.target === e.currentTarget) closeEditTalashPrice();
- }}
- >
-
e.stopPropagation()}>
-
-
Talas fiyatini duzenle
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/modals/TalashSaleEditModal.jsx b/frontend/src/features/app/modals/TalashSaleEditModal.jsx
deleted file mode 100644
index 1ed0eff57cd8ef4a00db3e54f037e3695e9e1b79..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/modals/TalashSaleEditModal.jsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-
-export function TalashSaleEditModal({
- companies,
- editingTalashSale,
- editTalashSaleForm,
- setEditTalashSaleForm,
- closeEditTalashSale,
- handleUpdateTalashSale,
-}) {
- if (!editTalashSaleForm || !editingTalashSale) return null;
- return (
- {
- if (e.target === e.currentTarget) closeEditTalashSale();
- }}
- >
-
e.stopPropagation()}>
-
-
Talas satisini duzenle
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/modals/TalashUnitCostEditModal.jsx b/frontend/src/features/app/modals/TalashUnitCostEditModal.jsx
deleted file mode 100644
index dc53b7446bde9c0c36869baac261a977964fe272..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/modals/TalashUnitCostEditModal.jsx
+++ /dev/null
@@ -1,70 +0,0 @@
-export function TalashUnitCostEditModal({
- editingTalashUnitCost,
- editTalashUnitCostForm,
- setEditTalashUnitCostForm,
- closeEditTalashUnitCost,
- handleUpdateTalashUnitCost,
-}) {
- if (!editTalashUnitCostForm || !editingTalashUnitCost) return null;
- return (
- {
- if (e.target === e.currentTarget) closeEditTalashUnitCost();
- }}
- >
-
e.stopPropagation()}>
-
-
Tedarik maliyetini duzenle
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/CompaniesListPage.jsx b/frontend/src/features/app/pages/CompaniesListPage.jsx
deleted file mode 100644
index 86633b44862e08d709a78da5fdc3c4bd41f7cecc..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/CompaniesListPage.jsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useState } from "react";
-
-import { isCompanyActive } from "../../firma/companyActive.js";
-import { FirmaListPanel } from "../../firma/FirmaListPanel.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-/** Kayitli firmalar — kart gorunumu. */
-export function CompaniesListPage({
- companies,
- openEditCompany,
- handleDeleteCompany,
- openCompanyTalashSales,
- openCompanyTalashPrices,
- setActivePage,
-}) {
- const [pendingRemoveId, setPendingRemoveId] = useState(null);
- const [removingId, setRemovingId] = useState(null);
-
- const activeCompanies = companies.filter(isCompanyActive);
- const countLabel =
- activeCompanies.length === 1 ? "1 firma" : `${activeCompanies.length} firma`;
-
- return (
- setActivePage("company-entry")}>
- + Yeni firma
-
- }
- >
-
- {activeCompanies.length === 0 ? (
-
- Henuz firma yok
- Ilk firmayi eklemek icin ustteki "Yeni firma" butonunu kullanin.
-
- ) : (
-
- {activeCompanies.map((item) => (
-
-
-
-
{item.name || "—"}
- {item.tax_number ? (
- VKN {item.tax_number}
- ) : null}
-
-
-
-
-
-
- {pendingRemoveId === item.id ? (
-
-
- {item.name} listeden kaldırılsın mı? Talaş kayıtları silinmez,
- yalnızca yeni işlemlerde seçilemez.
-
-
-
-
-
-
- ) : null}
-
-
-
- Vergi no
- - {item.tax_number || "—"}
-
-
-
- Adres
- - {item.address || "—"}
-
- {item.notes ? (
-
-
- Not
- - {item.notes}
-
- ) : null}
-
-
-
- ))}
-
- )}
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/CompanyEntryPage.jsx b/frontend/src/features/app/pages/CompanyEntryPage.jsx
deleted file mode 100644
index 0059e74ac64c27f3348056ef79934f6d26242e6b..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/CompanyEntryPage.jsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { FirmaEntryLayout } from "../../firma/FirmaEntryLayout.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-const TIPS = [
- "Firma adi benzersiz olmalidir; ayni isimle tekrar kayit acilamaz.",
- "Adres ve vergi numarasi fatura ve talas satis kayitlarinda referans olarak kullanilir.",
- "Kayit sonrasi otomatik olarak firma listesine yonlendirilirsiniz.",
-];
-
-/** Firma kayit formu. */
-export function CompanyEntryPage({ companyForm, setCompanyForm, handleCreateCompany }) {
- return (
-
-
- Firma bilgileri
-
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashCollectionSlipPage.jsx b/frontend/src/features/app/pages/TalashCollectionSlipPage.jsx
deleted file mode 100644
index 4f51ec2ccf3e845879b73846e8cd327f8c0fd07b..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashCollectionSlipPage.jsx
+++ /dev/null
@@ -1,237 +0,0 @@
-import { useState } from "react";
-
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-import { money } from "../../../lib/format.js";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-import { TalashPaymentModal } from "../modals/TalashPaymentModal.jsx";
-import { printTalashSlip } from "../printTalashSlip.js";
-
-function formatDateTr(iso) {
- if (!iso || typeof iso !== "string") return "—";
- const [y, m, d] = iso.split("-");
- if (!y || !m || !d) return iso;
- return `${d.padStart(2, "0")}.${m.padStart(2, "0")}.${y}`;
-}
-
-function slipDocumentNo(slip) {
- const day = (slip?.issued_date || "").replace(/-/g, "");
- const id = String(slip?.company?.id ?? 0).padStart(4, "0");
- return `TI-${id}-${day || "00000000"}`;
-}
-
-export function TalashCollectionSlipPage({
- companies,
- collectionSlipCompanyId,
- setCollectionSlipCompanyId,
- collectionSlip,
- loadCollectionSlip,
- collectTalashCompanyPayment,
- setActivePage,
-}) {
- const slip = collectionSlip;
- const lineCount = slip?.line_count ?? 0;
- const [paymentOpen, setPaymentOpen] = useState(false);
- const totalDue = slip?.total_remaining ?? slip?.total_amount ?? 0;
-
- function handlePrint() {
- printTalashSlip(collectionSlipCompanyId);
- }
-
- return (
-
-
-
-
- }
- >
-
-
-
- {
- setCollectionSlipCompanyId(v);
- loadCollectionSlip(v);
- }}
- required
- />
-
- {slip && lineCount > 0 ? (
-
-
-
- Alinan tutar acik satislara eski tarihten yeniye islenir; kalan bakiye sonraki
- irsaliyede gorunur.
-
-
- ) : null}
-
-
- {!collectionSlipCompanyId ? (
-
- Firma secin
- Irsaliye icin once yukaridan firmayi secin.
-
- ) : null}
-
- {collectionSlipCompanyId && slip && lineCount === 0 ? (
-
- Bekleyen satis yok
- Bu firma icin tahsil edilecek kayit kalmadi.
-
- ) : null}
-
- {slip && lineCount > 0 ? (
-
-
-
-
-
- Tahsilat yapılacak firma
- {slip.company.name}
-
- {slip.company.tax_number ? (
-
- VKN / TCKN
- {slip.company.tax_number}
-
- ) : null}
- {slip.company.address ? (
-
- Adres
- {slip.company.address}
-
- ) : null}
-
-
-
-
-
- Kalem sayısı
- {lineCount}
-
-
- Toplam çuval
- {slip.total_bags}
-
-
- Tahsil edilecek tutar
- {money(slip.total_amount)}
-
-
-
-
- Asagida yalnizca kalan bakiyeler listelenir. Kismi odeme yapilmis satislarda onceki
- tahsilat dusulmustur.
-
-
-
-
-
- | # |
- Satis tarihi |
- Cuval |
- Satis |
- Tahsil |
- Kalan |
-
-
-
- {slip.lines.map((line, index) => (
-
- | {index + 1} |
- {formatDateTr(line.sale_date)} |
- {line.bag_count} |
- {money(line.total_amount)} |
- {money(line.collected_amount ?? 0)} |
-
- {money(line.remaining_amount ?? line.total_amount)}
- |
-
- ))}
-
-
-
- |
- Tahsil edilecek toplam
- |
-
- {slip.total_bags}
- |
- |
-
- {money(slip.total_remaining ?? slip.total_amount)}
- |
-
-
-
-
-
-
-
- ) : null}
-
- setPaymentOpen(false)}
- onSubmit={async (amount) => {
- if (!slip?.company?.id) return;
- await collectTalashCompanyPayment(slip.company.id, amount);
- setPaymentOpen(false);
- }}
- />
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashCostEntryPage.jsx b/frontend/src/features/app/pages/TalashCostEntryPage.jsx
deleted file mode 100644
index 5df10090f614531974e398cf60ab28563f11b083..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashCostEntryPage.jsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { FirmaEntryLayout } from "../../firma/FirmaEntryLayout.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-const TIPS = [
- "Tedarik maliyeti: cuval basina sizin odemeniz (or. 3 TL, sonra 4 TL). Satis tarihine gore otomatik secilir.",
- "Diger giderler: nakliye, iscilik, yakıt gibi donem masraflari kar/zarar raporundan dusulur.",
- "Finans ozetinde donem satisi - tedarik maliyeti = brut kar; diger giderler sonrasi net kar gorunur.",
-];
-
-const EXPENSE_CATEGORIES = ["Tedarik", "Nakliye", "Iscilik", "Yakit", "Diger"];
-
-export function TalashCostEntryPage({
- talashUnitCostForm,
- setTalashUnitCostForm,
- handleCreateTalashUnitCost,
- talashExpenseForm,
- setTalashExpenseForm,
- handleCreateTalashExpense,
-}) {
- return (
-
-
-
- Cuval tedarik maliyeti
-
- Satilan her cuval icin satis tarihinde gecerli maliyet tarifesi kullanilir.
-
-
-
-
-
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashCostsListPage.jsx b/frontend/src/features/app/pages/TalashCostsListPage.jsx
deleted file mode 100644
index 883c1305d14808149760009e0784e29f0f095ced..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashCostsListPage.jsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { money } from "../../../lib/format.js";
-import { FirmaListPanel } from "../../firma/FirmaListPanel.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-export function TalashCostsListPage({
- talashUnitCosts,
- talashExpenses,
- openEditTalashUnitCost,
- handleDeleteTalashUnitCost,
- openEditTalashExpense,
- handleDeleteTalashExpense,
- setActivePage,
-}) {
- const costCount = talashUnitCosts.length;
- const expenseCount = talashExpenses.length;
- const badge =
- costCount + expenseCount === 0
- ? "Kayit yok"
- : `${costCount} maliyet · ${expenseCount} gider`;
-
- return (
- setActivePage("talash-cost-entry")}>
- + Yeni kayit
-
- }
- >
-
-
- {talashUnitCosts.length === 0 ? (
-
- Maliyet tarifesi yok
- Cuval basina tedarik maliyeti girin; aksi halde kar hesabinda maliyet 0 kabul edilir.
-
- ) : (
-
-
-
-
- | Gecerlilik |
- Cuval maliyeti |
- Not |
-
- Islem
- |
-
-
-
- {talashUnitCosts.map((item) => (
-
- | {item.effective_date} |
- {money(item.cost_per_bag)} |
- {item.notes || "—"} |
-
-
-
- |
-
- ))}
-
-
-
- )}
-
-
-
-
- Donem giderleri
- Tedarik disi masraflar
-
- {talashExpenses.length === 0 ? (
-
- Gider kaydi yok
-
- ) : (
-
-
-
-
- | Tarih |
- Kategori |
- Tutar |
- Not |
-
- Islem
- |
-
-
-
- {talashExpenses.map((item) => (
-
- | {item.expense_date} |
- {item.category || "—"} |
- {money(item.amount)} |
- {item.notes || "—"} |
-
-
-
- |
-
- ))}
-
-
-
- )}
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashDashboardPage.jsx b/frontend/src/features/app/pages/TalashDashboardPage.jsx
deleted file mode 100644
index b11e795225da87d84dcf94548cac8ce170f19657..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashDashboardPage.jsx
+++ /dev/null
@@ -1,298 +0,0 @@
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-import { formatMonthLabel, money } from "../../../lib/format.js";
-import { FirmaListPanel } from "../../firma/FirmaListPanel.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-import { FirmaStatTiles } from "../../firma/FirmaStatTiles.jsx";
-
-function pct(value) {
- const n = Number(value);
- if (!Number.isFinite(n)) return "0%";
- return `${n.toFixed(1)}%`;
-}
-
-function monthShort(ym) {
- const label = formatMonthLabel(ym);
- const parts = label.split(" ");
- if (parts.length < 2) return ym;
- return `${parts[0].slice(0, 3)} ${parts[1].slice(2)}`;
-}
-
-export function TalashDashboardPage({
- companies,
- talashDashboard,
- talashDashboardLoading,
- talashDashboardMonth,
- setTalashDashboardMonth,
- talashDashboardCompanyId,
- applyTalashDashboardFilter,
- openCompanyTalashSales,
- setActivePage,
-}) {
- const dash = talashDashboard;
- const period = dash?.period;
- const open = dash?.open_receivable;
- const profit = dash?.profitability;
- const series = dash?.monthly_series || [];
- const maxBar = Math.max(
- 1,
- ...series.flatMap((row) => [row.sales_amount || 0, row.collected_amount || 0]),
- );
-
- const heroStats = period
- ? [
- { label: "Donem satisi", value: money(period.sales_amount) },
- {
- label: "Net kar / zarar",
- value: money(profit?.net_profit ?? 0),
- },
- { label: "Acik alacak", value: money(open?.amount ?? 0) },
- ]
- : [];
-
- return (
-
-
-
-
- }
- heroExtra={heroStats.length > 0 ? : null}
- >
-
-
-
-
- setTalashDashboardMonth(e.target.value)}
- />
-
-
-
-
-
-
-
-
- {talashDashboardLoading && !dash ? (
-
- Yukleniyor
- Finansal ozet hazirlaniyor…
-
- ) : null}
-
- {dash && period ? (
- <>
-
-
- Donem satis tutari
- {money(period.sales_amount)}
-
- {period.sale_count} kayit · {period.total_bags} cuval
-
-
-
- Bu ay tahsil edilen
- {money(period.collected_cash_amount)}
- Tahsilat tarihi bu ay olan odemeler
-
-
- Donem satislarindan bekleyen
- {money(period.pending_on_sales)}
- Secilen ay satislarinda henuz tahsil edilmemis
-
-
- Toplam acik alacak
- {money(open?.amount ?? 0)}
-
- {open?.sale_count ?? 0} satir · tum donemler
-
-
-
-
- {profit ? (
-
-
-
-
- Ciro (satis)
- {money(profit.sales_revenue)}
-
-
- Tedarik maliyeti
- {money(profit.procurement_cost)}
- Cuval basi tarifeye gore
-
-
- Brut kar
- {money(profit.gross_profit)}
- Ciro − tedarik
-
-
- Diger giderler
- {money(profit.operating_expenses)}
- Secilen ay
-
-
= 0
- ? "talash-dash-kpi--profit"
- : "talash-dash-kpi--loss"
- }`}
- >
- Net kar / zarar
- {money(profit.net_profit)}
-
- Marj {pct(profit.margin_rate)}
- {profit.missing_cost_sale_count > 0
- ? ` · ${profit.missing_cost_sale_count} satista maliyet tarifesi yok`
- : null}
-
-
-
-
- ) : null}
-
-
-
-
-
- {series.map((row) => (
-
-
-
{monthShort(row.month)}
-
- ))}
-
-
-
- Satis
-
-
- Tahsilat
-
-
-
-
-
-
- {(dash.open_by_company || []).length === 0 ? (
- Bekleyen alacak yok.
- ) : (
-
- {dash.open_by_company.map((row) => (
- -
-
-
- ))}
-
- )}
-
-
-
-
-
- {(dash.by_company || []).length === 0 ? (
-
- Kayit yok
- Bu donemde satis bulunamadi.
-
- ) : (
-
-
-
-
- | Firma |
- Cuval |
- Satis |
- Tahsil |
- Bekleyen |
- Tahsil orani |
-
-
-
- {dash.by_company.map((row) => (
-
- |
-
- |
- {row.total_bags} |
- {money(row.sales_amount)} |
- {money(row.collected_amount)} |
- {money(row.pending_amount)} |
-
-
-
- {pct(row.collection_rate)}
-
- |
-
- ))}
-
-
-
- )}
-
- >
- ) : null}
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashPriceEntryPage.jsx b/frontend/src/features/app/pages/TalashPriceEntryPage.jsx
deleted file mode 100644
index 33b98a00cea833d0220b9b68d6ad9411543d3e3f..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashPriceEntryPage.jsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-import { FirmaEntryLayout } from "../../firma/FirmaEntryLayout.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-const TIPS = [
- "Her firma icin birden fazla fiyat satiri tanimlayabilirsiniz.",
- "Gecerlilik tarihi: o gun ve sonrasinda bu cuval fiyati uygulanir.",
- "Ornek: 1 Ocak 200 TL, 1 Haziran 230 TL — satis tarihine gore dogru satir secilir.",
-];
-
-export function TalashPriceEntryPage({
- companies,
- talashPriceForm,
- setTalashPriceForm,
- handleCreateTalashPrice,
-}) {
- return (
-
-
- Yeni fiyat tarifesi
-
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashPricesListPage.jsx b/frontend/src/features/app/pages/TalashPricesListPage.jsx
deleted file mode 100644
index 3b54c71b575dbdd0c8622d77587747067960abb6..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashPricesListPage.jsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { money } from "../../../lib/format.js";
-import { FirmaCompanyFilter } from "../../firma/FirmaCompanyFilter.jsx";
-import { FirmaListPanel } from "../../firma/FirmaListPanel.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-export function TalashPricesListPage({
- companies,
- talashPrices,
- talashFilterCompanyId,
- applyTalashCompanyFilter,
- openEditTalashPrice,
- handleDeleteTalashPrice,
- setActivePage,
-}) {
- const count = talashPrices.length;
- const badgeLabel = count === 1 ? "1 tarife" : `${count} tarife`;
-
- return (
- setActivePage("talash-price-entry")}>
- + Yeni fiyat
-
- }
- >
- applyTalashCompanyFilter(v)}
- label="Listeyi firmaya gore filtrele"
- />
- }
- >
- {talashPrices.length === 0 ? (
-
- Fiyat kaydi yok
- Ustteki "Yeni fiyat" ile tarife ekleyin veya filtreyi temizleyin.
-
- ) : (
-
-
-
-
- | Firma |
- Gecerlilik |
- Cuval fiyat |
- Not |
-
- Islem
- |
-
-
-
- {talashPrices.map((item) => (
-
- | {item.company_name} |
- {item.effective_date} |
- {money(item.unit_price)} |
- {item.notes || "—"} |
-
-
-
- |
-
- ))}
-
-
-
- )}
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashSaleEntryPage.jsx b/frontend/src/features/app/pages/TalashSaleEntryPage.jsx
deleted file mode 100644
index 27541ad9fc382b90b20c25de8427007115fd0bc6..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashSaleEntryPage.jsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { useEffect } from "react";
-
-import { CompanySelect } from "../../../components/CompanySelect.jsx";
-import { money } from "../../../lib/format.js";
-import { FirmaEntryLayout } from "../../firma/FirmaEntryLayout.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-
-const TIPS = [
- "Once ilgili firma icin fiyat tarifesi tanimli olmali (veya birim fiyat elle girilir).",
- "Satis tarihine gore gecerli tarife otomatik form alanina dolar.",
- "Kayit edilen birim fiyat satisa yazilir; sonraki tarife degisikligi gecmisi etkilemez.",
-];
-
-function previewTotal(form) {
- const bags = Number(form.bag_count);
- const unit = Number(form.unit_price);
- if (!Number.isFinite(bags) || !Number.isFinite(unit) || bags <= 0 || unit <= 0) return null;
- return money(bags * unit);
-}
-
-export function TalashSaleEntryPage({
- companies,
- talashSaleForm,
- setTalashSaleForm,
- talashQuoteHint,
- fetchTalashQuote,
- handleCreateTalashSale,
-}) {
- useEffect(() => {
- fetchTalashQuote(talashSaleForm.company_id, talashSaleForm.sale_date, true);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [talashSaleForm.company_id, talashSaleForm.sale_date]);
-
- const totalPreview = previewTotal(talashSaleForm);
-
- return (
-
-
- Satis kaydi
-
-
-
- );
-}
diff --git a/frontend/src/features/app/pages/TalashSalesListPage.jsx b/frontend/src/features/app/pages/TalashSalesListPage.jsx
deleted file mode 100644
index 763da635c6633797387dbd629d39726a8cf6eba2..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/pages/TalashSalesListPage.jsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import { useState } from "react";
-
-import { money } from "../../../lib/format.js";
-import { FirmaCompanyFilter } from "../../firma/FirmaCompanyFilter.jsx";
-import { FirmaListPanel } from "../../firma/FirmaListPanel.jsx";
-import { FirmaPageShell } from "../../firma/FirmaPageShell.jsx";
-import { FirmaStatTiles } from "../../firma/FirmaStatTiles.jsx";
-import { TalashPaymentModal } from "../modals/TalashPaymentModal.jsx";
-
-function CollectionBadge({ status }) {
- const label =
- status === "collected" ? "Kapandi" : status === "partial" ? "Kismi" : "Acik";
- const className =
- status === "collected"
- ? "firma-collection-badge--collected"
- : status === "partial"
- ? "firma-collection-badge--partial"
- : "firma-collection-badge--pending";
- return {label};
-}
-
-export function TalashSalesListPage({
- companies,
- talashSales,
- talashSalesSummary,
- talashFilterCompanyId,
- talashCollectionFilter,
- applyTalashCompanyFilter,
- applyTalashCollectionFilter,
- openEditTalashSale,
- handleDeleteTalashSale,
- addTalashSalePayment,
- resetTalashSaleCollection,
- openTalashCollectionSlip,
- setActivePage,
-}) {
- const [paymentSale, setPaymentSale] = useState(null);
-
- const openRemaining = talashSalesSummary?.pending_amount ?? talashSalesSummary?.remaining_amount ?? 0;
- const badgeLabel =
- talashSalesSummary?.pending_count != null
- ? `${talashSalesSummary.pending_count} acik`
- : `${talashSales.length} satis`;
-
- const heroStats =
- talashSalesSummary && talashSales.length > 0
- ? [
- { label: "Kalan alacak", value: money(openRemaining) },
- { label: "Tahsil edilen", value: money(talashSalesSummary.collected_amount ?? 0) },
- ]
- : [];
-
- return (
-
-
-
-
- }
- heroExtra={heroStats.length > 0 ? : null}
- >
-
- applyTalashCompanyFilter(v)}
- label="Firmaya gore"
- />
-
-
-
-
-
- }
- >
- {talashSales.length === 0 ? (
-
- Satis kaydi yok
- Filtreyi degistirin veya yeni satis ekleyin.
-
- ) : (
-
-
-
-
- | Tarih |
- Firma |
- Cuval |
- Toplam |
- Tahsil |
- Kalan |
- Durum |
- Not |
-
- Islem
- |
-
-
-
- {talashSales.map((item) => {
- const remaining = item.remaining_amount ?? item.total_amount;
- const hasOpen = remaining > 0.005;
- return (
-
- | {item.sale_date} |
- {item.company_name} |
- {item.bag_count} |
- {money(item.total_amount)} |
- {money(item.collected_amount ?? 0)} |
- {money(remaining)} |
-
-
- |
- {item.notes || "—"} |
-
- {hasOpen ? (
-
- ) : (
-
- )}
-
-
- |
-
- );
- })}
-
-
-
- )}
-
- {openRemaining > 0 && talashFilterCompanyId ? (
-
- Secili firma icin {money(openRemaining)} alacak var.{" "}
-
-
- ) : null}
-
- setPaymentSale(null)}
- onSubmit={async (amount) => {
- if (!paymentSale) return;
- await addTalashSalePayment(paymentSale.id, amount);
- setPaymentSale(null);
- }}
- />
-
- );
-}
diff --git a/frontend/src/features/app/printTalashSlip.js b/frontend/src/features/app/printTalashSlip.js
deleted file mode 100644
index b62fafb24035e06fd5f79da534c20904437d8459..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/printTalashSlip.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Tahsilat irsaliyesini sunucu PDF'i ile yazdirir (HTML altbilgisinde site URL'si cikmaz).
- */
-export async function printTalashSlip(companyId) {
- const id = String(companyId || "").trim();
- if (!id) return;
-
- const url = `/api/talash/collection-slip.pdf?company_id=${encodeURIComponent(id)}`;
- let response;
- try {
- response = await fetch(url, { credentials: "same-origin" });
- } catch {
- return;
- }
- if (!response.ok) return;
-
- const blob = await response.blob();
- const blobUrl = URL.createObjectURL(blob);
-
- const iframe = document.createElement("iframe");
- iframe.setAttribute("title", "Tahsilat irsaliyesi yazdir");
- iframe.style.cssText =
- "position:fixed;right:0;bottom:0;width:0;height:0;border:0;opacity:0;pointer-events:none;";
- iframe.src = blobUrl;
- document.body.appendChild(iframe);
-
- const cleanup = () => {
- URL.revokeObjectURL(blobUrl);
- iframe.remove();
- };
-
- const runPrint = () => {
- try {
- iframe.contentWindow?.focus();
- iframe.contentWindow?.print();
- } finally {
- window.setTimeout(cleanup, 2000);
- }
- };
-
- iframe.onload = () => window.setTimeout(runPrint, 400);
- window.setTimeout(runPrint, 2500);
-}
diff --git a/frontend/src/features/app/slices/useCompaniesSlice.js b/frontend/src/features/app/slices/useCompaniesSlice.js
deleted file mode 100644
index 1afeb51ef253f3c6a570ff7271ea1d324f1ea16d..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/slices/useCompaniesSlice.js
+++ /dev/null
@@ -1,128 +0,0 @@
-import { useCallback, useState } from "react";
-
-import { apiRequest } from "../../../api/client.js";
-import { isCompanyActive } from "../../firma/companyActive.js";
-import { createCompanyForm } from "../../forms/defaults.js";
-
-function companyBody(form) {
- return {
- name: form.name.trim(),
- address: form.address.trim(),
- tax_number: form.tax_number.trim(),
- notes: form.notes.trim(),
- };
-}
-
-function formFromItem(item) {
- return {
- name: item.name != null ? String(item.name) : "",
- address: item.address != null ? String(item.address) : "",
- tax_number: item.tax_number != null ? String(item.tax_number) : "",
- notes: item.notes != null ? String(item.notes) : "",
- };
-}
-
-/** Firma katalogu: listeleme, ekleme, duzenleme, silme. */
-export function useCompaniesSlice({ setError, setActivePage, refreshAll, onCompanyArchived }) {
- const [companies, setCompanies] = useState([]);
- const [companyForm, setCompanyForm] = useState(() => createCompanyForm());
- const [editingCompany, setEditingCompany] = useState(null);
- const [editCompanyForm, setEditCompanyForm] = useState(null);
-
- const loadCompanies = useCallback(async () => {
- try {
- const data = await apiRequest("/api/companies");
- setCompanies((data.companies || []).filter(isCompanyActive));
- } catch (err) {
- setCompanies([]);
- const st = err && err.status;
- const silent =
- st === 404 ||
- st === 405 ||
- (err.message && String(err.message).toLowerCase().includes("not found"));
- if (silent) return;
- throw err;
- }
- }, []);
-
- const resetCompanies = useCallback(() => {
- setCompanies([]);
- setCompanyForm(createCompanyForm());
- setEditingCompany(null);
- setEditCompanyForm(null);
- }, []);
-
- function openEditCompany(item) {
- setEditingCompany(item);
- setEditCompanyForm(formFromItem(item));
- }
-
- function closeEditCompany() {
- setEditingCompany(null);
- setEditCompanyForm(null);
- }
-
- async function handleCreateCompany(event) {
- event.preventDefault();
- setError("");
- try {
- await apiRequest("/api/companies", {
- method: "POST",
- body: JSON.stringify(companyBody(companyForm)),
- });
- setCompanyForm(createCompanyForm());
- await refreshAll();
- setActivePage("companies");
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleDeleteCompany(id) {
- setError("");
- try {
- await apiRequest(`/api/companies/${Number(id)}`, { method: "DELETE" });
- setCompanies((prev) => prev.filter((c) => Number(c.id) !== Number(id)));
- onCompanyArchived?.(id);
- try {
- await refreshAll();
- } catch {
- await loadCompanies();
- }
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleUpdateCompany(event) {
- event.preventDefault();
- if (!editingCompany || !editCompanyForm) return;
- setError("");
- try {
- await apiRequest(`/api/companies/${editingCompany.id}`, {
- method: "PATCH",
- body: JSON.stringify(companyBody(editCompanyForm)),
- });
- closeEditCompany();
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- return {
- companies,
- companyForm,
- setCompanyForm,
- editingCompany,
- editCompanyForm,
- setEditCompanyForm,
- loadCompanies,
- resetCompanies,
- openEditCompany,
- closeEditCompany,
- handleCreateCompany,
- handleDeleteCompany,
- handleUpdateCompany,
- };
-}
diff --git a/frontend/src/features/app/slices/useTalashSlice.js b/frontend/src/features/app/slices/useTalashSlice.js
deleted file mode 100644
index 70b23f32a85379cc49353dacea649e943a728253..0000000000000000000000000000000000000000
--- a/frontend/src/features/app/slices/useTalashSlice.js
+++ /dev/null
@@ -1,711 +0,0 @@
-import { useCallback, useState } from "react";
-
-import { apiRequest } from "../../../api/client.js";
-import { currentMonthValue } from "../../../lib/format.js";
-import {
- createTalashExpenseForm,
- createTalashPriceForm,
- createTalashSaleForm,
- createTalashUnitCostForm,
-} from "../../forms/defaults.js";
-
-function priceBody(form) {
- return {
- company_id: Number(form.company_id),
- effective_date: form.effective_date,
- unit_price: Number(form.unit_price),
- notes: form.notes.trim(),
- };
-}
-
-function saleBody(form) {
- const body = {
- company_id: Number(form.company_id),
- sale_date: form.sale_date,
- bag_count: Number(form.bag_count),
- notes: form.notes.trim(),
- };
- if (form.unit_price !== "" && form.unit_price != null) {
- body.unit_price = Number(form.unit_price);
- }
- return body;
-}
-
-function priceFormFromItem(item) {
- return {
- company_id: String(item.company_id),
- effective_date: item.effective_date || "",
- unit_price: item.unit_price != null ? String(item.unit_price) : "",
- notes: item.notes != null ? String(item.notes) : "",
- };
-}
-
-function saleFormFromItem(item) {
- return {
- company_id: String(item.company_id),
- sale_date: item.sale_date || "",
- bag_count: item.bag_count != null ? String(item.bag_count) : "",
- unit_price: item.unit_price != null ? String(item.unit_price) : "",
- notes: item.notes != null ? String(item.notes) : "",
- };
-}
-
-function unitCostBody(form) {
- return {
- effective_date: form.effective_date,
- cost_per_bag: Number(form.cost_per_bag),
- notes: form.notes.trim(),
- };
-}
-
-function expenseBody(form) {
- return {
- expense_date: form.expense_date,
- category: form.category.trim(),
- amount: Number(form.amount),
- notes: form.notes.trim(),
- };
-}
-
-function unitCostFormFromItem(item) {
- return {
- effective_date: item.effective_date || "",
- cost_per_bag: item.cost_per_bag != null ? String(item.cost_per_bag) : "",
- notes: item.notes != null ? String(item.notes) : "",
- };
-}
-
-function expenseFormFromItem(item) {
- return {
- expense_date: item.expense_date || "",
- category: item.category != null ? String(item.category) : "",
- amount: item.amount != null ? String(item.amount) : "",
- notes: item.notes != null ? String(item.notes) : "",
- };
-}
-
-/** Talas cuval fiyat tarifeleri ve firma satislari. */
-export function useTalashSlice({ setError, setActivePage, refreshAll }) {
- const [talashPrices, setTalashPrices] = useState([]);
- const [talashSales, setTalashSales] = useState([]);
- const [talashSalesSummary, setTalashSalesSummary] = useState(null);
- const [talashFilterCompanyId, setTalashFilterCompanyId] = useState("");
- const [talashCollectionFilter, setTalashCollectionFilter] = useState("");
- const [collectionSlip, setCollectionSlip] = useState(null);
- const [collectionSlipCompanyId, setCollectionSlipCompanyId] = useState("");
- const [talashDashboard, setTalashDashboard] = useState(null);
- const [talashDashboardLoading, setTalashDashboardLoading] = useState(false);
- const [talashDashboardMonth, setTalashDashboardMonth] = useState(() => currentMonthValue());
- const [talashDashboardCompanyId, setTalashDashboardCompanyId] = useState("");
- const [talashPriceForm, setTalashPriceForm] = useState(() => createTalashPriceForm());
- const [talashSaleForm, setTalashSaleForm] = useState(() => createTalashSaleForm());
- const [talashQuoteHint, setTalashQuoteHint] = useState("");
- const [editingTalashPrice, setEditingTalashPrice] = useState(null);
- const [editTalashPriceForm, setEditTalashPriceForm] = useState(null);
- const [editingTalashSale, setEditingTalashSale] = useState(null);
- const [editTalashSaleForm, setEditTalashSaleForm] = useState(null);
- const [talashUnitCosts, setTalashUnitCosts] = useState([]);
- const [talashExpenses, setTalashExpenses] = useState([]);
- const [talashUnitCostForm, setTalashUnitCostForm] = useState(() => createTalashUnitCostForm());
- const [talashExpenseForm, setTalashExpenseForm] = useState(() => createTalashExpenseForm());
- const [editingTalashUnitCost, setEditingTalashUnitCost] = useState(null);
- const [editTalashUnitCostForm, setEditTalashUnitCostForm] = useState(null);
- const [editingTalashExpense, setEditingTalashExpense] = useState(null);
- const [editTalashExpenseForm, setEditTalashExpenseForm] = useState(null);
-
- const pricesQuery = useCallback(
- (companyId) => {
- const params = new URLSearchParams();
- if (companyId) params.set("company_id", companyId);
- const q = params.toString();
- return q ? `/api/talash/prices?${q}` : "/api/talash/prices";
- },
- [],
- );
-
- const salesQuery = useCallback((companyId, collectionStatus = "") => {
- const params = new URLSearchParams();
- if (companyId) params.set("company_id", companyId);
- if (
- collectionStatus === "pending" ||
- collectionStatus === "partial" ||
- collectionStatus === "collected"
- ) {
- params.set("collection_status", collectionStatus);
- }
- const q = params.toString();
- return q ? `/api/talash/sales?${q}` : "/api/talash/sales";
- }, []);
-
- const loadTalashPrices = useCallback(
- async (companyId = talashFilterCompanyId) => {
- try {
- const data = await apiRequest(pricesQuery(companyId));
- setTalashPrices(data.prices || []);
- } catch (err) {
- setTalashPrices([]);
- throw err;
- }
- },
- [pricesQuery, talashFilterCompanyId],
- );
-
- const loadTalashSales = useCallback(
- async (
- companyId = talashFilterCompanyId,
- collectionStatus = talashCollectionFilter,
- ) => {
- try {
- const data = await apiRequest(salesQuery(companyId, collectionStatus));
- setTalashSales(data.sales || []);
- setTalashSalesSummary(data.summary || null);
- } catch (err) {
- setTalashSales([]);
- setTalashSalesSummary(null);
- throw err;
- }
- },
- [salesQuery, talashFilterCompanyId, talashCollectionFilter],
- );
-
- const loadTalashUnitCosts = useCallback(async () => {
- try {
- const data = await apiRequest("/api/talash/unit-costs");
- setTalashUnitCosts(data.unit_costs || []);
- } catch (err) {
- setTalashUnitCosts([]);
- throw err;
- }
- }, []);
-
- const loadTalashExpenses = useCallback(async () => {
- try {
- const data = await apiRequest("/api/talash/expenses");
- setTalashExpenses(data.expenses || []);
- } catch (err) {
- setTalashExpenses([]);
- throw err;
- }
- }, []);
-
- const loadTalashAll = useCallback(async () => {
- await Promise.all([
- loadTalashPrices(),
- loadTalashSales(),
- loadTalashUnitCosts(),
- loadTalashExpenses(),
- ]);
- }, [loadTalashPrices, loadTalashSales, loadTalashUnitCosts, loadTalashExpenses]);
-
- const resetTalash = useCallback(() => {
- setTalashPrices([]);
- setTalashSales([]);
- setTalashSalesSummary(null);
- setTalashFilterCompanyId("");
- setTalashCollectionFilter("");
- setCollectionSlip(null);
- setCollectionSlipCompanyId("");
- setTalashPriceForm(createTalashPriceForm());
- setTalashSaleForm(createTalashSaleForm());
- setTalashQuoteHint("");
- setEditingTalashPrice(null);
- setEditTalashPriceForm(null);
- setEditingTalashSale(null);
- setEditTalashSaleForm(null);
- setTalashUnitCosts([]);
- setTalashExpenses([]);
- setTalashUnitCostForm(createTalashUnitCostForm());
- setTalashExpenseForm(createTalashExpenseForm());
- setEditingTalashUnitCost(null);
- setEditTalashUnitCostForm(null);
- setEditingTalashExpense(null);
- setEditTalashExpenseForm(null);
- }, []);
-
- async function fetchTalashQuote(companyId, saleDate, applyToForm = false) {
- if (!companyId || !saleDate) {
- setTalashQuoteHint("");
- return;
- }
- try {
- const params = new URLSearchParams({
- company_id: companyId,
- sale_date: saleDate,
- });
- const data = await apiRequest(`/api/talash/quote?${params.toString()}`);
- const quote = data.quote;
- if (!quote) {
- setTalashQuoteHint("Bu tarih icin tanimli fiyat yok; birim fiyat elle girilebilir.");
- return;
- }
- setTalashQuoteHint(
- `${quote.effective_date} tarihinden itibaren gecerli tarife: ${Number(quote.unit_price).toFixed(2)} TL / cuval`,
- );
- if (applyToForm) {
- setTalashSaleForm((s) => ({
- ...s,
- unit_price: String(quote.unit_price),
- }));
- }
- } catch (err) {
- setTalashQuoteHint("");
- const msg = err?.message || "";
- if (msg.includes("pasif") || msg.includes("bulunamadi")) {
- if (applyToForm) {
- setTalashSaleForm((s) => {
- if (String(s.company_id) !== String(companyId)) return s;
- return { ...createTalashSaleForm(), sale_date: s.sale_date };
- });
- }
- return;
- }
- setError(msg);
- }
- }
-
- const clearReferencesToCompany = useCallback((companyId) => {
- const id = String(companyId);
- setTalashFilterCompanyId((fid) => (String(fid) === id ? "" : fid));
- setTalashSaleForm((s) => (String(s.company_id) === id ? createTalashSaleForm() : s));
- setTalashPriceForm((s) => (String(s.company_id) === id ? createTalashPriceForm() : s));
- setTalashQuoteHint("");
- }, []);
-
- async function applyTalashCompanyFilter(nextId, collectionStatus = talashCollectionFilter) {
- setTalashFilterCompanyId(nextId);
- setError("");
- try {
- const [priceData, saleData] = await Promise.all([
- apiRequest(pricesQuery(nextId)),
- apiRequest(salesQuery(nextId, collectionStatus)),
- ]);
- setTalashPrices(priceData.prices || []);
- setTalashSales(saleData.sales || []);
- setTalashSalesSummary(saleData.summary || null);
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function applyTalashCollectionFilter(nextStatus) {
- setTalashCollectionFilter(nextStatus);
- setError("");
- try {
- const saleData = await apiRequest(
- salesQuery(talashFilterCompanyId, nextStatus),
- );
- setTalashSales(saleData.sales || []);
- setTalashSalesSummary(saleData.summary || null);
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function loadTalashDashboard(
- month = talashDashboardMonth,
- companyId = talashDashboardCompanyId,
- ) {
- const m = String(month || "").trim();
- if (!m) return;
- setTalashDashboardLoading(true);
- setError("");
- try {
- const params = new URLSearchParams({ month: m });
- const cid = String(companyId || "").trim();
- if (cid) params.set("company_id", cid);
- const data = await apiRequest(`/api/talash/dashboard?${params.toString()}`);
- setTalashDashboard(data.dashboard || null);
- } catch (err) {
- setTalashDashboard(null);
- setError(err.message);
- } finally {
- setTalashDashboardLoading(false);
- }
- }
-
- async function applyTalashDashboardFilter(companyId) {
- const id = companyId != null ? String(companyId) : "";
- setTalashDashboardCompanyId(id);
- await loadTalashDashboard(talashDashboardMonth, id);
- }
-
- async function setTalashDashboardMonthAndLoad(nextMonth) {
- const m = String(nextMonth || "").trim();
- setTalashDashboardMonth(m);
- await loadTalashDashboard(m, talashDashboardCompanyId);
- }
-
- async function loadCollectionSlip(companyId) {
- const id = String(companyId || "").trim();
- setCollectionSlipCompanyId(id);
- if (!id) {
- setCollectionSlip(null);
- return;
- }
- setError("");
- try {
- const data = await apiRequest(
- `/api/talash/collection-slip?company_id=${encodeURIComponent(id)}`,
- );
- setCollectionSlip(data.slip || null);
- } catch (err) {
- setCollectionSlip(null);
- setError(err.message);
- }
- }
-
- async function addTalashSalePayment(saleId, amount) {
- setError("");
- try {
- await apiRequest(`/api/talash/sales/${saleId}/collection`, {
- method: "PATCH",
- body: JSON.stringify({ add_collected_amount: Number(amount) }),
- });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function resetTalashSaleCollection(saleId) {
- setError("");
- try {
- await apiRequest(`/api/talash/sales/${saleId}/collection`, {
- method: "PATCH",
- body: JSON.stringify({ status: "pending" }),
- });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function collectTalashCompanyPayment(companyId, amount) {
- const id = Number(companyId);
- if (!id) return;
- setError("");
- try {
- await apiRequest(`/api/talash/companies/${id}/collect-payment`, {
- method: "POST",
- body: JSON.stringify({ amount: Number(amount) }),
- });
- await refreshAll();
- if (String(collectionSlipCompanyId) === String(id)) {
- await loadCollectionSlip(id);
- }
- } catch (err) {
- setError(err.message);
- }
- }
-
- function openTalashCollectionSlip(companyId) {
- const id = companyId != null ? String(companyId) : talashFilterCompanyId;
- setCollectionSlipCompanyId(id);
- setActivePage("talash-collection-slip");
- if (id) loadCollectionSlip(id);
- }
-
- async function openCompanyTalashSales(companyId) {
- const id = String(companyId);
- setTalashFilterCompanyId(id);
- setTalashSaleForm((s) => ({ ...s, company_id: id }));
- setActivePage("talash-sales");
- await applyTalashCompanyFilter(id);
- }
-
- async function openCompanyTalashPrices(companyId) {
- const id = String(companyId);
- setTalashFilterCompanyId(id);
- setTalashPriceForm((s) => ({ ...s, company_id: id }));
- setActivePage("talash-prices");
- await applyTalashCompanyFilter(id);
- }
-
- function openEditTalashPrice(item) {
- setEditingTalashPrice(item);
- setEditTalashPriceForm(priceFormFromItem(item));
- }
-
- function closeEditTalashPrice() {
- setEditingTalashPrice(null);
- setEditTalashPriceForm(null);
- }
-
- function openEditTalashSale(item) {
- setEditingTalashSale(item);
- setEditTalashSaleForm(saleFormFromItem(item));
- }
-
- function closeEditTalashSale() {
- setEditingTalashSale(null);
- setEditTalashSaleForm(null);
- }
-
- async function handleCreateTalashPrice(event) {
- event.preventDefault();
- setError("");
- try {
- await apiRequest("/api/talash/prices", {
- method: "POST",
- body: JSON.stringify(priceBody(talashPriceForm)),
- });
- setTalashPriceForm(createTalashPriceForm());
- await refreshAll();
- setActivePage("talash-prices");
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleDeleteTalashPrice(id) {
- setError("");
- try {
- await apiRequest(`/api/talash/prices/${id}`, { method: "DELETE" });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleUpdateTalashPrice(event) {
- event.preventDefault();
- if (!editingTalashPrice || !editTalashPriceForm) return;
- setError("");
- try {
- await apiRequest(`/api/talash/prices/${editingTalashPrice.id}`, {
- method: "PATCH",
- body: JSON.stringify(priceBody(editTalashPriceForm)),
- });
- closeEditTalashPrice();
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleCreateTalashSale(event) {
- event.preventDefault();
- setError("");
- try {
- await apiRequest("/api/talash/sales", {
- method: "POST",
- body: JSON.stringify(saleBody(talashSaleForm)),
- });
- setTalashSaleForm(createTalashSaleForm());
- setTalashQuoteHint("");
- await refreshAll();
- setActivePage("talash-sales");
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleDeleteTalashSale(id) {
- setError("");
- try {
- await apiRequest(`/api/talash/sales/${id}`, { method: "DELETE" });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleUpdateTalashSale(event) {
- event.preventDefault();
- if (!editingTalashSale || !editTalashSaleForm) return;
- setError("");
- try {
- await apiRequest(`/api/talash/sales/${editingTalashSale.id}`, {
- method: "PATCH",
- body: JSON.stringify(saleBody(editTalashSaleForm)),
- });
- closeEditTalashSale();
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- function openEditTalashUnitCost(item) {
- setEditingTalashUnitCost(item);
- setEditTalashUnitCostForm(unitCostFormFromItem(item));
- }
-
- function closeEditTalashUnitCost() {
- setEditingTalashUnitCost(null);
- setEditTalashUnitCostForm(null);
- }
-
- function openEditTalashExpense(item) {
- setEditingTalashExpense(item);
- setEditTalashExpenseForm(expenseFormFromItem(item));
- }
-
- function closeEditTalashExpense() {
- setEditingTalashExpense(null);
- setEditTalashExpenseForm(null);
- }
-
- async function handleCreateTalashUnitCost(event) {
- event.preventDefault();
- setError("");
- try {
- await apiRequest("/api/talash/unit-costs", {
- method: "POST",
- body: JSON.stringify(unitCostBody(talashUnitCostForm)),
- });
- setTalashUnitCostForm(createTalashUnitCostForm());
- await refreshAll();
- setActivePage("talash-costs");
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleDeleteTalashUnitCost(id) {
- setError("");
- try {
- await apiRequest(`/api/talash/unit-costs/${id}`, { method: "DELETE" });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleUpdateTalashUnitCost(event) {
- event.preventDefault();
- if (!editingTalashUnitCost || !editTalashUnitCostForm) return;
- setError("");
- try {
- await apiRequest(`/api/talash/unit-costs/${editingTalashUnitCost.id}`, {
- method: "PATCH",
- body: JSON.stringify(unitCostBody(editTalashUnitCostForm)),
- });
- closeEditTalashUnitCost();
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleCreateTalashExpense(event) {
- event.preventDefault();
- setError("");
- try {
- await apiRequest("/api/talash/expenses", {
- method: "POST",
- body: JSON.stringify(expenseBody(talashExpenseForm)),
- });
- setTalashExpenseForm(createTalashExpenseForm());
- await refreshAll();
- setActivePage("talash-costs");
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleDeleteTalashExpense(id) {
- setError("");
- try {
- await apiRequest(`/api/talash/expenses/${id}`, { method: "DELETE" });
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- async function handleUpdateTalashExpense(event) {
- event.preventDefault();
- if (!editingTalashExpense || !editTalashExpenseForm) return;
- setError("");
- try {
- await apiRequest(`/api/talash/expenses/${editingTalashExpense.id}`, {
- method: "PATCH",
- body: JSON.stringify(expenseBody(editTalashExpenseForm)),
- });
- closeEditTalashExpense();
- await refreshAll();
- } catch (err) {
- setError(err.message);
- }
- }
-
- return {
- talashPrices,
- talashSales,
- talashSalesSummary,
- talashFilterCompanyId,
- talashCollectionFilter,
- collectionSlip,
- collectionSlipCompanyId,
- setCollectionSlipCompanyId,
- talashDashboard,
- talashDashboardLoading,
- talashDashboardMonth,
- setTalashDashboardMonth: setTalashDashboardMonthAndLoad,
- talashDashboardCompanyId,
- loadTalashDashboard,
- applyTalashDashboardFilter,
- talashPriceForm,
- setTalashPriceForm,
- talashSaleForm,
- setTalashSaleForm,
- talashQuoteHint,
- setTalashQuoteHint,
- editingTalashPrice,
- editTalashPriceForm,
- setEditTalashPriceForm,
- editingTalashSale,
- editTalashSaleForm,
- setEditTalashSaleForm,
- loadTalashPrices,
- loadTalashSales,
- loadTalashAll,
- resetTalash,
- fetchTalashQuote,
- applyTalashCompanyFilter,
- applyTalashCollectionFilter,
- loadCollectionSlip,
- addTalashSalePayment,
- resetTalashSaleCollection,
- collectTalashCompanyPayment,
- openTalashCollectionSlip,
- openCompanyTalashSales,
- openCompanyTalashPrices,
- openEditTalashPrice,
- closeEditTalashPrice,
- openEditTalashSale,
- closeEditTalashSale,
- handleCreateTalashPrice,
- handleDeleteTalashPrice,
- handleUpdateTalashPrice,
- handleCreateTalashSale,
- handleDeleteTalashSale,
- handleUpdateTalashSale,
- talashUnitCosts,
- talashExpenses,
- talashUnitCostForm,
- setTalashUnitCostForm,
- talashExpenseForm,
- setTalashExpenseForm,
- editingTalashUnitCost,
- editTalashUnitCostForm,
- setEditTalashUnitCostForm,
- editingTalashExpense,
- editTalashExpenseForm,
- setEditTalashExpenseForm,
- loadTalashUnitCosts,
- loadTalashExpenses,
- openEditTalashUnitCost,
- closeEditTalashUnitCost,
- openEditTalashExpense,
- closeEditTalashExpense,
- handleCreateTalashUnitCost,
- handleDeleteTalashUnitCost,
- handleUpdateTalashUnitCost,
- handleCreateTalashExpense,
- handleDeleteTalashExpense,
- handleUpdateTalashExpense,
- clearReferencesToCompany,
- };
-}
diff --git a/frontend/src/features/app/useAppController.js b/frontend/src/features/app/useAppController.js
index 6f68b14e7c8eecd984f41d8c24c869da5b3027b4..c6d9488b3aae0a427fceeccd4b1368696b926b1f 100644
--- a/frontend/src/features/app/useAppController.js
+++ b/frontend/src/features/app/useAppController.js
@@ -17,8 +17,6 @@ import { useProductCostsSlice } from "./slices/useProductCostsSlice.js";
import { useExpensesSlice } from "./slices/useExpensesSlice.js";
import { useOrdersListSlice } from "./slices/useOrdersListSlice.js";
import { useLumberSlice } from "./slices/useLumberSlice.js";
-import { useCompaniesSlice } from "./slices/useCompaniesSlice.js";
-import { useTalashSlice } from "./slices/useTalashSlice.js";
import { useOrderFormsSlice } from "./slices/useOrderFormsSlice.js";
export function useAppController() {
@@ -27,7 +25,6 @@ export function useAppController() {
const report = useReportSlice();
const ordersList = useOrdersListSlice();
const refreshAllRef = useRef(() => Promise.resolve());
- const talashCompanyCleanupRef = useRef(() => {});
const refreshAllFn = () => refreshAllRef.current();
@@ -48,19 +45,6 @@ export function useAppController() {
setActivePage: auth.setActivePage,
});
- const talash = useTalashSlice({
- setError: auth.setError,
- setActivePage: auth.setActivePage,
- refreshAll: refreshAllFn,
- });
-
- const companies = useCompaniesSlice({
- setError: auth.setError,
- setActivePage: auth.setActivePage,
- refreshAll: refreshAllFn,
- onCompanyArchived: (id) => talashCompanyCleanupRef.current(id),
- });
-
const refreshAll = useCallback(async () => {
try {
await Promise.all([
@@ -70,9 +54,6 @@ export function useAppController() {
productCosts.loadProductCosts(),
lumber.loadLumberRules(),
lumber.loadLumberTransactions(),
- companies.loadCompanies(),
- talash.loadTalashAll(),
- talash.loadTalashDashboard(),
report.loadReport(report.reportPeriod, report.reportRefDate),
]);
} catch (err) {
@@ -92,9 +73,6 @@ export function useAppController() {
productCosts.loadProductCosts,
lumber.loadLumberRules,
lumber.loadLumberTransactions,
- companies.loadCompanies,
- talash.loadTalashAll,
- talash.loadTalashDashboard,
report.loadReport,
report.reportPeriod,
report.reportRefDate,
@@ -106,10 +84,6 @@ export function useAppController() {
refreshAllRef.current = refreshAll;
}, [refreshAll]);
- useEffect(() => {
- talashCompanyCleanupRef.current = (id) => talash.clearReferencesToCompany(id);
- }, [talash.clearReferencesToCompany]);
-
const orderForms = useOrderFormsSlice({
setError: auth.setError,
setActivePage: auth.setActivePage,
@@ -148,12 +122,6 @@ export function useAppController() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- yalnizca loadProductCosts
}, [auth.activePage, auth.user, productCosts.loadProductCosts]);
- useEffect(() => {
- if (!auth.user || auth.activePage !== "talash-dashboard") return;
- talash.loadTalashDashboard();
- // eslint-disable-next-line react-hooks/exhaustive-deps -- dashboard sayfasi
- }, [auth.activePage, auth.user]);
-
async function handleLogin(event) {
event.preventDefault();
auth.setError("");
@@ -186,8 +154,6 @@ export function useAppController() {
productCosts.resetProductCosts();
report.resetReport();
lumber.resetLumber();
- companies.resetCompanies();
- talash.resetTalash();
orderForms.resetOrderForms();
} catch (err) {
auth.setError(err.message);
@@ -283,50 +249,6 @@ export function useAppController() {
reportViz,
dashboardViz,
lumberViz,
- companies: companies.companies,
- companyForm: companies.companyForm,
- setCompanyForm: companies.setCompanyForm,
- editingCompany: companies.editingCompany,
- editCompanyForm: companies.editCompanyForm,
- setEditCompanyForm: companies.setEditCompanyForm,
- talashPrices: talash.talashPrices,
- talashSales: talash.talashSales,
- talashSalesSummary: talash.talashSalesSummary,
- talashFilterCompanyId: talash.talashFilterCompanyId,
- talashCollectionFilter: talash.talashCollectionFilter,
- collectionSlip: talash.collectionSlip,
- collectionSlipCompanyId: talash.collectionSlipCompanyId,
- setCollectionSlipCompanyId: talash.setCollectionSlipCompanyId,
- talashDashboard: talash.talashDashboard,
- talashDashboardLoading: talash.talashDashboardLoading,
- talashDashboardMonth: talash.talashDashboardMonth,
- setTalashDashboardMonth: talash.setTalashDashboardMonth,
- talashDashboardCompanyId: talash.talashDashboardCompanyId,
- applyTalashDashboardFilter: talash.applyTalashDashboardFilter,
- loadTalashDashboard: talash.loadTalashDashboard,
- talashPriceForm: talash.talashPriceForm,
- setTalashPriceForm: talash.setTalashPriceForm,
- talashSaleForm: talash.talashSaleForm,
- setTalashSaleForm: talash.setTalashSaleForm,
- talashQuoteHint: talash.talashQuoteHint,
- editingTalashPrice: talash.editingTalashPrice,
- editTalashPriceForm: talash.editTalashPriceForm,
- setEditTalashPriceForm: talash.setEditTalashPriceForm,
- editingTalashSale: talash.editingTalashSale,
- editTalashSaleForm: talash.editTalashSaleForm,
- setEditTalashSaleForm: talash.setEditTalashSaleForm,
- talashUnitCosts: talash.talashUnitCosts,
- talashExpenses: talash.talashExpenses,
- talashUnitCostForm: talash.talashUnitCostForm,
- setTalashUnitCostForm: talash.setTalashUnitCostForm,
- talashExpenseForm: talash.talashExpenseForm,
- setTalashExpenseForm: talash.setTalashExpenseForm,
- editingTalashUnitCost: talash.editingTalashUnitCost,
- editTalashUnitCostForm: talash.editTalashUnitCostForm,
- setEditTalashUnitCostForm: talash.setEditTalashUnitCostForm,
- editingTalashExpense: talash.editingTalashExpense,
- editTalashExpenseForm: talash.editTalashExpenseForm,
- setEditTalashExpenseForm: talash.setEditTalashExpenseForm,
loadDashboard: dashboard.loadDashboard,
loadOrders: ordersList.loadOrders,
handleOrdersDateModeChange: ordersList.handleOrdersDateModeChange,
@@ -341,7 +263,6 @@ export function useAppController() {
loadProductCosts: productCosts.loadProductCosts,
loadLumberRules: lumber.loadLumberRules,
loadLumberTransactions: lumber.loadLumberTransactions,
- loadCompanies: companies.loadCompanies,
loadReport: report.loadReport,
refreshAll,
handleLogin,
@@ -376,41 +297,6 @@ export function useAppController() {
openEditProductCost: productCosts.openEditProductCost,
closeEditProductCost: productCosts.closeEditProductCost,
handleUpdateProductCost: productCosts.handleUpdateProductCost,
- openEditCompany: companies.openEditCompany,
- closeEditCompany: companies.closeEditCompany,
- handleCreateCompany: companies.handleCreateCompany,
- handleDeleteCompany: companies.handleDeleteCompany,
- handleUpdateCompany: companies.handleUpdateCompany,
- fetchTalashQuote: talash.fetchTalashQuote,
- applyTalashCompanyFilter: talash.applyTalashCompanyFilter,
- applyTalashCollectionFilter: talash.applyTalashCollectionFilter,
- loadCollectionSlip: talash.loadCollectionSlip,
- addTalashSalePayment: talash.addTalashSalePayment,
- resetTalashSaleCollection: talash.resetTalashSaleCollection,
- collectTalashCompanyPayment: talash.collectTalashCompanyPayment,
- openTalashCollectionSlip: talash.openTalashCollectionSlip,
- openCompanyTalashSales: talash.openCompanyTalashSales,
- openCompanyTalashPrices: talash.openCompanyTalashPrices,
- openEditTalashPrice: talash.openEditTalashPrice,
- closeEditTalashPrice: talash.closeEditTalashPrice,
- handleCreateTalashPrice: talash.handleCreateTalashPrice,
- handleDeleteTalashPrice: talash.handleDeleteTalashPrice,
- handleUpdateTalashPrice: talash.handleUpdateTalashPrice,
- handleCreateTalashSale: talash.handleCreateTalashSale,
- handleDeleteTalashSale: talash.handleDeleteTalashSale,
- openEditTalashSale: talash.openEditTalashSale,
- closeEditTalashSale: talash.closeEditTalashSale,
- handleUpdateTalashSale: talash.handleUpdateTalashSale,
- openEditTalashUnitCost: talash.openEditTalashUnitCost,
- closeEditTalashUnitCost: talash.closeEditTalashUnitCost,
- handleCreateTalashUnitCost: talash.handleCreateTalashUnitCost,
- handleDeleteTalashUnitCost: talash.handleDeleteTalashUnitCost,
- handleUpdateTalashUnitCost: talash.handleUpdateTalashUnitCost,
- openEditTalashExpense: talash.openEditTalashExpense,
- closeEditTalashExpense: talash.closeEditTalashExpense,
- handleCreateTalashExpense: talash.handleCreateTalashExpense,
- handleDeleteTalashExpense: talash.handleDeleteTalashExpense,
- handleUpdateTalashExpense: talash.handleUpdateTalashExpense,
handleReportPeriodChange,
handleReportDateChange,
};
diff --git a/frontend/src/features/firma/FirmaCompanyFilter.jsx b/frontend/src/features/firma/FirmaCompanyFilter.jsx
deleted file mode 100644
index 5267227f0b2857d295d19afdeab0052c3fc77053..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/FirmaCompanyFilter.jsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { CompanySelect } from "../../components/CompanySelect.jsx";
-
-export function FirmaCompanyFilter({ companies, value, onChange, label = "Firma filtresi" }) {
- return (
-
-
-
-
- );
-}
diff --git a/frontend/src/features/firma/FirmaEntryLayout.jsx b/frontend/src/features/firma/FirmaEntryLayout.jsx
deleted file mode 100644
index 9c949ee9de27a79356e175b702c552807bd5027f..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/FirmaEntryLayout.jsx
+++ /dev/null
@@ -1,18 +0,0 @@
-/** Giris sayfalari: sol ipucu paneli + sag form. */
-export function FirmaEntryLayout({ tipsTitle = "Kisa rehber", tips, children }) {
- return (
-
- {tips && tips.length > 0 ? (
-
- ) : null}
-
{children}
-
- );
-}
diff --git a/frontend/src/features/firma/FirmaListPanel.jsx b/frontend/src/features/firma/FirmaListPanel.jsx
deleted file mode 100644
index 44461fd20c1b313cd7788c568b325374ec062d9e..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/FirmaListPanel.jsx
+++ /dev/null
@@ -1,15 +0,0 @@
-/** Liste sayfalari: filtre + istatistik + tablo/kart alani. */
-export function FirmaListPanel({ filter, stats, plain = false, children }) {
- const showBar = !plain && (filter || stats);
- return (
-
- {showBar ? (
-
- {filter ?
{filter}
: null}
- {stats ?
{stats}
: null}
-
- ) : null}
- {children}
-
- );
-}
diff --git a/frontend/src/features/firma/FirmaPageShell.jsx b/frontend/src/features/firma/FirmaPageShell.jsx
deleted file mode 100644
index f002d4d5a7449eb1d5b4824f39de481b7381d006..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/FirmaPageShell.jsx
+++ /dev/null
@@ -1,21 +0,0 @@
-/** Firmalar modulu — ust hero + govde (dashboard benzeri). */
-export function FirmaPageShell({ badge, title, subtitle, action, heroExtra, children }) {
- return (
-
-
-
-
-
{title}
- {subtitle ?
{subtitle}
: null}
-
-
- {badge ?
{badge} : null}
- {action ?
{action}
: null}
-
-
- {heroExtra ? {heroExtra}
: null}
-
-
{children}
-
- );
-}
diff --git a/frontend/src/features/firma/FirmaStatTiles.jsx b/frontend/src/features/firma/FirmaStatTiles.jsx
deleted file mode 100644
index 00fe2595e3fbeb86a5c4b59c30fc40e65be22163..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/FirmaStatTiles.jsx
+++ /dev/null
@@ -1,14 +0,0 @@
-/** Kucuk ozet kutucuklari. */
-export function FirmaStatTiles({ items }) {
- if (!items || items.length === 0) return null;
- return (
-
- {items.map(({ label, value }) => (
-
- {label}
- {value}
-
- ))}
-
- );
-}
diff --git a/frontend/src/features/firma/companyActive.js b/frontend/src/features/firma/companyActive.js
deleted file mode 100644
index a8780d97ed9fdb8df6e0dab2e8a31154a55c9edf..0000000000000000000000000000000000000000
--- a/frontend/src/features/firma/companyActive.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/** API'den gelen firma kaydinin aktif listede gosterilip gosterilmeyecegi. */
-export function isCompanyActive(company) {
- if (!company) return false;
- if (company.is_active === undefined || company.is_active === null) return true;
- return company.is_active !== false && company.is_active !== 0;
-}
diff --git a/frontend/src/features/forms/defaults.js b/frontend/src/features/forms/defaults.js
index 95dfd02a6fb87fe412a12e3ab382b5e88f5b22a2..4fbe9d606d6305dd7a6c8f2d1f783260be939613 100644
--- a/frontend/src/features/forms/defaults.js
+++ b/frontend/src/features/forms/defaults.js
@@ -39,51 +39,6 @@ export function createProductCostForm() {
};
}
-export function createCompanyForm() {
- return {
- name: "",
- address: "",
- tax_number: "",
- notes: "",
- };
-}
-
-export function createTalashPriceForm() {
- return {
- company_id: "",
- effective_date: currentDateValue(),
- unit_price: "",
- notes: "",
- };
-}
-
-export function createTalashSaleForm() {
- return {
- company_id: "",
- sale_date: currentDateValue(),
- bag_count: "",
- unit_price: "",
- notes: "",
- };
-}
-
-export function createTalashUnitCostForm() {
- return {
- effective_date: currentDateValue(),
- cost_per_bag: "",
- notes: "",
- };
-}
-
-export function createTalashExpenseForm() {
- return {
- expense_date: currentDateValue(),
- category: "",
- amount: "",
- notes: "",
- };
-}
-
export function createLumberForm() {
return {
lumber_kind: "serit",
diff --git a/frontend/src/features/layout/AppShell.jsx b/frontend/src/features/layout/AppShell.jsx
index baa8830fac10e99e63ce55b9d6285b1247b1f501..3fb85f3f98221f0fcc6a65183830c6cf274192c5 100644
--- a/frontend/src/features/layout/AppShell.jsx
+++ b/frontend/src/features/layout/AppShell.jsx
@@ -1,10 +1,7 @@
import {
isCatalogNavKey,
- SIDEBAR_ECOMMERCE_KICKER,
- SIDEBAR_FIRMA_NAV,
SIDEBAR_LUMBER_NAV,
SIDEBAR_MAIN_NAV,
- SIDEBAR_TALASH_KICKER,
} from "../../constants/nav.js";
/**
@@ -17,50 +14,31 @@ export function AppShell({ user, activePage, onSelectPage, onLogout, children })