diff --git a/.env.example b/.env.example index aeeeb09..93685fc 100644 --- a/.env.example +++ b/.env.example @@ -12,3 +12,9 @@ SMTP_PASS=replace-with-smtp-password SMTP_FROM="InvoiceFlow " 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 diff --git a/README.md b/README.md index 128d5de..b5de3f0 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/client/src/hooks/useAI.ts b/client/src/hooks/useAI.ts new file mode 100644 index 0000000..2d3a38d --- /dev/null +++ b/client/src/hooks/useAI.ts @@ -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(null); + const [error, setError] = useState(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(null); + const [error, setError] = useState(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(null); + const [error, setError] = useState(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 }; +} diff --git a/client/src/lib/api/ai.ts b/client/src/lib/api/ai.ts new file mode 100644 index 0000000..5242276 --- /dev/null +++ b/client/src/lib/api/ai.ts @@ -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 = { + success: true; + data: T; +}; + +export const aiApi = { + analyzeInvoice: async (invoiceId: string): Promise => { + const response = await api.post>("/ai/analyze-invoice", { + invoiceId, + }); + + return response.data.data; + }, + getCashFlowInsights: async (): Promise => { + const response = await api.post>("/ai/cash-flow-insights"); + return response.data.data; + }, + generatePaymentReminder: async (invoiceId: string): Promise => { + const response = await api.post>("/ai/payment-reminder", { + invoiceId, + }); + + return response.data.data; + }, +}; diff --git a/client/src/pages/DashboardPage.tsx b/client/src/pages/DashboardPage.tsx index 0d0f728..864375f 100644 --- a/client/src/pages/DashboardPage.tsx +++ b/client/src/pages/DashboardPage.tsx @@ -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"; @@ -183,6 +184,12 @@ export function DashboardPage() { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [downloadingInvoiceId, setDownloadingInvoiceId] = useState(null); + const { + data: cashFlowInsights, + error: cashFlowInsightsError, + fetch: fetchCashFlowInsights, + loading: cashFlowInsightsLoading, + } = useCashFlowInsights(); const { active: loadingBarActive, complete: loadingBarComplete, @@ -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"; @@ -421,6 +434,49 @@ export function DashboardPage() { +
+
+
+

AI cash flow insights

+

Last 90 days, translated into decisions.

+
+ {cashFlowInsights ? ( +
+

Next 30 days

+

+ {formatCurrency(cashFlowInsights.predicted_revenue_30d)} +

+
+ ) : null} +
+ + {cashFlowInsightsLoading ? ( +
+ + + +
+ ) : cashFlowInsights ? ( + <> +

+ {cashFlowInsights.summary} +

+
    + {cashFlowInsights.insights.map((insight, index) => ( +
  1. + 0{index + 1} + {insight} +
  2. + ))} +
+ + ) : ( +

+ {cashFlowInsightsError ?? "AI insights are not available yet."} +

+ )} +
+

Revenue

diff --git a/client/src/pages/InvoiceDetailPage.tsx b/client/src/pages/InvoiceDetailPage.tsx index 8e9685b..edcf1f3 100644 --- a/client/src/pages/InvoiceDetailPage.tsx +++ b/client/src/pages/InvoiceDetailPage.tsx @@ -5,6 +5,7 @@ import { Button } from "@/components/Button"; import { StatusBadge } from "@/components/StatusBadge"; import { Toast } from "@/components/Toast"; import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar"; +import { useInvoiceAnalysis, usePaymentReminder } from "@/hooks/useAI"; import { invoicesApi } from "@/lib/api/invoices"; import { getApiErrorMessage } from "@/lib/apiErrors"; import { @@ -87,6 +88,7 @@ export function InvoiceDetailPage() { const [downloadLoading, setDownloadLoading] = useState(false); const [downloaded, setDownloaded] = useState(false); const [gmailLoading, setGmailLoading] = useState(false); + const [statusLoading, setStatusLoading] = useState(null); const [copied, setCopied] = useState(false); const [toast, setToast] = useState(null); const [error, setError] = useState(null); @@ -98,6 +100,18 @@ export function InvoiceDetailPage() { done: finishLoadingBar, start: startLoadingBar, } = useLoadingBar(); + const { + analyze, + error: analysisError, + loading: analysisLoading, + result: analysis, + } = useInvoiceAnalysis(); + const { + error: reminderError, + generate: generateReminder, + loading: reminderLoading, + reminder, + } = usePaymentReminder(); useEffect(() => { if (!id) { @@ -109,6 +123,16 @@ export function InvoiceDetailPage() { void loadInvoice(id); }, [id]); + useEffect(() => { + if (!invoice) { + return; + } + + void analyze(invoice.id).catch((err) => { + console.error("Error analyzing invoice:", err); + }); + }, [analyze, invoice]); + useEffect( () => () => { if (copiedTimer.current !== null) { @@ -176,6 +200,25 @@ export function InvoiceDetailPage() { } }; + const handleStatusUpdate = async (status: Extract) => { + if (!invoice) { + return; + } + + try { + setStatusLoading(status); + const updatedInvoice = await invoicesApi.updateStatus(invoice.id, status); + setInvoice(updatedInvoice); + setToast(status === "SENT" ? "Invoice marked as sent." : "Invoice marked as paid."); + setError(null); + } catch (error) { + setError(getApiErrorMessage(error, `Failed to mark invoice as ${status.toLowerCase()}`)); + console.error("Error updating invoice status:", error); + } finally { + setStatusLoading(null); + } + }; + useEffect(() => { const handler = (event: KeyboardEvent) => { const target = event.target as HTMLElement | null; @@ -219,7 +262,24 @@ export function InvoiceDetailPage() { copiedTimer.current = window.setTimeout(() => setCopied(false), 1500); }; + const handleGenerateReminder = async () => { + if (!invoice) { + return; + } + + try { + await generateReminder(invoice.id); + setToast("Reminder drafted."); + setError(null); + } catch (err) { + console.error("Error generating payment reminder:", err); + } + }; + const pageTitle = useMemo(() => invoice?.number ?? "Invoice", [invoice]); + const isReminderAvailable = + invoice?.status === "OVERDUE" || + (invoice?.status !== "PAID" && invoice ? new Date(invoice.dueDate) < new Date() : false); if (loading) { return ( @@ -270,6 +330,26 @@ export function InvoiceDetailPage() { Open in Gmail ) : null} + {invoice.status === "DRAFT" ? ( + + ) : null} + {invoice.status === "SENT" || invoice.status === "OVERDUE" ? ( + + ) : null} @@ -374,6 +454,103 @@ export function InvoiceDetailPage() {
+ +
+
+
+

AI invoice analysis

+ {analysis ? ( + + {analysis.risk_level} risk + + ) : null} +
+ + {analysisLoading ? ( +
+ + + +
+ ) : analysis ? ( + <> +

{analysis.summary}

+
+
+

Issues

+
    + {(analysis.issues.length ? analysis.issues : ["No obvious issues detected."]).map((issue) => ( +
  • • {issue}
  • + ))} +
+
+
+

Suggestions

+
    + {(analysis.suggestions.length ? analysis.suggestions : ["No action needed right now."]).map( + (suggestion) => ( +
  • • {suggestion}
  • + ), + )} +
+
+
+ + ) : ( +

+ {analysisError ?? "AI analysis is not available yet."} +

+ )} +
+ +
+
+

Payment reminder

+ {isReminderAvailable ? ( + + ) : null} +
+ + {!isReminderAvailable ? ( +

Available once this invoice becomes overdue.

+ ) : reminder ? ( +
+
+

Subject

+

{reminder.subject}

+
+
+

Body

+

+ {reminder.body} +

+
+
+ ) : ( +

+ {reminderError ?? "Generate a tailored reminder when you are ready to follow up."} +

+ )} +
+
); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c6a9167..6984d41 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -143,6 +143,9 @@ importers: bcrypt: specifier: ^6.0.0 version: 6.0.0 + bottleneck: + specifier: ^2.19.5 + version: 2.19.5 cookie-parser: specifier: ^1.4.7 version: 1.4.7 @@ -155,6 +158,9 @@ importers: express: specifier: ^5.2.1 version: 5.2.1 + express-rate-limit: + specifier: ^8.5.2 + version: 8.5.2(express@5.2.1) helmet: specifier: ^8.1.0 version: 8.1.0 @@ -167,6 +173,9 @@ importers: nodemailer: specifier: ^8.0.7 version: 8.0.7 + openai: + specifier: ^6.37.0 + version: 6.37.0(zod@4.4.3) pdfkit: specifier: ^0.18.0 version: 0.18.0 @@ -1243,6 +1252,9 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} + bottleneck@2.19.5: + resolution: {integrity: sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==} + brace-expansion@5.0.6: resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} engines: {node: 18 || 20 || >=22} @@ -1647,6 +1659,12 @@ packages: resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} engines: {node: '>=12.0.0'} + express-rate-limit@8.5.2: + resolution: {integrity: sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==} + engines: {node: '>= 16'} + peerDependencies: + express: '>= 4.11' + express@5.2.1: resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==} engines: {node: '>= 18'} @@ -1900,6 +1918,10 @@ packages: resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} engines: {node: '>=12'} + ip-address@10.2.0: + resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} + engines: {node: '>= 12'} + ipaddr.js@1.9.1: resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} engines: {node: '>= 0.10'} @@ -2391,6 +2413,18 @@ packages: once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + openai@6.37.0: + resolution: {integrity: sha512-0H5dEGFmmLv6KSd0W1w2nyL8WsLkX6yoLeQpU+dZAOuGcany5qkYQMmj35ZrKgb6yiyYqpUzFOpR8mZQkgqeEQ==} + hasBin: true + peerDependencies: + ws: ^8.18.0 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + ws: + optional: true + zod: + optional: true + pako@0.2.9: resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==} @@ -4219,6 +4253,8 @@ snapshots: boolbase@1.0.0: {} + bottleneck@2.19.5: {} + brace-expansion@5.0.6: dependencies: balanced-match: 4.0.4 @@ -4601,6 +4637,11 @@ snapshots: expect-type@1.3.0: {} + express-rate-limit@8.5.2(express@5.2.1): + dependencies: + express: 5.2.1 + ip-address: 10.2.0 + express@5.2.1: dependencies: accepts: 2.0.0 @@ -4947,6 +4988,8 @@ snapshots: internmap@2.0.3: {} + ip-address@10.2.0: {} + ipaddr.js@1.9.1: {} is-alphabetical@2.0.1: {} @@ -5591,6 +5634,10 @@ snapshots: dependencies: wrappy: 1.0.2 + openai@6.37.0(zod@4.4.3): + optionalDependencies: + zod: 4.4.3 + pako@0.2.9: {} pako@1.0.11: {} diff --git a/server/package.json b/server/package.json index 4bd546f..e830d28 100644 --- a/server/package.json +++ b/server/package.json @@ -29,14 +29,17 @@ "@types/nodemailer": "^8.0.0", "@types/pdfkit": "^0.17.6", "bcrypt": "^6.0.0", + "bottleneck": "^2.19.5", "cookie-parser": "^1.4.7", "cors": "^2.8.6", "dotenv": "^17.4.2", "express": "^5.2.1", + "express-rate-limit": "^8.5.2", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.3", "multer": "^2.1.1", "nodemailer": "^8.0.7", + "openai": "^6.37.0", "pdfkit": "^0.18.0", "pg": "^8.20.0", "prisma": "^7.8.0", diff --git a/server/prisma/migrations/20260516093000_ai_assistant/migration.sql b/server/prisma/migrations/20260516093000_ai_assistant/migration.sql new file mode 100644 index 0000000..e74c7a3 --- /dev/null +++ b/server/prisma/migrations/20260516093000_ai_assistant/migration.sql @@ -0,0 +1,36 @@ +-- AlterTable +ALTER TABLE "Invoice" ADD COLUMN "paidAt" TIMESTAMP(3); + +-- Backfill a best-effort paid timestamp for historical paid invoices. +UPDATE "Invoice" +SET "paidAt" = "updatedAt" +WHERE "status" = 'PAID'; + +-- CreateTable +CREATE TABLE "AiUsageLog" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "invoiceId" TEXT, + "feature" TEXT NOT NULL, + "model" TEXT NOT NULL, + "success" BOOLEAN NOT NULL, + "latencyMs" INTEGER NOT NULL, + "promptTokens" INTEGER, + "completionTokens" INTEGER, + "totalTokens" INTEGER, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AiUsageLog_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "AiUsageLog_userId_createdAt_idx" ON "AiUsageLog"("userId", "createdAt"); + +-- CreateIndex +CREATE INDEX "AiUsageLog_invoiceId_feature_createdAt_idx" ON "AiUsageLog"("invoiceId", "feature", "createdAt"); + +-- AddForeignKey +ALTER TABLE "AiUsageLog" ADD CONSTRAINT "AiUsageLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AiUsageLog" ADD CONSTRAINT "AiUsageLog_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index e052971..4f37d32 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -27,6 +27,7 @@ model User { stripeCustomerId String? invoices Invoice[] proposals Proposal[] + aiUsageLogs AiUsageLog[] } model Invoice { @@ -45,15 +46,36 @@ model Invoice { taxRate Float taxAmount Float total Float + paidAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User @relation(fields: [userId], references: [id], onDelete: Cascade) lineItems LineItem[] + aiUsageLogs AiUsageLog[] @@unique([userId, number]) @@index([userId]) } +model AiUsageLog { + id String @id @default(cuid()) + userId String + invoiceId String? + feature String + model String + success Boolean + latencyMs Int + promptTokens Int? + completionTokens Int? + totalTokens Int? + createdAt DateTime @default(now()) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull) + + @@index([userId, createdAt]) + @@index([invoiceId, feature, createdAt]) +} + model LineItem { id String @id @default(cuid()) invoiceId String diff --git a/server/src/index.ts b/server/src/index.ts index 1d06d51..3b88529 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -7,6 +7,7 @@ import type {} from "./types/express"; import "./config/env"; import { corsOptions } from "./config/cors"; import { errorHandler } from "./middleware/errorHandler"; +import { aiRouter } from "./routes/ai"; import { authRouter } from "./routes/auth"; import { dashboardRouter } from "./routes/dashboard"; import { healthRouter } from "./routes/health"; @@ -25,6 +26,7 @@ app.use(express.json()); app.use("/uploads", express.static("uploads")); app.use("/auth", authRouter); +app.use("/ai", aiRouter); app.use("/dashboard", dashboardRouter); app.use("/health", healthRouter); app.use("/invoices", invoiceRouter); diff --git a/server/src/lib/llama.ts b/server/src/lib/llama.ts new file mode 100644 index 0000000..b19b59e --- /dev/null +++ b/server/src/lib/llama.ts @@ -0,0 +1,23 @@ +import OpenAI from "openai"; + +import { HttpError } from "../utils/httpError"; + +export const LLAMA_MODEL = + process.env.LLAMA_MODEL ?? "meta/llama-4-scout-17b-16e-instruct"; + +let llamaClient: OpenAI | null = null; + +export const getLlamaClient = () => { + if (!process.env.NVIDIA_API_KEY) { + throw new HttpError(503, "AI service is not configured."); + } + + llamaClient ??= new OpenAI({ + apiKey: process.env.NVIDIA_API_KEY, + baseURL: process.env.NVIDIA_BASE_URL ?? "https://integrate.api.nvidia.com/v1", + timeout: 30_000, + maxRetries: 2, + }); + + return llamaClient; +}; diff --git a/server/src/middleware/aiRateLimit.ts b/server/src/middleware/aiRateLimit.ts new file mode 100644 index 0000000..88c725f --- /dev/null +++ b/server/src/middleware/aiRateLimit.ts @@ -0,0 +1,18 @@ +import rateLimit from "express-rate-limit"; + +const windowMs = Number(process.env.AI_RATE_LIMIT_WINDOW_MS) || 60_000; +const max = Number(process.env.AI_RATE_LIMIT_MAX_REQUESTS) || 20; + +export const aiRateLimiter = rateLimit({ + windowMs, + max, + keyGenerator: (request) => request.user?.id ?? "anonymous", + handler: (_request, response) => { + response.status(429).json({ + message: "AI rate limit exceeded. Please wait before making more AI requests.", + retryAfter: Math.ceil(windowMs / 1_000), + }); + }, + standardHeaders: true, + legacyHeaders: false, +}); diff --git a/server/src/routes/ai.ts b/server/src/routes/ai.ts new file mode 100644 index 0000000..e1fa452 --- /dev/null +++ b/server/src/routes/ai.ts @@ -0,0 +1,68 @@ +import { Router } from "express"; +import { z } from "zod"; + +import { authMiddleware } from "../middleware/authMiddleware"; +import { aiRateLimiter } from "../middleware/aiRateLimit"; +import { + analyzeInvoiceForUser, + generateCashFlowInsightsForUser, + generatePaymentReminderForUser, +} from "../services/aiService"; +import { HttpError } from "../utils/httpError"; + +const invoiceRequestSchema = z.object({ + invoiceId: z.string().trim().min(1, "Invoice id is required."), +}); + +const router = Router(); + +router.use(authMiddleware, aiRateLimiter); + +router.post("/analyze-invoice", async (request, response, next) => { + try { + const { invoiceId } = invoiceRequestSchema.parse(request.body); + const result = await analyzeInvoiceForUser(request.user!.id, invoiceId); + response.json({ success: true, data: result }); + } catch (error) { + if (error instanceof HttpError || error instanceof z.ZodError) { + next(error); + return; + } + + console.error("[AI] analyze-invoice error:", error); + next(new HttpError(502, "AI analysis failed.")); + } +}); + +router.post("/cash-flow-insights", async (request, response, next) => { + try { + const result = await generateCashFlowInsightsForUser(request.user!.id); + response.json({ success: true, data: result }); + } catch (error) { + if (error instanceof HttpError) { + next(error); + return; + } + + console.error("[AI] cash-flow-insights error:", error); + next(new HttpError(502, "AI insights failed.")); + } +}); + +router.post("/payment-reminder", async (request, response, next) => { + try { + const { invoiceId } = invoiceRequestSchema.parse(request.body); + const result = await generatePaymentReminderForUser(request.user!.id, invoiceId); + response.json({ success: true, data: result }); + } catch (error) { + if (error instanceof HttpError || error instanceof z.ZodError) { + next(error); + return; + } + + console.error("[AI] payment-reminder error:", error); + next(new HttpError(502, "Reminder generation failed.")); + } +}); + +export { router as aiRouter }; diff --git a/server/src/routes/invoices.ts b/server/src/routes/invoices.ts index 68708d3..5d2b8c7 100644 --- a/server/src/routes/invoices.ts +++ b/server/src/routes/invoices.ts @@ -241,7 +241,7 @@ export const sendInvoice = async (req: Request, res: Response, next: NextFunctio const updatedInvoice = await prisma.invoice.update({ where: { id }, - data: { status: "SENT" }, + data: { status: "SENT", paidAt: null }, include: { lineItems: true }, }); @@ -385,7 +385,10 @@ export const updateInvoiceStatus = async (req: Request, res: Response, next: Nex const updatedInvoice = await prisma.invoice.update({ where: { id }, - data: { status }, + data: { + status, + paidAt: status === "PAID" ? existingInvoice.paidAt ?? new Date() : null, + }, include: { lineItems: true }, }); diff --git a/server/src/services/aiService.ts b/server/src/services/aiService.ts new file mode 100644 index 0000000..1c9c777 --- /dev/null +++ b/server/src/services/aiService.ts @@ -0,0 +1,453 @@ +import Bottleneck from "bottleneck"; +import { z } from "zod"; + +import { getLlamaClient, LLAMA_MODEL } from "../lib/llama"; +import { prisma } from "../lib/prisma"; +import { HttpError } from "../utils/httpError"; + +const invoiceAnalysisSchema = z.object({ + risk_level: z.enum(["low", "medium", "high"]), + issues: z.array(z.string()), + suggestions: z.array(z.string()), + summary: z.string(), +}); + +const cashFlowInsightSchema = z.object({ + summary: z.string(), + insights: z.array(z.string()).length(3), + predicted_revenue_30d: z.number().finite().nonnegative(), +}); + +const paymentReminderSchema = z.object({ + subject: z.string().min(1), + body: z.string().min(1), +}); + +export type InvoiceAnalysis = z.infer; +export type CashFlowInsight = z.infer; +export type PaymentReminder = z.infer; + +type AiFeature = "invoice_analysis" | "cash_flow_insights" | "payment_reminder"; + +const aiLimiter = new Bottleneck({ + maxConcurrent: Number(process.env.AI_MAX_CONCURRENT_REQUESTS) || 4, +}); + +const startOfDay = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate()); + +const daysBetween = (later: Date, earlier: Date) => + Math.max(0, Math.ceil((startOfDay(later).getTime() - startOfDay(earlier).getTime()) / 86_400_000)); + +const parseModelJson = (raw: string) => { + const clean = raw + .replace(/^```(?:json)?\s*/i, "") + .replace(/\s*```$/i, "") + .trim(); + + return JSON.parse(clean) as unknown; +}; + +const writeUsageLog = async (data: { + userId: string; + invoiceId?: string; + feature: AiFeature; + success: boolean; + latencyMs: number; + promptTokens?: number; + completionTokens?: number; + totalTokens?: number; +}) => { + try { + await prisma.aiUsageLog.create({ + data: { + ...data, + model: LLAMA_MODEL, + }, + }); + } catch (error) { + console.error("[AI USAGE LOG ERROR]", error); + } +}; + +const createStructuredCompletion = async (data: { + feature: AiFeature; + userId: string; + invoiceId?: string; + prompt: string; + schema: TSchema; + maxTokens: number; + temperature: number; +}): Promise> => { + const startedAt = Date.now(); + + try { + const response = await aiLimiter.schedule(() => + getLlamaClient().chat.completions.create({ + model: LLAMA_MODEL, + messages: [{ role: "user", content: data.prompt }], + max_tokens: data.maxTokens, + temperature: data.temperature, + }), + ); + + const raw = response.choices[0]?.message?.content; + + if (!raw) { + throw new Error("AI response did not contain content."); + } + + const parsed = data.schema.parse(parseModelJson(raw)); + + await writeUsageLog({ + userId: data.userId, + invoiceId: data.invoiceId, + feature: data.feature, + success: true, + latencyMs: Date.now() - startedAt, + promptTokens: response.usage?.prompt_tokens, + completionTokens: response.usage?.completion_tokens, + totalTokens: response.usage?.total_tokens, + }); + + return parsed; + } catch (error) { + await writeUsageLog({ + userId: data.userId, + invoiceId: data.invoiceId, + feature: data.feature, + success: false, + latencyMs: Date.now() - startedAt, + }); + + throw error; + } +}; + +const isPaidOnTime = (invoice: { + status: string; + dueDate: Date; + paidAt: Date | null; + updatedAt: Date; +}) => { + if (invoice.status !== "PAID") { + return false; + } + + const paidDate = invoice.paidAt ?? invoice.updatedAt; + return paidDate <= invoice.dueDate; +}; + +const getInvoiceWithHistory = async (userId: string, invoiceId: string) => { + const invoice = await prisma.invoice.findFirst({ + where: { id: invoiceId, userId }, + include: { + lineItems: { + orderBy: { id: "asc" }, + }, + }, + }); + + if (!invoice) { + throw new HttpError(404, "Invoice not found."); + } + + const clientInvoices = await prisma.invoice.findMany({ + where: { + userId, + clientEmail: invoice.clientEmail, + id: { not: invoice.id }, + }, + select: { + id: true, + dueDate: true, + paidAt: true, + status: true, + total: true, + updatedAt: true, + }, + orderBy: { dueDate: "desc" }, + take: 12, + }); + + return { invoice, clientInvoices }; +}; + +export const analyzeInvoiceForUser = async (userId: string, invoiceId: string) => { + const { invoice, clientInvoices } = await getInvoiceWithHistory(userId, invoiceId); + const now = new Date(); + const clientPaymentHistory = clientInvoices.map((item) => ({ + invoiceId: item.id, + paidOnTime: isPaidOnTime(item), + status: item.status, + })); + const overdueInvoices = clientInvoices.filter( + (item) => item.status === "OVERDUE" || (item.status !== "PAID" && item.dueDate < now), + ).length; + + const prompt = `You are an expert invoice risk analyst. Analyze the following invoice and respond ONLY with a valid JSON object matching this exact schema: +{ + "risk_level": "low" | "medium" | "high", + "issues": string[], + "suggestions": string[], + "summary": string +} + +Invoice data: +${JSON.stringify( + { + amount: invoice.total, + clientName: invoice.clientName, + lineItems: invoice.lineItems.map((item) => ({ + description: item.description, + quantity: item.quantity, + unitPrice: item.unitPrice, + })), + dueDate: invoice.dueDate.toISOString(), + clientPaymentHistory, + overdueInvoices, + }, + null, + 2, +)} + +Rules: +- Use "high" risk if the client has more than 2 late payments or overdue invoices, or if the amount is over $10,000 with no history. +- Detect missing fields, suspicious amounts, repeated line-item descriptions, and duplicate-looking line items. +- Keep the summary under 2 sentences. +- Return only JSON.`; + + return createStructuredCompletion({ + userId, + invoiceId, + feature: "invoice_analysis", + prompt, + schema: invoiceAnalysisSchema, + maxTokens: 512, + temperature: 0.1, + }); +}; + +export const generateCashFlowInsightsForUser = async (userId: string) => { + const now = new Date(); + const ninetyDaysAgo = new Date(now); + ninetyDaysAgo.setDate(now.getDate() - 90); + const thirtyDaysFromNow = new Date(now); + thirtyDaysFromNow.setDate(now.getDate() + 30); + + const [paidInvoices, billedInvoices, pendingInvoices] = await Promise.all([ + prisma.invoice.findMany({ + where: { + userId, + status: "PAID", + OR: [ + { paidAt: { gte: ninetyDaysAgo } }, + { paidAt: null, updatedAt: { gte: ninetyDaysAgo } }, + ], + }, + select: { + clientName: true, + dueDate: true, + paidAt: true, + total: true, + updatedAt: true, + }, + }), + prisma.invoice.findMany({ + where: { + userId, + issueDate: { gte: ninetyDaysAgo }, + }, + select: { + clientName: true, + dueDate: true, + paidAt: true, + status: true, + total: true, + updatedAt: true, + }, + }), + prisma.invoice.findMany({ + where: { + userId, + status: { in: ["SENT", "OVERDUE"] }, + }, + select: { + dueDate: true, + status: true, + total: true, + }, + }), + ]); + + const totalReceived90d = paidInvoices.reduce((sum, invoice) => sum + invoice.total, 0); + const totalPending = pendingInvoices.reduce((sum, invoice) => sum + invoice.total, 0); + const overdueCount = pendingInvoices.filter( + (invoice) => invoice.status === "OVERDUE" || invoice.dueDate < now, + ).length; + const paymentDelays = paidInvoices.map((invoice) => + daysBetween(invoice.paidAt ?? invoice.updatedAt, invoice.dueDate), + ); + const avgPaymentDelay = + paymentDelays.length === 0 + ? 0 + : Math.round(paymentDelays.reduce((sum, delay) => sum + delay, 0) / paymentDelays.length); + + const clients = new Map< + string, + { + name: string; + totalBilled: number; + paidOnTime: boolean; + } + >(); + + billedInvoices.forEach((invoice) => { + const current = clients.get(invoice.clientName) ?? { + name: invoice.clientName, + totalBilled: 0, + paidOnTime: true, + }; + + current.totalBilled += invoice.total; + current.paidOnTime &&= invoice.status !== "PAID" || isPaidOnTime(invoice); + clients.set(invoice.clientName, current); + }); + + const topClients = [...clients.values()] + .sort((left, right) => right.totalBilled - left.totalBilled) + .slice(0, 3); + const pendingDueSoon = pendingInvoices + .filter((invoice) => invoice.status === "SENT" && invoice.dueDate >= now && invoice.dueDate <= thirtyDaysFromNow) + .map((invoice) => ({ + amount: invoice.total, + dueDate: invoice.dueDate.toISOString(), + })); + const predictedRevenue30d = Math.round( + pendingDueSoon.reduce((sum, invoice) => sum + invoice.amount, 0), + ); + + const prompt = `You are a financial advisor for small businesses. Analyze this cash-flow data and respond ONLY with valid JSON: +{ + "summary": string, + "insights": string[], + "predicted_revenue_30d": number +} + +Data: +${JSON.stringify( + { + totalReceived90d, + totalPending, + overdueCount, + avgPaymentDelay, + topClients, + pendingInvoices: pendingDueSoon, + predictedRevenue30d, + }, + null, + 2, +)} + +Rules: +- The summary should be 3 to 4 concise sentences in a conversational tone. +- Return exactly 3 actionable insights. +- predicted_revenue_30d must exactly equal ${predictedRevenue30d}; this figure is precomputed from pending invoices due in the next 30 days. +- Return only JSON.`; + + const insight = await createStructuredCompletion({ + userId, + feature: "cash_flow_insights", + prompt, + schema: cashFlowInsightSchema, + maxTokens: 600, + temperature: 0.3, + }); + + return { + ...insight, + predicted_revenue_30d: predictedRevenue30d, + }; +}; + +export const generatePaymentReminderForUser = async (userId: string, invoiceId: string) => { + const { invoice, clientInvoices } = await getInvoiceWithHistory(userId, invoiceId); + const today = new Date(); + const isOverdue = invoice.status === "OVERDUE" || (invoice.status !== "PAID" && invoice.dueDate < today); + + if (!isOverdue) { + throw new HttpError(400, "Payment reminders are only available for overdue invoices."); + } + + const [user, previousReminders] = await Promise.all([ + prisma.user.findUnique({ + where: { id: userId }, + select: { + businessName: true, + name: true, + }, + }), + prisma.aiUsageLog.count({ + where: { + invoiceId, + feature: "payment_reminder", + success: true, + }, + }), + ]); + + if (!user) { + throw new HttpError(404, "User not found."); + } + + const paymentHistory = clientInvoices.map((item) => ({ + status: item.status, + paidOnTime: isPaidOnTime(item), + })); + const daysOverdue = daysBetween(today, invoice.dueDate); + const tone = + previousReminders === 0 + ? "friendly and polite" + : previousReminders === 1 + ? "firm but professional" + : "direct and urgent"; + + const prompt = `Write a ${tone} payment reminder email for an overdue invoice. +Respond ONLY with valid JSON: +{ + "subject": string, + "body": string +} + +Details: +${JSON.stringify( + { + clientName: invoice.clientName, + invoiceNumber: invoice.number, + amount: invoice.total, + currency: invoice.currency, + daysOverdue, + businessName: user.businessName ?? user.name, + previousReminders, + previousPaymentHistory: paymentHistory, + }, + null, + 2, +)} + +Rules: +- Stay under 150 words. +- Include the invoice number and amount. +- Include a clear call to action. +- Do not sound aggressive, threatening, or robotic. +- Return only JSON.`; + + return createStructuredCompletion({ + userId, + invoiceId, + feature: "payment_reminder", + prompt, + schema: paymentReminderSchema, + maxTokens: 400, + temperature: 0.5, + }); +}; diff --git a/server/test/ai.test.ts b/server/test/ai.test.ts new file mode 100644 index 0000000..ead0b38 --- /dev/null +++ b/server/test/ai.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import request from "supertest"; + +import { testAccessToken, testApp } from "./setup"; + +describe("AI Endpoints", () => { + it("requires authentication", async () => { + const response = await request(testApp).post("/ai/analyze-invoice").expect(401); + + expect(response.body.message).toContain("Authorization token is required"); + }); + + it("validates invoice requests before calling the model", async () => { + const response = await request(testApp) + .post("/ai/analyze-invoice") + .set("Authorization", `Bearer ${testAccessToken}`) + .send({}) + .expect(400); + + expect(response.body.message).toBe("Validation failed"); + }); +}); diff --git a/server/test/setup.ts b/server/test/setup.ts index c79df1b..e52dbbf 100644 --- a/server/test/setup.ts +++ b/server/test/setup.ts @@ -10,6 +10,7 @@ import helmet from "helmet"; import "../src/config/env"; import { corsOptions } from "../src/config/cors"; import { errorHandler } from "../src/middleware/errorHandler"; +import { aiRouter } from "../src/routes/ai"; import { authRouter } from "../src/routes/auth"; import { dashboardRouter } from "../src/routes/dashboard"; import { healthRouter } from "../src/routes/health"; @@ -29,6 +30,7 @@ app.use(express.json()); app.use("/uploads", express.static("uploads")); app.use("/auth", authRouter); +app.use("/ai", aiRouter); app.use("/dashboard", dashboardRouter); app.use("/health", healthRouter); app.use("/invoices", invoiceRouter); @@ -54,6 +56,7 @@ let testUserIdInternal: string; let testAccessTokenInternal: string; beforeAll(async () => { + await prisma.aiUsageLog.deleteMany(); await prisma.lineItem.deleteMany(); await prisma.invoice.deleteMany(); await prisma.proposal.deleteMany();