DEV Community

Cover image for Cashflow Insights — AI-Enhanced Backend with Xano
shourya soneji
shourya soneji

Posted on

Cashflow Insights — AI-Enhanced Backend with Xano

Xano AI-Powered Backend Challenge: Public API Submission

This is a submission for the Xano AI-Powered Backend Challenge: Production-Ready Public API

What I Built

Late payments and unpredictable cash inflows are among the biggest operational risks for small and mid-sized businesses. While most accounting tools record invoices and payments, they rarely provide actionable insight into when cash will actually arrive, which customers pose the highest risk, or what actions a business should take next. As a result, finance teams often rely on spreadsheets, static reports, or intuition to manage cashflow — leading to delayed collections and liquidity stress.

This project addresses that gap by providing a production-ready Cashflow Intelligence API built on Xano, designed to sit on top of raw invoice data and transform it into clear financial signals. The API aggregates receivables, analyzes payment behavior, identifies high-risk customers, and generates plain-language insights that explain not just what is happening, but why.

At its core, the API solves three key problems:

  1. Lack of visibility — Businesses struggle to understand how much of their receivables are genuinely collectible versus overdue and risky.

  2. Delayed risk detection — High-risk customers are often identified too late, after invoices become severely overdue.

  3. Data without guidance — Numeric reports alone don’t tell teams what actions to prioritize.

To solve these, the API exposes endpoints that:

  • Compute receivables aging and overdue exposure.
  • Forecast near-term cash inflows based on real outstanding balances.
  • Rank customers by payment risk using behavioral signals.
  • Produce AI-generated explanations and recommendations that translate financial data into operational guidance.

Built entirely in Xano, this backend emphasizes correctness, clarity, and real-world usability. It handles edge cases (such as missing data), avoids misleading parameters, and exposes a clean API contract suitable for dashboards, finance tools, or integrations. The result is a backend service that turns fragmented invoice data into actionable cashflow intelligence, helping businesses focus their efforts where it matters most.

API Documentation

Base URL

https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN

Authentication
All endpoints require API key authentication:

#Sign up to create account in /signup endpoint
{
"business_name":"example name"
}
#this will generate an API key that the user will use to access each endpoint.
#Example key: ec49f7f0-089b-47f8-9f74-b81e6e474fba
Enter fullscreen mode Exit fullscreen mode

Endpoint 1: POST /insert_invoice_data

Used to enter invoice data

Request:

curl -X 'POST' \
'https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN/insert_invoice_data' \
-H 'Content-Type: application/json' \
-H 'x-api-key: 10ebbb4b-a128-479b-b7b9-550d79bcf7cd' \
--data '{
  "invoice_amount": 250,
  "due_date": "2025-12-23",
  "invoice_date": "2025-12-13",
  "status": "unpaid",
  "paid_date": null,
  "customer_name": "Example_name",
  "Currency": "dollars",
  "invoice_number": "1"
}'

Enter fullscreen mode Exit fullscreen mode

Result:

{
message: Invoice created successfully,
invoice: {
id: 411,
created_at: 1765656533022,
invoice_date: 2025-12-13,
customer_name: Example_name,
business_id: 6,
due_date: 2025-12-23,
amount: 250,
status: unpaid,
paid_date: null,
currency: dollars,
invoice_number: 1}
}
Enter fullscreen mode Exit fullscreen mode

Endpoint 2: GET /receivables_analytics

Used to analyze data for user's business, and generate DSO, ageing buckets and overdue percentage.

Request:
curl -X 'GET' \
'https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN/insert_invoice_data' \
-H 'Content-Type: application/json' \
-H 'x-api-key: ec49f7f0-089b-47f8-9f74-b81e6e474fba'
Enter fullscreen mode Exit fullscreen mode

Result:

{
response: {
days_sales_outstanding: 167.75147928994087,
ageing: {
0_30: 78.2,
31_60: 183.25,
61_90: 0,
90_plus: 0},
overdue: 70.08988334289538}
}
Enter fullscreen mode Exit fullscreen mode

Endpoint 3: POST /cashflow_forecast

Used to forecast user's business cashflow based on invoice data.

Request:

curl -X 'POST' \
'https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN/cashflow_forecast' \
-H 'Content-Type: application/json' \
-H 'x-api-key: 89d9f509-573e-4ff8-94c7-2457832483ca'
Enter fullscreen mode Exit fullscreen mode

Result:

{
forecast: {
expected_inflows: {
0_30_days: 234.36999999999998,
31_60_days: 0,
61_90_days: 0},
assumptions: {
average_delay_days: 26}
}
}
Enter fullscreen mode Exit fullscreen mode

Endpoint 4: POST /calculate_risk_score

Used to do a risk analysis for any given customer of the user's business. Each customer is assigned a score based on payment history. It also has an AI notes parameter which can either be set to 0 (no AI note needed, returns null) or 1 (returns a risk analysis in plain language powered by Google's Gemini).

Request:

curl -X 'POST' \
'https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN/calculate_risk_score' \
-H 'Content-Type: application/json' \
-H 'x-api-key: 89d9f509-573e-4ff8-94c7-2457832483ca' \
--data '{
  "ai_notes": 1,
  "customer_name": "Judith Morales"
}'
Enter fullscreen mode Exit fullscreen mode

Result:

{
risk_data: {
customer_name: Judith Morales,
score: 31,
risk_level: High,
late_payment_probability: 1},
ai_note: Despite a low percentage of late invoices and no significant long-term overdues, the "High" risk level is primarily driven by the substantial average payment delay of 49 days. This indicates consistent cash flow inefficiencies or slow internal payment processes for the customer, impacting your working capital. We recommend shortening payment terms or requiring partial upfront payments to mitigate exposure and improve cash conversion.}
Enter fullscreen mode Exit fullscreen mode

Endpoint 5: POST /business_dashboard

Used to combine all endpoints (invoice data analysis, forecast data, customer risk analysis) and return the top 5 most risky customers, along with an AI summary of the user's business' cashflow.

Request:

curl -X 'POST' \
'https://xbty-lwqs-omi0.m2.xano.io/api:HiJHfYhN/business_dashboard' \
-H 'Content-Type: application/json' \
-H 'x-api-key: ec49f7f0-089b-47f8-9f74-b81e6e474fba'
Enter fullscreen mode Exit fullscreen mode

Result:

{
stats: {
dso: 167.75147928994087,
overdue_percent: 70.08988334289538,
total_ar_0_30: 78.2,
total_ar_31_60: 183.25,
total_ar_61_90: 0,
total_ar_90_plus: 0,
forecast_0_30: 261.45000000000005,
forecast_31_60: 0,
forecast_61_90: 0},
risky_customers: {
itemsReceived: 5,
items: [
{
customer_name: Sue Grant,
score: 20,
risk_level: High,
late_payment_probability: 1},
{
customer_name: Philip Herrera,
score: 23,
risk_level: High,
late_payment_probability: 1},
{
customer_name: Elsie Dunn,
score: 56,
risk_level: Medium,
late_payment_probability: 1},
{
customer_name: Katie Weaver,
score: 100,
risk_level: Low,
late_payment_probability: 0},
{
customer_name: Terry Ortiz,
score: 100,
risk_level: Low,
late_payment_probability: 0}]},
summary: Your accounts receivable health is concerning. Your Days Sales Outstanding (DSO) is very high at 168 days, indicating very slow collections. An alarming 70% of your current receivables are overdue, with a significant amount ($183.25) already 31-60 days past due. While you forecast $261.45 in cash inflows for the next 30 days, there are no significant inflows projected beyond that for the 31-90 day period. This gap is critical, especially considering the large existing overdue balance from 31-60 days. High-risk customers like Sue Grant, Philip Herrera, and Elsie Dunn are very likely to cause payment delays, directly impacting your recovery of these older balances. To improve this, I recommend: 1. **Aggressive Collections**: Immediately target the $183.25 in 31-60 day overdue receivables, prioritizing collection from high-risk customers like Sue Grant and Philip Herrera. 2. **Proactive Follow-up**: Strengthen your pre-due date and early overdue follow-up process for all customers to prevent future invoices from aging. 3. **Credit Policy Review**: Consider tighter credit terms or upfront payments for new customers or those with a history of late payments.}
Enter fullscreen mode Exit fullscreen mode

Demo

Example 1:-Calling the /calculate_risk_score for an invalid customer-

Demonstrates working customer matching.

Example 2:-Using the /business_dashboard endpoint to check the state of a user's business cashflow-

Note on authentication format
During development and early testing, the API key was passed in the request body to simplify debugging and demonstration.
In the final production design, the API is intended to accept the API key via the x-api-key request header, which ensures better security and aligns with standard API practices.
The backend logic already derives the business context exclusively from the API key, regardless of transport method.

The AI Prompt I Used

Following the the original AI prompts I used to build the various endpoints-

Database Schema generation prompt:-

Create a production-ready backend schema for a cashflow analytics platform.

Entities:
- Business
- Customer
- Invoice
- Risk Score
- API Key

Relationships:
- A Business has many Customers
- A Customer has many Invoices
- A Customer has one Risk Score
- A Business has one or more API Keys

Invoice fields must support:
- Due date tracking
- Partial payments
- Overdue calculations
- Currency handling

Include timestamps and proper foreign key constraints.
Enter fullscreen mode Exit fullscreen mode

Endpoint 1:- /receivables_analytics
Prompt:-

Build an API endpoint that calculates receivables analytics for a business.

Inputs:
- business_id

Logic:
- Fetch all unpaid or partially paid invoices for the business
- Calculate total accounts receivable (AR)
- Calculate Days Sales Outstanding (DSO) using:
  DSO = (Total AR / Total credit sales in last 90 days) * 90
- Group outstanding invoices into ageing buckets:
  - 0–30 days
  - 31–60 days
  - 61–90 days
  - 90+ days
- Calculate overdue percentage

Output:
{
  dso,
  ageing: {
    "0_30",
    "31_60",
    "61_90",
    "90_plus"
  },
  overdue_percent
}

Handle null dates safely and prevent numeric calculation errors.
Enter fullscreen mode Exit fullscreen mode

Endpoint 2:- /cashflow_forecast
Prompt:-

Build a cashflow forecasting endpoint.

Inputs:
- business_id
- forecast_days (default 90)

Logic:
- Fetch unpaid or partially paid invoices
- Estimate expected payment date using average delay
- Bucket expected inflows into:
  - 0–30 days
  - 31–60 days
  - 61–90 days

Output:
{
  expected_inflows: {
    "0_30_days",
    "31_60_days",
    "61_90_days"
  },
  assumptions: {
    forecast_period_days,
    average_delay_days
  }
}

Ensure null-safe calculations and numeric stability.
Enter fullscreen mode Exit fullscreen mode

Endpoint 3:- /calculate_risk_score
Prompt:-

Create an API endpoint to calculate and persist a customer credit risk score.

Inputs:
- customer_id

Metrics:
- Average payment delay (paid_date - due_date)
- Percentage of late-paid invoices
- Count of invoices overdue more than 90 days
- Amount overdue more than 60 days

Scoring:
- Start score at 100
- Subtract points based on delay, overdue invoices, and overdue amounts
- Clamp score between 0 and 100

Risk levels:
- 0–30: High
- 31–70: Medium
- 71–100: Low

Persist results in the risk_score table with timestamps.
Return the latest saved risk score.
Enter fullscreen mode Exit fullscreen mode

Endpoint 4:- /business_dashboard
Prompt:-

Create a consolidated business insights endpoint.

Steps:
1. Call receivables analytics endpoint
2. Call cashflow forecast endpoint
3. Retrieve top 5 high-risk customers by AR
4. Aggregate all metrics into a single key_stats object
5. Generate a concise AI-powered business summary

Output:
{
  key_stats: {
    dso,
    overdue_percent,
    ageing buckets,
    forecast buckets
  },
  high_risk_customers,
  business_summary_text
}
Enter fullscreen mode Exit fullscreen mode

Risk Analysis agent prompt:-

You are an experienced credit risk analyst.

Given this data:
- Average payment delay in days: {{$args.avg_delay}}
- Percentage of late invoices: {{$args.late_invoice_percent}}
- Number of invoices overdue more than 90 days: {{$args.overdue_90_count}}
- Total amount overdue more than 60 days: {{$args.overdue_60_amount}}
- Final risk level: {{$args.risk_level}}

Write a short professional explanation (3 sentences) describing:
1. Why this customer has this risk level
2. What the main issues are
3. One or two practical recommendations.
Enter fullscreen mode Exit fullscreen mode

Business summary prompt:-

You are a virtual CFO.

You will be given structured JSON with:
- key_stats: containing DSO, overdue_percent, ageing totals, and forecast inflows.
- high_risk_customers: list of customers with fields name, score, risk_level, late_payment_probability.

Using this, write a concise business insight summary (1–3 short paragraphs) that explains:
1. Overall receivables health (DSO, overdue %, ageing).
2. Short-term cashflow outlook (0-30, 31-60, 61-90 days forecast).
3. Which customers are most risky and why.
4. 2–3 practical recommendations (e.g. focus collections on specific customers, adjust credit terms, improve follow-ups).

Keep it non-technical and business-friendly. Refer to customers by name from the high_risk_customers list when helpful.

The structured data is:

key_stats = {{ $args.key_stats }}
high_risk_customers = {{ $args.high_risk_customers }}
Enter fullscreen mode Exit fullscreen mode

How I Refined the AI-Generated Code

While Xano’s AI helped bootstrap the backend quickly, I made several deliberate architectural refinements to make the API more practical, secure, and easier to adopt by third-party systems.

1. Removed the Dedicated Customers Table

Original AI approach:-

The AI initially modeled Customer as a first-class entity with its own table. All downstream analytics referenced customer_id.

Refinement:-

I removed the customers table entirely. Customers are now identified directly by customer_name within invoices and risk records.

Why this change matters:-

Most accounting and ERP systems do not maintain stable customer IDs across integrations. Customer names are the only reliable shared identifier when ingesting external invoice data. This significantly reduces integration friction for third-party apps.

Result:-

Third-party systems can push invoice data without performing a prior customer-sync step. The backend automatically aggregates analytics per customer name.

2. Replaced business_id with x-api-key as the Primary Context

Original AI approach:-

Endpoints required an explicit business_id parameter. This created unnecessary exposure of internal identifiers.

Refinement:-

I removed business_id from all public endpoints. The business context is now derived entirely from the x-api-key header.

Why this change matters:-

Prevents clients from spoofing or guessing business identifiers. Enforces strict tenant isolation at the API layer. Aligns with industry-standard SaaS API security practices.

Result:-

Every request is automatically scoped to the authenticated business. No client can access or query another business’s data.

3. Simplified Third-Party Data Ingestion

Original AI approach:-

Required structured relationships (business → customer → invoice).

Refinement:-

Invoices are now the source of truth. Risk scores, receivables analytics, and forecasts are derived directly from invoice data.

Why this change matters:-

Makes the API write-optimized, which is critical for real-world accounting integrations. Eliminates dependency on pre-created entities.
Supports bulk invoice ingestion from multiple external platforms.

Result:-

Third-party apps only need to:

  1. Send invoices
  2. Include x-api-key

Everything else is calculated automatically.

4. Improved Security and Data Isolation

  • Enhancements beyond AI defaults
  • API key–based authentication enforced on all endpoints
  • Business context resolved server-side
  • No internal IDs exposed in public contracts
  • Defensive handling for missing customer risk records

Outcome:-

The backend is multi-tenant safe, secure by default and production-ready without additional middleware.

These refinements transformed the AI-generated backend from a theoretical data model into a practical, integration-friendly, production-ready API:

  • Easier onboarding for third-party systems
  • Stronger security guarantees
  • Cleaner API contracts
  • Lower operational complexity

This balance of AI acceleration + human architectural judgment was key to delivering a robust solution.

My Experience with Xano

Xano’s no-code backend builder made it incredibly easy to model complex financial logic such as receivables ageing, risk scoring, and cashflow forecasting without writing traditional server code. The visual function stack allowed me to reason about business logic step-by-step, which was particularly helpful when implementing calculations like Days Sales Outstanding (DSO) and overdue percentages. After I familiarized myself with Xano, I was able to build a working prototype in under a couple hours.

The ability to compose APIs by calling other internal APIs was a major strength. It enabled me to build reusable endpoints (risk scoring, receivables analytics, cashflow forecasting) and then combine them into a higher-level business dashboard endpoint without duplicating logic. This made the system easier to debug, extend, and reason about.

Xano's AI agent feature helped me seamlessly integrate AI into my solution, which is the standout feature of the API.

My final takeaway is that Xano allowed me to focus on solving the actual business problem—cashflow and credit risk insights—rather than infrastructure. With thoughtful refinements on top of the AI-generated base, I was able to deliver a backend that feels both developer-friendly and production-ready.

Conclusion

This project represents more than just a backend implementation—it’s a step toward making cashflow intelligence and credit risk insights accessible through simple, developer-friendly APIs. In a landscape where many businesses struggle with delayed payments and limited financial visibility, enabling third-party systems to surface these insights programmatically can drive better decisions and healthier operations.

By combining AI-assisted development with thoughtful architectural refinements, this backend demonstrates how powerful financial analytics can be delivered securely, efficiently, and at scale—without requiring teams to build complex infrastructure from scratch.

Thank you for reading, and happy building! 🚀

Top comments (0)