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

- -
-
-
- - setEditCompanyForm((s) => ({ ...s, name: e.target.value }))} - required - /> -
-
- -