""" SQLite bağlantısı, şema oluşturma ve başlangıç seed işlemleri. Uygulama katmanı doğrudan `get_db()` kullanır; bağlantı yönetimi ileride bir connection pool ile değiştirilebilir — bu yüzden erişim tek yerden yapılır. """ from __future__ import annotations import sqlite3 from app.core.config import DATA_DIR, DB_PATH from app.security.password import pwd_context def get_db(): """SQLite bağlantısını `Row` erişimiyle (dict-benzeri) döndürür.""" conn = sqlite3.connect(DB_PATH, check_same_thread=False) conn.row_factory = sqlite3.Row return conn def init_db(): """Tüm tabloları/indeksleri hazırlar ve varsayılan kullanıcıyı seed eder.""" DATA_DIR.mkdir(parents=True, exist_ok=True) conn = get_db() cur = conn.cursor() cur.execute( """ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL ) """ ) _ensure_users_schema(cur) cur.execute( """ CREATE TABLE IF NOT EXISTS orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, order_date TEXT NOT NULL, order_no TEXT NOT NULL DEFAULT '', platform TEXT NOT NULL DEFAULT '', store_name TEXT NOT NULL DEFAULT '', product_name TEXT NOT NULL DEFAULT '', unit_sale_price REAL NOT NULL DEFAULT 0, unit_cost REAL NOT NULL DEFAULT 0, order_total REAL NOT NULL DEFAULT 0, commission REAL NOT NULL DEFAULT 0, discount REAL NOT NULL DEFAULT 0, shipping_cost REAL NOT NULL DEFAULT 0, return_shipping_cost REAL NOT NULL DEFAULT 0, penalty REAL NOT NULL DEFAULT 0, cancellation_amount REAL NOT NULL DEFAULT 0, refund_amount REAL NOT NULL DEFAULT 0, other_fees REAL NOT NULL DEFAULT 0, net_platform_amount REAL, international_return_fee REAL NOT NULL DEFAULT 0, international_service_fee REAL NOT NULL DEFAULT 0, platform_service_fee REAL NOT NULL DEFAULT 0, quantity INTEGER NOT NULL DEFAULT 1, notes TEXT DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ) """ ) _ensure_orders_schema(cur) cur.execute( """ CREATE TABLE IF NOT EXISTS fixed_expenses ( id INTEGER PRIMARY KEY AUTOINCREMENT, expense_month TEXT NOT NULL, expense_date TEXT, category TEXT NOT NULL, amount REAL NOT NULL, template_id INTEGER, notes TEXT DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(template_id) REFERENCES expense_templates(id) ) """ ) cur.execute( """ CREATE TABLE IF NOT EXISTS expense_templates ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, default_amount REAL NOT NULL, is_active INTEGER NOT NULL DEFAULT 1, notes TEXT DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ) """ ) _ensure_expenses_schema(cur) cur.execute( """ CREATE TABLE IF NOT EXISTS product_costs ( id INTEGER PRIMARY KEY AUTOINCREMENT, product_name TEXT NOT NULL, unit_cost REAL NOT NULL DEFAULT 0, unit_sale_price REAL NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ) """ ) _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( "CREATE INDEX IF NOT EXISTS idx_expenses_expense_month ON fixed_expenses(expense_month)" ) cur.execute( "CREATE INDEX IF NOT EXISTS idx_expenses_expense_date ON fixed_expenses(expense_date)" ) cur.execute( "CREATE INDEX IF NOT EXISTS idx_expenses_template_id ON fixed_expenses(template_id)" ) ensure_lumber_schema(cur) existing_user = cur.execute( "SELECT id FROM users WHERE username = ?", ("nazan_cinaz",), ).fetchone() if not existing_user: cur.execute( "INSERT INTO users (username, password_hash) VALUES (?, ?)", ("nazan_cinaz", pwd_context.hash("523734Nazan")), ) conn.commit() conn.close() def _ensure_orders_schema(cur): columns = { row["name"] for row in cur.execute("PRAGMA table_info(orders)").fetchall() } additions = { "order_no": "TEXT NOT NULL DEFAULT ''", "platform": "TEXT NOT NULL DEFAULT ''", "store_name": "TEXT NOT NULL DEFAULT ''", "unit_sale_price": "REAL NOT NULL DEFAULT 0", "unit_cost": "REAL NOT NULL DEFAULT 0", "penalty": "REAL NOT NULL DEFAULT 0", "order_total": "REAL NOT NULL DEFAULT 0", "discount": "REAL NOT NULL DEFAULT 0", "return_shipping_cost": "REAL NOT NULL DEFAULT 0", "cancellation_amount": "REAL NOT NULL DEFAULT 0", "refund_amount": "REAL NOT NULL DEFAULT 0", "other_fees": "REAL NOT NULL DEFAULT 0", "net_platform_amount": "REAL", "international_return_fee": "REAL NOT NULL DEFAULT 0", "international_service_fee": "REAL NOT NULL DEFAULT 0", "platform_service_fee": "REAL NOT NULL DEFAULT 0", } for name, definition in additions.items(): if name not in columns: cur.execute(f"ALTER TABLE orders ADD COLUMN {name} {definition}") if "unit_cost" in columns: cur.execute("UPDATE orders SET unit_cost = 0 WHERE unit_cost IS NULL") if "unit_sale_price" in columns: cur.execute("UPDATE orders SET unit_sale_price = 0 WHERE unit_sale_price IS NULL") if "sale_price" in columns: cur.execute( "UPDATE orders SET unit_sale_price = sale_price " "WHERE unit_sale_price = 0 AND sale_price IS NOT NULL" ) if "cost" in columns: cur.execute( "UPDATE orders SET unit_cost = cost " "WHERE unit_cost = 0 AND cost IS NOT NULL" ) if "sales_channel" in columns: cur.execute( "UPDATE orders SET platform = sales_channel " "WHERE platform = '' AND sales_channel IS NOT NULL" ) def _ensure_users_schema(cur): columns = { row["name"] for row in cur.execute("PRAGMA table_info(users)").fetchall() } if "password_hash" not in columns: cur.execute("ALTER TABLE users ADD COLUMN password_hash TEXT") if "password" in columns: # Migrate old plain/hash field into the new column when needed. cur.execute( """ UPDATE users SET password_hash = password WHERE (password_hash IS NULL OR password_hash = '') AND password IS NOT NULL """ ) def _ensure_companies_schema(cur): columns = { row["name"] for row in cur.execute("PRAGMA table_info(companies)").fetchall() } if "address" not in columns: cur.execute("ALTER TABLE companies ADD COLUMN address TEXT DEFAULT ''") if "tax_number" not in columns: cur.execute("ALTER TABLE companies ADD COLUMN tax_number TEXT DEFAULT ''") if "is_active" not in columns: cur.execute( "ALTER TABLE companies ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1" ) _rename_legacy_inactive_company_names(cur) def _ensure_talash_sales_schema(cur) -> None: columns = { row["name"] for row in cur.execute("PRAGMA table_info(company_talash_sales)").fetchall() } if "collection_status" not in columns: cur.execute( "ALTER TABLE company_talash_sales " "ADD COLUMN collection_status TEXT NOT NULL DEFAULT 'pending'" ) if "collected_at" not in columns: cur.execute("ALTER TABLE company_talash_sales ADD COLUMN collected_at TEXT") if "collected_amount" not in columns: cur.execute( "ALTER TABLE company_talash_sales " "ADD COLUMN collected_amount REAL NOT NULL DEFAULT 0" ) cur.execute( """ UPDATE company_talash_sales SET collected_amount = total_amount WHERE COALESCE(collection_status, 'pending') = 'collected' """ ) def _rename_legacy_inactive_company_names(cur) -> None: """Pasif firmalar eski isimle duruyorsa adini arsivler (aynı isimle yeni kayit icin).""" rows = cur.execute( """ SELECT id, name FROM companies WHERE COALESCE(is_active, 1) = 0 """ ).fetchall() for row in rows: cid = int(row["id"]) name = row["name"] or "" suffix = f" (pasif #{cid})" if name.endswith(suffix): continue base = " ".join(name.strip().split()) max_base = max(1, 240 - len(suffix)) if len(base) > max_base: base = base[:max_base].rstrip() cur.execute( "UPDATE companies SET name = ? WHERE id = ?", (f"{base}{suffix}", cid), ) def _ensure_product_costs_schema(cur): columns = { row["name"] for row in cur.execute("PRAGMA table_info(product_costs)").fetchall() } if "unit_sale_price" not in columns: cur.execute("ALTER TABLE product_costs ADD COLUMN unit_sale_price REAL NOT NULL DEFAULT 0") def _ensure_expenses_schema(cur): columns = { row["name"] for row in cur.execute("PRAGMA table_info(fixed_expenses)").fetchall() } if "template_id" not in columns: cur.execute("ALTER TABLE fixed_expenses ADD COLUMN template_id INTEGER") if "expense_date" not in columns: cur.execute("ALTER TABLE fixed_expenses ADD COLUMN expense_date TEXT") # Backfill old rows that only had YYYY-MM with day=01. cur.execute( """ UPDATE fixed_expenses SET expense_date = expense_month || '-01' WHERE (expense_date IS NULL OR expense_date = '') AND expense_month IS NOT NULL """ ) def _tier_insert_sql(): return """ INSERT INTO lumber_price_tiers (lumber_kind, sort_order, range_label, amount, lo, hi, lo_exclusive, hi_exclusive) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """ def _rows_serit_yatar_tariff_apr2026(): """Şerit / Yatar varsayilan tablo (tek + 1-3 ... 5-7); vaynik ayri kalir.""" return [ ("serit", 1, "Tek islem", 1000.0, 1.0, 1.0, 0, 0), ("serit", 2, "1 - 3 islem", 1500.0, 2.0, 3.0, 0, 0), ("serit", 3, "3 - 5 islem", 2000.0, 4.0, 5.0, 0, 0), ("serit", 4, "5 - 7 islem", 2500.0, 6.0, 7.0, 0, 0), ("yatar", 1, "1 - 3 arasi", 50.0, 1.0, 3.0, 0, 0), ("yatar", 2, "3 - 5 arasi", 100.0, 3.0, 5.0, 1, 0), ("yatar", 3, "5 - 7 arasi", 150.0, 5.0, 7.0, 1, 0), ] def _rows_vaynik_default(): return [ ("vaynik", 1, "1.5 - 3 arasi", 2000.0, 1.5, 3.0, 0, 0), ("vaynik", 2, "3 - 5 arasi", 1500.0, 3.0, 5.0, 1, 0), ("vaynik", 3, "5 - 10 arasi", 1000.0, 5.0, 10.0, 1, 0), ] def _seed_lumber_price_tiers(cur): count = cur.execute("SELECT COUNT(*) FROM lumber_price_tiers").fetchone()[0] if count > 0: return rows = _rows_serit_yatar_tariff_apr2026() + _rows_vaynik_default() cur.executemany(_tier_insert_sql(), rows) def _migrate_lumber_tariff_apr2026(cur): """Eski serit/yatar satirlarini yeni tarifeye ceker (tek sefer / DB).""" done = cur.execute( "SELECT 1 FROM app_meta WHERE key = ?", ("lumber_tariff_apr2026_v1",) ).fetchone() if done: return cur.execute("DELETE FROM lumber_price_tiers WHERE lumber_kind IN ('serit', 'yatar')") cur.executemany(_tier_insert_sql(), _rows_serit_yatar_tariff_apr2026()) cur.execute( "INSERT INTO app_meta (key, value) VALUES (?, ?)", ("lumber_tariff_apr2026_v1", "1"), ) def ensure_lumber_schema(cur): """ Hugging Face Space vb. ortamlarda onceki DB dosyasinda kereste tablolari hic olusturulmadiyse CREATE IF NOT EXISTS + varsayilan tarife. """ cur.execute( """ CREATE TABLE IF NOT EXISTS lumber_transactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, lumber_kind TEXT NOT NULL, quantity REAL NOT NULL, total_amount REAL NOT NULL, tier_label TEXT NOT NULL DEFAULT '', notes TEXT DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ) """ ) cur.execute( "CREATE INDEX IF NOT EXISTS idx_lumber_transactions_created ON lumber_transactions(created_at)" ) cur.execute( """ CREATE TABLE IF NOT EXISTS lumber_price_tiers ( id INTEGER PRIMARY KEY AUTOINCREMENT, lumber_kind TEXT NOT NULL, sort_order INTEGER NOT NULL DEFAULT 0, range_label TEXT NOT NULL DEFAULT '', amount REAL NOT NULL, lo REAL NOT NULL, hi REAL, lo_exclusive INTEGER NOT NULL DEFAULT 0, hi_exclusive INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ) """ ) cur.execute( "CREATE INDEX IF NOT EXISTS idx_lumber_tiers_kind_order ON lumber_price_tiers(lumber_kind, sort_order)" ) cur.execute( """ CREATE TABLE IF NOT EXISTS app_meta ( key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL ) """ ) _seed_lumber_price_tiers(cur) _migrate_lumber_tariff_apr2026(cur)