Skip to content
Open
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
89 changes: 89 additions & 0 deletions src/__tests__/useSplitCalculator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { resolveRounding } from '@/hooks/useSplitCalculator';

describe('resolveRounding', () => {
const STROOP_SCALE = 1e7;

it('should resolve rounding for 3-recipient split', () => {
const percentages = [33.33, 33.33, 33.34];
const totalAmount = 100;

const result = resolveRounding(percentages, totalAmount);

expect(result.amounts).toHaveLength(3);
const sumStroops = result.amounts.reduce(
(s, a) => s + Math.round(a * STROOP_SCALE),
0
);
const totalStroops = Math.round(totalAmount * STROOP_SCALE);
expect(sumStroops).toBe(totalStroops);
});

it('should resolve rounding for 7-recipient split', () => {
const percentages = [14.28, 14.28, 14.28, 14.28, 14.28, 14.29, 14.31];
const totalAmount = 1000;

const result = resolveRounding(percentages, totalAmount);

expect(result.amounts).toHaveLength(7);
const sumStroops = result.amounts.reduce(
(s, a) => s + Math.round(a * STROOP_SCALE),
0
);
const totalStroops = Math.round(totalAmount * STROOP_SCALE);
expect(sumStroops).toBe(totalStroops);
});

it('should resolve rounding for 11-recipient split', () => {
const percentages = Array(11)
.fill(0)
.map((_, i) => (i === 10 ? 9.1 : 9.09));
const totalAmount = 5000;

const result = resolveRounding(percentages, totalAmount);

expect(result.amounts).toHaveLength(11);
const sumStroops = result.amounts.reduce(
(s, a) => s + Math.round(a * STROOP_SCALE),
0
);
const totalStroops = Math.round(totalAmount * STROOP_SCALE);
expect(sumStroops).toBe(totalStroops);
});

it('should assign adjustment to first recipient', () => {
const percentages = [50, 50];
const totalAmount = 100;

const result = resolveRounding(percentages, totalAmount);

expect(result.recipientIndex).toBe(0);
});

it('should return zero adjustment when no rounding needed', () => {
const percentages = [25, 25, 25, 25];
const totalAmount = 100;

const result = resolveRounding(percentages, totalAmount);

const sumStroops = result.amounts.reduce(
(s, a) => s + Math.round(a * STROOP_SCALE),
0
);
const totalStroops = Math.round(totalAmount * STROOP_SCALE);
expect(sumStroops).toBe(totalStroops);
});

it('should handle fractional stroop amounts', () => {
const percentages = [33.333, 33.333, 33.334];
const totalAmount = 123.456789;

const result = resolveRounding(percentages, totalAmount);

const sumStroops = result.amounts.reduce(
(s, a) => s + Math.round(a * STROOP_SCALE),
0
);
const totalStroops = Math.round(totalAmount * STROOP_SCALE);
expect(sumStroops).toBe(totalStroops);
});
});
39 changes: 39 additions & 0 deletions src/app/api/validate-email/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { promises as dns } from "dns";

export async function POST(request: Request) {
try {
const { email } = await request.json();

if (!email || typeof email !== "string") {
return NextResponse.json(
{ error: "Email is required" },
{ status: 400 }
);
}

const parts = email.split("@");
if (parts.length !== 2) {
return NextResponse.json(
{ valid: false, hasMX: false },
{ status: 200 }
);
}

const domain = parts[1];

try {
const mxRecords = await dns.resolveMx(domain);
const hasMX = Array.isArray(mxRecords) && mxRecords.length > 0;
return NextResponse.json({ valid: true, hasMX }, { status: 200 });
} catch {
return NextResponse.json({ valid: true, hasMX: false }, { status: 200 });
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return NextResponse.json(
{ error: `Validation failed: ${message}` },
{ status: 500 }
);
}
}
62 changes: 62 additions & 0 deletions src/components/EmailField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use client";

import { useEmailValidation } from "@/hooks/useEmailValidation";

interface EmailFieldProps {
email: string;
onEmailChange: (email: string) => void;
onBlur?: () => void;
placeholder?: string;
}

export default function EmailField({
email,
onEmailChange,
onBlur,
placeholder = "recipient@example.com",
}: EmailFieldProps) {
const { isValidFormat, isCheckingMX, mxValid } = useEmailValidation(email);

return (
<div className="flex flex-col gap-1">
<div className="relative flex items-center gap-2">
<input
type="email"
value={email}
onChange={(e) => onEmailChange(e.target.value)}
onBlur={onBlur}
placeholder={placeholder}
className={`flex-1 bg-gray-800 border rounded-lg px-3 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 ${
!email
? "border-gray-700 focus:ring-indigo-500"
: !isValidFormat
? "border-red-500 focus:ring-red-500"
: mxValid === false
? "border-yellow-500 focus:ring-yellow-500"
: "border-green-500 focus:ring-green-500"
}`}
/>
{email && isValidFormat && (
<>
{isCheckingMX && (
<span className="text-xs text-gray-400">Checking...</span>
)}
{!isCheckingMX && mxValid === true && (
<span className="text-green-500 text-sm">✓</span>
)}
{!isCheckingMX && mxValid === false && (
<span className="text-yellow-500 text-sm">⚠</span>
)}
</>
)}
</div>

{email && !isValidFormat && (
<p className="text-xs text-red-400">Invalid email format</p>
)}
{email && isValidFormat && mxValid === false && !isCheckingMX && (
<p className="text-xs text-yellow-400">Domain has no MX records (delivery may fail)</p>
)}
</div>
);
}
140 changes: 78 additions & 62 deletions src/components/RecipientForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import { searchAddressHistory, searchAmountHistory } from "@/lib/invoiceHistory"
import { searchRecipients, touchRecipient, type RecipientEntry } from "@/lib/recipients";
import { truncateAddress } from "@stellar-split/sdk";
import CsvRecipientImport from "@/components/CsvRecipientImport";
import { useEmailValidation } from "@/hooks/useEmailValidation";
import EmailField from "@/components/EmailField";

export interface RecipientRow {
address: string;
amount: string;
label?: string;
email?: string;
}

interface Props {
Expand Down Expand Up @@ -67,9 +70,9 @@ export default function RecipientForm({
}).filter((r) => r.address);
};

const updateRow = (index: number, address: string, label?: string) => {
const updateRow = (index: number, address: string, label?: string, email?: string) => {
const next = recipients.map((r, i) =>
i === index ? { ...r, address, label: label !== undefined ? label : r.label } : r
i === index ? { ...r, address, label: label !== undefined ? label : r.label, email: email !== undefined ? email : r.email } : r
);
onChange(next);
};
Expand Down Expand Up @@ -168,71 +171,84 @@ export default function RecipientForm({
return (
<div className="flex flex-col gap-3">
{recipients.map((row, i) => (
<div key={i} className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-start min-w-0">
<Avatar
address={row.address}
email={emailByAddress[row.address]}
size={32}
className="mt-1.5 hidden sm:inline-flex"
/>

<div className="relative flex-1 min-w-0 w-full">
<AddressBookPicker
value={row.address}
label={row.label}
onChange={(address, label) => updateRow(i, address, label)}
placeholder="G... or name*domain.com address"
ariaLabel={`Recipient ${i + 1} address`}
<div key={i} className="flex flex-col gap-2">
<div className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-start min-w-0">
<Avatar
address={row.address}
email={emailByAddress[row.address]}
size={32}
className="mt-1.5 hidden sm:inline-flex"
/>
</div>

<div className="relative w-full sm:w-28">
<input
type="number"
placeholder="USDC"
step="0.0000001"
min="0.0000001"
value={equalSplit ? (amountOverride ?? "") : row.amount}
onChange={
equalSplit ? undefined : (e) => handleAmountChange(i, e.target.value)
}
onFocus={() => !equalSplit && handleAmountFocus(i)}
readOnly={equalSplit}
required
aria-label={`Recipient ${i + 1} amount`}
className={`w-full bg-gray-800 border rounded-lg px-3 py-2 min-h-11 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
equalSplit
? "border-gray-600 text-gray-400 cursor-not-allowed"
: "border-gray-700"
}`}
/>
{activeField === "amount" && activeIndex === i && amountSuggestions.length > 0 && !equalSplit && (
<ul className="absolute z-10 right-0 w-full bg-gray-800 border border-gray-700 rounded-lg mt-1 max-h-40 overflow-y-auto shadow-lg">
{amountSuggestions.map((amount) => (
<li key={amount}>
<button
type="button"
onMouseDown={() => selectAmountSuggestion(i, amount)}
className="w-full min-h-11 text-left px-3 py-2 text-sm hover:bg-gray-700 font-mono text-gray-200"
>
{amount} USDC
</button>
</li>
))}
</ul>
<div className="relative flex-1 min-w-0 w-full">
<AddressBookPicker
value={row.address}
label={row.label}
onChange={(address, label) => updateRow(i, address, label, row.email)}
placeholder="G... or name*domain.com address"
ariaLabel={`Recipient ${i + 1} address`}
/>
</div>

<div className="relative w-full sm:w-28">
<input
type="number"
placeholder="USDC"
step="0.0000001"
min="0.0000001"
value={equalSplit ? (amountOverride ?? "") : row.amount}
onChange={
equalSplit ? undefined : (e) => handleAmountChange(i, e.target.value)
}
onFocus={() => !equalSplit && handleAmountFocus(i)}
readOnly={equalSplit}
required
aria-label={`Recipient ${i + 1} amount`}
className={`w-full bg-gray-800 border rounded-lg px-3 py-2 min-h-11 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
equalSplit
? "border-gray-600 text-gray-400 cursor-not-allowed"
: "border-gray-700"
}`}
/>
{activeField === "amount" && activeIndex === i && amountSuggestions.length > 0 && !equalSplit && (
<ul className="absolute z-10 right-0 w-full bg-gray-800 border border-gray-700 rounded-lg mt-1 max-h-40 overflow-y-auto shadow-lg">
{amountSuggestions.map((amount) => (
<li key={amount}>
<button
type="button"
onMouseDown={() => selectAmountSuggestion(i, amount)}
className="w-full min-h-11 text-left px-3 py-2 text-sm hover:bg-gray-700 font-mono text-gray-200"
>
{amount} USDC
</button>
</li>
))}
</ul>
)}
</div>

{recipients.length > 1 && (
<button
type="button"
onClick={() => removeRow(i)}
aria-label={`Remove recipient ${i + 1}`}
className="min-h-11 px-3 py-2 rounded-lg bg-gray-700 hover:bg-red-700 text-sm transition-colors sm:self-start focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500"
>
</button>
)}
</div>

{recipients.length > 1 && (
<button
type="button"
onClick={() => removeRow(i)}
aria-label={`Remove recipient ${i + 1}`}
className="min-h-11 px-3 py-2 rounded-lg bg-gray-700 hover:bg-red-700 text-sm transition-colors sm:self-start focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500"
>
</button>
)}
<div className="flex items-center gap-2 min-w-0 w-full">
<div className="hidden sm:block w-8" />
<div className="flex-1">
<EmailField
email={row.email || ""}
onEmailChange={(email) => updateRow(i, row.address, row.label, email)}
onBlur={() => {}}
/>
</div>
</div>
</div>
))}

Expand Down
Loading