### Deals - Quick Start API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Create a deal and upload a document in a single call for rapid onboarding. ```APIDOC ## Deals - Quick Start Create a deal and upload a document in a single call for rapid onboarding. ### POST /deals/quick-start **Description**: Creates a new deal and uploads an initial document in one operation. **Method**: POST **Endpoint**: `/deals/quick-start` **Parameters** #### Request Body - **business_name** (string) - Required - The name of the business for the new deal. - **file** (string) - Required - The file path to the document to upload. - **document_type** (string) - Required - The type of the document (e.g., "bank_statement"). - **idempotency_key** (string) - Required - A unique key to ensure the request is processed only once. #### Response ##### Success Response (200) - **deal_id** (integer) - The ID of the newly created deal. - **document_id** (integer) - The ID of the uploaded document. - **status** (string) - The processing status of the deal and document (e.g., "processing"). ``` -------------------------------- ### Install Banklyze Node.js SDK Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md This command installs the Banklyze SDK using npm. It requires Node.js version 20 or higher and has no runtime dependencies. ```bash npm install @banklyze/sdk ``` -------------------------------- ### Create and Manage Deals Source: https://context7.com/thornebridge/banklyze-node/llms.txt Shows how to create a new underwriting deal by providing business and owner details. The example highlights the use of idempotency keys to ensure safe retries. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const deal = await client.deals.create({ business_name: "Acme Trucking LLC", dba_name: "Acme Transport", owner_name: "John Smith", industry: "Transportation", funding_amount_requested: 50000, entity_type: "LLC", ein: "12-3456789", business_start_date: "2019-03-15", business_address_street: "123 Main St", business_address_city: "Chicago", business_address_state: "IL", business_address_zip: "60601", owner_email: "john@acmetrucking.com", owner_phone: "312-555-0100", ownership_pct: 100, owner_credit_score: 680, self_reported_monthly_revenue: 85000, existing_mca_positions: 1, existing_mca_balance: 15000, source_type: "broker", broker_name: "Jane Doe", broker_company: "ABC Funding", commission_pct: 10, idempotency_key: "unique-request-id-123", }); console.log(deal.id); console.log(deal.business_name); console.log(deal.status); ``` -------------------------------- ### Create Deal and Upload Statement with Banklyze SDK (TypeScript) Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md This snippet demonstrates how to initialize the Banklyze client, create a new deal, upload a bank statement PDF, and retrieve the underwriting decision. It requires an API key and assumes the SDK is installed. The output is the underwriting decision. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const deal = await client.deals.create({ business_name: "Acme Trucking LLC" }); await client.documents.upload(deal.id, "./statements/chase_jan.pdf"); const result = await client.deals.get(deal.id); console.log(result.recommendation.decision); // "approved" ``` -------------------------------- ### Initialize Banklyze Client Source: https://context7.com/thornebridge/banklyze-node/llms.txt Demonstrates how to instantiate the Banklyze client with custom configuration, including API keys, retry settings, and timeout presets. It also shows how to access request metadata and close the client connection. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_your_api_key_here", baseUrl: "https://api.banklyze.com", timeout: 30_000, maxRetries: 2, retryBackoff: 500, retryMaxBackoff: 30_000, logger: console, }); console.log(Banklyze.TIMEOUT_READ); console.log(Banklyze.TIMEOUT_WRITE); console.log(Banklyze.TIMEOUT_UPLOAD); console.log(Banklyze.TIMEOUT_REPORT); console.log(client.lastRequestId); client.close(); ``` -------------------------------- ### SDK Configuration Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Initialize the Banklyze client with your API credentials and custom configuration options. ```APIDOC ## Configuration ### Description Initialize the client to interact with the Banklyze API. The client supports custom timeouts, retry policies, and logging. ### Request Example ```typescript const client = new Banklyze({ apiKey: "bk_live_...", baseUrl: "https://api.banklyze.com", timeout: 30000, maxRetries: 2, logger: console }); ``` ``` -------------------------------- ### Configure and Verify Webhooks Source: https://context7.com/thornebridge/banklyze-node/llms.txt Demonstrates how to update webhook configurations, test delivery, list history, and verify incoming webhook signatures using the Banklyze SDK and Express.js. ```typescript import { Banklyze, verifySignature, InvalidSignatureError } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const config = await client.webhooks.updateConfig({ url: "https://your-app.com/webhooks/banklyze", secret: "whsec_your_secret_here", events: ["deal.ready", "document.complete", "document.failed"], }); app.post("/webhooks/banklyze", (req, res) => { try { verifySignature(req.body, req.headers["x-webhook-signature"], "whsec_your_secret_here"); const event = JSON.parse(req.body); res.status(200).send("OK"); } catch (err) { if (err instanceof InvalidSignatureError) { res.status(401).send("Invalid signature"); } } }); ``` -------------------------------- ### Quick Deal Creation with Document Upload - TypeScript Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet illustrates how to create a new deal and upload an associated document in a single API call using the Banklyze SDK. This is useful for rapid onboarding of new clients or deals, streamlining the initial data submission process. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); // Create deal + upload document in one call const result = await client.deals.quickStart({ business_name: "Quick Coffee Shop", file: "./statements/chase_jan_2024.pdf", document_type: "bank_statement", idempotency_key: "quick-start-coffee-001", }); console.log(result.deal_id); // 43 console.log(result.document_id); // 156 console.log(result.status); // "processing" ``` -------------------------------- ### List and Search Deals with Pagination - TypeScript Source: https://context7.com/thornebridge/banklyze-node/llms.txt Demonstrates how to list deals with various filtering, sorting, and pagination parameters. It also shows how to use auto-pagination for iterating through all results seamlessly and how to retrieve aggregate statistics for deals. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); // List deals with filters const response = await client.deals.list({ status: "ready", health_grade: "A", industry: "Transportation", min_funding: 25000, max_funding: 100000, date_from: "2024-01-01", date_to: "2024-12-31", sort: "created_at", order: "desc", page: 1, per_page: 25, }); console.log(response.meta.total); // 156 console.log(response.meta.total_pages); // 7 for (const deal of response.data) { console.log(`${deal.business_name}: ${deal.health_grade} (${deal.avg_monthly_deposits})`); } // Auto-paginate through all matching deals for await (const deal of client.deals.listAll({ status: "ready" })) { console.log(deal.business_name, deal.health_grade, deal.fundability_score); // Automatically fetches next pages as needed } // Get aggregate statistics const stats = await client.deals.stats(); console.log(stats.total); // 1250 console.log(stats.by_status); // { pending: 45, processing: 12, ready: 890, ... } console.log(stats.avg_health); // 72.5 console.log(stats.total_volume); // 62500000 // Get daily stats for trend analysis const daily = await client.deals.dailyStats({ days: 30 }); for (const day of daily.data) { console.log(`${day.date}: ${day.total} deals, ${day.approved} approved, avg score: ${day.avg_score}`); } ``` -------------------------------- ### Manage Deal Notes Source: https://context7.com/thornebridge/banklyze-node/llms.txt Demonstrates how to list existing notes for a deal and add new notes with idempotency keys to ensure reliable operations. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const dealId = 42; const notes = await client.deals.notes(dealId, { per_page: 25 }); const newNote = await client.deals.addNote(dealId, { content: "Spoke with business owner. Confirmed revenue figures.", author: "Jane Analyst", idempotency_key: "note-42-call-jan15" }); ``` -------------------------------- ### Configure Banklyze Client (TypeScript) Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Initializes the Banklyze client with required and optional parameters. This includes setting the API key, base URL, timeouts, retry counts, and a logger for debugging. ```typescript const client = new Banklyze({ apiKey: "bk_live_...", // required baseUrl: "https://api.banklyze.com", // default timeout: 30_000, // default (ms) maxRetries: 2, // default logger: console, // optional debug logging }); ``` -------------------------------- ### Export Deal Data to CSV Source: https://context7.com/thornebridge/banklyze-node/llms.txt Shows how to export deal data as a CSV file using the SDK's export methods and Node.js file system utilities. ```typescript import { Banklyze } from "@banklyze/sdk"; import { writeFileSync } from "node:fs"; const client = new Banklyze({ apiKey: "bk_live_..." }); const csvData = await client.deals.exportCsv({ status: "ready", q: "trucking" }); writeFileSync("deals_export.csv", Buffer.from(csvData)); ``` -------------------------------- ### Record Underwriting Decisions and Evaluate Deals - TypeScript Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet demonstrates how to record underwriting decisions (approve/reject) for a deal and retrieve detailed recommendations including weighted scores, risk tiers, and financial projections. It also shows how to evaluate a deal against multiple custom rulesets for comparative analysis, outputting the decision and score for each ruleset. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const dealId = 42; // Record a final decision await client.deals.decision(dealId, { decision: "approved", idempotency_key: "decision-42-v1", }); // Get detailed recommendation const rec = await client.deals.recommendation(dealId); console.log(rec.decision); // "approved" console.log(rec.weighted_score); // 78.5 console.log(rec.risk_tier); // "moderate" console.log(rec.paper_grade); // "B+" console.log(rec.advance_amount); // 45000 console.log(rec.factor_rate); // 1.35 console.log(rec.holdback_pct); // 15 console.log(rec.est_daily_payment); // 456.75 console.log(rec.est_term_months); // 8 console.log(rec.dscr); // 1.42 console.log(rec.cash_flow_coverage_ratio); // 1.85 console.log(rec.stress_test_passed); // true console.log(rec.risk_factors); // ["Existing MCA positions detected"] console.log(rec.strengths); // ["Strong deposit consistency", "Low NSF history"] // Evaluate against multiple rulesets for comparison const evaluation = await client.deals.evaluate(dealId, { ruleset_ids: [1, 2, 3], }); for (const result of evaluation.results) { console.log(`Ruleset ${result.ruleset_name}: ${result.decision} (score: ${result.weighted_score})`); } ``` -------------------------------- ### POST /deals Source: https://context7.com/thornebridge/banklyze-node/llms.txt Creates a new underwriting deal with business and owner details, supporting idempotency keys for safe retries. ```APIDOC ## POST /deals ### Description Creates a new deal record within the Banklyze platform. This endpoint accepts business information, owner details, and financial metrics to initiate the underwriting process. ### Method POST ### Endpoint /deals ### Parameters #### Request Body - **business_name** (string) - Required - Legal name of the business - **dba_name** (string) - Optional - Doing Business As name - **owner_name** (string) - Required - Full name of the primary owner - **industry** (string) - Required - Business industry sector - **funding_amount_requested** (number) - Required - Requested MCA amount - **idempotency_key** (string) - Optional - Unique key to prevent duplicate requests ### Request Example { "business_name": "Acme Trucking LLC", "owner_name": "John Smith", "funding_amount_requested": 50000, "idempotency_key": "unique-request-id-123" } ### Response #### Success Response (200) - **id** (number) - Unique identifier for the created deal - **status** (string) - Current status of the deal (e.g., "pending") #### Response Example { "id": 42, "business_name": "Acme Trucking LLC", "status": "pending" } ``` -------------------------------- ### Accessing Deal Sub-Resources (TypeScript) Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Demonstrates how to interact with sub-resources associated with a deal, such as comments, assignments, document requests, timeline, and user searches. These operations are crucial for managing deal workflows and team collaboration. ```typescript client.deals.comments.list(dealId); client.deals.assignments.create(dealId); client.deals.docRequests.create(dealId); client.deals.timeline.list(dealId); client.deals.users.search({ q: "jane" }); ``` -------------------------------- ### Retrieve Typed Deal Data with TypeScript Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Demonstrates how to fetch deal details using the client SDK. The response is fully typed, providing IDE autocompletion for health scores, recommendations, and financial metrics. ```typescript const detail = await client.deals.get(dealId); // IDE knows every field, every nested object, every type detail.health.health_score; // number detail.health.health_grade; // string detail.recommendation.decision; // "approved" | "conditional" | "declined" detail.recommendation.risk_factors; // string[] detail.recommendation.strengths; // string[] detail.financials.avg_monthly_deposits; // number detail.mca?.mca_credit_score; // number | undefined // 12 health sub-factors, individually scored and weighted for (const [name, factor] of Object.entries(detail.health.factors)) { console.log(`${name}: ${factor.score}/${factor.max} (weight: ${factor.weight})`); } ``` -------------------------------- ### Process Documents with Built-in Intelligence Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Shows how to retrieve structured intelligence from documents. Includes pre-screening, tamper detection, and confidence scoring without requiring manual OCR or LLM prompt tuning. ```typescript const doc = await client.documents.get(docId); // Pre-screen (regex-based, instant, no LLM cost) doc.prescreen.bank_name; // "Chase" doc.prescreen.opening_balance; // 15420.00 doc.prescreen.viable; // true doc.prescreen.confidence; // 0.95 // Tamper detection doc.integrity.tampering_risk_level; // "clean" | "low" | "medium" | "high" doc.integrity.tampering_flags; // string[] // Extraction confidence scoring doc.extraction_confidence_detail.overall_confidence; // 0.94 doc.extraction_confidence_detail.overall_tier; // "HIGH" // Cross-document validation doc.analysis.validation_is_reliable; // true doc.analysis.validation_discrepancies; // ValidationDiscrepancy[] ``` -------------------------------- ### Upload Bank Statements and Financial Documents - TypeScript Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet shows how to upload various financial documents, such as bank statements, tax returns, or P&L statements, to a specific deal using the Banklyze SDK. It supports uploading from file paths, Node.js Buffers, and demonstrates both single and bulk upload functionalities. ```typescript import { Banklyze } from "@banklyze/sdk"; import { readFileSync } from "node:fs"; const client = new Banklyze({ apiKey: "bk_live_..." }); const dealId = 42; // Upload from file path const doc1 = await client.documents.upload(dealId, "./statements/chase_jan.pdf", { documentType: "bank_statement", idempotencyKey: "upload-chase-jan", }); console.log(doc1.id); // 101 console.log(doc1.status); // "queued" // Upload from Buffer const buffer = readFileSync("./statements/chase_feb.pdf"); const doc2 = await client.documents.upload(dealId, buffer, { filename: "chase_feb.pdf", documentType: "bank_statement", }); // Bulk upload multiple files const bulkResult = await client.documents.uploadBulk( dealId, [ "./statements/march.pdf", "./statements/april.pdf", "./statements/may.pdf", ], { documentType: "bank_statement" }, ); console.log(bulkResult.total); // 3 console.log(bulkResult.queued); // 3 console.log(bulkResult.failed); // 0 for (const result of bulkResult.results) { console.log(`${result.filename}: ${result.status} (ID: ${result.document_id})`); } ``` -------------------------------- ### Perform Instant Document Analysis Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Processes a PDF file instantly without requiring an account or data persistence. Returns summary metrics and per-file breakdowns. ```typescript const result = await client.instant.analyze("./statement.pdf"); console.log(result.summary.total_deposits); // 284500.00 console.log(result.summary.total_mca_positions); // 3 console.log(result.summary.avg_revenue_quality); // 0.82 // Per-file breakdown for (const file of result.results) { console.log(file.bank_name, file.nsf_count, file.mca_daily_obligation); } ``` -------------------------------- ### Manage Rulesets with Node.js SDK Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet shows how to manage underwriting rulesets using the Banklyze Node.js SDK. It includes operations for listing all rulesets, creating new ones with specific criteria, updating existing rulesets, setting a default ruleset, and deleting unused ones. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); // List all rulesets const rulesets = await client.rulesets.list(); for (const rs of rulesets.data) { console.log(`${rs.name} (v${rs.version}): ${rs.is_default ? "DEFAULT" : ""}`); } // Create a new ruleset const newRuleset = await client.rulesets.create({ name: "Conservative MCA Criteria", description: "Stricter requirements for high-risk industries", criteria: { min_health_score: 70, min_avg_daily_balance: 5000, max_nsf_count: 2, max_mca_positions: 2, min_months_in_business: 24, required_deposit_consistency: 0.8, }, }); console.log(newRuleset.id); // 5 console.log(newRuleset.version); // 1 // Update ruleset criteria const updated = await client.rulesets.update(5, { criteria: { min_health_score: 75, max_nsf_count: 1, }, }); console.log(updated.version); // 2 // Set as default for all new evaluations await client.rulesets.setDefault(5); // Delete an unused ruleset await client.rulesets.delete(3); ``` -------------------------------- ### Stream Real-time Events with Node.js SDK Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet demonstrates how to subscribe to real-time Server-Sent Events (SSE) streams provided by the Banklyze Node.js SDK. It covers streaming events for a specific deal with filtering and resumption, streaming all organization events, and monitoring batch processing progress. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); // Stream events for a specific deal for await (const event of client.events.stream(42)) { console.log(`[${event.id}] ${event.event}: ${event.data}`); switch (event.event) { case "stage": console.log(`Processing stage: ${event.data}`); // "extracting_text" → "parsing" → "screening" → "scoring" break; case "progress": console.log(`Progress: ${event.data}%`); break; case "document_complete": console.log(`Document finished: ${event.data}`); break; case "complete": console.log("Deal analysis complete!"); break; case "error": console.error(`Error: ${event.data}`); break; } } // Stream with filters and resumption for await (const event of client.events.stream(42, { documentId: 101, // Filter to specific document lastEventId: 500, // Resume from event ID })) { console.log(event.event, event.data); } // Stream all organization events for await (const event of client.events.streamOrg()) { console.log(`Org event: ${event.event} - ${event.data}`); } // Stream batch processing progress for await (const event of client.events.streamBatch("batch_abc123")) { console.log(`Batch progress: ${event.data}`); } ``` -------------------------------- ### Retrieve and Update Deal Details - TypeScript Source: https://context7.com/thornebridge/banklyze-node/llms.txt Fetches comprehensive deal details, including all analysis sections, and demonstrates how to update existing deal information. It utilizes the Banklyze SDK to interact with the API, providing access to structured data like financial, health, and recommendation insights. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const dealId = 42; // Get full deal detail with all analysis const detail = await client.deals.get(dealId); // Access structured analysis data console.log(detail.business.business_name); // "Acme Trucking LLC" console.log(detail.financials.avg_monthly_deposits); // 82500.00 console.log(detail.financials.avg_daily_balance); // 15420.00 console.log(detail.health.health_score); // 78 console.log(detail.health.health_grade); // "B+" console.log(detail.recommendation?.decision); // "approved" console.log(detail.recommendation?.risk_factors); // ["High MCA stacking"] console.log(detail.recommendation?.strengths); // ["Strong deposit consistency"] console.log(detail.recommendation?.advance_amount); // 45000 console.log(detail.mca?.positions_detected); // 2 console.log(detail.mca?.total_daily_obligation); // 850.00 console.log(detail.mca?.mca_credit_score); // 72 // Access 12-factor health scoring breakdown if (detail.health.factors) { for (const [name, factor] of Object.entries(detail.health.factors)) { console.log(`${name}: ${factor.score}/${factor.max} (weight: ${factor.weight})`); // revenue: 18/20 (weight: 0.15) // adb_stability: 14/15 (weight: 0.12) // nsf_cleanliness: 10/10 (weight: 0.10) } } // Update deal information const updated = await client.deals.update(dealId, { funding_amount_requested: 60000, notes: "Customer requested higher amount after review", owner_credit_score: 695, }); ``` -------------------------------- ### Manage Bank Transactions with Node.js SDK Source: https://context7.com/thornebridge/banklyze-node/llms.txt This snippet demonstrates how to list, paginate, correct, and view the history of transactions using the Banklyze Node.js SDK. It covers filtering transactions by document, auto-pagination for deals, and correcting misclassified entries. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); // List transactions for a document const docTxns = await client.transactions.listForDocument(101, { type: "deposit", flagged: true, start_date: "2024-01-01", end_date: "2024-01-31", page: 1, per_page: 50, }); for (const txn of docTxns.data) { console.log(`${txn.date}: ${txn.description} - $${txn.amount} (${txn.type})`); } // Auto-paginate through all transactions for a deal for await (const txn of client.transactions.listAllForDeal(42)) { if (txn.flagged) { console.log(`Flagged: ${txn.description} - $${txn.amount}`); } } // Correct a misclassified transaction const corrected = await client.transactions.correct(101, 5001, { type: "operating_expense", description: "Monthly rent payment", flagged: false, }); // View correction history const history = await client.transactions.corrections(5001); for (const correction of history.data) { console.log(`${correction.changed_at}: ${correction.field} changed from "${correction.old_value}" to "${correction.new_value}"`); } ``` -------------------------------- ### Retry & Error Handling Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Details on how the SDK handles network failures, rate limits, and server errors. ```APIDOC ## Retry Behavior ### Description The SDK implements exponential backoff with jitter. It honors the `Retry-After` header. ### Retry Logic | Method | Rate limit (429) | Server error (5xx) | Connection error | |--------|:---:|:---:|:---:| | GET / DELETE | Retry | Retry | Retry | | POST / PUT / PATCH | - | - | Retry | ### Request Tracking Every request is assigned a UUID. Errors include this ID, and it is accessible via `client.lastRequestId`. ``` -------------------------------- ### Iterate Records with Auto-pagination Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Simplifies data retrieval by using an async iterator to fetch and traverse thousands of records automatically. ```typescript for await (const deal of client.deals.listAll({ status: "ready" })) { console.log(deal.business_name, deal.health_grade); } ``` -------------------------------- ### Deals Resource Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Endpoints for managing deals, including CRUD operations, analytics, and sub-resources like comments and assignments. ```APIDOC ## [GET/POST] /deals ### Description Manage deal lifecycles, including evaluation, analytics, and batch processing. ### Sub-resources - **client.deals.comments.list(dealId)**: Retrieve threaded discussions for a deal. - **client.deals.assignments.create(dealId)**: Assign reviewers to a specific deal. - **client.deals.docRequests.create(dealId)**: Request missing documentation. - **client.deals.timeline.list(dealId)**: Fetch full activity history. - **client.deals.users.search({ q: "name" })**: Search team members. ### Response #### Success Response (200) - **data** (object) - The requested deal resource or list of resources. ``` -------------------------------- ### Verify Webhook Signatures Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Provides a secure method to verify incoming webhook signatures using HMAC-SHA256 with constant-time comparison to prevent timing attacks. ```typescript import { verifySignature } from "@banklyze/sdk/webhooks"; // HMAC-SHA256 with constant-time comparison. Timing attacks don't apply. verifySignature(requestBody, headers["x-webhook-signature"], "whsec_..."); ``` -------------------------------- ### Events API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Subscribe to real-time Server-Sent Events (SSE) for deal processing updates and system notifications. ```APIDOC ## GET /events/stream/{dealId} ### Description Establish a real-time stream for a specific deal to monitor processing stages and progress. ### Method GET ### Endpoint /events/stream/{dealId} ### Parameters #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to monitor. #### Query Parameters - **documentId** (integer) - Optional - Filter stream to a specific document. - **lastEventId** (integer) - Optional - Resume stream from a specific event ID. ``` -------------------------------- ### Deals - Decision and Evaluation API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Record underwriting decisions and evaluate deals against custom rulesets for comparative analysis. ```APIDOC ## Deals - Decision and Evaluation Record underwriting decisions and evaluate deals against custom rulesets for comparative analysis. ### POST /deals/:dealId/decision **Description**: Records a final underwriting decision for a specific deal. **Method**: POST **Endpoint**: `/deals/:dealId/decision` **Parameters** #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to record a decision for. #### Request Body - **decision** (string) - Required - The final decision (e.g., "approved", "declined"). - **idempotency_key** (string) - Required - A unique key to ensure the request is processed only once. ### POST /deals/:dealId/recommendation **Description**: Retrieves a detailed underwriting recommendation for a specific deal. **Method**: POST **Endpoint**: `/deals/:dealId/recommendation` **Parameters** #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to get a recommendation for. #### Response ##### Success Response (200) - **decision** (string) - The recommended decision. - **weighted_score** (number) - The calculated weighted score. - **risk_tier** (string) - The assessed risk tier. - **paper_grade** (string) - The assessed paper grade. - **advance_amount** (number) - The recommended advance amount. - **factor_rate** (number) - The recommended factor rate. - **holdback_pct** (number) - The recommended holdback percentage. - **est_daily_payment** (number) - The estimated daily payment. - **est_term_months** (number) - The estimated term in months. - **dscr** (number) - The Debt Service Coverage Ratio. - **cash_flow_coverage_ratio** (number) - The cash flow coverage ratio. - **stress_test_passed** (boolean) - Indicates if the stress test was passed. - **risk_factors** (array of strings) - A list of identified risk factors. - **strengths** (array of strings) - A list of identified strengths. ### POST /deals/:dealId/evaluate **Description**: Evaluates a deal against multiple specified rulesets for comparative analysis. **Method**: POST **Endpoint**: `/deals/:dealId/evaluate` **Parameters** #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to evaluate. #### Request Body - **ruleset_ids** (array of integers) - Required - A list of ruleset IDs to evaluate the deal against. #### Response ##### Success Response (200) - **results** (array of objects) - A list of evaluation results for each ruleset. - **ruleset_name** (string) - The name of the ruleset. - **decision** (string) - The decision made by the ruleset. - **weighted_score** (number) - The weighted score from the ruleset. ``` -------------------------------- ### Manage Deal Collaboration and Timeline Source: https://context7.com/thornebridge/banklyze-node/llms.txt Covers managing threaded comments, team assignments, document requests, and retrieving activity timelines for specific deals or the entire organization. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const dealId = 42; const comments = await client.deals.comments.list(dealId); const newComment = await client.deals.comments.create(dealId, { content: "Reviewed financials", parent_id: comments.data[0]?.id }); const docRequest = await client.deals.docRequests.create(dealId, { document_type: "bank_statement", description: "Please provide February 2024 statement", recipient_email: "john@acmetrucking.com", due_date: "2024-03-15" }); const timeline = await client.deals.timeline.dealTimeline(dealId, { per_page: 50 }); ``` -------------------------------- ### Retrieve Document Details and Analysis Source: https://context7.com/thornebridge/banklyze-node/llms.txt Fetches comprehensive document data including pre-screen results, tamper detection, extraction confidence, and full financial analysis. It also demonstrates how to check the processing status of a document. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const documentId = 101; const doc = await client.documents.get(documentId); console.log(doc.filename); console.log(doc.analysis?.health_score); const status = await client.documents.status(documentId); console.log(status.status); ``` -------------------------------- ### Handle Typed API Errors Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Demonstrates how to catch and handle specific error classes provided by the SDK, allowing for precise debugging and support correlation via request IDs. ```typescript import { NotFoundError, RateLimitError, ValidationError } from "@banklyze/sdk"; try { await client.deals.get(dealId); } catch (err) { if (err instanceof NotFoundError) { // err.statusCode === 404 } else if (err instanceof RateLimitError) { // err.retryAfter — seconds until you can retry } else if (err instanceof ValidationError) { // err.body — full validation error details } // Every error has err.requestId for instant support correlation } ``` -------------------------------- ### Stream Pipeline Events in Real-time Source: https://github.com/thornebridge/banklyze-node/blob/main/README.md Utilizes an async iterator to watch document processing stages in real-time, eliminating the need for polling. ```typescript for await (const event of client.events.stream(dealId)) { switch (event.event) { case "stage": console.log(`Stage: ${event.data}`); // "extracting_text" → "parsing" → "screening" → "scoring" break; case "complete": console.log("Analysis complete"); break; } } ``` -------------------------------- ### Manage Organization Team Members Source: https://context7.com/thornebridge/banklyze-node/llms.txt Provides methods to list team members, invite new users, update existing roles, and deactivate team accounts. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const team = await client.team.list(); const invite = await client.team.invite({ email: "new.analyst@company.com", role: "analyst", display_name: "New Analyst" }); await client.team.update(15, { role: "underwriter" }); await client.team.deactivate(15); ``` -------------------------------- ### Perform Instant Document Analysis Source: https://context7.com/thornebridge/banklyze-node/llms.txt Executes rapid, non-persistent analysis of PDF documents suitable for demos or pre-qualification. Includes methods for submitting feedback on the analysis results. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const result = await client.instant.analyze("./statement.pdf", { visionFallback: true }); console.log(result.session_id); await client.instant.submitFeedback({ sessionId: result.session_id, filename: "statement.pdf", rating: "accurate" }); ``` -------------------------------- ### Documents - Upload API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Upload bank statements, tax returns, or P&L documents to a deal. Supports file paths, Buffers, and Blobs. ```APIDOC ## Documents - Upload Upload bank statements, tax returns, or P&L documents to a deal. Supports file paths, Buffers, and Blobs. ### POST /deals/:dealId/documents **Description**: Uploads a single document to a specified deal. **Method**: POST **Endpoint**: `/deals/:dealId/documents` **Parameters** #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to which the document will be uploaded. #### Request Body - **file** (string | Buffer | Blob) - Required - The document file content (can be a file path, Buffer, or Blob). - **documentType** (string) - Required - The type of the document (e.g., "bank_statement", "tax_return"). - **filename** (string) - Optional - The name of the file, required when uploading from Buffer or Blob. - **idempotencyKey** (string) - Optional - A unique key to ensure the request is processed only once. #### Response ##### Success Response (200) - **id** (integer) - The ID of the uploaded document. - **status** (string) - The status of the document upload (e.g., "queued"). ### POST /deals/:dealId/documents/bulk **Description**: Uploads multiple documents to a specified deal in a single request. **Method**: POST **Endpoint**: `/deals/:dealId/documents/bulk` **Parameters** #### Path Parameters - **dealId** (integer) - Required - The ID of the deal to which the documents will be uploaded. #### Request Body - **files** (array of strings | Buffers | Blobs) - Required - An array of document file contents. - **documentType** (string) - Required - The type of the documents (e.g., "bank_statement"). - **filenames** (array of strings) - Optional - An array of filenames corresponding to the files, required when uploading from Buffer or Blob. #### Response ##### Success Response (200) - **total** (integer) - The total number of files attempted to upload. - **queued** (integer) - The number of files successfully queued for processing. - **failed** (integer) - The number of files that failed to upload. - **results** (array of objects) - Details for each uploaded document. - **filename** (string) - The name of the file. - **status** (string) - The status of the document upload. - **document_id** (integer) - The ID of the uploaded document. ``` -------------------------------- ### Rulesets API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Manage versioned underwriting criteria to ensure consistent and auditable decision-making. ```APIDOC ## POST /rulesets ### Description Create a new versioned ruleset for underwriting evaluations. ### Method POST ### Endpoint /rulesets ### Request Body - **name** (string) - Required - Name of the ruleset. - **description** (string) - Optional - Purpose of the ruleset. - **criteria** (object) - Required - Key-value pairs defining underwriting thresholds. ## PUT /rulesets/{id} ### Description Update the criteria of an existing ruleset, which increments the version. ### Method PUT ### Endpoint /rulesets/{id} ### Request Body - **criteria** (object) - Required - Updated criteria thresholds. ``` -------------------------------- ### Implement Auto-Pagination for Large Datasets Source: https://context7.com/thornebridge/banklyze-node/llms.txt Uses the PageIterator pattern to fetch and iterate through large collections of deals, documents, or transactions without manual page management. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); for await (const deal of client.deals.listAll({ status: "ready", health_grade: "A" })) { console.log(`${deal.business_name}: ${deal.health_score}`); } ``` -------------------------------- ### Triage, Classify, and Reprocess Documents Source: https://context7.com/thornebridge/banklyze-node/llms.txt Provides methods to perform initial document triage for classification and quality assessment, reclassify existing documents, and reprocess failed uploads. ```typescript import { Banklyze } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); const triage = await client.documents.triage("./unknown_document.pdf", { visionFallback: true }); const reclassified = await client.documents.reclassify(101, "tax_return"); const reprocessed = await client.documents.reprocess(101); const statuses = await client.documents.batchStatus([101, 102, 103]); ``` -------------------------------- ### Handle API Errors with Typed Exceptions Source: https://context7.com/thornebridge/banklyze-node/llms.txt Demonstrates how to catch and handle specific API error types such as AuthenticationError, NotFoundError, and RateLimitError. Each error includes a requestId for debugging purposes. ```typescript import { Banklyze, BanklyzeError, AuthenticationError, NotFoundError, ValidationError, RateLimitError } from "@banklyze/sdk"; const client = new Banklyze({ apiKey: "bk_live_..." }); try { const deal = await client.deals.get(99999); } catch (err) { if (err instanceof AuthenticationError) { console.error("Auth failed:", err.message); } else if (err instanceof NotFoundError) { console.error("Deal not found:", err.message); } else if (err instanceof ValidationError) { console.error("Validation error:", err.message); } else if (err instanceof RateLimitError) { console.error("Rate limited. Retry after:", err.retryAfter, "seconds"); } else if (err instanceof BanklyzeError) { console.error(`API Error ${err.statusCode}:`, err.message); } else { throw err; } } ``` -------------------------------- ### Transactions API Source: https://context7.com/thornebridge/banklyze-node/llms.txt Endpoints for listing, filtering, and correcting financial transactions associated with documents or deals. ```APIDOC ## GET /transactions/document/{docId} ### Description Retrieve a paginated list of transactions for a specific document with optional filtering. ### Method GET ### Endpoint /transactions/document/{docId} ### Parameters #### Path Parameters - **docId** (integer) - Required - The ID of the document. #### Query Parameters - **type** (string) - Optional - Filter by transaction type (e.g., deposit). - **flagged** (boolean) - Optional - Filter by flagged status. - **start_date** (string) - Optional - ISO date string. - **end_date** (string) - Optional - ISO date string. ### Response #### Success Response (200) - **data** (array) - List of transaction objects. ## POST /transactions/{docId}/{txnId}/correct ### Description Correct a misclassified transaction and update its metadata. ### Method POST ### Endpoint /transactions/{docId}/{txnId}/correct ### Request Body - **type** (string) - Optional - New transaction type. - **description** (string) - Optional - Updated description. - **flagged** (boolean) - Optional - Updated flagged status. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.