diff --git a/frontend/docs/FRAUD_DETECTION.md b/frontend/docs/FRAUD_DETECTION.md new file mode 100644 index 0000000..73999f3 --- /dev/null +++ b/frontend/docs/FRAUD_DETECTION.md @@ -0,0 +1,34 @@ +# Fraud Detection System Guide (Backend + ML) + +## Overview + +The fraud detection system is a **cross-service pipeline** involving: + +- Backend API (request orchestration + storage) +- Fraud Detection Service (rules + orchestration layer) +- ML Microservice (model inference + scoring) +- Feedback loop (retraining system) + +This document explains the **full lifecycle of fraud analysis**. + +--- + +## 1. Fraud Detection Flow + +### Step-by-step pipeline: + +1. Backend receives transaction/event +2. Backend forwards payload to fraud-detection service +3. Fraud service calls ML microservice for scoring +4. ML service returns risk score + explanation +5. Backend evaluates thresholds +6. Alert is created if risk is high +7. Result is stored in database +8. User/admin feedback is collected later +9. Feedback is used for retraining + +--- + +## 2. API Request Flow + +### Backend Entry Point diff --git a/frontend/docs/SEARCH.md b/frontend/docs/SEARCH.md new file mode 100644 index 0000000..9fbaa54 --- /dev/null +++ b/frontend/docs/SEARCH.md @@ -0,0 +1,143 @@ +# Search System Behavior Guide + +## Overview + +The search system supports multiple ranking and retrieval strategies depending on database capabilities and query type. It is designed to gracefully degrade when advanced features are unavailable. + +--- + +## 1. Feature Detection Model + +At runtime, the search service detects available database capabilities: + +### Supported features: +- Full Text Search (FTS) +- Trigram similarity (pg_trgm) +- Basic ILIKE fallback + +### Detection order: +1. Check if FTS indexes exist +2. Check if trigram extension is enabled +3. Fall back to basic LIKE queries + +--- + +## 2. Query Execution Strategy + +Search execution follows a layered approach: + +### Layer 1 — Full Text Search (Primary) +Used when FTS is available. + +- Uses `to_tsvector` +- Ranked using `ts_rank` +- Best performance + semantic matching + +--- + +### Layer 2 — Trigram Similarity (Secondary) +Used when FTS is unavailable or insufficient. + +- Uses `similarity(column, query)` +- Requires `pg_trgm` +- Handles typos and fuzzy matching + +--- + +### Layer 3 — Fallback LIKE Search (Last Resort) + +Used when no advanced DB features are available. + +- Uses `ILIKE '%query%'` +- No ranking intelligence +- Lowest performance and relevance + +--- + +## 3. Ranking Model + +When multiple strategies are active, results are merged and ranked using: + +Priority order: +1. FTS rank score (highest weight) +2. Trigram similarity score +3. Relevance boost (exact match in title/name) +4. Recency boost (if timestamp exists) + +Final score is normalized before sorting. + +--- + +## 4. Pagination Model (Cursor-Based) + +Search uses cursor pagination, not offset pagination. + +### Request parameters: +- `limit` → number of results per page +- `cursor` → last seen result identifier + +### How cursor works: +- Cursor stores `(score, id)` pair +- Next query uses: + - `WHERE (score, id) < cursor` + - ordered by `(score DESC, id DESC)` + +### Benefits: +- Stable pagination under inserts +- No duplicates across pages +- Better performance than OFFSET + +--- + +## 5. Fallback Behavior Summary + +| Capability Missing | System Behavior | +|--------------------|-----------------| +| FTS disabled | Switch to trigram | +| Trigram disabled | Switch to LIKE | +| No indexes | Full table scan (last resort) | + +--- + +## 6. Query Degradation Rules + +When performance constraints exist: + +- Reduce ranking complexity +- Skip trigram scoring +- Limit result set early +- Prefer indexed columns only + +--- + +## 7. DTO Contract Alignment + +Search DTO supports: + +- `query: string` +- `limit?: number` +- `cursor?: string` +- `filters?: object` + +Validation ensures: +- limit max cap enforced +- cursor format validated +- empty query rejected + +--- + +## 8. Validation Source of Truth + +This document aligns with: + +- `backend/src/search/search.service.ts` +- Search DTO definitions +- Database index configuration + +--- + +## 9. Notes for Frontend Consumers + +- Always treat results as **ranked, not ordered by insertion** +- Do not assume stable ordering without cursor usage +- Cursor must be treated as opaque string \ No newline at end of file diff --git a/frontend/docs/deployment.md b/frontend/docs/deployment.md new file mode 100644 index 0000000..66a0293 --- /dev/null +++ b/frontend/docs/deployment.md @@ -0,0 +1,32 @@ +## Fraud Detection System Deployment + +The fraud detection system consists of: + +### Services: +- Backend API (Node/NestJS) +- Fraud Detection Service (internal module) +- ML Microservice (Python/FastAPI or similar) + +--- + +### Dependency Flow: + +Backend → Fraud Service → ML Service + +--- + +### Critical Requirements: + +- ML service must be deployed before enabling fraud scoring +- Timeout fallback must be enabled in backend +- Feature flags control: + - enableFraudDetection + - enableMLScoring + +--- + +### Failure Handling: + +If ML service is down: +- system falls back to rule engine +- alerts still generated in degraded mode \ No newline at end of file diff --git a/frontend/src/components/usePaymentCheckout.ts b/frontend/src/components/usePaymentCheckout.ts new file mode 100644 index 0000000..a73a7c7 --- /dev/null +++ b/frontend/src/components/usePaymentCheckout.ts @@ -0,0 +1,64 @@ +import { useState } from "react"; + +type CheckoutParams = { + amount: number; + splitId: string; +}; + +export const usePaymentCheckout = () => { + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [lastSubmittedId, setLastSubmittedId] = useState(null); + + const isWalletConnected = () => { + // replace with real wallet hook + return Boolean(window?.ethereum?.selectedAddress); + }; + + const isCorrectNetwork = () => { + // replace with real chain check + return true; + }; + + const submitPayment = async (params: CheckoutParams) => { + const { splitId } = params; + + // 🚫 prevent duplicate submits + if (loading || lastSubmittedId === splitId) return; + + setError(null); + + if (!isWalletConnected()) { + setError("Wallet not connected"); + return; + } + + if (!isCorrectNetwork()) { + setError("Wrong network"); + return; + } + + try { + setLoading(true); + setLastSubmittedId(splitId); + + // simulate payment request + await new Promise((res) => setTimeout(res, 1000)); + + // replace with real API call + console.log("Payment successful for split:", splitId); + } catch (e: any) { + setError(e.message || "Payment failed"); + } finally { + setLoading(false); + } + }; + + return { + submitPayment, + loading, + error, + isWalletConnected: isWalletConnected(), + isCorrectNetwork: isCorrectNetwork(), + }; +}; \ No newline at end of file