feat: Add manual response dialog and update debt status handling

- Introduced ManualResponseDialog component for user-initiated responses when AI analysis is unclear.
- Updated DebtTimeline to include AlertTriangle icon for debts requiring manual review.
- Enhanced supabase functions to handle new debt status 'requires_manual_review' and message type 'manual_response'.
- Implemented email variable processing utilities to support dynamic email content generation.
- Created tests for email variable extraction and replacement functions.
- Updated database schema to accommodate new statuses and message types, including relevant constraints and indexes.
- Adjusted negotiation and email sending logic to ensure proper handling of manual responses and variable replacements.
This commit is contained in:
2025-06-08 01:49:19 -03:00
parent bddc3a344d
commit 7c91b625a6
13 changed files with 1059 additions and 171 deletions

View File

@@ -48,6 +48,7 @@ const messageTypeLabels = {
counter_offer: "Counter Offer",
acceptance: "Offer Accepted",
rejection: "Offer Rejected",
manual_response: "Manual Response",
};
const statusColors = {
@@ -57,6 +58,7 @@ const statusColors = {
sent: "text-orange-600 dark:text-orange-400",
awaiting_response: "text-blue-600 dark:text-blue-400",
counter_negotiating: "text-yellow-600 dark:text-yellow-400",
requires_manual_review: "text-amber-600 dark:text-amber-400",
accepted: "text-green-600 dark:text-green-400",
rejected: "text-red-600 dark:text-red-400",
settled: "text-green-600 dark:text-green-400",
@@ -71,6 +73,7 @@ const statusLabels = {
sent: "Sent",
awaiting_response: "Awaiting Response",
counter_negotiating: "Counter Negotiating",
requires_manual_review: "Manual Review Required",
accepted: "Accepted",
rejected: "Rejected",
settled: "Settled",
@@ -384,7 +387,9 @@ export function ConversationTimeline({
?.proposedAmount && (
<div className="text-xs text-gray-600 dark:text-gray-400">
Proposed Amount: $
{message.ai_analysis.extractedTerms.proposedAmount}
{formatCurrency(
message.ai_analysis.extractedTerms.proposedAmount
)}
</div>
)}

View File

@@ -162,6 +162,7 @@ export function Dashboard() {
"approved",
"awaiting_response",
"counter_negotiating",
"requires_manual_review",
].includes(debt.status)
),
settled: debts.filter((debt) =>
@@ -309,7 +310,7 @@ export function Dashboard() {
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{debtList.map((debt) => (
<div key={debt.id} className="space-y-4">
<DebtCard debt={debt} onUpdate={fetchDebts} />

View File

@@ -47,6 +47,13 @@ import {
import { supabase, type Debt, type DebtVariable } from "../lib/supabase";
import { toast } from "sonner";
import { formatCurrency } from "../lib/utils";
import {
replaceVariables,
saveVariablesToDatabase,
getVariablesForTemplate,
updateVariablesForTextChange,
} from "../lib/emailVariables";
import { ManualResponseDialog } from "./ManualResponseDialog";
interface DebtCardProps {
debt: Debt;
@@ -65,6 +72,8 @@ const statusColors = {
"bg-blue-100 text-blue-800 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300 dark:border-blue-800",
counter_negotiating:
"bg-yellow-100 text-yellow-800 border-yellow-200 dark:bg-yellow-900/20 dark:text-yellow-300 dark:border-yellow-800",
requires_manual_review:
"bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300 dark:border-amber-800",
accepted:
"bg-green-100 text-green-800 border-green-200 dark:bg-green-900/20 dark:text-green-300 dark:border-green-800",
rejected:
@@ -84,6 +93,7 @@ const statusLabels = {
sent: "Sent",
awaiting_response: "Awaiting Response",
counter_negotiating: "Counter Negotiating",
requires_manual_review: "Manual Review Required",
accepted: "Accepted",
rejected: "Rejected",
settled: "Settled",
@@ -119,35 +129,6 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
});
};
// Extract variables from text in {{ variable }} format
const extractVariables = (text: string): string[] => {
const variableRegex = /\{\{\s*([^}]+)\s*\}\}/g;
const matches: string[] = [];
let match;
while ((match = variableRegex.exec(text)) !== null) {
if (!matches.includes(match[1].trim())) {
matches.push(match[1].trim());
}
}
return matches;
};
// Replace variables in text
const replaceVariables = (
text: string,
variables: Record<string, string>
): string => {
let result = text;
Object.entries(variables).forEach(([key, value]) => {
const regex = new RegExp(
`\\{\\{\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\}\\}`,
"g"
);
result = result.replace(regex, value);
});
return result;
};
const EditableResponseDialog = () => {
const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
@@ -157,56 +138,6 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
// Check if debt is in read-only state (approved or sent)
// Load variables from database
const loadVariables = async () => {
try {
const { data: dbVariables, error } = await supabase
.from("debt_variables")
.select("variable_name, variable_value")
.eq("debt_id", debt.id);
if (error) throw error;
const loadedVariables: Record<string, string> = {};
dbVariables?.forEach((dbVar) => {
loadedVariables[dbVar.variable_name] = dbVar.variable_value || "";
});
return loadedVariables;
} catch (error) {
console.error("Error loading variables:", error);
return {};
}
};
// Save variables to database
const saveVariables = async (variablesToSave: Record<string, string>) => {
try {
// First, delete existing variables for this debt
await supabase.from("debt_variables").delete().eq("debt_id", debt.id);
// Then insert new variables
const variableRecords = Object.entries(variablesToSave).map(
([name, value]) => ({
debt_id: debt.id,
variable_name: name,
variable_value: value,
})
);
if (variableRecords.length > 0) {
const { error } = await supabase
.from("debt_variables")
.insert(variableRecords);
if (error) throw error;
}
} catch (error) {
console.error("Error saving variables:", error);
throw error;
}
};
// Initialize data when dialog opens
useEffect(() => {
const initializeData = async () => {
@@ -215,18 +146,12 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
setSubject(aiEmail.subject || "");
setBody(aiEmail.body || "");
// Extract variables from both subject and body
const allText = `${aiEmail.subject || ""} ${aiEmail.body || ""}`;
const extractedVars = extractVariables(allText);
// Load saved variables from database
const savedVariables = await loadVariables();
// Merge extracted variables with saved values
const initialVariables: Record<string, string> = {};
extractedVars.forEach((variable) => {
initialVariables[variable] = savedVariables[variable] || "";
});
// Get variables for the template using the modular function
const initialVariables = await getVariablesForTemplate(
debt.id,
aiEmail.subject || "",
aiEmail.body || ""
);
setVariables(initialVariables);
}
@@ -238,54 +163,24 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
// Update variables when body changes
const handleBodyChange = (newBody: string) => {
setBody(newBody);
// Extract variables from the new body text
const newVariables = extractVariables(newBody);
const updatedVariables = { ...variables };
// Add new variables if they don't exist
newVariables.forEach((variable) => {
if (!(variable in updatedVariables)) {
updatedVariables[variable] = "";
}
});
// Remove variables that no longer exist in the text
Object.keys(updatedVariables).forEach((variable) => {
if (
!newVariables.includes(variable) &&
!extractVariables(subject).includes(variable)
) {
delete updatedVariables[variable];
}
});
// Update variables using the modular function
const updatedVariables = updateVariablesForTextChange(
variables,
newBody,
subject
);
setVariables(updatedVariables);
};
// Update variables when subject changes
const handleSubjectChange = (newSubject: string) => {
setSubject(newSubject);
// Extract variables from the new subject text
const newVariables = extractVariables(newSubject);
const updatedVariables = { ...variables };
// Add new variables if they don't exist
newVariables.forEach((variable) => {
if (!(variable in updatedVariables)) {
updatedVariables[variable] = "";
}
});
// Remove variables that no longer exist in the text
Object.keys(updatedVariables).forEach((variable) => {
if (
!newVariables.includes(variable) &&
!extractVariables(body).includes(variable)
) {
delete updatedVariables[variable];
}
});
// Update variables using the modular function
const updatedVariables = updateVariablesForTextChange(
variables,
newSubject,
body
);
setVariables(updatedVariables);
};
@@ -295,11 +190,6 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
setVariables(newVariables);
};
// Get preview text with variables replaced
const getPreviewText = () => {
return replaceVariables(`Subject: ${subject}\n\n${body}`, variables);
};
// Get display text for subject (for preview in input)
const getSubjectDisplay = () => {
return replaceVariables(subject, variables);
@@ -338,7 +228,7 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
}
// Save variables to database
await saveVariables(variables);
await saveVariablesToDatabase(debt.id, variables);
toast.success("Changes saved", {
description:
@@ -722,6 +612,11 @@ export function DebtCard({ debt, onUpdate }: DebtCardProps) {
{debt.metadata?.aiEmail && <EditableResponseDialog />}
</div>
{/* Manual Response Dialog - show when requires manual review */}
{debt.status === "requires_manual_review" && (
<ManualResponseDialog debt={debt} onResponseSent={onUpdate} />
)}
{/* Approve/Reject Buttons */}
{showApproveRejectButtons() && (
<div className="space-y-2">

View File

@@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react";
import {
CheckCircle,
Clock,
AlertCircle,
AlertTriangle,
XCircle,
StopCircle,
Send,
@@ -76,6 +76,7 @@ const statusIcons = {
sent: Send,
awaiting_response: Clock,
counter_negotiating: RefreshCw,
requires_manual_review: AlertTriangle,
accepted: ThumbsUp,
rejected: ThumbsDown,
settled: CheckCircle,

View File

@@ -0,0 +1,341 @@
import React, { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "./ui/dialog";
import { Button } from "./ui/button";
import { Textarea } from "./ui/textarea";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Separator } from "./ui/separator";
import {
AlertCircle,
Mail,
Send,
Eye,
MessageSquare,
Building2,
User,
Calendar,
} from "lucide-react";
import { supabase, type Debt } from "../lib/supabase";
import { toast } from "sonner";
interface ConversationMessage {
id: string;
debt_id: string;
message_type: string;
direction: "inbound" | "outbound";
subject?: string;
body: string;
from_email?: string;
to_email?: string;
ai_analysis?: any;
created_at: string;
}
interface ManualResponseDialogProps {
debt: Debt;
onResponseSent?: () => void;
}
export function ManualResponseDialog({
debt,
onResponseSent,
}: ManualResponseDialogProps) {
const [open, setOpen] = useState(false);
const [subject, setSubject] = useState("");
const [body, setBody] = useState("");
const [isSending, setIsSending] = useState(false);
const [lastMessage, setLastMessage] = useState<ConversationMessage | null>(
null
);
// Fetch the last inbound message when dialog opens
useEffect(() => {
if (open) {
fetchLastInboundMessage();
generateDefaultResponse();
}
}, [open, debt.id]);
const fetchLastInboundMessage = async () => {
try {
const { data, error } = await supabase
.from("conversation_messages")
.select("*")
.eq("debt_id", debt.id)
.eq("direction", "inbound")
.order("created_at", { ascending: false })
.limit(1)
.single();
if (error) {
console.error("Error fetching last message:", error);
return;
}
setLastMessage(data);
} catch (error) {
console.error("Error fetching last message:", error);
}
};
const generateDefaultResponse = () => {
// Generate a default subject line
const defaultSubject = `Re: ${
debt.metadata?.subject || `Account ${debt.vendor}`
}`;
setSubject(defaultSubject);
// Generate a basic template response
const defaultBody = `Dear ${debt.vendor},
Thank you for your recent correspondence regarding this account.
I am writing to discuss the terms of this debt and explore options for resolution. I would like to work with you to find a mutually acceptable solution.
Please let me know what options are available for resolving this matter.
Thank you for your time and consideration.
Sincerely,
{{ Your Name }}`;
setBody(defaultBody);
};
const handleSendResponse = async () => {
if (!subject.trim() || !body.trim()) {
toast.error("Please fill in both subject and message");
return;
}
setIsSending(true);
try {
// Create conversation message
const { error: messageError } = await supabase
.from("conversation_messages")
.insert({
debt_id: debt.id,
message_type: "manual_response",
direction: "outbound",
subject: subject.trim(),
body: body.trim(),
from_email: debt.metadata?.toEmail || "user@example.com",
to_email: debt.metadata?.fromEmail || debt.vendor,
message_id: `manual-${Date.now()}`,
});
if (messageError) {
throw messageError;
}
// Update debt status
const { error: debtError } = await supabase
.from("debts")
.update({
status: "awaiting_response",
last_message_at: new Date().toISOString(),
conversation_count: (debt.conversation_count || 0) + 1,
})
.eq("id", debt.id);
if (debtError) {
throw debtError;
}
// Log the action
await supabase.from("audit_logs").insert({
debt_id: debt.id,
action: "manual_response_sent",
details: {
subject: subject.trim(),
bodyLength: body.trim().length,
sentAt: new Date().toISOString(),
},
});
toast.success("Response Sent", {
description:
"Your manual response has been recorded and the debt status updated.",
});
setOpen(false);
onResponseSent?.();
} catch (error) {
console.error("Error sending manual response:", error);
toast.error("Failed to send response", {
description: "Please try again or contact support.",
});
} finally {
setIsSending(false);
}
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="w-full">
<MessageSquare className="h-4 w-4 mr-2" />
Manual Response Required
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-amber-500" />
Manual Response Required
</DialogTitle>
<DialogDescription>
The AI couldn't determine the creditor's intent clearly. Please
review their response and compose a manual reply.
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Left Column: Creditor's Last Response */}
<div className="space-y-4">
<div>
<h3 className="text-lg font-semibold mb-3">
Creditor's Last Response
</h3>
{lastMessage ? (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium">
{lastMessage.subject || "No Subject"}
</CardTitle>
<Badge variant="outline" className="text-xs">
{formatDate(lastMessage.created_at)}
</Badge>
</div>
<div className="flex items-center gap-2 text-sm text-gray-600">
<Building2 className="h-3 w-3" />
<span>{lastMessage.from_email} You</span>
</div>
</CardHeader>
<CardContent>
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-3 text-sm">
<p className="whitespace-pre-wrap text-gray-700 dark:text-gray-300">
{lastMessage.body}
</p>
</div>
{lastMessage.ai_analysis && (
<div className="mt-3 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800">
<div className="text-sm">
<div className="font-medium text-amber-800 dark:text-amber-200 mb-1">
AI Analysis
</div>
<div className="text-amber-700 dark:text-amber-300">
Intent:{" "}
{lastMessage.ai_analysis.intent || "unclear"}
{lastMessage.ai_analysis.confidence && (
<span className="ml-2">
(
{Math.round(
lastMessage.ai_analysis.confidence * 100
)}
% confidence)
</span>
)}
</div>
{lastMessage.ai_analysis.reasoning && (
<div className="text-xs text-amber-600 dark:text-amber-400 mt-1">
{lastMessage.ai_analysis.reasoning}
</div>
)}
</div>
</div>
)}
</CardContent>
</Card>
) : (
<div className="text-center py-8 text-gray-500">
<Mail className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p>No recent creditor response found</p>
</div>
)}
</div>
</div>
{/* Right Column: Compose Response */}
<div className="space-y-4">
<div>
<h3 className="text-lg font-semibold mb-3">
Compose Your Response
</h3>
<div className="space-y-4">
<div>
<Label htmlFor="subject">Subject Line</Label>
<Input
id="subject"
value={subject}
onChange={(e) => setSubject(e.target.value)}
placeholder="Enter subject line..."
className="mt-1"
/>
</div>
<div>
<Label htmlFor="body">Message Body</Label>
<Textarea
id="body"
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Compose your response..."
className="mt-1 min-h-[300px]"
/>
<div className="text-xs text-gray-500 mt-1">
{
"Use {{ Your Name }} for placeholders that will be replaced with your actual information."
}
</div>
</div>
</div>
</div>
</div>
</div>
<Separator />
<DialogFooter className="flex justify-between">
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={handleSendResponse} disabled={isSending}>
{isSending ? (
<>
<Send className="h-4 w-4 mr-2 animate-pulse" />
Sending...
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
Send Response
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,124 @@
/**
* Test file for email variables utility functions
* This file contains unit tests to verify the modular variable processing logic
*/
import { describe, it, expect } from 'vitest';
import {
extractVariables,
replaceVariables,
updateVariablesForTextChange
} from './emailVariables';
describe('Email Variables Utility Functions', () => {
describe('extractVariables', () => {
it('should extract variables from text with {{ }} format', () => {
const text = 'Hello {{ name }}, your balance is {{ amount }}.';
const result = extractVariables(text);
expect(result).toEqual(['name', 'amount']);
});
it('should handle variables with extra spaces', () => {
const text = 'Hello {{ name }}, your balance is {{amount}}.';
const result = extractVariables(text);
expect(result).toEqual(['name', 'amount']);
});
it('should return unique variables only', () => {
const text = 'Hello {{ name }}, {{ name }} owes {{ amount }}.';
const result = extractVariables(text);
expect(result).toEqual(['name', 'amount']);
});
it('should return empty array for text without variables', () => {
const text = 'Hello there, no variables here.';
const result = extractVariables(text);
expect(result).toEqual([]);
});
it('should handle empty text', () => {
const text = '';
const result = extractVariables(text);
expect(result).toEqual([]);
});
});
describe('replaceVariables', () => {
it('should replace variables with their values', () => {
const text = 'Hello {{ name }}, your balance is {{ amount }}.';
const variables = { name: 'John', amount: '$500' };
const result = replaceVariables(text, variables);
expect(result).toBe('Hello John, your balance is $500.');
});
it('should handle variables with extra spaces', () => {
const text = 'Hello {{ name }}, your balance is {{ amount }}.';
const variables = { name: 'John', amount: '$500' };
const result = replaceVariables(text, variables);
expect(result).toBe('Hello John, your balance is $500.');
});
it('should leave unreplaced variables as-is when no value provided', () => {
const text = 'Hello {{ name }}, your balance is {{ amount }}.';
const variables = { name: 'John' };
const result = replaceVariables(text, variables);
expect(result).toBe('Hello John, your balance is {{ amount }}.');
});
it('should handle special characters in variable names', () => {
const text = 'Hello {{ user-name }}, your balance is {{ total_amount }}.';
const variables = { 'user-name': 'John', 'total_amount': '$500' };
const result = replaceVariables(text, variables);
expect(result).toBe('Hello John, your balance is $500.');
});
it('should handle empty variables object', () => {
const text = 'Hello {{ name }}, your balance is {{ amount }}.';
const variables = {};
const result = replaceVariables(text, variables);
expect(result).toBe('Hello {{ name }}, your balance is {{ amount }}.');
});
});
describe('updateVariablesForTextChange', () => {
it('should add new variables from text', () => {
const currentVariables = { name: 'John' };
const newText = 'Hello {{ name }}, your balance is {{ amount }}.';
const otherText = '';
const result = updateVariablesForTextChange(currentVariables, newText, otherText);
expect(result).toEqual({ name: 'John', amount: '' });
});
it('should remove variables not present in any text', () => {
const currentVariables = { name: 'John', amount: '$500', oldVar: 'value' };
const newText = 'Hello {{ name }}, your balance is {{ amount }}.';
const otherText = '';
const result = updateVariablesForTextChange(currentVariables, newText, otherText);
expect(result).toEqual({ name: 'John', amount: '$500' });
});
it('should preserve variables present in other text', () => {
const currentVariables = { name: 'John', amount: '$500', subject: 'Payment' };
const newText = 'Hello {{ name }}, your balance is {{ amount }}.';
const otherText = 'Subject: {{ subject }}';
const result = updateVariablesForTextChange(currentVariables, newText, otherText);
expect(result).toEqual({ name: 'John', amount: '$500', subject: 'Payment' });
});
it('should handle empty current variables', () => {
const currentVariables = {};
const newText = 'Hello {{ name }}, your balance is {{ amount }}.';
const otherText = '';
const result = updateVariablesForTextChange(currentVariables, newText, otherText);
expect(result).toEqual({ name: '', amount: '' });
});
it('should handle empty new text', () => {
const currentVariables = { name: 'John', amount: '$500' };
const newText = '';
const otherText = '';
const result = updateVariablesForTextChange(currentVariables, newText, otherText);
expect(result).toEqual({});
});
});
});

245
src/lib/emailVariables.ts Normal file
View File

@@ -0,0 +1,245 @@
/**
* Email Variables Utility Module
*
* This module provides functions for handling email template variables:
* - Extracting variables from text in {{ variable }} format
* - Replacing variables with their values
* - Loading and saving variables from/to the database
* - Processing complete email templates
*/
import { supabase } from "./supabase";
export interface VariableProcessingResult {
processedSubject: string;
processedBody: string;
hasUnfilledVariables: boolean;
unfilledVariables: string[];
}
/**
* Extract variables from text in {{ variable }} format
* @param text - The text to extract variables from
* @returns Array of unique variable names found in the text
*/
export function extractVariables(text: string): string[] {
const variableRegex = /\{\{\s*([^}]+)\s*\}\}/g;
const matches: string[] = [];
let match;
while ((match = variableRegex.exec(text)) !== null) {
const variableName = match[1].trim();
if (!matches.includes(variableName)) {
matches.push(variableName);
}
}
return matches;
}
/**
* Replace variables in text with their values
* @param text - The text containing variable placeholders
* @param variables - Object mapping variable names to their values
* @returns Text with variables replaced by their values
*/
export function replaceVariables(
text: string,
variables: Record<string, string>
): string {
let result = text;
Object.entries(variables).forEach(([key, value]) => {
// Escape special regex characters in the variable name
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`\\{\\{\\s*${escapedKey}\\s*\\}\\}`, "g");
result = result.replace(regex, value);
});
return result;
}
/**
* Load variables from database for a specific debt
* @param debtId - The ID of the debt record
* @returns Object mapping variable names to their values
*/
export async function loadVariablesFromDatabase(
debtId: string
): Promise<Record<string, string>> {
try {
const { data: dbVariables, error } = await supabase
.from("debt_variables")
.select("variable_name, variable_value")
.eq("debt_id", debtId);
if (error) {
console.error("Error loading variables from database:", error);
throw error;
}
const loadedVariables: Record<string, string> = {};
dbVariables?.forEach((dbVar) => {
loadedVariables[dbVar.variable_name] = dbVar.variable_value || "";
});
return loadedVariables;
} catch (error) {
console.error("Error in loadVariablesFromDatabase:", error);
return {};
}
}
/**
* Save variables to database for a specific debt
* @param debtId - The ID of the debt record
* @param variables - Object mapping variable names to their values
*/
export async function saveVariablesToDatabase(
debtId: string,
variables: Record<string, string>
): Promise<void> {
try {
// First, delete existing variables for this debt
const { error: deleteError } = await supabase
.from("debt_variables")
.delete()
.eq("debt_id", debtId);
if (deleteError) {
console.error("Error deleting existing variables:", deleteError);
throw deleteError;
}
// Then insert new variables
const variableRecords = Object.entries(variables).map(([name, value]) => ({
debt_id: debtId,
variable_name: name,
variable_value: value,
}));
if (variableRecords.length > 0) {
const { error: insertError } = await supabase
.from("debt_variables")
.insert(variableRecords);
if (insertError) {
console.error("Error inserting variables:", insertError);
throw insertError;
}
}
} catch (error) {
console.error("Error in saveVariablesToDatabase:", error);
throw error;
}
}
/**
* Process email template by extracting variables, loading values, and replacing placeholders
* @param debtId - The ID of the debt record
* @param subject - The email subject template
* @param body - The email body template
* @returns Object containing processed subject/body and unfilled variable information
*/
export async function processEmailTemplate(
debtId: string,
subject: string,
body: string
): Promise<VariableProcessingResult> {
try {
// Extract all variables from subject and body
const allText = `${subject} ${body}`;
const extractedVars = extractVariables(allText);
// Load saved variables from database
const savedVariables = await loadVariablesFromDatabase(debtId);
// Check which variables don't have values
const unfilledVariables = extractedVars.filter(
variable => !savedVariables[variable] || savedVariables[variable].trim() === ""
);
const hasUnfilledVariables = unfilledVariables.length > 0;
// Replace variables in subject and body
const processedSubject = replaceVariables(subject, savedVariables);
const processedBody = replaceVariables(body, savedVariables);
return {
processedSubject,
processedBody,
hasUnfilledVariables,
unfilledVariables,
};
} catch (error) {
console.error("Error in processEmailTemplate:", error);
throw error;
}
}
/**
* Get all variables from subject and body text, merging with saved values
* @param debtId - The ID of the debt record
* @param subject - The email subject template
* @param body - The email body template
* @returns Object mapping variable names to their values (empty string if not saved)
*/
export async function getVariablesForTemplate(
debtId: string,
subject: string,
body: string
): Promise<Record<string, string>> {
try {
// Extract variables from both subject and body
const allText = `${subject} ${body}`;
const extractedVars = extractVariables(allText);
// Load saved variables from database
const savedVariables = await loadVariablesFromDatabase(debtId);
// Merge extracted variables with saved values
const variables: Record<string, string> = {};
extractedVars.forEach((variable) => {
variables[variable] = savedVariables[variable] || "";
});
return variables;
} catch (error) {
console.error("Error in getVariablesForTemplate:", error);
return {};
}
}
/**
* Update variables when template text changes
* @param currentVariables - Current variable values
* @param newText - New template text
* @param otherText - Other template text (e.g., if updating body, pass subject here)
* @returns Updated variables object
*/
export function updateVariablesForTextChange(
currentVariables: Record<string, string>,
newText: string,
otherText: string = ""
): Record<string, string> {
// Extract variables from the new text and other text
const allText = `${newText} ${otherText}`;
const newVariables = extractVariables(allText);
const updatedVariables = { ...currentVariables };
// Add new variables if they don't exist
newVariables.forEach((variable) => {
if (!(variable in updatedVariables)) {
updatedVariables[variable] = "";
}
});
// Remove variables that no longer exist in any text
Object.keys(updatedVariables).forEach((variable) => {
if (!newVariables.includes(variable)) {
delete updatedVariables[variable];
}
});
return updatedVariables;
}

View File

@@ -29,6 +29,7 @@ export type Debt = {
| "sent"
| "awaiting_response"
| "counter_negotiating"
| "requires_manual_review"
| "accepted"
| "rejected"
| "settled"
@@ -103,7 +104,8 @@ export type ConversationMessage = {
| "response_received"
| "counter_offer"
| "acceptance"
| "rejection";
| "rejection"
| "manual_response";
direction: "inbound" | "outbound";
subject?: string;
body: string;

View File

@@ -284,7 +284,7 @@ async function handleNegotiationResponse(
// Update status to require user review
await supabaseAdmin
.from("debts")
.update({ status: "awaiting_response" })
.update({ status: "requires_manual_review" })
.eq("id", debt.id);
return new Response(

View File

@@ -506,6 +506,8 @@ serve(async (req) => {
debt.metadata?.aiEmail,
);
console.log({ analysis });
// Store the conversation message
const { error: messageError } = await supabaseClient
.from("conversation_messages")
@@ -557,11 +559,11 @@ serve(async (req) => {
nextAction = analysis.suggestedNextAction;
break;
case "request_info":
newStatus = "awaiting_response";
newStatus = "requires_manual_review";
nextAction = "escalate_to_user";
break;
default:
newStatus = "awaiting_response";
newStatus = "requires_manual_review";
nextAction = "escalate_to_user";
}
@@ -670,6 +672,12 @@ serve(async (req) => {
});
}
console.log({
shouldAutoRespond,
analysisIntent: analysis.intent,
analysisConfidence: analysis.confidence,
});
// If auto-response is recommended and confidence is high, trigger negotiation
if (
shouldAutoRespond && analysis.confidence > 0.8 &&

View File

@@ -73,13 +73,42 @@ interface DebtRecord {
isDebtCollection?: boolean;
subject?: string;
fromEmail?: string;
toEmail?: string;
aiEmail?: {
subject: string;
body: string;
strategy: string;
confidence: number;
reasoning: string;
customTerms: Record<string, unknown>;
};
lastResponse?: {
analysis: Record<string, unknown>;
receivedAt: string;
fromEmail: string;
subject: string;
};
};
}
interface CounterOfferContext {
previousResponse: string;
extractedTerms: {
proposedAmount?: number;
proposedPaymentPlan?: string;
monthlyAmount?: number;
numberOfPayments?: number;
totalAmount?: number;
paymentFrequency?: string;
};
sentiment: string;
}
// AI-powered negotiation email generator
async function generateNegotiationEmail(
record: DebtRecord,
personalData: PersonalData,
counterOfferContext?: CounterOfferContext,
) {
try {
const googleApiKey = Deno.env.get("GOOGLE_GENERATIVE_AI_API_KEY");
@@ -88,12 +117,9 @@ async function generateNegotiationEmail(
return generateFallbackEmail(record, personalData);
}
const result = await generateObject({
model: createGoogleGenerativeAI({
apiKey: googleApiKey,
})("gemini-2.5-flash-preview-04-17"),
system:
`You are an expert debt negotiation advisor specializing in FDCPA-compliant email generation.
// Build context-aware system prompt
let systemPrompt =
`You are an expert debt negotiation advisor specializing in FDCPA-compliant email generation.
Create professional, formal negotiation emails that:
- Include appropriate subject line and email body
- Follow Fair Debt Collection Practices Act requirements
@@ -110,8 +136,10 @@ async function generateNegotiationEmail(
- Dispute: If debt validity is questionable
For missing personal data, use appropriate placeholders.
For uncertain information like account numbers, use {{ Account Number }} format.`,
prompt: `Generate a complete negotiation email for this debt:
For uncertain information like account numbers, use {{ Account Number }} format.`;
// Build context-aware prompt
let prompt = `Generate a complete negotiation email for this debt:
Debt Amount: $${record.amount}
Vendor: ${record.vendor}
@@ -122,14 +150,47 @@ async function generateNegotiationEmail(
Personal Data Available:
- Full Name: ${personalData.full_name || "{{ Full Name }}"}
- Address: ${personalData.address_line_1 || "{{ Address Line 1 }}"} ${
personalData.address_line_2 ? personalData.address_line_2 : ""
}
personalData.address_line_2 ? personalData.address_line_2 : ""
}
- City: ${personalData.city || "{{ City }}"}
- State: ${personalData.state || "{{ State }}"}
- Zip: ${personalData.zip_code || "{{ Zip Code }}"}
- Phone: ${personalData.phone_number || "{{ Phone Number }}"}
- Phone: ${personalData.phone_number || "{{ Phone Number }}"}`;
Create a professional negotiation email with subject and body.`,
// Add counter-offer context if this is a response to a creditor's counter-offer
if (counterOfferContext) {
systemPrompt += `
IMPORTANT: This is a COUNTER-RESPONSE to a creditor's previous response. You must:
- Acknowledge their previous response professionally
- Address their specific terms or concerns
- Make a strategic counter-offer that moves toward resolution
- Show willingness to negotiate while protecting the debtor's interests
- Reference specific amounts or terms they mentioned
- Maintain momentum in the negotiation process`;
prompt += `
CREDITOR'S PREVIOUS RESPONSE CONTEXT:
- Their Response: ${counterOfferContext.previousResponse}
- Sentiment: ${counterOfferContext.sentiment}
- Extracted Terms: ${JSON.stringify(counterOfferContext.extractedTerms)}
Generate a strategic counter-response that acknowledges their position and makes a reasonable counter-offer.`;
} else {
prompt += `
Create a professional initial negotiation email with subject and body.`;
}
console.log({ systemPrompt, prompt });
const result = await generateObject({
model: createGoogleGenerativeAI({
apiKey: googleApiKey,
})("gemini-2.5-flash-preview-04-17"),
system: systemPrompt,
prompt: prompt,
schema: negotiationEmailSchema,
});
@@ -310,7 +371,10 @@ Deno.serve(async (req) => {
);
// For webhook calls, we'll get the userId from the request body along with the record
const { record }: { record: DebtRecord } = await req.json();
const { record, counterOfferContext }: {
record: DebtRecord;
counterOfferContext?: CounterOfferContext;
} = await req.json();
if (!record || !record.user_id) {
return new Response(
@@ -328,7 +392,12 @@ Deno.serve(async (req) => {
// Use the record as-is for webhook calls
const personalData = await fetchUserPersonalData(supabaseClient, user.id);
return await processNegotiation(supabaseClient, record, personalData);
return await processNegotiation(
supabaseClient,
record,
personalData,
counterOfferContext,
);
} else {
// This is an authenticated user call
if (!authHeader) {
@@ -452,21 +521,43 @@ async function processNegotiation(
supabaseClient: ReturnType<typeof createClient>,
record: DebtRecord,
personalData: PersonalData,
counterOfferContext?: CounterOfferContext,
): Promise<Response>;
async function processNegotiation(
supabaseClient: unknown,
record: DebtRecord,
personalData: PersonalData,
counterOfferContext?: CounterOfferContext,
): Promise<Response>;
async function processNegotiation(
supabaseClient: unknown,
record: DebtRecord,
personalData: PersonalData,
counterOfferContext?: CounterOfferContext,
): Promise<Response> {
const client = supabaseClient as ReturnType<typeof createClient>;
// Generate AI-powered negotiation email
const emailResult = await generateNegotiationEmail(record, personalData);
const emailResult = await generateNegotiationEmail(
record,
personalData,
counterOfferContext,
);
// Create conversation message for the AI-generated response
const messageType = counterOfferContext
? "counter_offer"
: "negotiation_sent";
await client.from("conversation_messages").insert({
debt_id: record.id,
message_type: messageType,
direction: "outbound",
subject: emailResult.subject,
body: emailResult.body,
from_email: record.metadata?.toEmail || "user@example.com",
to_email: record.metadata?.fromEmail || record.vendor,
message_id: `ai-generated-${Date.now()}`,
});
// Update debt record with AI-generated content - using provided client
const { error: updateError } = await client
@@ -474,7 +565,7 @@ async function processNegotiation(
.update({
negotiated_plan: `Subject: ${emailResult.subject}\n\n${emailResult.body}`,
projected_savings: emailResult.projectedSavings,
status: "negotiating",
status: counterOfferContext ? "counter_negotiating" : "negotiating",
metadata: {
...record.metadata,
aiEmail: {
@@ -498,13 +589,17 @@ async function processNegotiation(
.from("audit_logs")
.insert({
debt_id: record.id,
action: "negotiation_generated",
action: counterOfferContext
? "auto_counter_response_generated"
: "negotiation_generated",
details: {
strategy: emailResult.strategy,
amount: record.amount,
projected_savings: emailResult.projectedSavings,
ai_confidence: emailResult.confidenceLevel,
reasoning: emailResult.reasoning,
isCounterResponse: !!counterOfferContext,
counterOfferContext: counterOfferContext || null,
},
});

View File

@@ -3,6 +3,7 @@
This function sends negotiated emails via Postmark:
- Validates user has server token configured
- Processes email variables and replaces placeholders
- Sends the approved negotiation email to the debt collector
- Updates debt status and logs the action
- Ensures FDCPA compliance
@@ -81,6 +82,100 @@ async function sendEmailViaPostmark(
return await response.json();
}
// Extract variables from text in {{ variable }} format
function extractVariables(text: string): string[] {
const variableRegex = /\{\{\s*([^}]+)\s*\}\}/g;
const matches: string[] = [];
let match;
while ((match = variableRegex.exec(text)) !== null) {
if (!matches.includes(match[1].trim())) {
matches.push(match[1].trim());
}
}
return matches;
}
// Replace variables in text with their values
function replaceVariables(
text: string,
variables: Record<string, string>,
): string {
let result = text;
Object.entries(variables).forEach(([key, value]) => {
const regex = new RegExp(
`\\{\\{\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\}\\}`,
"g",
);
result = result.replace(regex, value);
});
return result;
}
// Load variables from database for a specific debt
async function loadVariablesFromDatabase(
supabaseClient: any,
debtId: string,
): Promise<Record<string, string>> {
try {
const { data: dbVariables, error } = await supabaseClient
.from("debt_variables")
.select("variable_name, variable_value")
.eq("debt_id", debtId);
if (error) throw error;
const loadedVariables: Record<string, string> = {};
dbVariables?.forEach((dbVar: any) => {
loadedVariables[dbVar.variable_name] = dbVar.variable_value || "";
});
return loadedVariables;
} catch (error) {
console.error("Error loading variables:", error);
return {};
}
}
// Process email template by replacing variables with their values
async function processEmailTemplate(
supabaseClient: any,
debtId: string,
subject: string,
body: string,
): Promise<
{
processedSubject: string;
processedBody: string;
hasUnfilledVariables: boolean;
}
> {
// Extract all variables from subject and body
const allText = `${subject} ${body}`;
const extractedVars = extractVariables(allText);
// Load saved variables from database
const savedVariables = await loadVariablesFromDatabase(
supabaseClient,
debtId,
);
// Check if all variables have values
const unfilledVariables = extractedVars.filter((variable) =>
!savedVariables[variable] || savedVariables[variable].trim() === ""
);
const hasUnfilledVariables = unfilledVariables.length > 0;
// Replace variables in subject and body
const processedSubject = replaceVariables(subject, savedVariables);
const processedBody = replaceVariables(body, savedVariables);
return {
processedSubject,
processedBody,
hasUnfilledVariables,
};
}
// Extract email address from various formats
function extractEmailAddress(emailString: string): string {
// Handle formats like "Name <email@domain.com>" or just "email@domain.com"
@@ -209,8 +304,8 @@ Deno.serve(async (req) => {
);
}
// Extract email details
const { subject, body } = debt.metadata.aiEmail;
// Extract email details and process variables
const { subject: rawSubject, body: rawBody } = debt.metadata.aiEmail;
const fromEmail = debt.metadata?.toEmail || user.email;
if (!fromEmail) {
@@ -223,6 +318,33 @@ Deno.serve(async (req) => {
);
}
// Process email template and replace variables
const { processedSubject, processedBody, hasUnfilledVariables } =
await processEmailTemplate(
supabaseClient,
debtId,
rawSubject,
rawBody,
);
// Check if there are unfilled variables
if (hasUnfilledVariables) {
return new Response(
JSON.stringify({
error: "Email contains unfilled variables",
details:
"Please fill in all required variables before sending the email.",
}),
{
status: 400,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
const subject = processedSubject;
const body = processedBody;
// Determine recipient email
let toEmail = debt.vendor;
if (debt.metadata?.fromEmail) {

View File

@@ -0,0 +1,49 @@
-- Add manual review status and message type
-- This migration adds support for manual review when AI can't determine creditor intent
-- Update debts table status constraint to include requires_manual_review
ALTER TABLE debts
DROP CONSTRAINT IF EXISTS debts_status_check;
ALTER TABLE debts
ADD CONSTRAINT debts_status_check
CHECK (status IN (
'received',
'negotiating',
'approved',
'sent',
'awaiting_response',
'counter_negotiating',
'requires_manual_review',
'accepted',
'rejected',
'settled',
'failed',
'opted_out'
));
-- Update conversation_messages table message_type constraint to include manual_response
ALTER TABLE conversation_messages
DROP CONSTRAINT IF EXISTS conversation_messages_message_type_check;
ALTER TABLE conversation_messages
ADD CONSTRAINT conversation_messages_message_type_check
CHECK (message_type IN (
'initial_debt',
'negotiation_sent',
'response_received',
'counter_offer',
'acceptance',
'rejection',
'manual_response'
));
-- Add comments for documentation
COMMENT ON CONSTRAINT debts_status_check ON debts IS 'Valid debt statuses including manual review for unclear AI responses';
COMMENT ON CONSTRAINT conversation_messages_message_type_check ON conversation_messages IS 'Valid message types including manual responses from users';
-- Add index for manual review status for performance
CREATE INDEX IF NOT EXISTS idx_debts_manual_review ON debts(status) WHERE status = 'requires_manual_review';
-- Update RLS policies to handle manual responses (already covered by existing policies)
-- No additional RLS changes needed as existing policies cover manual_response message type