Spaces:
Sleeping
Sleeping
talas
#2
by Caner7 - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- app/api/router.py-4
- app/api/routes/companies.pyDeleted-234
- app/api/routes/talash.pyDeleted-882
- app/infrastructure/database.py-151
- app/main.py+3-127
- app/schemas/__init__.py-18
- app/schemas/companies.pyDeleted-12
- app/schemas/talash.pyDeleted-55
- app/services/talash_collection.pyDeleted-168
- app/services/talash_costs.pyDeleted-84
- app/services/talash_dashboard.pyDeleted-261
- app/services/talash_pricing.pyDeleted-35
- app/services/talash_slip_pdf.pyDeleted-189
- app/static_assets.pyDeleted-42
- frontend/index.html-1
- frontend/src/components/CompanySelect.jsxDeleted-48
- frontend/src/constants/nav.js-22
- frontend/src/features/app/ActivePageSwitch.jsx-128
- frontend/src/features/app/AppModals.jsx-42
- frontend/src/features/app/modals/CompanyEditModal.jsxDeleted-69
- frontend/src/features/app/modals/TalashExpenseEditModal.jsxDeleted-87
- frontend/src/features/app/modals/TalashPaymentModal.jsxDeleted-69
- frontend/src/features/app/modals/TalashPriceEditModal.jsxDeleted-86
- frontend/src/features/app/modals/TalashSaleEditModal.jsxDeleted-99
- frontend/src/features/app/modals/TalashUnitCostEditModal.jsxDeleted-70
- frontend/src/features/app/pages/CompaniesListPage.jsxDeleted-146
- frontend/src/features/app/pages/CompanyEntryPage.jsxDeleted-67
- frontend/src/features/app/pages/TalashCollectionSlipPage.jsxDeleted-237
- frontend/src/features/app/pages/TalashCostEntryPage.jsxDeleted-139
- frontend/src/features/app/pages/TalashCostsListPage.jsxDeleted-144
- frontend/src/features/app/pages/TalashDashboardPage.jsxDeleted-298
- frontend/src/features/app/pages/TalashPriceEntryPage.jsxDeleted-84
- frontend/src/features/app/pages/TalashPricesListPage.jsxDeleted-92
- frontend/src/features/app/pages/TalashSaleEntryPage.jsxDeleted-133
- frontend/src/features/app/pages/TalashSalesListPage.jsxDeleted-212
- frontend/src/features/app/printTalashSlip.jsDeleted-43
- frontend/src/features/app/slices/useCompaniesSlice.jsDeleted-128
- frontend/src/features/app/slices/useTalashSlice.jsDeleted-711
- frontend/src/features/app/useAppController.js-114
- frontend/src/features/firma/FirmaCompanyFilter.jsxDeleted-10
- frontend/src/features/firma/FirmaEntryLayout.jsxDeleted-18
- frontend/src/features/firma/FirmaListPanel.jsxDeleted-15
- frontend/src/features/firma/FirmaPageShell.jsxDeleted-21
- frontend/src/features/firma/FirmaStatTiles.jsxDeleted-14
- frontend/src/features/firma/companyActive.jsDeleted-6
- frontend/src/features/forms/defaults.js-45
- frontend/src/features/layout/AppShell.jsx+24-46
- frontend/src/lib/format.js-24
- frontend/src/styles/app.css-4
- frontend/src/styles/partials/01-base-shell-lumber.css-3
6 unmodified lines789101112131415161718195 unmodified lines25262728296 unmodified linesfrom fastapi import FastAPIfrom app.api.routes.auth import router as auth_routerfrom app.api.routes.companies import router as companies_routerfrom app.api.routes.expenses import product_costs_router, router as expenses_routerfrom app.api.routes.exports import router as exports_routerfrom app.api.routes.lumber import router as lumber_routerfrom app.api.routes.orders import router as orders_routerfrom app.api.routes.reports import router as reports_routerfrom app.api.routes.talash import router as talash_routerdef include_api_routers(application: FastAPI) -> None:5 unmodified linesapplication.include_router(reports_router)application.include_router(exports_router)application.include_router(lumber_router)application.include_router(companies_router)application.include_router(talash_router)6 unmodified lines78910111213141516175 unmodified lines2324256 unmodified linesfrom fastapi import FastAPIfrom app.api.routes.auth import router as auth_routerfrom app.api.routes.expenses import product_costs_router, router as expenses_routerfrom app.api.routes.exports import router as exports_routerfrom app.api.routes.lumber import router as lumber_routerfrom app.api.routes.orders import router as orders_routerfrom app.api.routes.reports import router as reports_routerdef include_api_routers(application: FastAPI) -> None:5 unmodified linesapplication.include_router(reports_router)application.include_router(exports_router)application.include_router(lumber_router)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234"""Firma katalog endpoint'leri."""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from app.auth import get_active_userfrom app.infrastructure.database import get_dbfrom 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882"""Talas cuval fiyat tarifesi ve firma satis kayitlari."""
from datetime import datefrom typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Queryfrom fastapi.responses import Response
from app.auth import get_active_userfrom app.infrastructure.database import get_dbfrom app.schemas import ( TalashBulkCollectionPayload, TalashCollectionPayload, TalashCompanyPaymentPayload, TalashExpensePayload, TalashPricePayload, TalashSalePayload, TalashUnitCostPayload,)from app.services.talash_costs import resolve_unit_costfrom 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_totalfrom app.services.talash_dashboard import build_talash_dashboardfrom 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_amountFROM company_talash_sales sJOIN 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}112 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420589 unmodified lines295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364112 unmodified lines_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(89 unmodified lines)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_salesSET collected_amount = total_amountWHERE 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 companiesWHERE 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):continuebase = " ".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()112 unmodified lines11311411511611711889 unmodified lines208209210211212213112 unmodified lines_ensure_product_costs_schema(cur)cur.execute("CREATE INDEX IF NOT EXISTS idx_product_costs_name ON product_costs(product_name)")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(89 unmodified lines)def _ensure_product_costs_schema(cur):columns = {row["name"] for row in cur.execute("PRAGMA table_info(product_costs)").fetchall()
5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331346 unmodified lines1411421431441451461471486 unmodified lines1551561571581591601611621631641651661671681691701711725 unmodified linesfrom __future__ import annotationsimport refrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import FileResponse, HTMLResponse, RedirectResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.middleware.base import BaseHTTPMiddlewarefrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.requests import Requestfrom starlette.responses import Responsefrom app.api.router import include_api_routersfrom app.core.config import SESSION_SECRET, STATIC_DIRfrom app.infrastructure.database import init_dbfrom 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"""<!doctype html><html lang="tr"><head><meta charset="UTF-8" /><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Muhasebe App</title><script type="module" crossorigin src="/assets/index.js?v={version}"></script><link rel="stylesheet" crossorigin href="/assets/index.css?v={version}"></head><body><div id="root"></div></body></html>"""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.pathif 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.pathif path.startswith("/assets/") and not (_LEGACY_ENTRY_JS.match(path) or _LEGACY_ENTRY_CSS.match(path)):response.headers["Cache-Control"] = _ASSETS_CACHEelif path == "/" or path.endswith(".html"):response.headers["Cache-Control"] = _HTML_NO_CACHEresponse.headers["Pragma"] = "no-cache"elif response.headers.get("content-type", "").startswith("text/html"):response.headers["Cache-Control"] = _HTML_NO_CACHEresponse.headers["Pragma"] = "no-cache"return response@asynccontextmanager6 unmodified linesdef 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,6 unmodified linesinclude_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()application.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")5 unmodified lines67891011121314151617181920216 unmodified lines2829303132336 unmodified lines4041424344454647485 unmodified linesfrom __future__ import annotationsfrom contextlib import asynccontextmanagerfrom fastapi import FastAPIfrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.middleware.sessions import SessionMiddlewarefrom app.api.router import include_api_routersfrom app.core.config import SESSION_SECRET, STATIC_DIRfrom app.infrastructure.database import init_db@asynccontextmanager6 unmodified linesdef create_app() -> FastAPI:"""FastAPI uygulamasını middleware ve route'larla oluşturur."""application = FastAPI(title="Muhasebe App", lifespan=lifespan)application.add_middleware(SessionMiddleware,secret_key=SESSION_SECRET,6 unmodified linesinclude_api_routers(application)@application.get("/")def serve_index():"""React giriş dosyasını döndürür."""return FileResponse(STATIC_DIR / "index.html")application.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")
4 unmodified lines5678910111213141516171819202122232425261 unmodified line28293031323334353637384 unmodified lines"""from app.schemas.auth import LoginPayloadfrom app.schemas.companies import CompanyPayloadfrom app.schemas.expenses import ExpensePayload, ProductCostPayloadfrom app.schemas.lumber import LumberTierCreatePayload, LumberTierPutPayload, LumberTransactionPayloadfrom app.schemas.orders import OrderPayloadfrom app.schemas.talash import (TalashBulkCollectionPayload,TalashCollectionPayload,TalashCompanyPaymentPayload,TalashExpensePayload,TalashPricePayload,TalashSalePayload,TalashUnitCostPayload,)__all__ = ["CompanyPayload","ExpensePayload","LoginPayload","LumberTierCreatePayload",1 unmodified line"LumberTransactionPayload","OrderPayload","ProductCostPayload","TalashBulkCollectionPayload","TalashCollectionPayload","TalashCompanyPaymentPayload","TalashExpensePayload","TalashPricePayload","TalashSalePayload","TalashUnitCostPayload",]4 unmodified lines567891011121314151 unmodified line171819204 unmodified lines"""from app.schemas.auth import LoginPayloadfrom app.schemas.expenses import ExpensePayload, ProductCostPayloadfrom app.schemas.lumber import LumberTierCreatePayload, LumberTierPutPayload, LumberTransactionPayloadfrom app.schemas.orders import OrderPayload__all__ = ["ExpensePayload","LoginPayload","LumberTierCreatePayload",1 unmodified line"LumberTransactionPayload","OrderPayload","ProductCostPayload",]
123456789101112"""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 = ""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""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 = ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Talaş satış tahsilatı: kismi odeme, kalan bakiye, durum senkronu."""
from __future__ import annotations
from datetime import datefrom 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 updates123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""Talaş satış / tahsilat finansal özet sorguları."""
from __future__ import annotations
import refrom datetime import datefrom 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(), }1234567891011121314151617181920212223242526272829303132333435"""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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Tahsilat irsaliyesi PDF (reportlab)."""
from __future__ import annotations
import iofrom typing import Any
from reportlab.lib import colorsfrom reportlab.lib.pagesizes import A4from reportlab.lib.units import mmfrom 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 lines123456789101112131415161718192021222324252627282930313233343536373839404142"""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"1 unmodified line23456781 unmodified line<html lang="tr"><head><meta charset="UTF-8" /><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Muhasebe App</title></head>1 unmodified line2345671 unmodified line<html lang="tr"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Muhasebe App</title></head>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import { 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 ( <select id={id} value={value} onChange={(e) => onChange(e.target.value)} required={required && !allowAll} > {allowAll ? <option value="">{allLabel}</option> : <option value="">{placeholder}</option>} {options.map((c) => ( <option key={c.id} value={String(c.id)}> {c.name} {!isCompanyActive(c) ? " (pasif)" : ""} </option> ))} </select> );}12345678910111212 unmodified lines252627282930313233343536373839404142434445464748/*** 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"],12 unmodified lines["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";}1234567812 unmodified lines212223242526/*** Kenar çubuğu sayfa anahtarları ve etiketleri.* Tek kaynak: rota adları hem navigasyonda hem olası ilerideki yönlendirmede kullanılır.*/export const SIDEBAR_MAIN_NAV = [["dashboard", "Dashboard"],["order-entry", "Siparis Girisi"],12 unmodified lines["lumber-charts", "Kereste grafikler"],];export function isCatalogNavKey(key) {return key === "product-cost-entry" || key === "product-costs";}
9 unmodified lines1011121314151617181920212223242574 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222239 unmodified linesimport { 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 }) {74 unmodified lineshandleDeleteProductCost={app.handleDeleteProductCost}/>);case "talash-dashboard":return (<TalashDashboardPagecompanies={app.companies}talashDashboard={app.talashDashboard}talashDashboardLoading={app.talashDashboardLoading}talashDashboardMonth={app.talashDashboardMonth}setTalashDashboardMonth={app.setTalashDashboardMonth}talashDashboardCompanyId={app.talashDashboardCompanyId}applyTalashDashboardFilter={app.applyTalashDashboardFilter}openCompanyTalashSales={app.openCompanyTalashSales}setActivePage={app.setActivePage}/>);case "talash-cost-entry":return (<TalashCostEntryPagetalashUnitCostForm={app.talashUnitCostForm}setTalashUnitCostForm={app.setTalashUnitCostForm}handleCreateTalashUnitCost={app.handleCreateTalashUnitCost}talashExpenseForm={app.talashExpenseForm}setTalashExpenseForm={app.setTalashExpenseForm}handleCreateTalashExpense={app.handleCreateTalashExpense}/>);case "talash-costs":return (<TalashCostsListPagetalashUnitCosts={app.talashUnitCosts}talashExpenses={app.talashExpenses}openEditTalashUnitCost={app.openEditTalashUnitCost}handleDeleteTalashUnitCost={app.handleDeleteTalashUnitCost}openEditTalashExpense={app.openEditTalashExpense}handleDeleteTalashExpense={app.handleDeleteTalashExpense}setActivePage={app.setActivePage}/>);case "company-entry":return (<CompanyEntryPagecompanyForm={app.companyForm}setCompanyForm={app.setCompanyForm}handleCreateCompany={app.handleCreateCompany}/>);case "companies":return (<CompaniesListPagecompanies={app.companies}openEditCompany={app.openEditCompany}handleDeleteCompany={app.handleDeleteCompany}openCompanyTalashSales={app.openCompanyTalashSales}openCompanyTalashPrices={app.openCompanyTalashPrices}setActivePage={app.setActivePage}/>);case "talash-price-entry":return (<TalashPriceEntryPagecompanies={app.companies}talashPriceForm={app.talashPriceForm}setTalashPriceForm={app.setTalashPriceForm}handleCreateTalashPrice={app.handleCreateTalashPrice}/>);case "talash-prices":return (<TalashPricesListPagecompanies={app.companies}talashPrices={app.talashPrices}talashFilterCompanyId={app.talashFilterCompanyId}applyTalashCompanyFilter={app.applyTalashCompanyFilter}openEditTalashPrice={app.openEditTalashPrice}handleDeleteTalashPrice={app.handleDeleteTalashPrice}setActivePage={app.setActivePage}/>);case "talash-sale-entry":return (<TalashSaleEntryPagecompanies={app.companies}talashSaleForm={app.talashSaleForm}setTalashSaleForm={app.setTalashSaleForm}talashQuoteHint={app.talashQuoteHint}fetchTalashQuote={app.fetchTalashQuote}handleCreateTalashSale={app.handleCreateTalashSale}/>);case "talash-sales":return (<TalashSalesListPagecompanies={app.companies}talashSales={app.talashSales}talashSalesSummary={app.talashSalesSummary}talashFilterCompanyId={app.talashFilterCompanyId}talashCollectionFilter={app.talashCollectionFilter}applyTalashCompanyFilter={app.applyTalashCompanyFilter}applyTalashCollectionFilter={app.applyTalashCollectionFilter}openEditTalashSale={app.openEditTalashSale}handleDeleteTalashSale={app.handleDeleteTalashSale}addTalashSalePayment={app.addTalashSalePayment}resetTalashSaleCollection={app.resetTalashSaleCollection}openTalashCollectionSlip={app.openTalashCollectionSlip}setActivePage={app.setActivePage}/>);case "talash-collection-slip":return (<TalashCollectionSlipPagecompanies={app.companies}collectionSlipCompanyId={app.collectionSlipCompanyId}setCollectionSlipCompanyId={app.setCollectionSlipCompanyId}collectionSlip={app.collectionSlip}loadCollectionSlip={app.loadCollectionSlip}collectTalashCompanyPayment={app.collectTalashCompanyPayment}setActivePage={app.setActivePage}/>);case "lumber-rules":return (<LumberRulesPage9 unmodified lines10111213141574 unmodified lines9091929394959 unmodified linesimport { LumberTransactionsPage } from "./pages/LumberTransactionsPage.jsx";import { LumberChartsPage } from "./pages/LumberChartsPage.jsx";import { ReportsPage } from "./pages/ReportsPage.jsx";/** `activePage` anahtarına göre tek tam ekran gövdesi. */export function ActivePageSwitch({ app }) {74 unmodified lineshandleDeleteProductCost={app.handleDeleteProductCost}/>);case "lumber-rules":return (<LumberRulesPage
2 unmodified lines34567891011121332 unmodified lines464748495051525354555657585960616263646566676869707172737475767778798081828384858687882 unmodified linesimport { ProductCostEditModal } from "./modals/ProductCostEditModal.jsx";import { LumberTierEditModal } from "./modals/LumberTierEditModal.jsx";import { LumberTransactionEditModal } from "./modals/LumberTransactionEditModal.jsx";import { CompanyEditModal } from "./modals/CompanyEditModal.jsx";import { TalashPriceEditModal } from "./modals/TalashPriceEditModal.jsx";import { TalashSaleEditModal } from "./modals/TalashSaleEditModal.jsx";import { TalashUnitCostEditModal } from "./modals/TalashUnitCostEditModal.jsx";import { TalashExpenseEditModal } from "./modals/TalashExpenseEditModal.jsx";/** Oturum boyunca üst üste açılabilen global modallar. */export function AppModals({ app }) {32 unmodified linescloseLumberTierEditor={app.closeLumberTierEditor}handleSaveLumberTier={app.handleSaveLumberTier}/><CompanyEditModaleditingCompany={app.editingCompany}editCompanyForm={app.editCompanyForm}setEditCompanyForm={app.setEditCompanyForm}closeEditCompany={app.closeEditCompany}handleUpdateCompany={app.handleUpdateCompany}/><TalashPriceEditModalcompanies={app.companies}editingTalashPrice={app.editingTalashPrice}editTalashPriceForm={app.editTalashPriceForm}setEditTalashPriceForm={app.setEditTalashPriceForm}closeEditTalashPrice={app.closeEditTalashPrice}handleUpdateTalashPrice={app.handleUpdateTalashPrice}/><TalashSaleEditModalcompanies={app.companies}editingTalashSale={app.editingTalashSale}editTalashSaleForm={app.editTalashSaleForm}setEditTalashSaleForm={app.setEditTalashSaleForm}closeEditTalashSale={app.closeEditTalashSale}handleUpdateTalashSale={app.handleUpdateTalashSale}/><TalashUnitCostEditModaleditingTalashUnitCost={app.editingTalashUnitCost}editTalashUnitCostForm={app.editTalashUnitCostForm}setEditTalashUnitCostForm={app.setEditTalashUnitCostForm}closeEditTalashUnitCost={app.closeEditTalashUnitCost}handleUpdateTalashUnitCost={app.handleUpdateTalashUnitCost}/><TalashExpenseEditModaleditingTalashExpense={app.editingTalashExpense}editTalashExpenseForm={app.editTalashExpenseForm}setEditTalashExpenseForm={app.setEditTalashExpenseForm}closeEditTalashExpense={app.closeEditTalashExpense}handleUpdateTalashExpense={app.handleUpdateTalashExpense}/><LumberTransactionEditModallumberRules={app.lumberRules}editingLumberTx={app.editingLumberTx}2 unmodified lines34567832 unmodified lines4142434445462 unmodified linesimport { ProductCostEditModal } from "./modals/ProductCostEditModal.jsx";import { LumberTierEditModal } from "./modals/LumberTierEditModal.jsx";import { LumberTransactionEditModal } from "./modals/LumberTransactionEditModal.jsx";/** Oturum boyunca üst üste açılabilen global modallar. */export function AppModals({ app }) {32 unmodified linescloseLumberTierEditor={app.closeLumberTierEditor}handleSaveLumberTier={app.handleSaveLumberTier}/><LumberTransactionEditModallumberRules={app.lumberRules}editingLumberTx={app.editingLumberTx}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869/** Firma duzenleme modali. */export function CompanyEditModal({ editingCompany, editCompanyForm, setEditCompanyForm, closeEditCompany, handleUpdateCompany,}) { if (!editCompanyForm || !editingCompany) return null; return ( <div className="modal-overlay" role="dialog" aria-labelledby="edit-company-title" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) closeEditCompany(); }} > <div className="modal-card card panel expense-edit-modal" onClick={(e) => e.stopPropagation()}> <div className="modal-head row-between"> <h3 id="edit-company-title">Firmayi duzenle</h3> <button type="button" className="icon-btn" title="Kapat" onClick={closeEditCompany}> ✕ </button> </div> <form className="expense-form-grid firma-modal-form" onSubmit={handleUpdateCompany}> <div className="field field-full"> <label>Firma adi</label> <input value={editCompanyForm.name} onChange={(e) => setEditCompanyForm((s) => ({ ...s, name: e.target.value }))} required /> </div> <div className="field field-full"> <label>Adres</label> <textarea rows={3} value={editCompanyForm.address} onChange={(e) => setEditCompanyForm((s) => ({ ...s, address: e.target.value }))} /> </div> <div className="field field-full"> <label>Vergi numarasi</label> <input value={editCompanyForm.tax_number} onChange={(e) => setEditCompanyForm((s) => ({ ...s, tax_number: e.target.value }))} inputMode="numeric" /> </div> <div className="field field-full"> <label>Not</label> <input value={editCompanyForm.notes} onChange={(e) => setEditCompanyForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="field-full modal-actions"> <button type="button" className="secondary" onClick={closeEditCompany}> Iptal </button> <button type="submit">Kaydet</button> </div> </form> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687const EXPENSE_CATEGORIES = ["Tedarik", "Nakliye", "Iscilik", "Yakit", "Diger"];
export function TalashExpenseEditModal({ editingTalashExpense, editTalashExpenseForm, setEditTalashExpenseForm, closeEditTalashExpense, handleUpdateTalashExpense,}) { if (!editTalashExpenseForm || !editingTalashExpense) return null; return ( <div className="modal-overlay" role="dialog" aria-labelledby="edit-talash-expense-title" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) closeEditTalashExpense(); }} > <div className="modal-card card panel expense-edit-modal" onClick={(e) => e.stopPropagation()}> <div className="modal-head row-between"> <h3 id="edit-talash-expense-title">Gideri duzenle</h3> <button type="button" className="icon-btn" title="Kapat" onClick={closeEditTalashExpense}> ✕ </button> </div> <form className="expense-form-grid firma-modal-form" onSubmit={handleUpdateTalashExpense}> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gider tarihi</label> <input type="date" value={editTalashExpenseForm.expense_date} onChange={(e) => setEditTalashExpenseForm((s) => ({ ...s, expense_date: e.target.value })) } required /> </div> <div className="field"> <label>Kategori</label> <input list="talash-expense-categories-edit" value={editTalashExpenseForm.category} onChange={(e) => setEditTalashExpenseForm((s) => ({ ...s, category: e.target.value })) } /> <datalist id="talash-expense-categories-edit"> {EXPENSE_CATEGORIES.map((c) => ( <option key={c} value={c} /> ))} </datalist> </div> </div> <div className="field field-full"> <label>Tutar (TL)</label> <input type="number" step="0.01" min="0.01" value={editTalashExpenseForm.amount} onChange={(e) => setEditTalashExpenseForm((s) => ({ ...s, amount: e.target.value })) } required /> </div> <div className="field field-full"> <label>Not</label> <input value={editTalashExpenseForm.notes} onChange={(e) => setEditTalashExpenseForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="field-full modal-actions"> <button type="button" className="secondary" onClick={closeEditTalashExpense}> Iptal </button> <button type="submit">Kaydet</button> </div> </form> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { 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 ( <div className="modal-backdrop" role="presentation" onClick={onClose}> <div className="card panel modal-card firma-modal-form" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()} > <h3>{title}</h3> {subtitle ? <p className="firma-slip-hint">{subtitle}</p> : null} <form onSubmit={handleSubmit}> <div className="field"> <label>Tahsil tutari (TL)</label> <input type="number" min="0.01" step="0.01" max={maxAmount != null ? String(maxAmount) : undefined} value={amount} onChange={(e) => setAmount(e.target.value)} required autoFocus /> </div> {maxAmount != null ? ( <p className="firma-slip-hint">En fazla {Number(maxAmount).toFixed(2)} TL</p> ) : null} <div className="modal-actions"> <button type="button" className="secondary" onClick={onClose}> Vazgec </button> <button type="submit" className="firma-hero-btn"> Kaydet </button> </div> </form> </div> </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import { CompanySelect } from "../../../components/CompanySelect.jsx";
export function TalashPriceEditModal({ companies, editingTalashPrice, editTalashPriceForm, setEditTalashPriceForm, closeEditTalashPrice, handleUpdateTalashPrice,}) { if (!editTalashPriceForm || !editingTalashPrice) return null; return ( <div className="modal-overlay" role="dialog" aria-labelledby="edit-talash-price-title" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) closeEditTalashPrice(); }} > <div className="modal-card card panel expense-edit-modal" onClick={(e) => e.stopPropagation()}> <div className="modal-head row-between"> <h3 id="edit-talash-price-title">Talas fiyatini duzenle</h3> <button type="button" className="icon-btn" title="Kapat" onClick={closeEditTalashPrice}> ✕ </button> </div> <form className="expense-form-grid firma-modal-form" onSubmit={handleUpdateTalashPrice}> <div className="field field-full"> <label>Firma</label> <CompanySelect companies={companies} value={editTalashPriceForm.company_id} onChange={(v) => setEditTalashPriceForm((s) => ({ ...s, company_id: v }))} fallbackCompany={{ id: editingTalashPrice.company_id, name: editingTalashPrice.company_name, }} required /> </div> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gecerlilik baslangic tarihi</label> <input type="date" value={editTalashPriceForm.effective_date} onChange={(e) => setEditTalashPriceForm((s) => ({ ...s, effective_date: e.target.value })) } required /> </div> <div className="field firma-price-field"> <label>Cuval birim fiyat (TL)</label> <input type="number" step="0.01" min="0.01" value={editTalashPriceForm.unit_price} onChange={(e) => setEditTalashPriceForm((s) => ({ ...s, unit_price: e.target.value })) } required /> </div> </div> <div className="field field-full"> <label>Not</label> <input value={editTalashPriceForm.notes} onChange={(e) => setEditTalashPriceForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="field-full modal-actions"> <button type="button" className="secondary" onClick={closeEditTalashPrice}> Iptal </button> <button type="submit">Kaydet</button> </div> </form> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import { CompanySelect } from "../../../components/CompanySelect.jsx";
export function TalashSaleEditModal({ companies, editingTalashSale, editTalashSaleForm, setEditTalashSaleForm, closeEditTalashSale, handleUpdateTalashSale,}) { if (!editTalashSaleForm || !editingTalashSale) return null; return ( <div className="modal-overlay" role="dialog" aria-labelledby="edit-talash-sale-title" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) closeEditTalashSale(); }} > <div className="modal-card card panel expense-edit-modal" onClick={(e) => e.stopPropagation()}> <div className="modal-head row-between"> <h3 id="edit-talash-sale-title">Talas satisini duzenle</h3> <button type="button" className="icon-btn" title="Kapat" onClick={closeEditTalashSale}> ✕ </button> </div> <form className="expense-form-grid firma-modal-form" onSubmit={handleUpdateTalashSale}> <div className="field field-full"> <label>Firma</label> <CompanySelect companies={companies} value={editTalashSaleForm.company_id} onChange={(v) => setEditTalashSaleForm((s) => ({ ...s, company_id: v }))} fallbackCompany={{ id: editingTalashSale.company_id, name: editingTalashSale.company_name, }} required /> </div> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Satis tarihi</label> <input type="date" value={editTalashSaleForm.sale_date} onChange={(e) => setEditTalashSaleForm((s) => ({ ...s, sale_date: e.target.value })) } required /> </div> <div className="field"> <label>Cuval adedi</label> <input type="number" step="1" min="1" value={editTalashSaleForm.bag_count} onChange={(e) => setEditTalashSaleForm((s) => ({ ...s, bag_count: e.target.value })) } required /> </div> </div> <div className="field field-full"> <label>Birim fiyat (TL / cuval)</label> <input type="number" step="0.01" min="0.01" value={editTalashSaleForm.unit_price} onChange={(e) => setEditTalashSaleForm((s) => ({ ...s, unit_price: e.target.value })) } required /> </div> <div className="field field-full"> <label>Not</label> <input value={editTalashSaleForm.notes} onChange={(e) => setEditTalashSaleForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="field-full modal-actions"> <button type="button" className="secondary" onClick={closeEditTalashSale}> Iptal </button> <button type="submit">Kaydet</button> </div> </form> </div> </div> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970export function TalashUnitCostEditModal({ editingTalashUnitCost, editTalashUnitCostForm, setEditTalashUnitCostForm, closeEditTalashUnitCost, handleUpdateTalashUnitCost,}) { if (!editTalashUnitCostForm || !editingTalashUnitCost) return null; return ( <div className="modal-overlay" role="dialog" aria-labelledby="edit-talash-unit-cost-title" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) closeEditTalashUnitCost(); }} > <div className="modal-card card panel expense-edit-modal" onClick={(e) => e.stopPropagation()}> <div className="modal-head row-between"> <h3 id="edit-talash-unit-cost-title">Tedarik maliyetini duzenle</h3> <button type="button" className="icon-btn" title="Kapat" onClick={closeEditTalashUnitCost}> ✕ </button> </div> <form className="expense-form-grid firma-modal-form" onSubmit={handleUpdateTalashUnitCost}> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gecerlilik baslangici</label> <input type="date" value={editTalashUnitCostForm.effective_date} onChange={(e) => setEditTalashUnitCostForm((s) => ({ ...s, effective_date: e.target.value })) } required /> </div> <div className="field firma-price-field"> <label>Cuval maliyeti (TL)</label> <input type="number" step="0.01" min="0.01" value={editTalashUnitCostForm.cost_per_bag} onChange={(e) => setEditTalashUnitCostForm((s) => ({ ...s, cost_per_bag: e.target.value })) } required /> </div> </div> <div className="field field-full"> <label>Not</label> <input value={editTalashUnitCostForm.notes} onChange={(e) => setEditTalashUnitCostForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="field-full modal-actions"> <button type="button" className="secondary" onClick={closeEditTalashUnitCost}> Iptal </button> <button type="submit">Kaydet</button> </div> </form> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import { 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 ( <FirmaPageShell badge={countLabel} title="Firma listesi" subtitle="Kayitli firmalari kart olarak gorun. Talas satis ve fiyat gecmisine tek tikla gidebilirsiniz." action={ <button type="button" className="firma-hero-btn" onClick={() => setActivePage("company-entry")}> + Yeni firma </button> } > <FirmaListPanel plain> {activeCompanies.length === 0 ? ( <div className="firma-empty-state"> <strong>Henuz firma yok</strong> Ilk firmayi eklemek icin ustteki "Yeni firma" butonunu kullanin. </div> ) : ( <div className="firma-company-grid"> {activeCompanies.map((item) => ( <article key={item.id} className="firma-company-card"> <header className="firma-company-card-head"> <div className="firma-company-card-title-wrap"> <h4>{item.name || "—"}</h4> {item.tax_number ? ( <span className="firma-company-card-vkn">VKN {item.tax_number}</span> ) : null} </div> <div className="firma-company-card-head-actions"> <button type="button" className="firma-card-icon-btn" title="Duzenle" aria-label="Duzenle" onClick={() => openEditCompany(item)} > ✏️ </button> <button type="button" className="firma-card-icon-btn firma-card-icon-btn--danger" title="Listeden kaldir (kayitlar kalir)" aria-label="Listeden kaldir" disabled={removingId === item.id} onClick={() => setPendingRemoveId(item.id)} > 🗑 </button> </div> </header> {pendingRemoveId === item.id ? ( <div className="firma-company-remove-confirm" role="status"> <p> <strong>{item.name}</strong> listeden kaldırılsın mı? Talaş kayıtları silinmez, yalnızca yeni işlemlerde seçilemez. </p> <div className="firma-company-remove-actions"> <button type="button" className="secondary" disabled={removingId === item.id} onClick={() => setPendingRemoveId(null)} > Hayir </button> <button type="button" className="firma-company-remove-confirm-btn" disabled={removingId === item.id} onClick={async () => { setRemovingId(item.id); try { await handleDeleteCompany(item.id); setPendingRemoveId(null); } finally { setRemovingId(null); } }} > {removingId === item.id ? "Kaldiriliyor…" : "Evet, kaldir"} </button> </div> </div> ) : null} <dl className="firma-company-card-meta"> <div> <dt>Vergi no</dt> <dd>{item.tax_number || "—"}</dd> </div> <div> <dt>Adres</dt> <dd className="firma-company-card-address">{item.address || "—"}</dd> </div> {item.notes ? ( <div> <dt>Not</dt> <dd>{item.notes}</dd> </div> ) : null} </dl> <footer className="firma-company-card-foot"> <button type="button" className="firma-link-btn" onClick={() => openCompanyTalashSales(item.id)} > Talas satislari </button> <button type="button" className="firma-link-btn" onClick={() => openCompanyTalashPrices(item.id)} > Fiyat tarifesi </button> </footer> </article> ))} </div> )} </FirmaListPanel> </FirmaPageShell> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { 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 ( <FirmaPageShell badge="Yeni kayit" title="Firma girisi" subtitle="Musteri veya tedarikci firmayi ekleyin. Talas satis ve fiyat tarifeleri bu kayda baglanir." > <FirmaEntryLayout tips={TIPS}> <h3 className="firma-form-panel-title">Firma bilgileri</h3> <form className="firma-form-grid expense-form-grid" onSubmit={handleCreateCompany}> <div className="field field-full"> <label>Firma adi</label> <input value={companyForm.name} onChange={(e) => setCompanyForm((s) => ({ ...s, name: e.target.value }))} placeholder="Ornek: ABC Lojistik A.S." required /> </div> <div className="field field-full"> <label>Adres</label> <textarea rows={4} value={companyForm.address} onChange={(e) => setCompanyForm((s) => ({ ...s, address: e.target.value }))} placeholder="Mahalle, cadde, il / ilce" /> </div> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Vergi numarasi</label> <input value={companyForm.tax_number} onChange={(e) => setCompanyForm((s) => ({ ...s, tax_number: e.target.value }))} placeholder="VKN / TCKN" inputMode="numeric" /> </div> <div className="field"> <label>Not</label> <input value={companyForm.notes} onChange={(e) => setCompanyForm((s) => ({ ...s, notes: e.target.value }))} placeholder="Istege bagli" /> </div> </div> <div className="firma-form-actions field-full"> <button type="submit" className="firma-submit-btn"> Firmayi kaydet </button> </div> </form> </FirmaEntryLayout> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237import { 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 ( <FirmaPageShell badge={lineCount ? `${lineCount} kalem` : "Tahsilat"} title="Tahsilat irsaliyesi" subtitle="Elemaniniz firmaya giderken elindeki belge: yalnizca odeme bekleyen satislar listelenir." action={ <div className="firma-hero-action-row no-print"> <button type="button" className="secondary" onClick={() => setActivePage("talash-sales")} > Satis listesi </button> <button type="button" className="firma-hero-btn" disabled={!slip || lineCount === 0} onClick={handlePrint} > Yazdir </button> </div> } > <section className="card panel firma-slip-panel no-print"> <div className="field"> <label>Firma secin</label> <CompanySelect companies={companies} value={collectionSlipCompanyId} onChange={(v) => { setCollectionSlipCompanyId(v); loadCollectionSlip(v); }} required /> </div> {slip && lineCount > 0 ? ( <div className="firma-slip-panel-actions"> <button type="button" className="firma-hero-btn" onClick={() => setPaymentOpen(true)}> Tahsilat kaydet </button> <p className="firma-slip-hint"> Alinan tutar acik satislara eski tarihten yeniye islenir; kalan bakiye sonraki irsaliyede gorunur. </p> </div> ) : null} </section>
{!collectionSlipCompanyId ? ( <div className="firma-empty-state no-print"> <strong>Firma secin</strong> Irsaliye icin once yukaridan firmayi secin. </div> ) : null}
{collectionSlipCompanyId && slip && lineCount === 0 ? ( <div className="firma-empty-state no-print"> <strong>Bekleyen satis yok</strong> Bu firma icin tahsil edilecek kayit kalmadi. </div> ) : null}
{slip && lineCount > 0 ? ( <div className="talash-slip-print-wrap"> <article className="talash-slip-print card panel" id="talash-collection-slip"> <header className="talash-slip-doc-bar"> <div className="talash-slip-doc-brand"> <p className="talash-slip-doc-eyebrow">Muhasebe · Talaş</p> <h2 className="talash-slip-doc-heading">Tahsilat irsaliyesi</h2> <p className="talash-slip-doc-tagline">Çuval talaş satışları — ödeme bekleyen kalemler</p> </div> <dl className="talash-slip-doc-ids"> <div> <dt>Belge no</dt> <dd>{slipDocumentNo(slip)}</dd> </div> <div> <dt>Düzenleme tarihi</dt> <dd>{formatDateTr(slip.issued_date)}</dd> </div> </dl> </header>
<section className="talash-slip-party" aria-label="Tahsilat yapılacak firma"> <p className="talash-slip-party-label">Tahsilat yapılacak firma</p> <h3 className="talash-slip-party-name">{slip.company.name}</h3> <div className="talash-slip-party-details"> {slip.company.tax_number ? ( <p> <span>VKN / TCKN</span> {slip.company.tax_number} </p> ) : null} {slip.company.address ? ( <p> <span>Adres</span> {slip.company.address} </p> ) : null} </div> </section>
<div className="talash-slip-highlights" aria-label="Özet"> <div className="talash-slip-highlight"> <span>Kalem sayısı</span> <strong>{lineCount}</strong> </div> <div className="talash-slip-highlight"> <span>Toplam çuval</span> <strong>{slip.total_bags}</strong> </div> <div className="talash-slip-highlight talash-slip-highlight--total"> <span>Tahsil edilecek tutar</span> <strong>{money(slip.total_amount)}</strong> </div> </div>
<p className="talash-slip-intro"> Asagida yalnizca kalan bakiyeler listelenir. Kismi odeme yapilmis satislarda onceki tahsilat dusulmustur. </p>
<table className="talash-slip-table"> <thead> <tr> <th className="talash-slip-th-seq">#</th> <th>Satis tarihi</th> <th className="talash-slip-th-num">Cuval</th> <th className="talash-slip-th-num">Satis</th> <th className="talash-slip-th-num">Tahsil</th> <th className="talash-slip-th-num">Kalan</th> </tr> </thead> <tbody> {slip.lines.map((line, index) => ( <tr key={line.id}> <td className="talash-slip-td-seq">{index + 1}</td> <td className="talash-slip-td-date">{formatDateTr(line.sale_date)}</td> <td className="talash-slip-td-num">{line.bag_count}</td> <td className="talash-slip-td-num">{money(line.total_amount)}</td> <td className="talash-slip-td-num">{money(line.collected_amount ?? 0)}</td> <td className="talash-slip-td-num talash-slip-td-amount"> {money(line.remaining_amount ?? line.total_amount)} </td> </tr> ))} </tbody> <tfoot> <tr> <td colSpan={2}> <strong>Tahsil edilecek toplam</strong> </td> <td className="talash-slip-td-num"> <strong>{slip.total_bags}</strong> </td> <td colSpan={2} /> <td className="talash-slip-td-num talash-slip-td-amount"> <strong>{money(slip.total_remaining ?? slip.total_amount)}</strong> </td> </tr> </tfoot> </table>
<footer className="talash-slip-signatures"> <div className="talash-slip-sign-block"> <span>Teslim eden (personel)</span> <div className="talash-slip-sign-line" /> <span className="talash-slip-sign-hint">Ad soyad · imza</span> </div> <div className="talash-slip-sign-block"> <span>Teslim alan (firma)</span> <div className="talash-slip-sign-line" /> <span className="talash-slip-sign-hint">Ad soyad · kaşe / imza · tarih</span> </div> </footer> </article> </div> ) : null}
<TalashPaymentModal open={paymentOpen} title="Firmadan tahsilat" subtitle={slip ? `${slip.company.name} · acik ${money(totalDue)}` : ""} defaultAmount={totalDue} maxAmount={totalDue} onClose={() => setPaymentOpen(false)} onSubmit={async (amount) => { if (!slip?.company?.id) return; await collectTalashCompanyPayment(slip.company.id, amount); setPaymentOpen(false); }} /> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139import { 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 ( <FirmaPageShell badge="Maliyet & gider" title="Talas maliyet ve gider girisi" subtitle="Degisen cuval tedarik maliyetini ve donemsel masraflari kaydedin; finans ozetinde kar/zarar hesaplanir." > <FirmaEntryLayout tips={TIPS} tipsTitle="Nasil calisir"> <section className="firma-form-panel"> <h3 className="firma-form-panel-title">Cuval tedarik maliyeti</h3> <p className="firma-form-panel-lead"> Satilan her cuval icin satis tarihinde gecerli maliyet tarifesi kullanilir. </p> <form className="firma-form-grid expense-form-grid" onSubmit={handleCreateTalashUnitCost}> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gecerlilik baslangici</label> <input type="date" value={talashUnitCostForm.effective_date} onChange={(e) => setTalashUnitCostForm((s) => ({ ...s, effective_date: e.target.value })) } required /> </div> <div className="field firma-price-field"> <label>Cuval maliyeti (TL)</label> <input type="number" step="0.01" min="0.01" placeholder="3.00" value={talashUnitCostForm.cost_per_bag} onChange={(e) => setTalashUnitCostForm((s) => ({ ...s, cost_per_bag: e.target.value })) } required /> </div> </div> <div className="field field-full"> <label>Not</label> <input value={talashUnitCostForm.notes} onChange={(e) => setTalashUnitCostForm((s) => ({ ...s, notes: e.target.value }))} placeholder="Or. yeni tedarikci fiyati" /> </div> <div className="firma-form-actions field-full"> <button type="submit" className="firma-submit-btn"> Maliyet tarifesini kaydet </button> </div> </form> </section>
<section className="firma-form-panel talash-cost-entry-gap"> <h3 className="firma-form-panel-title">Donem gideri</h3> <p className="firma-form-panel-lead"> Tedarik disi masraflar (tek seferlik veya donemsel). </p> <form className="firma-form-grid expense-form-grid" onSubmit={handleCreateTalashExpense}> <div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gider tarihi</label> <input type="date" value={talashExpenseForm.expense_date} onChange={(e) => setTalashExpenseForm((s) => ({ ...s, expense_date: e.target.value })) } required /> </div> <div className="field"> <label>Kategori</label> <input list="talash-expense-categories" value={talashExpenseForm.category} onChange={(e) => setTalashExpenseForm((s) => ({ ...s, category: e.target.value })) } placeholder="Nakliye" /> <datalist id="talash-expense-categories"> {EXPENSE_CATEGORIES.map((c) => ( <option key={c} value={c} /> ))} </datalist> </div> </div> <div className="field field-full"> <label>Tutar (TL)</label> <input type="number" step="0.01" min="0.01" value={talashExpenseForm.amount} onChange={(e) => setTalashExpenseForm((s) => ({ ...s, amount: e.target.value }))} required /> </div> <div className="field field-full"> <label>Not</label> <input value={talashExpenseForm.notes} onChange={(e) => setTalashExpenseForm((s) => ({ ...s, notes: e.target.value }))} /> </div> <div className="firma-form-actions field-full"> <button type="submit" className="firma-submit-btn"> Gideri kaydet </button> </div> </form> </section> </FirmaEntryLayout> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { 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 ( <FirmaPageShell badge={badge} title="Talas maliyet ve gider listesi" subtitle="Tedarik tarifeleri ve donem giderleri — finans ozetindeki kar/zarar bu kayitlara dayanir." action={ <button type="button" className="firma-hero-btn" onClick={() => setActivePage("talash-cost-entry")}> + Yeni kayit </button> } > <FirmaListPanel plain> <header className="talash-dash-panel-head talash-dash-table-head"> <h3>Cuval tedarik maliyetleri</h3> <p>Satis tarihine gore uygulanan birim maliyet gecmisi</p> </header> {talashUnitCosts.length === 0 ? ( <div className="firma-empty-state"> <strong>Maliyet tarifesi yok</strong> Cuval basina tedarik maliyeti girin; aksi halde kar hesabinda maliyet 0 kabul edilir. </div> ) : ( <div className="firma-table-wrap table-wrap expense-table-wrap"> <table className="expense-table firma-data-table firma-prices-table"> <thead> <tr> <th>Gecerlilik</th> <th className="firma-th-num">Cuval maliyeti</th> <th>Not</th> <th scope="col" className="firma-th-actions"> Islem </th> </tr> </thead> <tbody> {talashUnitCosts.map((item) => ( <tr key={item.id}> <td className="firma-td-date">{item.effective_date}</td> <td className="firma-td-num firma-td-price">{money(item.cost_per_bag)}</td> <td className="firma-td-note">{item.notes || "—"}</td> <td className="firma-row-actions"> <button type="button" className="firma-card-icon-btn" aria-label="Duzenle" onClick={() => openEditTalashUnitCost(item)} > ✏️ </button> <button type="button" className="firma-card-icon-btn firma-card-icon-btn--danger" aria-label="Sil" onClick={() => handleDeleteTalashUnitCost(item.id)} > 🗑 </button> </td> </tr> ))} </tbody> </table> </div> )} </FirmaListPanel>
<FirmaListPanel plain> <header className="talash-dash-panel-head talash-dash-table-head"> <h3>Donem giderleri</h3> <p>Tedarik disi masraflar</p> </header> {talashExpenses.length === 0 ? ( <div className="firma-empty-state"> <strong>Gider kaydi yok</strong> </div> ) : ( <div className="firma-table-wrap table-wrap expense-table-wrap"> <table className="expense-table firma-data-table"> <thead> <tr> <th>Tarih</th> <th>Kategori</th> <th className="firma-th-num">Tutar</th> <th>Not</th> <th scope="col" className="firma-th-actions"> Islem </th> </tr> </thead> <tbody> {talashExpenses.map((item) => ( <tr key={item.id}> <td className="firma-td-date">{item.expense_date}</td> <td>{item.category || "—"}</td> <td className="firma-td-num">{money(item.amount)}</td> <td className="firma-td-note">{item.notes || "—"}</td> <td className="firma-row-actions"> <button type="button" className="firma-card-icon-btn" aria-label="Duzenle" onClick={() => openEditTalashExpense(item)} > ✏️ </button> <button type="button" className="firma-card-icon-btn firma-card-icon-btn--danger" aria-label="Sil" onClick={() => handleDeleteTalashExpense(item.id)} > 🗑 </button> </td> </tr> ))} </tbody> </table> </div> )} </FirmaListPanel> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298import { 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 ( <FirmaPageShell badge={period ? formatMonthLabel(talashDashboardMonth) : "Talaş"} title="Talaş finansal durum" subtitle="Satis, tahsilat, tedarik maliyeti ve giderler — donem kar/zarar ozeti." action={ <div className="firma-hero-action-row no-print"> <button type="button" className="secondary" onClick={() => setActivePage("talash-cost-entry")}> Maliyet / gider </button> <button type="button" className="firma-hero-btn" onClick={() => setActivePage("talash-sales")}> Satis listesi </button> </div> } heroExtra={heroStats.length > 0 ? <FirmaStatTiles items={heroStats} /> : null} > <section className="card panel talash-dash-filters no-print"> <div className="talash-dash-filter-row"> <div className="field"> <label>Donem (ay)</label> <input type="month" value={talashDashboardMonth} onChange={(e) => setTalashDashboardMonth(e.target.value)} /> </div> <div className="field"> <label>Firma filtresi</label> <CompanySelect companies={companies} value={talashDashboardCompanyId} onChange={applyTalashDashboardFilter} allowAll /> </div> </div> </section>
{talashDashboardLoading && !dash ? ( <div className="firma-empty-state"> <strong>Yukleniyor</strong> Finansal ozet hazirlaniyor… </div> ) : null}
{dash && period ? ( <> <div className="talash-dash-kpi-grid"> <article className="talash-dash-kpi"> <span>Donem satis tutari</span> <strong>{money(period.sales_amount)}</strong> <small> {period.sale_count} kayit · {period.total_bags} cuval </small> </article> <article className="talash-dash-kpi talash-dash-kpi--cash"> <span>Bu ay tahsil edilen</span> <strong>{money(period.collected_cash_amount)}</strong> <small>Tahsilat tarihi bu ay olan odemeler</small> </article> <article className="talash-dash-kpi"> <span>Donem satislarindan bekleyen</span> <strong>{money(period.pending_on_sales)}</strong> <small>Secilen ay satislarinda henuz tahsil edilmemis</small> </article> <article className="talash-dash-kpi talash-dash-kpi--warn"> <span>Toplam acik alacak</span> <strong>{money(open?.amount ?? 0)}</strong> <small> {open?.sale_count ?? 0} satir · tum donemler </small> </article> </div>
{profit ? ( <section className="card panel talash-dash-profit-panel no-print"> <header className="talash-dash-panel-head"> <h3>Donem kar / zarar</h3> <p> Satis tutari uzerinden cuval tedarik maliyeti ve kayitli giderler dusulur. {talashDashboardCompanyId ? " Firma filtresi yalnizca satislara uygulanir; giderler tum isletme icindir." : null} </p> </header> <div className="talash-dash-kpi-grid talash-dash-kpi-grid--profit"> <article className="talash-dash-kpi"> <span>Ciro (satis)</span> <strong>{money(profit.sales_revenue)}</strong> </article> <article className="talash-dash-kpi talash-dash-kpi--cost"> <span>Tedarik maliyeti</span> <strong>{money(profit.procurement_cost)}</strong> <small>Cuval basi tarifeye gore</small> </article> <article className="talash-dash-kpi"> <span>Brut kar</span> <strong>{money(profit.gross_profit)}</strong> <small>Ciro − tedarik</small> </article> <article className="talash-dash-kpi talash-dash-kpi--cost"> <span>Diger giderler</span> <strong>{money(profit.operating_expenses)}</strong> <small>Secilen ay</small> </article> <article className={`talash-dash-kpi ${ (profit.net_profit ?? 0) >= 0 ? "talash-dash-kpi--profit" : "talash-dash-kpi--loss" }`} > <span>Net kar / zarar</span> <strong>{money(profit.net_profit)}</strong> <small> Marj {pct(profit.margin_rate)} {profit.missing_cost_sale_count > 0 ? ` · ${profit.missing_cost_sale_count} satista maliyet tarifesi yok` : null} </small> </article> </div> </section> ) : null}
<div className="talash-dash-panels"> <article className="card panel talash-dash-chart-panel"> <header className="talash-dash-panel-head"> <h3>Son 6 ay trendi</h3> <p>Satis (donem) ve tahsilat (nakit girisi) karsilastirmasi</p> </header> <div className="talash-dash-bar-chart" role="img" aria-label="Aylik satis ve tahsilat"> {series.map((row) => ( <div className="talash-dash-bar-group" key={row.month}> <div className="talash-dash-bars"> <div className="talash-dash-bar talash-dash-bar--sales" style={{ height: `${((row.sales_amount || 0) / maxBar) * 100}%` }} title={`Satis: ${money(row.sales_amount)}`} /> <div className="talash-dash-bar talash-dash-bar--collected" style={{ height: `${((row.collected_amount || 0) / maxBar) * 100}%` }} title={`Tahsilat: ${money(row.collected_amount)}`} /> </div> <span className="talash-dash-bar-label">{monthShort(row.month)}</span> </div> ))} </div> <div className="talash-dash-legend"> <span> <i className="talash-dash-dot talash-dash-dot--sales" /> Satis </span> <span> <i className="talash-dash-dot talash-dash-dot--collected" /> Tahsilat </span> </div> </article>
<article className="card panel talash-dash-open-panel"> <header className="talash-dash-panel-head"> <h3>Acik alacak (firma)</h3> <p>Tahsil edilmemis toplam tutarlar</p> </header> {(dash.open_by_company || []).length === 0 ? ( <p className="talash-dash-muted">Bekleyen alacak yok.</p> ) : ( <ul className="talash-dash-open-list"> {dash.open_by_company.map((row) => ( <li key={row.company_id}> <button type="button" className="talash-dash-open-row" onClick={() => openCompanyTalashSales(row.company_id)} > <span>{row.company_name}</span> <strong>{money(row.open_amount)}</strong> </button> </li> ))} </ul> )} </article> </div>
<FirmaListPanel plain> <header className="talash-dash-panel-head talash-dash-table-head"> <h3>{formatMonthLabel(talashDashboardMonth)} — firma kirilimi</h3> <p>Secilen aydaki satis ve tahsilat durumu</p> </header> {(dash.by_company || []).length === 0 ? ( <div className="firma-empty-state"> <strong>Kayit yok</strong> Bu donemde satis bulunamadi. </div> ) : ( <div className="firma-table-wrap"> <table className="expense-table firma-data-table talash-dash-company-table"> <thead> <tr> <th>Firma</th> <th className="firma-th-num">Cuval</th> <th className="firma-th-num">Satis</th> <th className="firma-th-num">Tahsil</th> <th className="firma-th-num">Bekleyen</th> <th>Tahsil orani</th> </tr> </thead> <tbody> {dash.by_company.map((row) => ( <tr key={row.company_id}> <td className="firma-td-name"> <button type="button" className="talash-dash-link" onClick={() => openCompanyTalashSales(row.company_id)} > {row.company_name} </button> </td> <td className="firma-td-num">{row.total_bags}</td> <td className="firma-td-num">{money(row.sales_amount)}</td> <td className="firma-td-num">{money(row.collected_amount)}</td> <td className="firma-td-num">{money(row.pending_amount)}</td> <td> <div className="talash-dash-rate"> <div className="talash-dash-rate-bar" style={{ width: `${Math.min(100, row.collection_rate || 0)}%` }} /> <span>{pct(row.collection_rate)}</span> </div> </td> </tr> ))} </tbody> </table> </div> )} </FirmaListPanel> </> ) : null} </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { 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 ( <FirmaPageShell badge="Cuval tarifesi" title="Talas fiyat girisi" subtitle="Secilen firmaya ozel cuval birim fiyatini ve gecerlilik baslangic tarihini kaydedin." > <FirmaEntryLayout tips={TIPS} tipsTitle="Kisa rehber"> <h3 className="firma-form-panel-title">Yeni fiyat tarifesi</h3> <form className="firma-form-grid expense-form-grid" onSubmit={handleCreateTalashPrice}> <div className="field field-full"> <label>Firma</label> <CompanySelect companies={companies} value={talashPriceForm.company_id} onChange={(v) => setTalashPriceForm((s) => ({ ...s, company_id: v }))} required /> </div>
<p className="firma-form-section-kicker field-full">Tarife detayi</p>
<div className="firma-form-grid-2 field-full"> <div className="field"> <label>Gecerlilik baslangici</label> <input type="date" value={talashPriceForm.effective_date} onChange={(e) => setTalashPriceForm((s) => ({ ...s, effective_date: e.target.value })) } required /> </div> <div className="field firma-price-field"> <label>Cuval birim fiyat (TL)</label> <input type="number" step="0.01" min="0.01" placeholder="200.00" value={talashPriceForm.unit_price} onChange={(e) => setTalashPriceForm((s) => ({ ...s, unit_price: e.target.value })) } required /> </div> </div>
<div className="field field-full"> <label>Not</label> <input value={talashPriceForm.notes} onChange={(e) => setTalashPriceForm((s) => ({ ...s, notes: e.target.value }))} placeholder="Istege bagli aciklama" /> </div>
<div className="firma-form-actions field-full"> <button type="submit" className="firma-submit-btn"> Fiyati kaydet </button> </div> </form> </FirmaEntryLayout> </FirmaPageShell> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import { 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 ( <FirmaPageShell badge={badgeLabel} title="Talas fiyat listesi" subtitle="Firmalara tanimli cuval birim fiyat gecmisini inceleyin ve duzenleyin." action={ <button type="button" className="firma-hero-btn" onClick={() => setActivePage("talash-price-entry")}> + Yeni fiyat </button> } > <FirmaListPanel filter={ <FirmaCompanyFilter companies={companies} value={talashFilterCompanyId} onChange={(v) => applyTalashCompanyFilter(v)} label="Listeyi firmaya gore filtrele" /> } > {talashPrices.length === 0 ? ( <div className="firma-empty-state"> <strong>Fiyat kaydi yok</strong> Ustteki "Yeni fiyat" ile tarife ekleyin veya filtreyi temizleyin. </div> ) : ( <div className="firma-table-wrap table-wrap expense-table-wrap"> <table className="expense-table firma-data-table firma-prices-table"> <thead> <tr> <th>Firma</th> <th>Gecerlilik</th> <th className="firma-th-num">Cuval fiyat</th> <th>Not</th> <th scope="col" className="firma-th-actions"> Islem </th> </tr> </thead> <tbody> {talashPrices.map((item) => ( <tr key={item.id}> <td className="firma-td-name">{item.company_name}</td> <td className="firma-td-date">{item.effective_date}</td> <td className="firma-td-num firma-td-price">{money(item.unit_price)}</td> <td className="firma-td-note">{item.notes || "—"}</td> <td className="firma-row-actions"> <button type="button" className="firma-card-icon-btn" aria-label="Duzenle" onClick={() => openEditTalashPrice(item)} > ✏️ </button> <button type="button" className="firma-card-icon-btn firma-card-icon-btn--danger" aria-label="Sil" onClick={() => handleDeleteTalashPrice(item.id)} > 🗑 </button> </td> </tr> ))} </tbody> </table> </div> )} </FirmaListPanel> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import { 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 ( <FirmaPageShell badge="Cuval satisi" title="Talas satis girisi" subtitle="Firmaya cuval talas satisi kaydedin. Toplam, cuval adedi ile birim fiyatin carpimidir." > <FirmaEntryLayout tips={TIPS} tipsTitle="Kisa rehber"> <h3 className="firma-form-panel-title">Satis kaydi</h3> <form className="firma-form-grid expense-form-grid" onSubmit={handleCreateTalashSale}> <div className="field field-full"> <label>Firma</label> <CompanySelect companies={companies} value={talashSaleForm.company_id} onChange={(v) => setTalashSaleForm((s) => ({ ...s, company_id: v }))} required /> </div>
<p className="firma-form-section-kicker field-full">Satis detayi</p>
<div className="firma-form-grid-2 field-full"> <div className="field"> <label>Satis tarihi</label> <input type="date" value={talashSaleForm.sale_date} onChange={(e) => setTalashSaleForm((s) => ({ ...s, sale_date: e.target.value })) } required /> </div> <div className="field firma-bag-field"> <label>Cuval adedi</label> <input type="number" step="1" min="1" placeholder="1" value={talashSaleForm.bag_count} onChange={(e) => setTalashSaleForm((s) => ({ ...s, bag_count: e.target.value })) } required /> </div> </div>
<div className="firma-sale-price-row field-full"> <div className="field firma-price-field"> <label>Birim fiyat (TL / cuval)</label> <input type="number" step="0.01" min="0.01" placeholder="0.00" value={talashSaleForm.unit_price} onChange={(e) => setTalashSaleForm((s) => ({ ...s, unit_price: e.target.value })) } required /> {talashQuoteHint ? <p className="talash-quote-hint">{talashQuoteHint}</p> : null} </div> <div className={`talash-total-box ${totalPreview ? "talash-total-box--ready" : "talash-total-box--idle"}`} aria-live="polite" > <span className="talash-total-box-label">Toplam tutar</span> <strong className="talash-total-box-value"> {totalPreview || "—"} </strong> {!totalPreview ? ( <span className="talash-total-box-hint">Cuval ve fiyat girin</span> ) : null} </div> </div>
<div className="field field-full"> <label>Not</label> <input value={talashSaleForm.notes} onChange={(e) => setTalashSaleForm((s) => ({ ...s, notes: e.target.value }))} placeholder="Istege bagli" /> </div>
<div className="firma-form-actions field-full"> <button type="submit" className="firma-submit-btn"> Satisi kaydet </button> </div> </form> </FirmaEntryLayout> </FirmaPageShell> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import { 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 <span className={`firma-collection-badge ${className}`}>{label}</span>;}
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 ( <FirmaPageShell badge={badgeLabel} title="Talas satis listesi" subtitle="Kismi tahsilat desteklenir: ornegin 4000 TL satisin 3000 TL odendi, 1000 TL kalir." action={ <div className="firma-hero-action-row no-print"> <button type="button" className="secondary" onClick={() => openTalashCollectionSlip(talashFilterCompanyId)} > Tahsilat irsaliyesi </button> <button type="button" className="firma-hero-btn" onClick={() => setActivePage("talash-sale-entry")}> + Yeni satis </button> </div> } heroExtra={heroStats.length > 0 ? <FirmaStatTiles items={heroStats} /> : null} > <FirmaListPanel filter={ <div className="firma-sales-filters"> <FirmaCompanyFilter companies={companies} value={talashFilterCompanyId} onChange={(v) => applyTalashCompanyFilter(v)} label="Firmaya gore" /> <div className="field"> <label>Tahsilat durumu</label> <select value={talashCollectionFilter} onChange={(e) => applyTalashCollectionFilter(e.target.value)} > <option value="">Tumu</option> <option value="pending">Acik bakiye</option> <option value="partial">Kismi odendi</option> <option value="collected">Tam kapandi</option> </select> </div> </div> } > {talashSales.length === 0 ? ( <div className="firma-empty-state"> <strong>Satis kaydi yok</strong> Filtreyi degistirin veya yeni satis ekleyin. </div> ) : ( <div className="firma-table-wrap table-wrap expense-table-wrap"> <table className="expense-table firma-data-table firma-sales-table firma-sales-table--collection"> <thead> <tr> <th>Tarih</th> <th>Firma</th> <th className="firma-th-num">Cuval</th> <th className="firma-th-num">Toplam</th> <th className="firma-th-num">Tahsil</th> <th className="firma-th-num">Kalan</th> <th>Durum</th> <th>Not</th> <th scope="col" className="firma-th-actions"> Islem </th> </tr> </thead> <tbody> {talashSales.map((item) => { const remaining = item.remaining_amount ?? item.total_amount; const hasOpen = remaining > 0.005; return ( <tr key={item.id}> <td className="firma-td-date">{item.sale_date}</td> <td className="firma-td-name">{item.company_name}</td> <td className="firma-td-num">{item.bag_count}</td> <td className="firma-td-num firma-td-price">{money(item.total_amount)}</td> <td className="firma-td-num">{money(item.collected_amount ?? 0)}</td> <td className="firma-td-num">{money(remaining)}</td> <td className="firma-td-collection"> <CollectionBadge status={item.collection_status} /> </td> <td className="firma-td-note">{item.notes || "—"}</td> <td className="firma-row-actions"> {hasOpen ? ( <button type="button" className="secondary firma-collection-toggle" onClick={() => setPaymentSale(item)} > Tahsilat </button> ) : ( <button type="button" className="secondary firma-collection-toggle" onClick={() => resetTalashSaleCollection(item.id)} > Sifirla </button> )} <button type="button" className="firma-card-icon-btn" aria-label="Duzenle" onClick={() => openEditTalashSale(item)} > ✏️ </button> <button type="button" className="firma-card-icon-btn firma-card-icon-btn--danger" aria-label="Sil" onClick={() => handleDeleteTalashSale(item.id)} > 🗑 </button> </td> </tr> ); })} </tbody> </table> </div> )} </FirmaListPanel> {openRemaining > 0 && talashFilterCompanyId ? ( <p className="firma-slip-hint no-print"> Secili firma icin {money(openRemaining)} alacak var.{" "} <button type="button" className="firma-link-btn" onClick={() => openTalashCollectionSlip(talashFilterCompanyId)} > Irsaliye olustur </button> </p> ) : null}
<TalashPaymentModal open={Boolean(paymentSale)} title="Tahsilat kaydi" subtitle={ paymentSale ? `${paymentSale.company_name} · kalan ${money(paymentSale.remaining_amount ?? paymentSale.total_amount)}` : "" } defaultAmount={paymentSale?.remaining_amount ?? paymentSale?.total_amount} maxAmount={paymentSale?.remaining_amount ?? paymentSale?.total_amount} onClose={() => setPaymentSale(null)} onSubmit={async (amount) => { if (!paymentSale) return; await addTalashSalePayment(paymentSale.id, amount); setPaymentSale(null); }} /> </FirmaPageShell> );}12345678910111213141516171819202122232425262728293031323334353637383940414243/** * 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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import { 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, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711import { 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, };}16 unmodified lines17181920212223242 unmodified lines2728293031323314 unmodified lines484950515253545556575859606162636465663 unmodified lines70717273747576777813 unmodified lines92939495969798991005 unmodified lines10610710810911011111211311411532 unmodified lines14814915015115215315415515615715815926 unmodified lines18618718818919019119219389 unmodified lines2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313328 unmodified lines34134234334434534634728 unmodified lines37637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541616 unmodified linesimport { 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() {2 unmodified linesconst report = useReportSlice();const ordersList = useOrdersListSlice();const refreshAllRef = useRef(() => Promise.resolve());const talashCompanyCleanupRef = useRef(() => {});const refreshAllFn = () => refreshAllRef.current();14 unmodified linessetActivePage: 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([3 unmodified linesproductCosts.loadProductCosts(),lumber.loadLumberRules(),lumber.loadLumberTransactions(),companies.loadCompanies(),talash.loadTalashAll(),talash.loadTalashDashboard(),report.loadReport(report.reportPeriod, report.reportRefDate),]);} catch (err) {13 unmodified linesproductCosts.loadProductCosts,lumber.loadLumberRules,lumber.loadLumberTransactions,companies.loadCompanies,talash.loadTalashAll,talash.loadTalashDashboard,report.loadReport,report.reportPeriod,report.reportRefDate,5 unmodified linesrefreshAllRef.current = refreshAll;}, [refreshAll]);useEffect(() => {talashCompanyCleanupRef.current = (id) => talash.clearReferencesToCompany(id);}, [talash.clearReferencesToCompany]);const orderForms = useOrderFormsSlice({setError: auth.setError,setActivePage: auth.setActivePage,32 unmodified lines// 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("");26 unmodified linesproductCosts.resetProductCosts();report.resetReport();lumber.resetLumber();companies.resetCompanies();talash.resetTalash();orderForms.resetOrderForms();} catch (err) {auth.setError(err.message);89 unmodified linesreportViz,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,8 unmodified linesloadProductCosts: productCosts.loadProductCosts,loadLumberRules: lumber.loadLumberRules,loadLumberTransactions: lumber.loadLumberTransactions,loadCompanies: companies.loadCompanies,loadReport: report.loadReport,refreshAll,handleLogin,28 unmodified linesopenEditProductCost: 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,};16 unmodified lines1718192021222 unmodified lines25262728293014 unmodified lines4546474849503 unmodified lines54555657585913 unmodified lines7374757677785 unmodified lines84858687888932 unmodified lines12212312412512612726 unmodified lines15415515615715815989 unmodified lines2492502512522532548 unmodified lines26326426526626726828 unmodified lines29729829930030130216 unmodified linesimport { useExpensesSlice } from "./slices/useExpensesSlice.js";import { useOrdersListSlice } from "./slices/useOrdersListSlice.js";import { useLumberSlice } from "./slices/useLumberSlice.js";import { useOrderFormsSlice } from "./slices/useOrderFormsSlice.js";export function useAppController() {2 unmodified linesconst report = useReportSlice();const ordersList = useOrdersListSlice();const refreshAllRef = useRef(() => Promise.resolve());const refreshAllFn = () => refreshAllRef.current();14 unmodified linessetActivePage: auth.setActivePage,});const refreshAll = useCallback(async () => {try {await Promise.all([3 unmodified linesproductCosts.loadProductCosts(),lumber.loadLumberRules(),lumber.loadLumberTransactions(),report.loadReport(report.reportPeriod, report.reportRefDate),]);} catch (err) {13 unmodified linesproductCosts.loadProductCosts,lumber.loadLumberRules,lumber.loadLumberTransactions,report.loadReport,report.reportPeriod,report.reportRefDate,5 unmodified linesrefreshAllRef.current = refreshAll;}, [refreshAll]);const orderForms = useOrderFormsSlice({setError: auth.setError,setActivePage: auth.setActivePage,32 unmodified lines// eslint-disable-next-line react-hooks/exhaustive-deps -- yalnizca loadProductCosts}, [auth.activePage, auth.user, productCosts.loadProductCosts]);async function handleLogin(event) {event.preventDefault();auth.setError("");26 unmodified linesproductCosts.resetProductCosts();report.resetReport();lumber.resetLumber();orderForms.resetOrderForms();} catch (err) {auth.setError(err.message);89 unmodified linesreportViz,dashboardViz,lumberViz,loadDashboard: dashboard.loadDashboard,loadOrders: ordersList.loadOrders,handleOrdersDateModeChange: ordersList.handleOrdersDateModeChange,8 unmodified linesloadProductCosts: productCosts.loadProductCosts,loadLumberRules: lumber.loadLumberRules,loadLumberTransactions: lumber.loadLumberTransactions,loadReport: report.loadReport,refreshAll,handleLogin,28 unmodified linesopenEditProductCost: productCosts.openEditProductCost,closeEditProductCost: productCosts.closeEditProductCost,handleUpdateProductCost: productCosts.handleUpdateProductCost,handleReportPeriodChange,handleReportDateChange,};
12345678910import { CompanySelect } from "../../components/CompanySelect.jsx";
export function FirmaCompanyFilter({ companies, value, onChange, label = "Firma filtresi" }) { return ( <div className="field"> <label>{label}</label> <CompanySelect companies={companies} value={value} onChange={onChange} allowAll /> </div> );}123456789101112131415161718/** Giris sayfalari: sol ipucu paneli + sag form. */export function FirmaEntryLayout({ tipsTitle = "Kisa rehber", tips, children }) { return ( <div className="firma-entry-grid"> {tips && tips.length > 0 ? ( <aside className="card panel firma-tips-panel"> <h4>{tipsTitle}</h4> <ol className="firma-tips-list"> {tips.map((tip) => ( <li key={tip}>{tip}</li> ))} </ol> </aside> ) : null} <div className="card panel firma-form-panel">{children}</div> </div> );}123456789101112131415/** Liste sayfalari: filtre + istatistik + tablo/kart alani. */export function FirmaListPanel({ filter, stats, plain = false, children }) { const showBar = !plain && (filter || stats); return ( <section className={`card panel firma-list-panel ${plain ? "firma-list-panel--plain" : ""}`}> {showBar ? ( <div className="firma-list-panel-bar"> {filter ? <div className="firma-list-panel-filter">{filter}</div> : null} {stats ? <div className="firma-list-panel-stats">{stats}</div> : null} </div> ) : null} <div className="firma-list-panel-content">{children}</div> </section> );}123456789101112131415161718192021/** Firmalar modulu — ust hero + govde (dashboard benzeri). */export function FirmaPageShell({ badge, title, subtitle, action, heroExtra, children }) { return ( <div className="firma-screen"> <section className="card panel firma-hero"> <div className="firma-hero-top"> <div className="firma-hero-text"> <h2>{title}</h2> {subtitle ? <p>{subtitle}</p> : null} </div> <div className="firma-hero-meta"> {badge ? <span className="firma-hero-badge">{badge}</span> : null} {action ? <div className="firma-hero-action">{action}</div> : null} </div> </div> {heroExtra ? <div className="firma-hero-extra">{heroExtra}</div> : null} </section> <div className="firma-screen-body">{children}</div> </div> );}1234567891011121314/** Kucuk ozet kutucuklari. */export function FirmaStatTiles({ items }) { if (!items || items.length === 0) return null; return ( <div className="firma-stat-tiles"> {items.map(({ label, value }) => ( <div key={label} className="firma-stat-tile"> <span className="firma-stat-tile-label">{label}</span> <strong className="firma-stat-tile-value">{value}</strong> </div> ))} </div> );}123456/** 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;}38 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888938 unmodified lines};}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",38 unmodified lines39404142434438 unmodified lines};}export function createLumberForm() {return {lumber_kind: "serit",
123456789106 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import {isCatalogNavKey,SIDEBAR_ECOMMERCE_KICKER,SIDEBAR_FIRMA_NAV,SIDEBAR_LUMBER_NAV,SIDEBAR_MAIN_NAV,SIDEBAR_TALASH_KICKER,} from "../../constants/nav.js";/**6 unmodified lines<aside className="sidebar"><h2>Finans Panel</h2><p>{user.username}</p><nav className="sidebar-nav"><div className="sidebar-nav-section"><div className="sidebar-kereste-kicker sidebar-ecommerce-kicker">{SIDEBAR_ECOMMERCE_KICKER}</div>{SIDEBAR_MAIN_NAV.map(([key, label]) => (<buttonkey={key}type="button"className={`nav-btn nav-btn-ecommerce ${isCatalogNavKey(key) ? "nav-btn-catalog" : ""} ${activePage === key ? "active" : ""}`}onClick={() => onSelectPage(key)}>{label}</button>))}</div><hr className="sidebar-kereste-divider" /><div className="sidebar-nav-section"><div className="sidebar-kereste-kicker sidebar-talas-kicker">{SIDEBAR_TALASH_KICKER}</div>{SIDEBAR_FIRMA_NAV.map(([key, label]) => (<buttonkey={key}type="button"className={`nav-btn nav-btn-firma ${activePage === key ? "active" : ""}`}onClick={() => onSelectPage(key)}>{label}</button>))}</div><hr className="sidebar-kereste-divider" /><div className="sidebar-nav-section"><div className="sidebar-kereste-kicker sidebar-lumber-kicker">Kereste</div>{SIDEBAR_LUMBER_NAV.map(([key, label]) => (<buttonkey={key}type="button"className={`nav-btn nav-btn-kereste ${activePage === key ? "active" : ""}`}onClick={() => onSelectPage(key)}>{label}</button>))}</div></nav><button className="secondary full logout-btn" type="button" onClick={onLogout}>Cikis Yap12345676 unmodified lines14151617181920212223242526272829303132333435363738394041424344import {isCatalogNavKey,SIDEBAR_LUMBER_NAV,SIDEBAR_MAIN_NAV,} from "../../constants/nav.js";/**6 unmodified lines<aside className="sidebar"><h2>Finans Panel</h2><p>{user.username}</p><nav>{SIDEBAR_MAIN_NAV.map(([key, label]) => (<buttonkey={key}type="button"className={`nav-btn ${isCatalogNavKey(key) ? "nav-btn-catalog" : ""} ${activePage === key ? "active" : ""}`}onClick={() => onSelectPage(key)}>{label}</button>))}<hr className="sidebar-kereste-divider" /><div className="sidebar-kereste-kicker">Kereste</div>{SIDEBAR_LUMBER_NAV.map(([key, label]) => (<buttonkey={key}type="button"className={`nav-btn nav-btn-kereste ${activePage === key ? "active" : ""}`}onClick={() => onSelectPage(key)}>{label}</button>))}</nav><button className="secondary full logout-btn" type="button" onClick={onLogout}>Cikis Yap
17 unmodified lines18192021222324252627282930313233343536373839404142434417 unmodified linesexport function currentMonthValue() {return new Date().toISOString().slice(0, 7);}const TR_MONTH_NAMES = ["Ocak","Subat","Mart","Nisan","Mayis","Haziran","Temmuz","Agustos","Eylul","Ekim","Kasim","Aralik",];/** YYYY-MM → "Eylul 2026" */export function formatMonthLabel(monthValue) {if (!monthValue || typeof monthValue !== "string") return "";const [y, m] = monthValue.split("-");const idx = Number(m) - 1;if (!y || idx < 0 || idx > 11) return monthValue;return `${TR_MONTH_NAMES[idx]} ${y}`;}17 unmodified lines18192017 unmodified linesexport function currentMonthValue() {return new Date().toISOString().slice(0, 7);}
4 unmodified lines5678910111213144 unmodified lines*/@import "./partials/01-base-shell-lumber.css";@import "./partials/02-product-orders-forms.css";@import "./partials/01-base-shell-lumber/03-firma-global-overrides.css";@import "./partials/03-orders-table-layout.css";@import "./partials/04-theme-report-charts.css";@import "./partials/05-dashboard-marketplace-modals.css";/* Irsaliye onizlemesi .card temasindan sonra yuklenmeli (beyaz belge + koyu yazi) */@import "./partials/01-base-shell-lumber/04-talash-collection-slip.css";@import "./partials/01-base-shell-lumber/05-talash-dashboard.css";4 unmodified lines56789104 unmodified lines*/@import "./partials/01-base-shell-lumber.css";@import "./partials/02-product-orders-forms.css";@import "./partials/03-orders-table-layout.css";@import "./partials/04-theme-report-charts.css";@import "./partials/05-dashboard-marketplace-modals.css";
1 unmodified line234567891 unmodified line* 01 — :root, body, giris, sidebar, kereste (parcalar ayni sira ile yuklenir).*/@import "./01-base-shell-lumber/01-root-shell-kereste-rules.css";@import "./01-base-shell-lumber/02-firma-module-pages.css";@import "./01-base-shell-lumber/02-lumber-inputs-list-table.css";@import "./01-base-shell-lumber/03-lumber-charts-ring-responsive.css";@import "./01-base-shell-lumber/04-talash-collection-slip.css";@import "./01-base-shell-lumber/05-talash-dashboard.css";1 unmodified line234561 unmodified line* 01 — :root, body, giris, sidebar, kereste (parcalar ayni sira ile yuklenir).*/@import "./01-base-shell-lumber/01-root-shell-kereste-rules.css";@import "./01-base-shell-lumber/02-lumber-inputs-list-table.css";@import "./01-base-shell-lumber/03-lumber-charts-ring-responsive.css";
app/api/router.py-4
app/api/routes/companies.pyDeleted-234
app/api/routes/talash.pyDeleted-882
app/infrastructure/database.py-151
app/main.py+3-127
app/schemas/__init__.py-18
app/schemas/companies.pyDeleted-12
app/schemas/talash.pyDeleted-55
app/services/talash_collection.pyDeleted-168
app/services/talash_costs.pyDeleted-84
app/services/talash_dashboard.pyDeleted-261
app/services/talash_pricing.pyDeleted-35
app/services/talash_slip_pdf.pyDeleted-189
app/static_assets.pyDeleted-42
frontend/index.html-1
frontend/src/components/CompanySelect.jsxDeleted-48
frontend/src/constants/nav.js-22
frontend/src/features/app/ActivePageSwitch.jsx-128
frontend/src/features/app/AppModals.jsx-42
frontend/src/features/app/modals/CompanyEditModal.jsxDeleted-69
frontend/src/features/app/modals/TalashExpenseEditModal.jsxDeleted-87
frontend/src/features/app/modals/TalashPaymentModal.jsxDeleted-69
frontend/src/features/app/modals/TalashPriceEditModal.jsxDeleted-86
frontend/src/features/app/modals/TalashSaleEditModal.jsxDeleted-99
frontend/src/features/app/modals/TalashUnitCostEditModal.jsxDeleted-70
frontend/src/features/app/pages/CompaniesListPage.jsxDeleted-146
frontend/src/features/app/pages/CompanyEntryPage.jsxDeleted-67
frontend/src/features/app/pages/TalashCollectionSlipPage.jsxDeleted-237
frontend/src/features/app/pages/TalashCostEntryPage.jsxDeleted-139
frontend/src/features/app/pages/TalashCostsListPage.jsxDeleted-144
frontend/src/features/app/pages/TalashDashboardPage.jsxDeleted-298
frontend/src/features/app/pages/TalashPriceEntryPage.jsxDeleted-84
frontend/src/features/app/pages/TalashPricesListPage.jsxDeleted-92
frontend/src/features/app/pages/TalashSaleEntryPage.jsxDeleted-133
frontend/src/features/app/pages/TalashSalesListPage.jsxDeleted-212
frontend/src/features/app/printTalashSlip.jsDeleted-43
frontend/src/features/app/slices/useCompaniesSlice.jsDeleted-128
frontend/src/features/app/slices/useTalashSlice.jsDeleted-711
frontend/src/features/app/useAppController.js-114
frontend/src/features/firma/FirmaCompanyFilter.jsxDeleted-10
frontend/src/features/firma/FirmaEntryLayout.jsxDeleted-18
frontend/src/features/firma/FirmaListPanel.jsxDeleted-15
frontend/src/features/firma/FirmaPageShell.jsxDeleted-21
frontend/src/features/firma/FirmaStatTiles.jsxDeleted-14
frontend/src/features/firma/companyActive.jsDeleted-6
frontend/src/features/forms/defaults.js-45
frontend/src/features/layout/AppShell.jsx+24-46
frontend/src/lib/format.js-24
frontend/src/styles/app.css-4
frontend/src/styles/partials/01-base-shell-lumber.css-3