Spaces:
Sleeping
Sleeping
Fix: Overwatch
Browse files- api_server.py +43 -15
- bank-classifier/bank_classifier/engines/llm_engine.py +1 -1
- bank-classifier/bank_classifier/pipeline.py +7 -7
- bank-classifier/bank_classifier/rules/rule_schema.py +2 -2
- befree-frontend/features/classify/ClassifyFeature.tsx +1 -1
- befree-frontend/features/history/HistoryFeature.tsx +39 -0
- befree-frontend/features/overwatch/OverwatchFeature.tsx +75 -12
- data/settings.json +1 -1
- overwatch/store.py +4 -1
api_server.py
CHANGED
|
@@ -2286,18 +2286,35 @@ async def start_processing(
|
|
| 2286 |
return {"statementId": statement_id, "status": "detecting_layout"}
|
| 2287 |
|
| 2288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2289 |
@app.post("/api/v1/statements/{statement_id}/finalise")
|
| 2290 |
-
async def finalise_statement(
|
| 2291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2292 |
if statement_id not in statements:
|
| 2293 |
raise HTTPException(status_code=404, detail="Statement not found")
|
| 2294 |
|
| 2295 |
stmt = statements[statement_id]
|
| 2296 |
stmt.status = "classifying"
|
| 2297 |
-
|
| 2298 |
-
#
|
| 2299 |
-
|
| 2300 |
-
|
|
|
|
|
|
|
|
|
|
| 2301 |
return {"status": "classifying", "message": "Classification started in background"}
|
| 2302 |
|
| 2303 |
# ── Singleton pipeline — initialised once, reused across all requests ─────────
|
|
@@ -2348,8 +2365,15 @@ def reload_pipeline_rules():
|
|
| 2348 |
pass
|
| 2349 |
|
| 2350 |
|
| 2351 |
-
async def run_statement_classification_task(statement_id: str):
|
| 2352 |
-
"""Internal helper to run the classification pipeline on a statement in the background.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2353 |
try:
|
| 2354 |
import logging
|
| 2355 |
logger = logging.getLogger("classification")
|
|
@@ -2367,13 +2391,17 @@ async def run_statement_classification_task(statement_id: str):
|
|
| 2367 |
logger.error(f"No transactions to classify for {statement_id}")
|
| 2368 |
return {"error": "No transactions to classify"}
|
| 2369 |
|
|
|
|
|
|
|
|
|
|
| 2370 |
classify_candidates = stmt.transactions
|
| 2371 |
-
if
|
| 2372 |
classify_candidates = _filter_transactions_by_last_n_months(stmt.transactions)
|
| 2373 |
|
| 2374 |
logger.info(
|
| 2375 |
f"Starting classification for statement {statement_id} "
|
| 2376 |
-
f"({
|
|
|
|
| 2377 |
)
|
| 2378 |
# ── Overwatch: wrap classify_batch with EventLog ─────────────────────
|
| 2379 |
try:
|
|
@@ -3971,8 +3999,8 @@ async def download_statement(statement_id: str, format: str = "xlsx", current_us
|
|
| 3971 |
ws_sum.column_dimensions['G'].width = 18
|
| 3972 |
|
| 3973 |
# ── Sheets 2-19: Category group sheets ──
|
| 3974 |
-
# "Miscellaneous
|
| 3975 |
-
sheet_names = [s for s in EXPENSE_SHEETS if s != "Miscellaneous
|
| 3976 |
sheet_headers = ["Date", "Description", "Category", "Sub-category", "Type", "Amount", "Bank Statement"]
|
| 3977 |
|
| 3978 |
# Helper to sanitize sheet titles
|
|
@@ -4115,13 +4143,13 @@ async def download_statement(statement_id: str, format: str = "xlsx", current_us
|
|
| 4115 |
ws_credit.column_dimensions['D'].width = 15
|
| 4116 |
ws_credit.column_dimensions['E'].width = 35
|
| 4117 |
|
| 4118 |
-
# ── Miscellaneous
|
| 4119 |
misc_expense_txs = [
|
| 4120 |
tx for tx in expense_transactions
|
| 4121 |
-
if (tx.get("category") or "").strip() == "Miscellaneous
|
| 4122 |
]
|
| 4123 |
if misc_expense_txs:
|
| 4124 |
-
ws_misc = wb.create_sheet(title="Miscellaneous
|
| 4125 |
ws_misc.append(sheet_headers)
|
| 4126 |
for cell in ws_misc[1]:
|
| 4127 |
cell.font = header_font_white
|
|
|
|
| 2286 |
return {"statementId": statement_id, "status": "detecting_layout"}
|
| 2287 |
|
| 2288 |
|
| 2289 |
+
class FinalisePayload(BaseModel):
|
| 2290 |
+
extract_last_3_months: Optional[bool] = None # None means "use saved settings value"
|
| 2291 |
+
|
| 2292 |
+
|
| 2293 |
@app.post("/api/v1/statements/{statement_id}/finalise")
|
| 2294 |
+
async def finalise_statement(
|
| 2295 |
+
statement_id: str,
|
| 2296 |
+
background_tasks: BackgroundTasks,
|
| 2297 |
+
payload: FinalisePayload = FinalisePayload(),
|
| 2298 |
+
current_user: User = Depends(get_current_user),
|
| 2299 |
+
):
|
| 2300 |
+
"""Lock the statement and trigger classification pipeline.
|
| 2301 |
+
|
| 2302 |
+
The optional body param ``extract_last_3_months`` lets the caller override
|
| 2303 |
+
the saved settings value for this run only (used by the pre-classification
|
| 2304 |
+
popup in the review screen). When omitted the saved settings value is used.
|
| 2305 |
+
"""
|
| 2306 |
if statement_id not in statements:
|
| 2307 |
raise HTTPException(status_code=404, detail="Statement not found")
|
| 2308 |
|
| 2309 |
stmt = statements[statement_id]
|
| 2310 |
stmt.status = "classifying"
|
| 2311 |
+
|
| 2312 |
+
# Resolve the filter flag: explicit payload beats saved settings
|
| 2313 |
+
use_3_months = payload.extract_last_3_months if payload.extract_last_3_months is not None else settings.extractLast3Months
|
| 2314 |
+
|
| 2315 |
+
# Run classification in the background, passing the resolved flag
|
| 2316 |
+
background_tasks.add_task(run_statement_classification_task, statement_id, use_3_months)
|
| 2317 |
+
|
| 2318 |
return {"status": "classifying", "message": "Classification started in background"}
|
| 2319 |
|
| 2320 |
# ── Singleton pipeline — initialised once, reused across all requests ─────────
|
|
|
|
| 2365 |
pass
|
| 2366 |
|
| 2367 |
|
| 2368 |
+
async def run_statement_classification_task(statement_id: str, extract_last_3_months: Optional[bool] = None):
|
| 2369 |
+
"""Internal helper to run the classification pipeline on a statement in the background.
|
| 2370 |
+
|
| 2371 |
+
Args:
|
| 2372 |
+
statement_id: The statement to classify.
|
| 2373 |
+
extract_last_3_months: When True, only the latest 3 calendar months are
|
| 2374 |
+
classified. When False, all transactions are classified. When None
|
| 2375 |
+
(default), the saved ``settings.extractLast3Months`` value is used.
|
| 2376 |
+
"""
|
| 2377 |
try:
|
| 2378 |
import logging
|
| 2379 |
logger = logging.getLogger("classification")
|
|
|
|
| 2391 |
logger.error(f"No transactions to classify for {statement_id}")
|
| 2392 |
return {"error": "No transactions to classify"}
|
| 2393 |
|
| 2394 |
+
# Resolve the filter flag: explicit arg beats saved global setting
|
| 2395 |
+
use_3_months = extract_last_3_months if extract_last_3_months is not None else settings.extractLast3Months
|
| 2396 |
+
|
| 2397 |
classify_candidates = stmt.transactions
|
| 2398 |
+
if use_3_months:
|
| 2399 |
classify_candidates = _filter_transactions_by_last_n_months(stmt.transactions)
|
| 2400 |
|
| 2401 |
logger.info(
|
| 2402 |
f"Starting classification for statement {statement_id} "
|
| 2403 |
+
f"(extract_last_3_months={use_3_months}, "
|
| 2404 |
+
f"{len(classify_candidates)}/{len(stmt.transactions)} transactions selected for classification)"
|
| 2405 |
)
|
| 2406 |
# ── Overwatch: wrap classify_batch with EventLog ─────────────────────
|
| 2407 |
try:
|
|
|
|
| 3999 |
ws_sum.column_dimensions['G'].width = 18
|
| 4000 |
|
| 4001 |
# ── Sheets 2-19: Category group sheets ──
|
| 4002 |
+
# "Miscellaneous" is handled separately after Credit Transactions.
|
| 4003 |
+
sheet_names = [s for s in EXPENSE_SHEETS if s != "Miscellaneous"] + ["Additional Expenses"]
|
| 4004 |
sheet_headers = ["Date", "Description", "Category", "Sub-category", "Type", "Amount", "Bank Statement"]
|
| 4005 |
|
| 4006 |
# Helper to sanitize sheet titles
|
|
|
|
| 4143 |
ws_credit.column_dimensions['D'].width = 15
|
| 4144 |
ws_credit.column_dimensions['E'].width = 35
|
| 4145 |
|
| 4146 |
+
# ── Miscellaneous sheet (debit only) ─────────────────────────
|
| 4147 |
misc_expense_txs = [
|
| 4148 |
tx for tx in expense_transactions
|
| 4149 |
+
if (tx.get("category") or "").strip() == "Miscellaneous"
|
| 4150 |
]
|
| 4151 |
if misc_expense_txs:
|
| 4152 |
+
ws_misc = wb.create_sheet(title="Miscellaneous")
|
| 4153 |
ws_misc.append(sheet_headers)
|
| 4154 |
for cell in ws_misc[1]:
|
| 4155 |
cell.font = header_font_white
|
bank-classifier/bank_classifier/engines/llm_engine.py
CHANGED
|
@@ -310,7 +310,7 @@ def _resolve_fallback_categories(valid_categories: list[str]) -> tuple[str, str]
|
|
| 310 |
valid_categories,
|
| 311 |
"additional expense", "miscellaneous expense", "other expense",
|
| 312 |
"general expense", "miscellaneous", "general retail", "retail",
|
| 313 |
-
) or "Miscellaneous
|
| 314 |
|
| 315 |
credit_fallback = _find_category(
|
| 316 |
valid_categories,
|
|
|
|
| 310 |
valid_categories,
|
| 311 |
"additional expense", "miscellaneous expense", "other expense",
|
| 312 |
"general expense", "miscellaneous", "general retail", "retail",
|
| 313 |
+
) or "Miscellaneous"
|
| 314 |
|
| 315 |
credit_fallback = _find_category(
|
| 316 |
valid_categories,
|
bank-classifier/bank_classifier/pipeline.py
CHANGED
|
@@ -40,7 +40,7 @@ def classify_bpay_transaction(biller_code: str, db_session: Any) -> Optional[tup
|
|
| 40 |
)
|
| 41 |
if not biller:
|
| 42 |
return None
|
| 43 |
-
return biller.category_name or "Miscellaneous
|
| 44 |
|
| 45 |
|
| 46 |
class ClassificationPipeline:
|
|
@@ -159,7 +159,7 @@ class ClassificationPipeline:
|
|
| 159 |
elif cat_name in ["Internal Transfer", "External Transfer", "Third Party Payment", "Financial Services", "Transfers & Internal Movements"]:
|
| 160 |
self._group_lookup[cat_name] = "Transfers & Internal Movements"
|
| 161 |
else:
|
| 162 |
-
self._group_lookup[cat_name] = "Miscellaneous
|
| 163 |
|
| 164 |
def reload_rules(self) -> None:
|
| 165 |
"""Reload rule engine and refresh category group cache."""
|
|
@@ -191,7 +191,7 @@ class ClassificationPipeline:
|
|
| 191 |
def _get_group(self, sub_category: str) -> str:
|
| 192 |
"""Get parent group name for a sub-category."""
|
| 193 |
if not sub_category:
|
| 194 |
-
return "Miscellaneous
|
| 195 |
|
| 196 |
group = self._group_lookup.get(sub_category)
|
| 197 |
if group:
|
|
@@ -202,7 +202,7 @@ class ClassificationPipeline:
|
|
| 202 |
elif sub_category in ["Internal Transfer", "External Transfer", "Third Party Payment", "Financial Services", "Transfers & Internal Movements"]:
|
| 203 |
group_name = "Transfers & Internal Movements"
|
| 204 |
else:
|
| 205 |
-
group_name = "Miscellaneous
|
| 206 |
|
| 207 |
log_event(
|
| 208 |
logger, "group_lookup_missing",
|
|
@@ -289,7 +289,7 @@ class ClassificationPipeline:
|
|
| 289 |
return None
|
| 290 |
|
| 291 |
result = ClassificationResult(
|
| 292 |
-
category=biller_entry.category_name or "Miscellaneous
|
| 293 |
source=ClassificationSource.RULE,
|
| 294 |
confidence=1.0,
|
| 295 |
matched_keyword=biller_code,
|
|
@@ -400,7 +400,7 @@ class ClassificationPipeline:
|
|
| 400 |
|
| 401 |
Uses debit/credit signal to assign 'Transfers & Internal Movements'
|
| 402 |
(credit), 'Transfers & Internal Movements' (unmatched OSKO/NPP debit),
|
| 403 |
-
or 'Miscellaneous
|
| 404 |
|
| 405 |
The credit default intentionally matches the LLM engine's own
|
| 406 |
low-confidence credit default (see llm_engine._resolve_fallback_categories)
|
|
@@ -424,7 +424,7 @@ class ClassificationPipeline:
|
|
| 424 |
sub_cat = "Inter-account Transfer"
|
| 425 |
source = "fallback:osko_unmatched"
|
| 426 |
else:
|
| 427 |
-
fallback_cat = "Miscellaneous
|
| 428 |
sub_cat = None
|
| 429 |
source = "fallback:debit_default"
|
| 430 |
|
|
|
|
| 40 |
)
|
| 41 |
if not biller:
|
| 42 |
return None
|
| 43 |
+
return biller.category_name or "Miscellaneous", biller.name
|
| 44 |
|
| 45 |
|
| 46 |
class ClassificationPipeline:
|
|
|
|
| 159 |
elif cat_name in ["Internal Transfer", "External Transfer", "Third Party Payment", "Financial Services", "Transfers & Internal Movements"]:
|
| 160 |
self._group_lookup[cat_name] = "Transfers & Internal Movements"
|
| 161 |
else:
|
| 162 |
+
self._group_lookup[cat_name] = "Miscellaneous"
|
| 163 |
|
| 164 |
def reload_rules(self) -> None:
|
| 165 |
"""Reload rule engine and refresh category group cache."""
|
|
|
|
| 191 |
def _get_group(self, sub_category: str) -> str:
|
| 192 |
"""Get parent group name for a sub-category."""
|
| 193 |
if not sub_category:
|
| 194 |
+
return "Miscellaneous"
|
| 195 |
|
| 196 |
group = self._group_lookup.get(sub_category)
|
| 197 |
if group:
|
|
|
|
| 202 |
elif sub_category in ["Internal Transfer", "External Transfer", "Third Party Payment", "Financial Services", "Transfers & Internal Movements"]:
|
| 203 |
group_name = "Transfers & Internal Movements"
|
| 204 |
else:
|
| 205 |
+
group_name = "Miscellaneous"
|
| 206 |
|
| 207 |
log_event(
|
| 208 |
logger, "group_lookup_missing",
|
|
|
|
| 289 |
return None
|
| 290 |
|
| 291 |
result = ClassificationResult(
|
| 292 |
+
category=biller_entry.category_name or "Miscellaneous",
|
| 293 |
source=ClassificationSource.RULE,
|
| 294 |
confidence=1.0,
|
| 295 |
matched_keyword=biller_code,
|
|
|
|
| 400 |
|
| 401 |
Uses debit/credit signal to assign 'Transfers & Internal Movements'
|
| 402 |
(credit), 'Transfers & Internal Movements' (unmatched OSKO/NPP debit),
|
| 403 |
+
or 'Miscellaneous' (debit).
|
| 404 |
|
| 405 |
The credit default intentionally matches the LLM engine's own
|
| 406 |
low-confidence credit default (see llm_engine._resolve_fallback_categories)
|
|
|
|
| 424 |
sub_cat = "Inter-account Transfer"
|
| 425 |
source = "fallback:osko_unmatched"
|
| 426 |
else:
|
| 427 |
+
fallback_cat = "Miscellaneous"
|
| 428 |
sub_cat = None
|
| 429 |
source = "fallback:debit_default"
|
| 430 |
|
bank-classifier/bank_classifier/rules/rule_schema.py
CHANGED
|
@@ -57,7 +57,7 @@ CATEGORY_TO_SHEET: dict[str, str] = {
|
|
| 57 |
"Owner Occupied Property Expense": "Owner Occupied Property Expense",
|
| 58 |
"Telephone & Internet": "Telephone & Internet",
|
| 59 |
"Medical, Health & Fitness": "Medical, Health & Fitness",
|
| 60 |
-
"Miscellaneous
|
| 61 |
"Public Education": "Public Education",
|
| 62 |
"Private Education": "Private Education",
|
| 63 |
"Health Insurance": "Health Insurance",
|
|
@@ -89,7 +89,7 @@ EXPENSE_SHEETS: list[str] = [
|
|
| 89 |
"Owner Occupied Property Expense",
|
| 90 |
"Telephone & Internet",
|
| 91 |
"Medical, Health & Fitness",
|
| 92 |
-
"Miscellaneous
|
| 93 |
"Public Education",
|
| 94 |
"Private Education",
|
| 95 |
"Health Insurance",
|
|
|
|
| 57 |
"Owner Occupied Property Expense": "Owner Occupied Property Expense",
|
| 58 |
"Telephone & Internet": "Telephone & Internet",
|
| 59 |
"Medical, Health & Fitness": "Medical, Health & Fitness",
|
| 60 |
+
"Miscellaneous": "Miscellaneous",
|
| 61 |
"Public Education": "Public Education",
|
| 62 |
"Private Education": "Private Education",
|
| 63 |
"Health Insurance": "Health Insurance",
|
|
|
|
| 89 |
"Owner Occupied Property Expense",
|
| 90 |
"Telephone & Internet",
|
| 91 |
"Medical, Health & Fitness",
|
| 92 |
+
"Miscellaneous",
|
| 93 |
"Public Education",
|
| 94 |
"Private Education",
|
| 95 |
"Health Insurance",
|
befree-frontend/features/classify/ClassifyFeature.tsx
CHANGED
|
@@ -88,7 +88,7 @@ export const SHEET_COLORS: Record<string, { bg: string; text: string; border: st
|
|
| 88 |
border: 'border-green-200', dot: 'bg-green-400',
|
| 89 |
badge: 'bg-green-100 text-green-700',
|
| 90 |
},
|
| 91 |
-
'Miscellaneous
|
| 92 |
bg: 'bg-indigo-50', text: 'text-indigo-700',
|
| 93 |
border: 'border-indigo-200', dot: 'bg-indigo-400',
|
| 94 |
badge: 'bg-indigo-100 text-indigo-700',
|
|
|
|
| 88 |
border: 'border-green-200', dot: 'bg-green-400',
|
| 89 |
badge: 'bg-green-100 text-green-700',
|
| 90 |
},
|
| 91 |
+
'Miscellaneous': {
|
| 92 |
bg: 'bg-indigo-50', text: 'text-indigo-700',
|
| 93 |
border: 'border-indigo-200', dot: 'bg-indigo-400',
|
| 94 |
badge: 'bg-indigo-100 text-indigo-700',
|
befree-frontend/features/history/HistoryFeature.tsx
CHANGED
|
@@ -32,14 +32,46 @@ import { Badge } from '@/components/ui/badge';
|
|
| 32 |
import { formatDate } from '@/utils/format';
|
| 33 |
import { motion } from 'framer-motion';
|
| 34 |
import { LoadingState, ErrorState, EmptyState } from '@/components/shared';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
export function HistoryFeature() {
|
| 37 |
const router = useRouter();
|
| 38 |
const [search, setSearch] = useState('');
|
|
|
|
| 39 |
const { data: historyData, isLoading, isError, refetch } = useStatementHistory();
|
| 40 |
const duplicateMutation = useDuplicateStatement();
|
| 41 |
const deleteMutation = useDeleteStatement();
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
const statements: HistoryRow[] = historyData || [];
|
| 44 |
|
| 45 |
const filteredStatements = useMemo(() => {
|
|
@@ -231,6 +263,13 @@ export function HistoryFeature() {
|
|
| 231 |
<DropdownMenuItem onSelect={() => router.push(`/export/${statement.id}`)}>
|
| 232 |
<Download className="w-4 h-4 mr-2" /> Export
|
| 233 |
</DropdownMenuItem>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
<DropdownMenuSeparator />
|
| 235 |
<DropdownMenuItem
|
| 236 |
className="text-error focus:text-error"
|
|
|
|
| 32 |
import { formatDate } from '@/utils/format';
|
| 33 |
import { motion } from 'framer-motion';
|
| 34 |
import { LoadingState, ErrorState, EmptyState } from '@/components/shared';
|
| 35 |
+
import { getApiBaseUrl } from '@/lib/api';
|
| 36 |
+
import { getToken } from '@/lib/auth';
|
| 37 |
+
|
| 38 |
+
function downloadStatementPdf(statementId: string, fileName: string) {
|
| 39 |
+
const token = getToken();
|
| 40 |
+
// Append ?token= so the browser navigates directly to the URL.
|
| 41 |
+
// get_current_user accepts both the Authorization header and the ?token= query param,
|
| 42 |
+
// so this works even when the API is on a different origin (avoids CORS preflight).
|
| 43 |
+
const base = `${getApiBaseUrl()}/api/v1/statements/${statementId}/pdf`;
|
| 44 |
+
const url = token ? `${base}?token=${encodeURIComponent(token)}` : base;
|
| 45 |
+
const a = document.createElement('a');
|
| 46 |
+
a.href = url;
|
| 47 |
+
a.download = fileName.endsWith('.pdf') ? fileName : `${fileName}.pdf`;
|
| 48 |
+
a.target = '_blank';
|
| 49 |
+
a.rel = 'noopener noreferrer';
|
| 50 |
+
document.body.appendChild(a);
|
| 51 |
+
a.click();
|
| 52 |
+
a.remove();
|
| 53 |
+
}
|
| 54 |
|
| 55 |
export function HistoryFeature() {
|
| 56 |
const router = useRouter();
|
| 57 |
const [search, setSearch] = useState('');
|
| 58 |
+
const [downloadingId, setDownloadingId] = useState<string | null>(null);
|
| 59 |
const { data: historyData, isLoading, isError, refetch } = useStatementHistory();
|
| 60 |
const duplicateMutation = useDuplicateStatement();
|
| 61 |
const deleteMutation = useDeleteStatement();
|
| 62 |
|
| 63 |
+
const handleDownloadPdf = (id: string, fileName: string) => {
|
| 64 |
+
setDownloadingId(id);
|
| 65 |
+
try {
|
| 66 |
+
downloadStatementPdf(id, fileName);
|
| 67 |
+
} catch (err) {
|
| 68 |
+
console.error('PDF download failed:', err);
|
| 69 |
+
alert('Failed to download PDF. Please try again.');
|
| 70 |
+
} finally {
|
| 71 |
+
setDownloadingId(null);
|
| 72 |
+
}
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
const statements: HistoryRow[] = historyData || [];
|
| 76 |
|
| 77 |
const filteredStatements = useMemo(() => {
|
|
|
|
| 263 |
<DropdownMenuItem onSelect={() => router.push(`/export/${statement.id}`)}>
|
| 264 |
<Download className="w-4 h-4 mr-2" /> Export
|
| 265 |
</DropdownMenuItem>
|
| 266 |
+
<DropdownMenuItem
|
| 267 |
+
onSelect={() => handleDownloadPdf(statement.id, statement.fileName)}
|
| 268 |
+
disabled={downloadingId === statement.id}
|
| 269 |
+
>
|
| 270 |
+
<FileText className="w-4 h-4 mr-2" />
|
| 271 |
+
{downloadingId === statement.id ? 'Downloading…' : 'Download PDF'}
|
| 272 |
+
</DropdownMenuItem>
|
| 273 |
<DropdownMenuSeparator />
|
| 274 |
<DropdownMenuItem
|
| 275 |
className="text-error focus:text-error"
|
befree-frontend/features/overwatch/OverwatchFeature.tsx
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
| 10 |
Clock,
|
| 11 |
ExternalLink,
|
| 12 |
FileSearch,
|
|
|
|
| 13 |
Inbox,
|
| 14 |
RefreshCw,
|
| 15 |
Users,
|
|
@@ -20,6 +21,25 @@ import { useOverwatchDocuments, useOverwatchInsights } from '@/hooks/useOverwatc
|
|
| 20 |
import { useAuthStore } from '@/store/authStore';
|
| 21 |
import { formatDate } from '@/utils/format';
|
| 22 |
import type { OverwatchDocumentSummary, OverwatchDocumentsResponse } from '@/types';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
const ACTION_LABELS: Record<string, string> = {
|
| 25 |
upload_statement: 'Uploads',
|
|
@@ -117,8 +137,23 @@ export function OverwatchFeature() {
|
|
| 117 |
const [hasWarnings, setHasWarnings] = useState(false);
|
| 118 |
const [usernameFilter, setUsernameFilter] = useState('');
|
| 119 |
const [page, setPage] = useState(1);
|
|
|
|
|
|
|
|
|
|
| 120 |
const PAGE_SIZE = 20;
|
| 121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
const { data, isLoading, isError, refetch } = useOverwatchDocuments({
|
| 123 |
from_time: fromTime || undefined,
|
| 124 |
to_time: toTime || undefined,
|
|
@@ -142,6 +177,20 @@ export function OverwatchFeature() {
|
|
| 142 |
setPage(1);
|
| 143 |
}
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
return (
|
| 146 |
<motion.div
|
| 147 |
initial={{ opacity: 0, y: 10 }}
|
|
@@ -160,18 +209,23 @@ export function OverwatchFeature() {
|
|
| 160 |
End-to-end visibility of every document through extraction and classification.
|
| 161 |
</p>
|
| 162 |
</div>
|
| 163 |
-
<
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
</div>
|
| 176 |
|
| 177 |
{/* Stats strip */}
|
|
@@ -441,6 +495,15 @@ export function OverwatchFeature() {
|
|
| 441 |
<ExternalLink className="w-3 h-3" />
|
| 442 |
View Statement
|
| 443 |
</Link>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
</div>
|
| 445 |
</td>
|
| 446 |
</tr>
|
|
|
|
| 10 |
Clock,
|
| 11 |
ExternalLink,
|
| 12 |
FileSearch,
|
| 13 |
+
FileDown,
|
| 14 |
Inbox,
|
| 15 |
RefreshCw,
|
| 16 |
Users,
|
|
|
|
| 21 |
import { useAuthStore } from '@/store/authStore';
|
| 22 |
import { formatDate } from '@/utils/format';
|
| 23 |
import type { OverwatchDocumentSummary, OverwatchDocumentsResponse } from '@/types';
|
| 24 |
+
import { getApiBaseUrl } from '@/lib/api';
|
| 25 |
+
import { getToken } from '@/lib/auth';
|
| 26 |
+
|
| 27 |
+
function downloadStatementPdf(statementId: string, documentName: string) {
|
| 28 |
+
const token = getToken();
|
| 29 |
+
// Append ?token= so the browser navigates directly to the URL.
|
| 30 |
+
// get_current_user accepts both the Authorization header and the ?token= query param,
|
| 31 |
+
// so this works even when the API is on a different origin (avoids CORS preflight).
|
| 32 |
+
const base = `${getApiBaseUrl()}/api/v1/statements/${statementId}/pdf`;
|
| 33 |
+
const url = token ? `${base}?token=${encodeURIComponent(token)}` : base;
|
| 34 |
+
const a = document.createElement('a');
|
| 35 |
+
a.href = url;
|
| 36 |
+
a.download = documentName.endsWith('.pdf') ? documentName : `${documentName}.pdf`;
|
| 37 |
+
a.target = '_blank';
|
| 38 |
+
a.rel = 'noopener noreferrer';
|
| 39 |
+
document.body.appendChild(a);
|
| 40 |
+
a.click();
|
| 41 |
+
a.remove();
|
| 42 |
+
}
|
| 43 |
|
| 44 |
const ACTION_LABELS: Record<string, string> = {
|
| 45 |
upload_statement: 'Uploads',
|
|
|
|
| 137 |
const [hasWarnings, setHasWarnings] = useState(false);
|
| 138 |
const [usernameFilter, setUsernameFilter] = useState('');
|
| 139 |
const [page, setPage] = useState(1);
|
| 140 |
+
const [downloadingId, setDownloadingId] = useState<string | null>(null);
|
| 141 |
+
const [isRefreshing, setIsRefreshing] = useState(false);
|
| 142 |
+
const [lastRefreshed, setLastRefreshed] = useState<Date | null>(null);
|
| 143 |
const PAGE_SIZE = 20;
|
| 144 |
|
| 145 |
+
const handleDownloadPdf = (documentId: string, documentName: string) => {
|
| 146 |
+
setDownloadingId(documentId);
|
| 147 |
+
try {
|
| 148 |
+
downloadStatementPdf(documentId, documentName);
|
| 149 |
+
} catch (err) {
|
| 150 |
+
console.error('PDF download failed:', err);
|
| 151 |
+
alert('Failed to download PDF. Please try again.');
|
| 152 |
+
} finally {
|
| 153 |
+
setDownloadingId(null);
|
| 154 |
+
}
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
const { data, isLoading, isError, refetch } = useOverwatchDocuments({
|
| 158 |
from_time: fromTime || undefined,
|
| 159 |
to_time: toTime || undefined,
|
|
|
|
| 177 |
setPage(1);
|
| 178 |
}
|
| 179 |
|
| 180 |
+
async function handleRefresh() {
|
| 181 |
+
setIsRefreshing(true);
|
| 182 |
+
try {
|
| 183 |
+
await Promise.all([refetch(), refetchInsights()]);
|
| 184 |
+
setLastRefreshed(new Date());
|
| 185 |
+
} finally {
|
| 186 |
+
setIsRefreshing(false);
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
function formatLastRefreshed(date: Date) {
|
| 191 |
+
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
return (
|
| 195 |
<motion.div
|
| 196 |
initial={{ opacity: 0, y: 10 }}
|
|
|
|
| 209 |
End-to-end visibility of every document through extraction and classification.
|
| 210 |
</p>
|
| 211 |
</div>
|
| 212 |
+
<div className="flex flex-col items-end gap-1">
|
| 213 |
+
<Button
|
| 214 |
+
variant="outline"
|
| 215 |
+
size="sm"
|
| 216 |
+
onClick={handleRefresh}
|
| 217 |
+
disabled={isRefreshing}
|
| 218 |
+
className="flex items-center gap-2"
|
| 219 |
+
>
|
| 220 |
+
<RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
|
| 221 |
+
{isRefreshing ? 'Refreshing…' : 'Refresh'}
|
| 222 |
+
</Button>
|
| 223 |
+
{lastRefreshed && (
|
| 224 |
+
<span className="text-xs text-gray-400">
|
| 225 |
+
Updated {formatLastRefreshed(lastRefreshed)}
|
| 226 |
+
</span>
|
| 227 |
+
)}
|
| 228 |
+
</div>
|
| 229 |
</div>
|
| 230 |
|
| 231 |
{/* Stats strip */}
|
|
|
|
| 495 |
<ExternalLink className="w-3 h-3" />
|
| 496 |
View Statement
|
| 497 |
</Link>
|
| 498 |
+
<button
|
| 499 |
+
type="button"
|
| 500 |
+
disabled={downloadingId === doc.document_id}
|
| 501 |
+
onClick={() => handleDownloadPdf(doc.document_id, doc.document_name)}
|
| 502 |
+
className="text-gray-500 text-xs font-medium hover:text-primary hover:underline whitespace-nowrap inline-flex items-center gap-1 disabled:opacity-40 disabled:cursor-not-allowed"
|
| 503 |
+
>
|
| 504 |
+
<FileDown className="w-3 h-3" />
|
| 505 |
+
{downloadingId === doc.document_id ? 'Downloading…' : 'Download PDF'}
|
| 506 |
+
</button>
|
| 507 |
</div>
|
| 508 |
</td>
|
| 509 |
</tr>
|
data/settings.json
CHANGED
|
@@ -4,5 +4,5 @@
|
|
| 4 |
"autoExportEnabled": false,
|
| 5 |
"auditRetentionDays": 90,
|
| 6 |
"defaultExportFormat": "xlsx",
|
| 7 |
-
"extractLast3Months":
|
| 8 |
}
|
|
|
|
| 4 |
"autoExportEnabled": false,
|
| 5 |
"auditRetentionDays": 90,
|
| 6 |
"defaultExportFormat": "xlsx",
|
| 7 |
+
"extractLast3Months": true
|
| 8 |
}
|
overwatch/store.py
CHANGED
|
@@ -25,7 +25,10 @@ from overwatch.models import (
|
|
| 25 |
|
| 26 |
_log = logging.getLogger("overwatch.store")
|
| 27 |
|
| 28 |
-
_DEFAULT_DB_PATH =
|
|
|
|
|
|
|
|
|
|
| 29 |
_DEFAULT_RETENTION_DAYS = 90
|
| 30 |
|
| 31 |
# If DATABASE_URL points to Postgres (NeonDB) we use that instead of SQLite.
|
|
|
|
| 25 |
|
| 26 |
_log = logging.getLogger("overwatch.store")
|
| 27 |
|
| 28 |
+
_DEFAULT_DB_PATH = os.environ.get(
|
| 29 |
+
"OVERWATCH_DB_PATH",
|
| 30 |
+
str(Path(os.environ.get("LOGS_DIR", "data/logs")) / "overwatch.db")
|
| 31 |
+
)
|
| 32 |
_DEFAULT_RETENTION_DAYS = 90
|
| 33 |
|
| 34 |
# If DATABASE_URL points to Postgres (NeonDB) we use that instead of SQLite.
|