diff --git a/client/src/lib/apiErrors.ts b/client/src/lib/apiErrors.ts new file mode 100644 index 0000000..dea9b55 --- /dev/null +++ b/client/src/lib/apiErrors.ts @@ -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; +}; diff --git a/client/src/pages/InvoiceDetailPage.tsx b/client/src/pages/InvoiceDetailPage.tsx index 87e43b7..fe92b1e 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 { invoicesApi } from "@/lib/api/invoices"; +import { getApiErrorMessage } from "@/lib/apiErrors"; import { Page } from "@/pages/Page"; import type { Invoice } from "@/types/invoice"; @@ -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); } diff --git a/client/src/pages/InvoicesPage.tsx b/client/src/pages/InvoicesPage.tsx index 114f533..59e60f1 100644 --- a/client/src/pages/InvoicesPage.tsx +++ b/client/src/pages/InvoicesPage.tsx @@ -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"; @@ -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); } diff --git a/client/src/pages/ProposalDetailPage.tsx b/client/src/pages/ProposalDetailPage.tsx index bae65c4..253ba35 100644 --- a/client/src/pages/ProposalDetailPage.tsx +++ b/client/src/pages/ProposalDetailPage.tsx @@ -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"; @@ -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); } diff --git a/client/src/pages/ProposalsListPage.tsx b/client/src/pages/ProposalsListPage.tsx index 95890ee..4e63f72 100644 --- a/client/src/pages/ProposalsListPage.tsx +++ b/client/src/pages/ProposalsListPage.tsx @@ -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"; @@ -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); } diff --git a/server/src/services/emailService.ts b/server/src/services/emailService.ts index e068495..d262678 100644 --- a/server/src/services/emailService.ts +++ b/server/src/services/emailService.ts @@ -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; @@ -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; @@ -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, @@ -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, diff --git a/server/test/invoices.test.ts b/server/test/invoices.test.ts index eb0514f..3c62fab 100644 --- a/server/test/invoices.test.ts +++ b/server/test/invoices.test.ts @@ -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'; @@ -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