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
9 changes: 9 additions & 0 deletions client/src/lib/apiErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { isAxiosError } from "axios";

export const getApiErrorMessage = (error: unknown, fallback: string) => {
if (isAxiosError<{ message?: string }>(error)) {
return error.response?.data.message ?? fallback;
}

return fallback;
};
7 changes: 4 additions & 3 deletions client/src/pages/InvoiceDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Button } from "@/components/Button";
import { StatusBadge } from "@/components/StatusBadge";
import { Toast } from "@/components/Toast";
import { invoicesApi } from "@/lib/api/invoices";
import { getApiErrorMessage } from "@/lib/apiErrors";
import { Page } from "@/pages/Page";
import type { Invoice } from "@/types/invoice";

Expand Down Expand Up @@ -87,9 +88,9 @@ export function InvoiceDetailPage() {
setInvoice(updatedInvoice);
setToast(`Invoice sent to ${invoice.clientEmail}`);
setError(null);
} catch (err) {
setError("Failed to send invoice");
console.error("Error sending invoice:", err);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send invoice"));
console.error("Error sending invoice:", error);
} finally {
setSendLoading(false);
}
Expand Down
7 changes: 4 additions & 3 deletions client/src/pages/InvoicesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Button } from "@/components/Button";
import { PlanBadge } from "@/components/PlanBadge";
import { Toast } from "@/components/Toast";
import { Page } from "@/pages/Page";
import { getApiErrorMessage } from "@/lib/apiErrors";
import { useAuthStore } from "@/store/auth";
import type { Invoice } from "@/types/invoice";

Expand Down Expand Up @@ -68,9 +69,9 @@ export function InvoicesPage() {
setInvoices(invoices.map((item) => (item.id === invoice.id ? updatedInvoice : item)));
setToast(`Invoice sent to ${invoice.clientEmail}`);
setError(null);
} catch (err) {
setError("Failed to send invoice");
console.error("Error sending invoice:", err);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send invoice"));
console.error("Error sending invoice:", error);
} finally {
setSendingInvoiceId(null);
}
Expand Down
7 changes: 4 additions & 3 deletions client/src/pages/ProposalDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Button } from "@/components/Button";
import { StatusBadge } from "@/components/StatusBadge";
import { Toast } from "@/components/Toast";
import { proposalsApi } from "@/lib/api/proposals";
import { getApiErrorMessage } from "@/lib/apiErrors";
import { Page } from "@/pages/Page";
import type { Proposal } from "@/types/invoice";

Expand Down Expand Up @@ -55,9 +56,9 @@ export function ProposalDetailPage() {
setProposal(updatedProposal);
setToast(`Proposal sent to ${proposal.clientEmail}`);
setError(null);
} catch (err) {
setError("Failed to send proposal");
console.error("Error sending proposal:", err);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send proposal"));
console.error("Error sending proposal:", error);
} finally {
setSendLoading(false);
}
Expand Down
7 changes: 4 additions & 3 deletions client/src/pages/ProposalsListPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Button } from "@/components/Button";
import { StatusBadge } from "@/components/StatusBadge";
import { Toast } from "@/components/Toast";
import { proposalsApi } from "@/lib/api/proposals";
import { getApiErrorMessage } from "@/lib/apiErrors";
import { Page } from "@/pages/Page";
import type { Proposal } from "@/types/invoice";

Expand Down Expand Up @@ -64,9 +65,9 @@ export function ProposalsListPage() {
);
setToast(`Proposal sent to ${proposal.clientEmail}`);
setError(null);
} catch (err) {
setError("Failed to send proposal");
console.error("Error sending proposal:", err);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send proposal"));
console.error("Error sending proposal:", error);
} finally {
setSendingId(null);
}
Expand Down
84 changes: 49 additions & 35 deletions server/src/services/emailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const getRequiredEnv = (name: string) => {
const value = process.env[name];

if (!value) {
throw new Error(`${name} is required.`);
console.error("[EMAIL CONFIG]", `${name} is required.`);
throw new HttpError(503, "Email service is not configured");
}

return value;
Expand All @@ -24,7 +25,8 @@ const getSmtpPort = () => {
const port = Number(getRequiredEnv("SMTP_PORT"));

if (!Number.isInteger(port) || port <= 0) {
throw new Error("SMTP_PORT must be a valid port number.");
console.error("[EMAIL CONFIG]", "SMTP_PORT must be a valid port number.");
throw new HttpError(503, "Email service is not configured");
}

return port;
Expand Down Expand Up @@ -157,31 +159,37 @@ export const sendInvoiceEmail = async (invoiceId: string, userId: string) => {
const publicUrl = getPublicInvoiceUrl(invoice.id);
const amountDue = formatInvoiceCurrency(invoice.total, invoice.currency);
const dueDate = formatInvoiceDate(invoice.dueDate);
const transporter = getTransporter();
const [pdfBuffer, filename] = await Promise.all([
generateInvoicePDF(invoice.id, userId),
getInvoicePdfFilename(invoice.id, userId),
]);

await getTransporter().sendMail({
from: process.env.SMTP_FROM ?? getRequiredEnv("SMTP_USER"),
to: invoice.clientEmail,
replyTo: invoice.user.email,
subject: `Invoice ${invoice.number} from ${invoice.user.name}`,
html: renderEmailHtml(invoice, publicUrl),
text: [
`Invoice ${invoice.number} from ${invoice.user.name}`,
`Amount due: ${amountDue}`,
`Due date: ${dueDate}`,
`View invoice: ${publicUrl}`,
].join("\n"),
attachments: [
{
filename,
content: pdfBuffer,
contentType: "application/pdf",
},
],
});
try {
await transporter.sendMail({
from: process.env.SMTP_FROM ?? getRequiredEnv("SMTP_USER"),
to: invoice.clientEmail,
replyTo: invoice.user.email,
subject: `Invoice ${invoice.number} from ${invoice.user.name}`,
html: renderEmailHtml(invoice, publicUrl),
text: [
`Invoice ${invoice.number} from ${invoice.user.name}`,
`Amount due: ${amountDue}`,
`Due date: ${dueDate}`,
`View invoice: ${publicUrl}`,
].join("\n"),
attachments: [
{
filename,
content: pdfBuffer,
contentType: "application/pdf",
},
],
});
} catch (error) {
console.error("[EMAIL SEND ERROR]", error);
throw new HttpError(502, "Unable to send email right now");
}

return {
clientEmail: invoice.clientEmail,
Expand Down Expand Up @@ -244,19 +252,25 @@ export const sendProposalEmail = async (proposalId: string, userId: string) => {
}

const publicUrl = getPublicProposalUrl(proposal.id);

await getTransporter().sendMail({
from: process.env.SMTP_FROM ?? getRequiredEnv("SMTP_USER"),
to: proposal.clientEmail,
replyTo: proposal.user.email,
subject: `${proposal.title} from ${proposal.user.name}`,
html: renderProposalEmailHtml(proposal, publicUrl),
text: [
`${proposal.title} from ${proposal.user.name}`,
`Client: ${proposal.clientName}`,
`View proposal: ${publicUrl}`,
].join("\n"),
});
const transporter = getTransporter();

try {
await transporter.sendMail({
from: process.env.SMTP_FROM ?? getRequiredEnv("SMTP_USER"),
to: proposal.clientEmail,
replyTo: proposal.user.email,
subject: `${proposal.title} from ${proposal.user.name}`,
html: renderProposalEmailHtml(proposal, publicUrl),
text: [
`${proposal.title} from ${proposal.user.name}`,
`Client: ${proposal.clientName}`,
`View proposal: ${publicUrl}`,
].join("\n"),
});
} catch (error) {
console.error("[EMAIL SEND ERROR]", error);
throw new HttpError(502, "Unable to send email right now");
}

return {
clientEmail: proposal.clientEmail,
Expand Down
74 changes: 73 additions & 1 deletion server/test/invoices.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import request from 'supertest';
import { testApp, testAccessToken, testUserId, prisma } from './setup';

Expand Down Expand Up @@ -358,6 +358,78 @@ describe('Invoice Endpoints', () => {
});
});

describe('POST /invoices/:id/send', () => {
const smtpEnvNames = ['SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS'] as const;
let previousSmtpEnv: Record<(typeof smtpEnvNames)[number], string | undefined>;

beforeEach(async () => {
previousSmtpEnv = {
SMTP_HOST: process.env.SMTP_HOST,
SMTP_PORT: process.env.SMTP_PORT,
SMTP_USER: process.env.SMTP_USER,
SMTP_PASS: process.env.SMTP_PASS,
};

for (const name of smtpEnvNames) {
delete process.env[name];
}

const invoice = await prisma.invoice.create({
data: {
number: 'INV-007',
userId: testUserId,
clientName: 'Email Test Client',
clientEmail: 'email@example.com',
clientAddress: '123 Email St',
issueDate: new Date(),
dueDate: new Date(),
status: 'DRAFT',
currency: 'USD',
notes: '',
subtotal: 100,
taxRate: 10,
taxAmount: 10,
total: 110,
lineItems: {
create: {
description: 'Email Test Item',
quantity: 1,
unitPrice: 100,
amount: 100,
}
}
}
});
userInvoiceId = invoice.id;
});

afterEach(() => {
for (const name of smtpEnvNames) {
const value = previousSmtpEnv[name];

if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
});

it('should return a clear error when SMTP is not configured', async () => {
const response = await request(testApp)
.post(`/invoices/${userInvoiceId}/send`)
.set('Authorization', `Bearer ${testAccessToken}`)
.expect(503);

expect(response.body.message).toBe('Email service is not configured');

const invoice = await prisma.invoice.findUnique({
where: { id: userInvoiceId },
});
expect(invoice?.status).toBe('DRAFT');
});
});

describe('PATCH /invoices/:id', () => {
beforeEach(async () => {
// Create a test invoice for update tests
Expand Down
Loading