Antoni09 commited on
Commit
b761316
·
verified ·
1 Parent(s): 4a96377

Upload server.py

Browse files
Files changed (1) hide show
  1. server.py +79 -86
server.py CHANGED
@@ -872,92 +872,85 @@ def api_invoice_detail(invoice_id: str) -> Any:
872
 
873
  @app.route("/api/invoices/summary", methods=["GET"])
874
  def api_invoice_summary() -> Any:
875
- try:
876
- login_key = require_auth()
877
- except PermissionError:
878
- return jsonify({"error": "Brak autoryzacji."}), 401
879
-
880
- now = datetime.utcnow()
881
- last_month_start = now - timedelta(days=30)
882
- quarter_first_month = ((now.month - 1) // 3) * 3 + 1
883
- quarter_start = now.replace(month=quarter_first_month, day=1, hour=0, minute=0, second=0, microsecond=0)
884
- year_start = now.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
885
-
886
- def aggregate_from_rows(rows: List[Dict[str, Any]], start: datetime) -> Dict[str, Any]:
887
- count = 0
888
- gross_total = Decimal("0.00")
889
- for row in rows:
890
- issued_dt = row["issued_at"]
891
- if issued_dt < start:
892
- continue
893
- count += 1
894
- gross_total += Decimal(row["total_gross"])
895
- return {"count": count, "gross_total": str(_quantize(gross_total))}
896
-
897
- if DATABASE_AVAILABLE:
898
- try:
899
- account_row = get_account_row(login_key)
900
- except KeyError:
901
- return jsonify({"error": "Nie znaleziono konta."}), 404
902
- rows = fetch_all(
903
- """
904
- SELECT issued_at, total_gross
905
- FROM invoices
906
- WHERE account_id = %s
907
- """,
908
- (account_row["id"],),
909
- )
910
- # rows zwraca datetime, ale upewniamy się, że są w Python datetime
911
- parsed = [
912
- {
913
- "issued_at": row["issued_at"],
914
- "total_gross": row["total_gross"],
915
- }
916
- for row in rows
917
- ]
918
- summary = {
919
- "last_month": aggregate_from_rows(parsed, last_month_start),
920
- "quarter": aggregate_from_rows(parsed, quarter_start),
921
- "year": aggregate_from_rows(parsed, year_start),
922
- }
923
- return jsonify({"summary": summary})
924
-
925
- data = load_store()
926
- try:
927
- account = get_account(data, login_key)
928
- except KeyError:
929
- return jsonify({"error": "Nie znaleziono konta."}), 404
930
- invoices = account.get("invoices", [])
931
-
932
- def parse_issued_at(value: Optional[str]) -> Optional[datetime]:
933
- if not value:
934
- return None
935
- try:
936
- return datetime.strptime(value, "%Y-%m-%d %H:%M")
937
- except ValueError:
938
- return None
939
-
940
- def aggregate(start: datetime) -> Dict[str, Any]:
941
- count = 0
942
- gross_total = Decimal("0.00")
943
- for invoice in invoices:
944
- issued_dt = parse_issued_at(invoice.get("issued_at"))
945
- if issued_dt is None or issued_dt < start:
946
- continue
947
- count += 1
948
- gross_value = invoice.get("totals", {}).get("gross", "0")
949
- try:
950
- gross_total += _decimal(gross_value)
951
- except ValueError:
952
- continue
953
- return {"count": count, "gross_total": str(_quantize(gross_total))}
954
-
955
- summary = {
956
- "last_month": aggregate(last_month_start),
957
- "quarter": aggregate(quarter_start),
958
- "year": aggregate(year_start),
959
- }
960
- return jsonify({"summary": summary})
961
 
962
 
963
  if __name__ == "__main__":
 
872
 
873
  @app.route("/api/invoices/summary", methods=["GET"])
874
  def api_invoice_summary() -> Any:
875
+ try:
876
+ login_key = require_auth()
877
+ except PermissionError:
878
+ return jsonify({"error": "Brak autoryzacji."}), 401
879
+
880
+ now = datetime.utcnow()
881
+ last_month_start = now - timedelta(days=30)
882
+ quarter_first_month = ((now.month - 1) // 3) * 3 + 1
883
+ quarter_start = now.replace(month=quarter_first_month, day=1, hour=0, minute=0, second=0, microsecond=0)
884
+ year_start = now.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
885
+
886
+ def normalize_issued_at(value: Any) -> Optional[datetime]:
887
+ if isinstance(value, datetime):
888
+ return value
889
+ if isinstance(value, str):
890
+ candidate = value.strip()
891
+ if not candidate:
892
+ return None
893
+ for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"):
894
+ try:
895
+ return datetime.strptime(candidate, fmt)
896
+ except ValueError:
897
+ continue
898
+ return None
899
+
900
+ def aggregate_from_rows(rows: List[Dict[str, Any]], start: datetime) -> Dict[str, Any]:
901
+ count = 0
902
+ gross_total = Decimal("0.00")
903
+ for row in rows:
904
+ issued_dt = normalize_issued_at(row.get("issued_at"))
905
+ if issued_dt is None or issued_dt < start:
906
+ continue
907
+ try:
908
+ gross_total += _decimal(row.get("total_gross") or "0")
909
+ except ValueError:
910
+ continue
911
+ count += 1
912
+ return {"count": count, "gross_total": str(_quantize(gross_total))}
913
+
914
+ if DATABASE_AVAILABLE:
915
+ try:
916
+ account_row = get_account_row(login_key)
917
+ except KeyError:
918
+ return jsonify({"error": "Nie znaleziono konta."}), 404
919
+ rows = fetch_all(
920
+ """
921
+ SELECT issued_at, total_gross
922
+ FROM invoices
923
+ WHERE account_id = %s
924
+ """,
925
+ (account_row["id"],),
926
+ )
927
+ summary = {
928
+ "last_month": aggregate_from_rows(rows, last_month_start),
929
+ "quarter": aggregate_from_rows(rows, quarter_start),
930
+ "year": aggregate_from_rows(rows, year_start),
931
+ }
932
+ return jsonify({"summary": summary})
933
+
934
+ data = load_store()
935
+ try:
936
+ account = get_account(data, login_key)
937
+ except KeyError:
938
+ return jsonify({"error": "Nie znaleziono konta."}), 404
939
+ invoices = account.get("invoices", [])
940
+ rows = [
941
+ {
942
+ "issued_at": invoice.get("issued_at"),
943
+ "total_gross": (invoice.get("totals") or {}).get("gross", "0"),
944
+ }
945
+ for invoice in invoices
946
+ ]
947
+
948
+ summary = {
949
+ "last_month": aggregate_from_rows(rows, last_month_start),
950
+ "quarter": aggregate_from_rows(rows, quarter_start),
951
+ "year": aggregate_from_rows(rows, year_start),
952
+ }
953
+ return jsonify({"summary": summary})
 
 
 
 
 
 
 
954
 
955
 
956
  if __name__ == "__main__":