mirror of
https://github.com/henry4682/linebot_finance.git
synced 2026-05-16 04:41:52 +00:00
feat: invoice fetch
1. complete invoice fetch 2. remove ddddocr library
This commit is contained in:
@@ -18,9 +18,9 @@ EINVOICE_PASS = os.getenv("EINVOICE_PASS")
|
||||
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
||||
|
||||
# 本地直接連 localhost
|
||||
DATABASE_URL = os.getenv("LOCAL_DATABASE_URL")
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
# DATABASE_URL = os.getenv("LOCAL_DATABASE_URL")
|
||||
# engine = create_engine(DATABASE_URL)
|
||||
# SessionLocal = sessionmaker(bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
class Transaction(Base):
|
||||
@@ -59,9 +59,6 @@ def solve_captcha(img_b64: str) -> str:
|
||||
|
||||
async def login_and_get_token() -> str | None:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 載入登入頁拿 login_challenge
|
||||
browser = await p.chromium.launch(headless=False)
|
||||
page = await browser.new_page()
|
||||
@@ -167,36 +164,52 @@ async def fetch_invoices(token: str, days: int = 7) -> list:
|
||||
json={"token": jwt_token},
|
||||
verify=False
|
||||
)
|
||||
await page.wait_for_timeout(3000)
|
||||
# await page.wait_for_timeout(3000)
|
||||
print(f"Invoice status: {res.status_code}")
|
||||
print(f"Invoice response: {res.text[:300]}")
|
||||
print(f"拿到 {len(res.json().get('invoices', []))} 筆發票")
|
||||
# return res.json().get("content", [])
|
||||
data = res.json()
|
||||
invoice_list = data.get("content", [])
|
||||
print(f"拿到 {len(invoice_list)} 筆發票")
|
||||
|
||||
# 務必取消註解並回傳,否則 main() 會拿到 None 並報錯
|
||||
return invoice_list
|
||||
|
||||
def save_invoices(invoices: list):
|
||||
db = SessionLocal()
|
||||
# db = SessionLocal()
|
||||
saved = 0
|
||||
try:
|
||||
for inv in invoices:
|
||||
existing = db.query(Transaction).filter(
|
||||
Transaction.note == inv["invoiceNumber"]
|
||||
).first()
|
||||
if existing:
|
||||
continue
|
||||
db.add(Transaction(
|
||||
user_id="auto_import",
|
||||
category=inv["sellerName"],
|
||||
amount=inv["totalAmount"],
|
||||
note=inv["invoiceNumber"],
|
||||
created_at=datetime.fromisoformat(
|
||||
inv["invoiceDate"].replace("Z", "+00:00")
|
||||
)
|
||||
))
|
||||
inv_date = inv.get("invoiceDate", "未知日期")
|
||||
seller = inv.get("sellerName", "未知店家")
|
||||
amount = inv.get("totalAmount", 0)
|
||||
inv_num = inv.get("invoiceNumber", "無號碼")
|
||||
# existing = db.query(Transaction).filter(
|
||||
# Transaction.note == inv["invoiceNumber"]
|
||||
# ).first()
|
||||
# if existing:
|
||||
# continue
|
||||
# db.add(Transaction(
|
||||
# user_id="auto_import",
|
||||
# category=inv["sellerName"],
|
||||
# amount=inv["totalAmount"],
|
||||
# note=inv["invoiceNumber"],
|
||||
# created_at=datetime.fromisoformat(
|
||||
# inv["invoiceDate"].replace("Z", "+00:00")
|
||||
# )
|
||||
# ))
|
||||
# 美化輸出格式
|
||||
print(f"新增發票 | 日期: {inv_date[:10]} | 店家: {seller[:15]:<15} | 金額: {amount:>6} | 號碼: {inv_num}")
|
||||
saved += 1
|
||||
db.commit()
|
||||
print(f"✅ 新增 {saved} 筆,略過 {len(invoices) - saved} 筆重複")
|
||||
finally:
|
||||
db.close()
|
||||
# db.commit()
|
||||
print("-" * 30)
|
||||
print(f"✅ 模擬處理完成:預計新增 {saved} 筆,總計來源 {len(invoices)} 筆")
|
||||
except Exception as e:
|
||||
print("❌ 儲存發票失敗:", e)
|
||||
if 'inv' in locals():
|
||||
print(f"錯誤發票內容: {inv}")
|
||||
# db.rollback()
|
||||
# finally:
|
||||
# db.close()
|
||||
|
||||
async def main():
|
||||
print("開始抓取發票...")
|
||||
@@ -204,12 +217,7 @@ async def main():
|
||||
if not token:
|
||||
print("登入失敗")
|
||||
return
|
||||
|
||||
invoices = await fetch_invoices(token)
|
||||
print(f"拿到 {len(invoices)} 筆發票")
|
||||
for inv in invoices:
|
||||
print(f" {inv['invoiceDate'][:10]} {inv['sellerName']} ${inv['totalAmount']}")
|
||||
|
||||
save_invoices(invoices)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user