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
45 changes: 45 additions & 0 deletions client/src/lib/gmail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { Invoice } from "@/types/invoice";

type GmailInvoice = Pick<Invoice, "clientEmail" | "clientName" | "number">;

const GMAIL_COMPOSE_URL = "https://mail.google.com/mail/";

const buildInvoiceEmailBody = (invoice: GmailInvoice) =>
[
`Hi ${invoice.clientName},`,
"",
`Please find invoice ${invoice.number} attached.`,
"",
"Thank you.",
].join("\n");

export const buildInvoiceGmailComposeUrl = (invoice: GmailInvoice) => {
const url = new URL(GMAIL_COMPOSE_URL);

url.searchParams.set("view", "cm");
url.searchParams.set("fs", "1");
url.searchParams.set("to", invoice.clientEmail);
url.searchParams.set("su", `Invoice ${invoice.number}`);
url.searchParams.set("body", buildInvoiceEmailBody(invoice));

return url.toString();
};

export const openInvoiceInGmail = (invoice: GmailInvoice) => {
window.open(buildInvoiceGmailComposeUrl(invoice), "_blank", "noopener,noreferrer");
};

export const getInvoicePdfFilename = (invoiceNumber: string) =>
`invoice-${invoiceNumber}.pdf`;

export const downloadBlobAsFile = (blob: Blob, filename: string) => {
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");

link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
};
39 changes: 19 additions & 20 deletions client/src/pages/InvoiceDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { Toast } from "@/components/Toast";
import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar";
import { invoicesApi } from "@/lib/api/invoices";
import { getApiErrorMessage } from "@/lib/apiErrors";
import {
downloadBlobAsFile,
getInvoicePdfFilename,
openInvoiceInGmail,
} from "@/lib/gmail";
import { Page } from "@/pages/Page";
import type { Invoice, InvoiceStatus } from "@/types/invoice";

Expand Down Expand Up @@ -81,7 +86,7 @@ export function InvoiceDetailPage() {
const [loading, setLoading] = useState(true);
const [downloadLoading, setDownloadLoading] = useState(false);
const [downloaded, setDownloaded] = useState(false);
const [sendLoading, setSendLoading] = useState(false);
const [gmailLoading, setGmailLoading] = useState(false);
const [copied, setCopied] = useState(false);
const [toast, setToast] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
Expand Down Expand Up @@ -140,14 +145,7 @@ export function InvoiceDetailPage() {
try {
setDownloadLoading(true);
const blob = await invoicesApi.downloadPdf(invoice.id);
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `invoice-${invoice.number}.pdf`;
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
downloadBlobAsFile(blob, getInvoicePdfFilename(invoice.number));
setDownloaded(true);
downloadedTimer.current = window.setTimeout(() => setDownloaded(false), 2000);
} catch (err) {
Expand All @@ -158,22 +156,23 @@ export function InvoiceDetailPage() {
}
};

const handleSendInvoice = async () => {
const handleOpenInGmail = async () => {
if (!invoice) {
return;
}

try {
setSendLoading(true);
const updatedInvoice = await invoicesApi.send(invoice.id);
setInvoice(updatedInvoice);
setToast(`Invoice sent to ${invoice.clientEmail}`);
setGmailLoading(true);
openInvoiceInGmail(invoice);
const blob = await invoicesApi.downloadPdf(invoice.id);
downloadBlobAsFile(blob, getInvoicePdfFilename(invoice.number));
setToast("Gmail opened with the client email filled. Attach the downloaded PDF before sending.");
setError(null);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send invoice"));
console.error("Error sending invoice:", error);
setError(getApiErrorMessage(error, "Failed to prepare invoice for Gmail"));
console.error("Error preparing invoice for Gmail:", error);
} finally {
setSendLoading(false);
setGmailLoading(false);
}
};

Expand All @@ -195,7 +194,7 @@ export function InvoiceDetailPage() {
}

if (event.key.toLowerCase() === "s" && invoice?.status === "DRAFT") {
void handleSendInvoice();
void handleOpenInGmail();
}

if (event.key === "Escape" || event.key === "Backspace") {
Expand Down Expand Up @@ -267,8 +266,8 @@ export function InvoiceDetailPage() {
Edit
</Button>
{invoice.status === "DRAFT" ? (
<Button loading={sendLoading} onClick={() => void handleSendInvoice()} size="sm">
Send Invoice
<Button loading={gmailLoading} onClick={() => void handleOpenInGmail()} size="sm">
Open in Gmail
</Button>
) : null}
<Button loading={downloadLoading} onClick={() => void handleDownloadPdf()} size="sm" variant="secondary">
Expand Down
28 changes: 18 additions & 10 deletions client/src/pages/InvoiceFormPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ import { z } from "zod";
import { Button } from "@/components/Button";
import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar";
import { invoicesApi } from "@/lib/api/invoices";
import {
downloadBlobAsFile,
getInvoicePdfFilename,
openInvoiceInGmail,
} from "@/lib/gmail";
import { Page } from "@/pages/Page";
import type { CreateInvoiceData, UpdateInvoiceData } from "@/types/invoice";
import type { CreateInvoiceData, Invoice, UpdateInvoiceData } from "@/types/invoice";

const lineItemSchema = z.object({
description: z.string().min(1, "Description is required"),
Expand Down Expand Up @@ -198,26 +203,29 @@ export function InvoiceFormPage() {
}
};

const handleSaveAndSend = () => {
const handleSaveAndOpenGmail = () => {
handleSubmit(async (data) => {
try {
setLoading(true);
setSaveState("loading");

let invoice: Invoice;

if (isEditing && id) {
await invoicesApi.update(id, data as UpdateInvoiceData);
await invoicesApi.send(id);
invoice = await invoicesApi.update(id, data as UpdateInvoiceData);
} else {
const invoice = await invoicesApi.create(data as CreateInvoiceData);
await invoicesApi.send(invoice.id);
invoice = await invoicesApi.create(data as CreateInvoiceData);
}

openInvoiceInGmail(invoice);
const blob = await invoicesApi.downloadPdf(invoice.id);
downloadBlobAsFile(blob, getInvoicePdfFilename(invoice.number));
showTransientState("success");
navigate("/invoices");
} catch (err: any) {
setError(err.response?.data?.message || "Failed to save and send invoice");
setError(err.response?.data?.message || "Failed to save and prepare invoice for Gmail");
showTransientState("error");
console.error("Error saving and sending invoice:", err);
console.error("Error saving and preparing invoice for Gmail:", err);
} finally {
setLoading(false);
}
Expand Down Expand Up @@ -499,8 +507,8 @@ export function InvoiceFormPage() {
>
{saveState === "success" ? "✓ Saved" : saveState === "error" ? "Failed" : "Save as draft"}
</Button>
<Button loading={saveState === "loading"} onClick={handleSaveAndSend}>
{saveState === "success" ? "✓ Saved" : saveState === "error" ? "Failed" : "Save & Send"}
<Button loading={saveState === "loading"} onClick={handleSaveAndOpenGmail}>
{saveState === "success" ? "✓ Saved" : saveState === "error" ? "Failed" : "Save & Open Gmail"}
</Button>
</div>
</div>
Expand Down
22 changes: 14 additions & 8 deletions client/src/pages/InvoicesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { StatusBadge } from "@/components/StatusBadge";
import { Toast } from "@/components/Toast";
import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar";
import { invoicesApi } from "@/lib/api/invoices";
import {
downloadBlobAsFile,
getInvoicePdfFilename,
openInvoiceInGmail,
} from "@/lib/gmail";
import { Page } from "@/pages/Page";
import { getApiErrorMessage } from "@/lib/apiErrors";
import { useAuthStore } from "@/store/auth";
Expand Down Expand Up @@ -147,16 +152,17 @@ export function InvoicesPage() {
}
};

const handleSendInvoice = async (invoice: Invoice) => {
const handleOpenInGmail = async (invoice: Invoice) => {
try {
setSendingInvoiceId(invoice.id);
const updatedInvoice = await invoicesApi.send(invoice.id);
setInvoices((items) => items.map((item) => (item.id === invoice.id ? updatedInvoice : item)));
setToast(`Invoice sent to ${invoice.clientEmail}`);
openInvoiceInGmail(invoice);
const blob = await invoicesApi.downloadPdf(invoice.id);
downloadBlobAsFile(blob, getInvoicePdfFilename(invoice.number));
setToast("Gmail opened with the client email filled. Attach the downloaded PDF before sending.");
setError(null);
} catch (error) {
setError(getApiErrorMessage(error, "Failed to send invoice"));
console.error("Error sending invoice:", error);
setError(getApiErrorMessage(error, "Failed to prepare invoice for Gmail"));
console.error("Error preparing invoice for Gmail:", error);
} finally {
setSendingInvoiceId(null);
}
Expand Down Expand Up @@ -366,11 +372,11 @@ export function InvoicesPage() {
disabled={sendingInvoiceId === invoice.id}
onClick={(event) => {
event.stopPropagation();
void handleSendInvoice(invoice);
void handleOpenInGmail(invoice);
}}
type="button"
>
{sendingInvoiceId === invoice.id ? "Sending..." : "Send"}
{sendingInvoiceId === invoice.id ? "Preparing..." : "Open Gmail"}
</button>
) : null}
{invoice.status === "SENT" ? (
Expand Down
Loading