Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ SMTP_PASS=replace-with-smtp-password
SMTP_FROM="InvoiceFlow <replace-with-smtp-user>"
STRIPE_SECRET_KEY=sk_test_replace_me
STRIPE_WEBHOOK_SECRET=whsec_replace_me
NVIDIA_API_KEY=nvapi_replace_me
NVIDIA_BASE_URL=https://integrate.api.nvidia.com/v1
LLAMA_MODEL=meta/llama-4-scout-17b-16e-instruct
AI_RATE_LIMIT_WINDOW_MS=60000
AI_RATE_LIMIT_MAX_REQUESTS=20
AI_MAX_CONCURRENT_REQUESTS=4
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ The client runs on `http://localhost:5173` and the server runs on `http://localh
- **Backend (Render)**: Set the service root to `server`, then use `npm install && npm run deploy:build` for the build command and `npm start` for the start command.
- **Frontend (Vercel)**: Configure environment variables in Vercel dashboard.
- Keep backend secrets such as `DATABASE_URL`, `JWT_SECRET`, and `JWT_REFRESH_SECRET` in the Render environment.
- To enable the AI assistant, also set `NVIDIA_API_KEY`, `NVIDIA_BASE_URL`, `LLAMA_MODEL`, `AI_RATE_LIMIT_WINDOW_MS`, `AI_RATE_LIMIT_MAX_REQUESTS`, and `AI_MAX_CONCURRENT_REQUESTS` in the backend environment.
- Set `CLIENT_URLS` to the allowed frontend origins, for example `https://invoice-flow-client.vercel.app`.

Each platform handles its own environment variables independently for separate deployments.
78 changes: 78 additions & 0 deletions client/src/hooks/useAI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { useCallback, useState } from "react";

import {
aiApi,
type CashFlowInsight,
type InvoiceAnalysis,
type PaymentReminder,
} from "@/lib/api/ai";
import { getApiErrorMessage } from "@/lib/apiErrors";

export function useInvoiceAnalysis() {
const [loading, setLoading] = useState(false);
const [result, setResult] = useState<InvoiceAnalysis | null>(null);
const [error, setError] = useState<string | null>(null);

const analyze = useCallback(async (invoiceId: string) => {
try {
setLoading(true);
setError(null);
const analysis = await aiApi.analyzeInvoice(invoiceId);
setResult(analysis);
return analysis;
} catch (err) {
setError(getApiErrorMessage(err, "Analysis failed"));
throw err;
} finally {
setLoading(false);
}
}, []);

return { analyze, error, loading, result };
}

export function useCashFlowInsights() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState<CashFlowInsight | null>(null);
const [error, setError] = useState<string | null>(null);

const fetchInsights = useCallback(async () => {
try {
setLoading(true);
setError(null);
const insights = await aiApi.getCashFlowInsights();
setData(insights);
return insights;
} catch (err) {
setError(getApiErrorMessage(err, "AI insights failed"));
throw err;
} finally {
setLoading(false);
}
}, []);

return { data, error, fetch: fetchInsights, loading };
}

export function usePaymentReminder() {
const [loading, setLoading] = useState(false);
const [reminder, setReminder] = useState<PaymentReminder | null>(null);
const [error, setError] = useState<string | null>(null);

const generate = useCallback(async (invoiceId: string) => {
try {
setLoading(true);
setError(null);
const nextReminder = await aiApi.generatePaymentReminder(invoiceId);
setReminder(nextReminder);
return nextReminder;
} catch (err) {
setError(getApiErrorMessage(err, "Reminder generation failed"));
throw err;
} finally {
setLoading(false);
}
}, []);

return { error, generate, loading, reminder };
}
45 changes: 45 additions & 0 deletions client/src/lib/api/ai.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { api } from "@/lib/axios";

export type InvoiceAnalysis = {
risk_level: "low" | "medium" | "high";
issues: string[];
suggestions: string[];
summary: string;
};

export type CashFlowInsight = {
summary: string;
insights: string[];
predicted_revenue_30d: number;
};

export type PaymentReminder = {
subject: string;
body: string;
};

type AiResponse<T> = {
success: true;
data: T;
};

export const aiApi = {
analyzeInvoice: async (invoiceId: string): Promise<InvoiceAnalysis> => {
const response = await api.post<AiResponse<InvoiceAnalysis>>("/ai/analyze-invoice", {
invoiceId,
});

return response.data.data;
},
getCashFlowInsights: async (): Promise<CashFlowInsight> => {
const response = await api.post<AiResponse<CashFlowInsight>>("/ai/cash-flow-insights");
return response.data.data;
},
generatePaymentReminder: async (invoiceId: string): Promise<PaymentReminder> => {
const response = await api.post<AiResponse<PaymentReminder>>("/ai/payment-reminder", {
invoiceId,
});

return response.data.data;
},
};
56 changes: 56 additions & 0 deletions client/src/pages/DashboardPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Bar, BarChart, CartesianGrid, Tooltip, XAxis, YAxis } from "recharts";
import { PlanBadge } from "@/components/PlanBadge";
import { StatusBadge } from "@/components/StatusBadge";
import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar";
import { useCashFlowInsights } from "@/hooks/useAI";
import { dashboardApi, type DashboardStats } from "@/lib/api/dashboard";
import { invoicesApi } from "@/lib/api/invoices";
import { api } from "@/lib/axios";
Expand Down Expand Up @@ -183,6 +184,12 @@ export function DashboardPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [downloadingInvoiceId, setDownloadingInvoiceId] = useState<string | null>(null);
const {
data: cashFlowInsights,
error: cashFlowInsightsError,
fetch: fetchCashFlowInsights,
loading: cashFlowInsightsLoading,
} = useCashFlowInsights();
const {
active: loadingBarActive,
complete: loadingBarComplete,
Expand Down Expand Up @@ -222,6 +229,12 @@ export function DashboardPage() {
};
}, [finishLoadingBar, startLoadingBar]);

useEffect(() => {
void fetchCashFlowInsights().catch((err) => {
console.error("Error loading cash-flow insights:", err);
});
}, [fetchCashFlowInsights]);

const initials = useMemo(() => getInitials(user?.name || user?.email), [user]);
const hour = new Date().getHours();
const greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";
Expand Down Expand Up @@ -421,6 +434,49 @@ export function DashboardPage() {
</Link>
</div>

<section className="card p-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="text-[13px] font-medium text-[var(--text-1)]">AI cash flow insights</h2>
<p className="mt-1 text-[11px] text-[var(--text-3)]">Last 90 days, translated into decisions.</p>
</div>
{cashFlowInsights ? (
<div className="text-right">
<p className="text-[11px] uppercase text-[var(--text-3)]">Next 30 days</p>
<p className="mono mt-1 text-[18px] text-[var(--accent)]">
{formatCurrency(cashFlowInsights.predicted_revenue_30d)}
</p>
</div>
) : null}
</div>

{cashFlowInsightsLoading ? (
<div className="mt-4 space-y-3">
<Skeleton height={14} width="92%" />
<Skeleton height={14} width="84%" />
<Skeleton height={14} width="78%" />
</div>
) : cashFlowInsights ? (
<>
<p className="mt-4 max-w-4xl text-[13px] leading-6 text-[var(--text-2)]">
{cashFlowInsights.summary}
</p>
<ol className="mt-4 grid gap-2 lg:grid-cols-3">
{cashFlowInsights.insights.map((insight, index) => (
<li className="rounded-md border border-[var(--border)] bg-[var(--bg-2)] p-3 text-[12px] leading-5 text-[var(--text-2)]" key={insight}>
<span className="mono mr-2 text-[var(--accent)]">0{index + 1}</span>
{insight}
</li>
))}
</ol>
</>
) : (
<p className="mt-4 text-[12px] text-[var(--text-2)]">
{cashFlowInsightsError ?? "AI insights are not available yet."}
</p>
)}
</section>

<section className="card p-4">
<div className="flex items-center justify-between">
<h2 className="text-[13px] font-medium text-[var(--text-1)]">Revenue</h2>
Expand Down
Loading
Loading