### Backend API Integration with Fetch Source: https://context7.com/steve-dusty/shieldnet/llms.txt Examples of how to integrate with ShieldNet's backend API endpoints using the Fetch API. These endpoints handle invoice analysis, threat reporting, and data retrieval for analytics and transactions. Assumes appropriate `formData` and `threatData` are prepared. ```typescript // POST /api/invoices/analyze // Request: multipart/form-data with invoice file // Response: InvoiceAnalysisResult fetch('/api/invoices/analyze', { method: 'POST', body: formData // containing invoice file }); // POST /api/threats/report // Request: { invoiceId, vendor, fraudScore, reason, amount } // Response: { success: boolean, threatId: string } fetch('/api/threats/report', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(threatData) }); // GET /api/threats/analytics // Response: ThreatAnalytics fetch('/api/threats/analytics'); // GET /api/wallet/balance // Response: WalletBalance fetch('/api/wallet/balance'); // GET /api/transactions // Response: Transaction[] fetch('/api/transactions'); ``` -------------------------------- ### GET /api/wallet/balance Source: https://context7.com/steve-dusty/shieldnet/llms.txt Retrieves the current balance of the user's wallet. ```APIDOC ## GET /api/wallet/balance ### Description Retrieves the current balance of the user's wallet, typically used for managing USDC payments. ### Method GET ### Endpoint /api/wallet/balance ### Parameters None ### Request Example ``` fetch('/api/wallet/balance'); ``` ### Response #### Success Response (200) - **WalletBalance** (object) - An object containing the wallet balance information. - **currency** (string) - The currency of the balance (e.g., 'USDC'). - **amount** (number) - The available balance amount. #### Response Example ```json { "currency": "USDC", "amount": 15000.75 } ``` ``` -------------------------------- ### GET /api/transactions Source: https://context7.com/steve-dusty/shieldnet/llms.txt Retrieves a list of recent transactions. ```APIDOC ## GET /api/transactions ### Description Retrieves a list of recent transactions, including payments made and received. ### Method GET ### Endpoint /api/transactions ### Parameters #### Query Parameters None ### Request Example ``` fetch('/api/transactions'); ``` ### Response #### Success Response (200) - **Transaction[]** (array) - An array of transaction objects. - **transactionId** (string) - The unique identifier for the transaction. - **type** (string) - The type of transaction ('payment', 'deposit', 'withdrawal'). - **vendor** (string) - The vendor involved in the transaction. - **amount** (number) - The amount of the transaction. - **currency** (string) - The currency of the transaction. - **timestamp** (string) - The date and time of the transaction (ISO 8601 format). #### Response Example ```json [ { "transactionId": "txn_abcdef", "type": "payment", "vendor": "Example Corp", "amount": 1500.50, "currency": "USDC", "timestamp": "2023-10-27T10:30:00Z" }, { "transactionId": "txn_ghijkl", "type": "deposit", "vendor": "Treasury", "amount": 10000.00, "currency": "USDC", "timestamp": "2023-10-26T15:00:00Z" } ] ``` ``` -------------------------------- ### GET /api/threats/analytics Source: https://context7.com/steve-dusty/shieldnet/llms.txt Retrieves analytics data related to reported threats and fraud patterns. ```APIDOC ## GET /api/threats/analytics ### Description Retrieves analytics data related to reported threats and fraud patterns across the network. ### Method GET ### Endpoint /api/threats/analytics ### Parameters None ### Request Example ``` fetch('/api/threats/analytics'); ``` ### Response #### Success Response (200) - **ThreatAnalytics** (object) - An object containing various threat analytics data. - **totalThreatsReported** (number) - Total number of threats reported. - **fraudTrends** (object) - Trends in fraud over time. - **topVendors** (array) - List of vendors with the most reported threats. - **averageFraudScore** (number) - Average fraud score across all reported threats. #### Response Example ```json { "totalThreatsReported": 542, "fraudTrends": { "last7Days": 55, "last30Days": 210 }, "topVendors": [ {"name": "Shady Deals Inc.", "count": 35}, {"name": "Questionable Goods LLC", "count": 28} ], "averageFraudScore": 72.5 } ``` ``` -------------------------------- ### React Component for Treasury Panel: Balance and Transactions Source: https://github.com/steve-dusty/shieldnet/blob/main/SHIELDNET_SUMMARY.md Displays the user's USDC wallet balance and a history of recent transactions. It provides monthly summaries of auto-paid and blocked amounts, along with details for each transaction. Includes loading states for data fetching. ```typescript import React, { useState, useEffect } from 'react'; import { getWalletBalance, getTransactions } from '../services/mockApi'; // Adjust path as needed import { WalletBalance, Transaction } from '../services/types'; // Assuming types are defined here import { Box, Typography, Paper, Grid, Card, CardContent, Chip, Stack, CircularProgress, Alert, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material'; const TreasuryPanel: React.FC = () => { const [balance, setBalance] = useState(null); const [transactions, setTransactions] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { setIsLoading(true); setError(null); try { const balanceData = await getWalletBalance(); const transactionsData = await getTransactions(); setBalance(balanceData); setTransactions(transactionsData); } catch (err) { setError('Failed to load treasury data.'); console.error(err); } finally { setIsLoading(false); } }; fetchData(); }, []); const getTransactionStatusColor = (status: string) => { switch (status) { case 'Success': return 'success'; case 'Blocked': return 'error'; case 'Pending': return 'warning'; default: return 'info'; } }; if (isLoading) { return ( ); } if (error) { return {error}; } if (!balance) { return Treasury data not available.; } return ( Treasury Current USDC Balance {balance.usdcBalance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USDC Transaction History Vendor Amount Date Status Reason {transactions.length > 0 ? ( transactions.map((tx) => ( {tx.vendor} {tx.amount} {new Date(tx.date).toLocaleDateString()} {tx.reason} )) ) : ( No transactions yet. )}
ShieldNet Protection: Your treasury is protected by AI-driven invoice verification. Only verified invoices trigger USDC payments via Locus, and blocked transactions are logged for review.
); }; export default TreasuryPanel; ``` -------------------------------- ### Mock API Layer for Invoice Analysis and Threat Reporting Source: https://github.com/steve-dusty/shieldnet/blob/main/SHIELDNET_SUMMARY.md Provides mock implementations for key API functions like analyzing invoices and reporting threats. It includes TypeScript interfaces for data structures and simulates API delays. This layer is intended for frontend development and testing before backend integration. ```typescript import { InvoiceAnalysisResult, ThreatSummary, Transaction, WalletBalance, } from './types'; const simulateApiDelay = (min = 500, max = 1500) => new Promise((resolve) => setTimeout(resolve, Math.random() * (max - min) + min)); export const analyzeInvoice = async (invoiceData: any): Promise => { await simulateApiDelay(); const fraudScore = Math.random() * 100; let status: 'Approved' | 'Hold' | 'Blocked'; if (fraudScore >= 85) { status = 'Blocked'; } else if (fraudScore >= 70) { status = 'Hold'; } else { status = 'Approved'; } return { status, confidenceScore: Math.random() * 100, fraudScore, localChecks: { poMatch: Math.random() > 0.2, hoursVerification: Math.random() > 0.1, }, networkSignals: Math.random() > 0.5 ? ['flagged_by_others'] : [], }; }; export const getThreatAnalytics = async (): Promise => { await simulateApiDelay(); const threats = Array.from({ length: 5 }, (_, i) => ({ id: `T${Date.now()}${i}`, vendor: `Vendor ${i + 1}`, fraudScore: Math.random() * 100, reason: 'Suspicious patterns detected', firstSeen: new Date(Date.now() - Math.random() * 100000000).toISOString(), timesSeen: Math.floor(Math.random() * 10) + 1, amountBlocked: `$${(Math.random() * 5000).toFixed(2)}`, })); return { totalThreatsBlocked: Math.floor(Math.random() * 1000), totalFraudAvoided: `$${(Math.random() * 1000000).toFixed(2)}`, uniqueThreats: Math.floor(Math.random() * 50) + 5, rewardsEarned: `$${(Math.random() * 10000).toFixed(2)}`, threats: threats, }; }; export const getTransactions = async (): Promise => { await simulateApiDelay(); return Array.from({ length: 6 }, (_, i) => ({ id: `TXN${Date.now()}${i}`, vendor: `Vendor ${i + 1}`, amount: `$${(Math.random() * 1000).toFixed(2)}`, date: new Date(Date.now() - Math.random() * 10000000).toISOString(), status: ['Success', 'Blocked', 'Pending'][Math.floor(Math.random() * 3)] as any, reason: 'Automated verification', invoiceId: `INV${Date.now()}${i}`, })); }; export const getWalletBalance = async (): Promise => { await simulateApiDelay(); return { usdcBalance: Math.random() * 100000, monthlySummary: { autoPaid: `$${(Math.random() * 50000).toFixed(2)}`, blocked: `$${(Math.random() * 5000).toFixed(2)}`, }, }; }; export const reportThreat = async (threatData: any) => { await simulateApiDelay(); console.log('Threat reported:', threatData); // TODO: Implement actual threat reporting logic }; // Define types in a separate file (e.g., types.ts) // export interface InvoiceAnalysisResult { ... } // export interface ThreatSummary { ... } // export interface Transaction { ... } // export interface WalletBalance { ... } ``` -------------------------------- ### Monitor Treasury Wallet Balance (TypeScript) Source: https://context7.com/steve-dusty/shieldnet/llms.txt Fetches the current USDC wallet balance and monthly summaries using `getWalletBalance`. It logs the current balance, auto-paid amounts, and blocked amounts for the month. This function depends on the '@/services/mockApi' module. ```typescript import { getWalletBalance, WalletBalance } from '@/services/mockApi'; // Get current wallet balance and monthly summaries const loadWalletData = async () => { try { const balance: WalletBalance = await getWalletBalance(); console.log('Current Balance:', balance.balance.toLocaleString(), balance.currency); // Output: Current Balance: 48,200 USDC console.log('Auto-Paid This Month:', balance.autoPaidThisMonth); // Output: Auto-Paid This Month: 34500 console.log('Blocked This Month:', balance.blockedThisMonth); // Output: Blocked This Month: 23400 return balance; } catch (error) { console.error('Failed to fetch wallet balance:', error); throw error; } }; ``` -------------------------------- ### React Component for Threat Analytics Summary and List Source: https://github.com/steve-dusty/shieldnet/blob/main/SHIELDNET_SUMMARY.md Displays key statistics related to fraud detection, such as threats blocked and rewards earned. It also provides a detailed list of detected threats, including vendor information, fraud scores, and timestamps. Features color-coded badges for fraud scores. ```typescript import React, { useState, useEffect } from 'react'; import { getThreatAnalytics } from '../services/mockApi'; // Adjust path as needed import { ThreatSummary, Threat } from '../services/types'; // Assuming types are defined here import { Box, Typography, Paper, Grid, Card, CardContent, Chip, CircularProgress, Alert } from '@mui/material'; const ThreatAnalytics: React.FC = () => { const [analytics, setAnalytics] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchAnalytics = async () => { setIsLoading(true); setError(null); try { const data = await getThreatAnalytics(); setAnalytics(data); } catch (err) { setError('Failed to load threat analytics.'); console.error(err); } finally { setIsLoading(false); } }; fetchAnalytics(); }, []); const getFraudScoreBadgeColor = (score: number) => { if (score >= 85) return 'error'; if (score >= 70) return 'warning'; return 'success'; }; if (isLoading) { return ( ); } if (error) { return {error}; } if (!analytics) { return No analytics data available.; } return ( Threat Analytics Threats Blocked {analytics.totalThreatsBlocked.toLocaleString()} Fraud Avoided {analytics.totalFraudAvoided} Unique Threats {analytics.uniqueThreats.toLocaleString()} Rewards Earned {analytics.rewardsEarned} Detected Threats {analytics.threats.length > 0 ? ( analytics.threats.map((threat: Threat) => ( Vendor: {threat.vendor} First Seen: {new Date(threat.firstSeen).toLocaleDateString()} {threat.amountBlocked} Blocked )) ) : ( No recent threats detected. )} Network Intelligence: ShieldNet anonymously shares detected threats across the network. Early detectors and participants who help identify threats earn micro-rewards, contributing to a collective defense system. ); }; export default ThreatAnalytics; ``` -------------------------------- ### Analyze Invoices for Fraud Risk with TypeScript Source: https://context7.com/steve-dusty/shieldnet/llms.txt Analyzes uploaded invoices for fraud risk using multi-agent verification. It takes a File object as input and returns an InvoiceAnalysisResult, including status, confidence, fraud score, and detailed local and network checks. This function relies on the 'analyzeInvoice' service from '@/services/mockApi'. ```typescript import { analyzeInvoice, InvoiceAnalysisResult } from '@/services/mockApi'; // Analyze an invoice file const handleInvoiceUpload = async (file: File) => { try { const result: InvoiceAnalysisResult = await analyzeInvoice(file); // Result includes status, confidence, fraud score, and detailed checks console.log('Status:', result.status); // 'approved' | 'hold' | 'blocked' console.log('Confidence:', result.confidence); // 0-100 console.log('Fraud Score:', result.fraudScore); // 0-100 // Local security checks (PO match, hours verification, vendor trust) result.localChecks.forEach(check => { console.log(`${check.name}: ${check.status} - ${check.detail}`); }); // Network signals (flagged by others, seen in network) result.networkSignals.forEach(signal => { console.log(`${signal.type}: ${signal.description}`); }); // Example approved invoice response: // { // invoiceId: 'INV-2024-001', // status: 'approved', // confidence: 96, // fraudScore: 8, // vendor: 'CloudHosting Inc.', // amount: 2450.00, // currency: 'USDC', // localChecks: [ // { name: 'PO Match', status: 'pass', detail: 'Matches PO-7781' }, // { name: 'Hours Verification', status: 'pass', detail: 'Logged hours: 82h, Invoice: 80h' } // ], // networkSignals: [ // { type: 'clean', description: 'No similar scams seen in ShieldNet' } // ], // explanation: 'Invoice matches PO-7781 and logged hours; no similar scams seen in ShieldNet.' // } return result; } catch (error) { console.error('Analysis failed:', error); throw error; } }; ``` -------------------------------- ### React Page Component for ShieldNet Platform View Source: https://github.com/steve-dusty/shieldnet/blob/main/SHIELDNET_SUMMARY.md This React component integrates various ShieldNet features into a single platform view. It manages the display of invoice analysis, treasury panel, and threat analytics, handling data fetching and UI state. It replaces previous trading-focused components. ```typescript import React, { useState, useEffect } from 'react'; import { Tabs, Tab, Box, Grid, Typography, Card, CardContent } from '@mui/material'; import InvoiceAnalysis from '../components/InvoiceAnalysis'; import ThreatAnalytics from '../components/ThreatAnalytics'; import TreasuryPanel from '../components/TreasuryPanel'; import ConnectWalletButton from '../components/ConnectWalletButton'; // Assuming this exists const PlatformPage: React.FC = () => { const [currentTab, setCurrentTab] = useState('invoice'); const handleTabChange = (event: React.SyntheticEvent, newValue: string) => { setCurrentTab(newValue); }; return ( ShieldNet Platform {currentTab === 'invoice' && ( )} {currentTab === 'threats' && ( )} {currentTab === 'treasury' && ( )} ); }; export default PlatformPage; ``` -------------------------------- ### Fetch Threat Analytics Data (TypeScript) Source: https://context7.com/steve-dusty/shieldnet/llms.txt Retrieves network-wide threat intelligence and reward data using the `getThreatAnalytics` function. It logs total blocked amounts, invoices stopped, unique threats, earned rewards, and details for individual threat records. This function requires the '@/services/mockApi' module. ```typescript import { getThreatAnalytics, ThreatAnalytics } from '@/services/mockApi'; // Fetch comprehensive threat analytics const loadThreatData = async () => { try { const analytics: ThreatAnalytics = await getThreatAnalytics(); // Network-wide statistics console.log('Total Blocked:', analytics.totalBlockedAmount); // $1,247,500 console.log('Invoices Stopped:', analytics.totalBlockedInvoices); // 2,847 console.log('Unique Threats:', analytics.totalThreatsDetected); // 156 console.log('Rewards Earned:', analytics.rewardsEarned); // $3,450 // Individual threat records with pattern details analytics.threats.forEach(threat => { console.log(`Threat: ${threat.vendor}`); console.log(` Risk Score: ${threat.fraudScore}/100`); console.log(` First Seen: ${threat.firstSeen}`); console.log(` Times Seen: ${threat.timesSeen}x across network`); console.log(` Amount Blocked: $${threat.amountBlocked.toLocaleString()}`); console.log(` Reason: ${threat.reason}`); if (threat.templateHash) { console.log(` Template Hash: ${threat.templateHash}`); } }); return analytics; } catch (error) { console.error('Failed to fetch analytics:', error); throw error; } }; ``` -------------------------------- ### Retrieve Transaction History (TypeScript) Source: https://context7.com/steve-dusty/shieldnet/llms.txt Fetches recent payment transaction records, including status and details, using the `getTransactions` function. It iterates through transactions, logging vendor, amount, currency, status, date, invoice ID, and reason. Requires the '@/services/mockApi' module. ```typescript import { getTransactions, Transaction } from '@/services/mockApi'; // Fetch recent transaction history const loadTransactions = async () => { try { const transactions: Transaction[] = await getTransactions(); transactions.forEach(tx => { console.log(`${tx.vendor}: $${tx.amount} ${tx.currency}`); console.log(` Status: ${tx.status}`); // 'paid' | 'held' | 'blocked' console.log(` Date: ${tx.date}`); console.log(` Invoice: ${tx.invoiceId}`); console.log(` Reason: ${tx.reason}`); }); return transactions; } catch (error) { console.error('Failed to fetch transactions:', error); throw error; } }; ``` -------------------------------- ### POST /api/threats/report Source: https://context7.com/steve-dusty/shieldnet/llms.txt Reports a detected threat to the shared intelligence network. ```APIDOC ## POST /api/threats/report ### Description Reports a detected threat to the shared intelligence network. This is typically called when an invoice is flagged as fraudulent. ### Method POST ### Endpoint /api/threats/report ### Parameters #### Query Parameters None #### Request Body - **invoiceId** (string) - Required - The ID of the invoice associated with the threat. - **vendor** (string) - Required - The name of the vendor. - **fraudScore** (number) - Required - The fraud score of the invoice. - **reason** (string) - Required - The reason why the invoice was flagged as a threat. - **amount** (number) - Required - The amount of the invoice. ### Request Example ```json { "invoiceId": "inv_12345", "vendor": "Example Corp", "fraudScore": 85, "reason": "High risk of fraudulent activity detected.", "amount": 1500.50 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the threat report was successful. - **threatId** (string) - The unique identifier for the reported threat. #### Response Example ```json { "success": true, "threatId": "tht_abcde" } ``` ``` -------------------------------- ### POST /api/invoices/analyze Source: https://context7.com/steve-dusty/shieldnet/llms.txt Analyzes an uploaded invoice for potential fraud and returns an analysis result. ```APIDOC ## POST /api/invoices/analyze ### Description Analyzes an uploaded invoice for potential fraud and returns an analysis result. ### Method POST ### Endpoint /api/invoices/analyze ### Parameters #### Query Parameters None #### Request Body - **invoice file** (multipart/form-data) - Required - The invoice file to be analyzed (e.g., PDF, PNG, JPG). ### Request Example ``` // Assuming formData is a FormData object containing the invoice file fetch('/api/invoices/analyze', { method: 'POST', body: formData }); ``` ### Response #### Success Response (200) - **InvoiceAnalysisResult** (object) - The result of the invoice analysis. - **status** (string) - The analysis status ('approved', 'blocked', 'hold'). - **invoiceId** (string) - The unique identifier for the invoice. - **vendor** (string) - The name of the vendor. - **fraudScore** (number) - The calculated fraud score (0-100). - **explanation** (string) - A detailed explanation of the analysis result. - **amount** (number) - The invoice amount. - **confidence** (number) - The confidence level of the analysis (0-100). - **localChecks** (array) - An array of local security check results. - **name** (string) - The name of the check. - **status** (string) - The status of the check ('passed', 'failed'). - **detail** (string) - Details about the check result. - **networkSignals** (array) - An array of network intelligence signals. - **type** (string) - The type of network signal. - **description** (string) - A description of the network signal. #### Response Example ```json { "status": "blocked", "invoiceId": "inv_12345", "vendor": "Example Corp", "fraudScore": 85, "explanation": "High risk of fraudulent activity detected.", "amount": 1500.50, "confidence": 92, "localChecks": [ { "name": "Signature Verification", "status": "failed", "detail": "Digital signature is invalid." } ], "networkSignals": [ { "type": "IP Blacklist", "description": "Submitting IP address is on a known blacklist." } ] } ``` ``` -------------------------------- ### React Component for Invoice Analysis and Upload Source: https://github.com/steve-dusty/shieldnet/blob/main/SHIELDNET_SUMMARY.md Handles the invoice submission and analysis flow. It includes a file upload interface and displays the AI analysis results, including status, confidence scores, and security check outcomes. Automatically reports blocked threats. ```typescript import React, { useState } from 'react'; import { analyzeInvoice, reportThreat } from '../services/mockApi'; // Adjust path as needed import { InvoiceAnalysisResult } from '../services/types'; // Assuming types are defined here import { Box, Button, Typography, Alert, CircularProgress, LinearProgress, Paper, Chip } from '@mui/material'; import CloudUploadIcon from '@mui/icons-material/CloudUpload'; const InvoiceAnalysis: React.FC = () => { const [file, setFile] = useState(null); const [analysisResult, setAnalysisResult] = useState(null); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const handleFileChange = (event: React.ChangeEvent) => { if (event.target.files && event.target.files.length > 0) { setFile(event.target.files[0]); setAnalysisResult(null); // Reset results on new file selection setError(null); } }; const handleAnalyzeClick = async () => { if (!file) { setError('Please select a file first.'); return; } setIsLoading(true); setError(null); setAnalysisResult(null); try { // In a real app, you would upload the file and then analyze // For mock, we just pass dummy data or the file object reference const result = await analyzeInvoice({ file }); setAnalysisResult(result); if (result.status === 'Blocked') { await reportThreat({ ...result, vendor: 'Unknown', invoiceId: 'mock_id' }); } } catch (err) { setError('Failed to analyze invoice. Please try again.'); console.error(err); } finally { setIsLoading(false); } }; const handleAnalyzeAnother = () => { setFile(null); setAnalysisResult(null); setError(null); // Reset file input if needed const inputElement = document.getElementById('invoice-upload-input') as HTMLInputElement; if (inputElement) { inputElement.value = ''; } }; const getAlertSeverity = (status: string): 'success' | 'warning' | 'error' => { switch (status) { case 'Approved': return 'success'; case 'Hold': return 'warning'; case 'Blocked': return 'error'; default: return 'info'; } }; return ( Invoice Verification {file && {file.name}} {isLoading && ( Analyzing... )} {error && {error}} {analysisResult && ( Decision: {analysisResult.status} Confidence Score: {analysisResult.confidenceScore.toFixed(2)}% Fraud Score: {analysisResult.fraudScore.toFixed(2)}% Local Security Checks: {/* Add more checks as needed */} Network Signals: {analysisResult.networkSignals.length > 0 ? ( analysisResult.networkSignals.map((signal, index) => ( )) ) : ( No network signals detected. )} )} ); }; export default InvoiceAnalysis; ``` -------------------------------- ### React Invoice Analyzer Component Source: https://context7.com/steve-dusty/shieldnet/llms.txt A React component for analyzing invoices. It handles file uploads, interacts with an API for analysis and threat reporting, and displays the results with status icons. Dependencies include React hooks and UI components from '@/components/ui/button'. ```tsx import { useState } from 'react'; import { analyzeInvoice, InvoiceAnalysisResult, reportThreat } from '@/services/mockApi'; import { Button } from '@/components/ui/button'; import { CheckCircle, XCircle, AlertCircle } from 'lucide-react'; export const InvoiceAnalyzer = () => { const [file, setFile] = useState(null); const [analyzing, setAnalyzing] = useState(false); const [result, setResult] = useState(null); const handleAnalyze = async () => { if (!file) return; setAnalyzing(true); try { // Analyze the invoice const analysisResult = await analyzeInvoice(file); setResult(analysisResult); // Report blocked threats to network if (analysisResult.status === 'blocked') { await reportThreat({ invoiceId: analysisResult.invoiceId, vendor: analysisResult.vendor, fraudScore: analysisResult.fraudScore, reason: analysisResult.explanation, amount: analysisResult.amount }); } } catch (error) { console.error('Analysis failed:', error); } finally { setAnalyzing(false); } }; const getStatusIcon = (status: string) => { switch (status) { case 'approved': return ; case 'blocked': return ; case 'hold': return ; } }; return (
{/* File upload */} setFile(e.target.files?.[0] || null)} /> {/* Results display */} {result && (

{getStatusIcon(result.status)} {result.status.toUpperCase()}

Confidence: {result.confidence}%

Fraud Score: {result.fraudScore}/100

{result.explanation}

{/* Local checks */}

Security Checks

{result.localChecks.map((check, i) => (
{check.name}: {check.status} - {check.detail}
))}
{/* Network signals */}

Network Intelligence

{result.networkSignals.map((signal, i) => (
{signal.type}: {signal.description}
))}
)}
); }; ``` -------------------------------- ### Threat Reporting API Source: https://context7.com/steve-dusty/shieldnet/llms.txt Report blocked threats to the ShieldNet network for shared intelligence. This endpoint allows the system to anonymously share threat fingerprints with the network, helping to protect other companies and potentially earning rewards. ```APIDOC ## POST /api/threats/report ### Description Reports a detected threat (e.g., a blocked invoice) to the ShieldNet network to enhance shared intelligence. This action contributes to the collective security of the network and may earn rewards for early detection. ### Method POST ### Endpoint /api/threats/report ### Parameters #### Request Body - **invoiceId** (string) - Required - The unique identifier of the invoice associated with the threat. - **vendor** (string) - Required - The name of the vendor involved in the threat. - **fraudScore** (number) - Required - The fraud score calculated for the invoice. - **reason** (string) - Required - A detailed explanation or reason for flagging the invoice as a threat. - **amount** (number) - Optional - The amount associated with the invoice. ### Request Example ```json { "invoiceId": "INV-2024-002", "vendor": "Shady Software LLC", "fraudScore": 85, "reason": "Invoice details do not match PO; vendor has multiple flags in network.", "amount": 15000.00 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the threat report was successfully submitted. - **threatId** (string) - A unique identifier for the reported threat. #### Response Example ```json { "success": true, "threatId": "THR-1699564321000" } ``` ``` -------------------------------- ### Report Blocked Threats to ShieldNet with TypeScript Source: https://context7.com/steve-dusty/shieldnet/llms.txt Reports blocked invoices to the ShieldNet network for shared intelligence. This function takes an InvoiceAnalysisResult object and, if the status is 'blocked', calls the 'reportThreat' service to submit threat details. It returns a response containing a threat ID upon successful reporting. ```typescript import { reportThreat } from '@/services/mockApi'; // Automatically report blocked invoices to the network const handleBlockedInvoice = async (analysisResult: InvoiceAnalysisResult) => { if (analysisResult.status === 'blocked') { try { const response = await reportThreat({ invoiceId: analysisResult.invoiceId, vendor: analysisResult.vendor, fraudScore: analysisResult.fraudScore, reason: analysisResult.explanation, amount: analysisResult.amount }); console.log('Threat reported:', response.threatId); // Example response: { success: true, threatId: 'THR-1699564321000' } // This threat is now shared with the network // When others query similar patterns, you earn rewards } catch (error) { console.error('Failed to report threat:', error); } } }; ```