Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

generate the invoice prefix and use it

Kiran K217b9cafd907
diff --git a/apps/web/app/api/stripe/webhook/payment-method-attached.ts b/apps/web/app/api/stripe/webhook/payment-method-attached.ts
index 581fddb969..04d47a1397 100644
--- a/apps/web/app/api/stripe/webhook/payment-method-attached.ts
+++ b/apps/web/app/api/stripe/webhook/payment-method-attached.ts
@@ -1,3 +1,4 @@
+import { generateInvoicePrefix } from "@/lib/api/invoices/utils";
import { prisma } from "@dub/prisma";
import Stripe from "stripe";
@@ -8,12 +9,28 @@ export async function paymentMethodAttached(event: Stripe.Event) {
return;
}
- await prisma.project.update({
+ const workspace = await prisma.project.update({
where: {
stripeId: customer as string,
},
data: {
payoutMethodId: id,
},
+ select: {
+ id: true,
+ invoicePrefix: true,
+ },
});
+
+ // Generate invoice prefix if it doesn't exist
+ if (!workspace.invoicePrefix) {
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ invoicePrefix: await generateInvoicePrefix(),
+ },
+ });
+ }
}
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/[invoiceId]/route.tsx b/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/[invoiceId]/route.tsx
index 1e5b271ed5..2b24dd2755 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/[invoiceId]/route.tsx
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/[invoiceId]/route.tsx
@@ -38,8 +38,9 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
amount: true,
fee: true,
total: true,
- createdAt: true,
status: true,
+ number: true,
+ createdAt: true,
payouts: {
select: {
periodStart: true,
@@ -78,6 +79,10 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
const customerAddress = customer.shipping?.address;
const invoiceMetadata = [
+ {
+ label: "Invoice #",
+ value: invoice.number,
+ },
{
label: "Date",
value: invoice.createdAt.toLocaleString("en-US", {
@@ -86,14 +91,6 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
year: "numeric",
}),
},
- {
- label: "Receipt #",
- value: "3149-0001",
- },
- {
- label: "Invoice #",
- value: "1354-2341-123",
- },
];
const invoiceSummaryDetails = [
@@ -148,22 +145,27 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
<View style={tw("flex-row justify-between mb-10 ")}>
<Address
title="From"
- name="Dub Technologies, Inc."
- line1="2261 Market Street STE 5906"
- city="San Francisco"
- state="CA"
- postalCode="94114"
+ address={{
+ name: "Dub Technologies, Inc.",
+ line1: "2261 Market Street STE 5906",
+ city: "San Francisco",
+ state: "CA",
+ postalCode: "94114",
+ email: "[email protected]",
+ }}
/>
<Address
title="Bill to"
- name={customer.shipping?.name}
- line1={customerAddress?.line1}
- line2={customerAddress?.line2}
- city={customerAddress?.city}
- state={customerAddress?.state}
- postalCode={customerAddress?.postal_code}
+ address={{
+ name: customer.shipping?.name,
+ line1: customerAddress?.line1,
+ line2: customerAddress?.line2,
+ city: customerAddress?.city,
+ state: customerAddress?.state,
+ postalCode: customerAddress?.postal_code,
+ email: customer.email,
+ }}
/>
</View>
@@ -297,46 +299,44 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
});
});
-// Address component
const Address = ({
- name,
- line1,
- line2,
- city,
- state,
- postalCode,
title,
- email,
+ address,
}: {
- name?: string | null;
- line1?: string | null;
- line2?: string | null;
- city?: string | null;
- state?: string | null;
- postalCode?: string | null;
title: string;
- email?: string | null;
+ address: {
+ name?: string | null;
+ line1?: string | null;
+ line2?: string | null;
+ city?: string | null;
+ state?: string | null;
+ postalCode?: string | null;
+ email?: string | null;
+ };
}) => {
+ const { name, line1, line2, city, state, postalCode, email } = address;
+
+ const records = [
+ name,
+ line1,
+ line2,
+ `${city}, ${state} ${postalCode}`,
+ email,
+ ].filter(Boolean);
+
return (
<View style={tw("w-1/2")}>
<Text style={tw("text-sm font-medium text-neutral-800 leading-6 mb-2")}>
{title}
</Text>
- <Text style={tw("font-normal text-sm text-neutral-500 leading-6")}>
- {name}
- </Text>
- <Text style={tw("font-normal text-sm text-neutral-500 leading-6")}>
- {line1}
- </Text>
- <Text style={tw("font-normal text-sm text-neutral-500 leading-6")}>
- {line2}
- </Text>
- <Text style={tw("font-normal text-sm text-neutral-500 leading-6")}>
- {city}, {state} {postalCode}
- </Text>
- <Text style={tw("font-normal text-sm text-neutral-500 leading-6")}>
- {email}
- </Text>
+ {records.map((record, index) => (
+ <Text
+ style={tw("font-normal text-sm text-neutral-500 leading-6")}
+ key={index}
+ >
+ {record}
+ </Text>
+ ))}
</View>
);
};
diff --git a/apps/web/lib/api/invoices/utils.ts b/apps/web/lib/api/invoices/utils.ts
new file mode 100644
index 0000000000..65cd7b30dc
--- /dev/null
+++ b/apps/web/lib/api/invoices/utils.ts
@@ -0,0 +1,33 @@
+import { prisma } from "@dub/prisma";
+import { randomBytes } from "crypto";
+
+export async function generateInvoicePrefix() {
+ const invoicePrefix = generateRandomString(8);
+
+ const existingPrefix = await prisma.project.findUnique({
+ where: {
+ invoicePrefix,
+ },
+ });
+
+ if (existingPrefix) {
+ return generateInvoicePrefix();
+ }
+
+ return invoicePrefix;
+}
+
+// TODO:
+// Move this to shared utils
+function generateRandomString(length: number): string {
+ const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ const randomBytesArray = randomBytes(length);
+ let result = "";
+
+ for (let i = 0; i < length; i++) {
+ const randomIndex = randomBytesArray[i] % charset.length;
+ result += charset[randomIndex];
+ }
+
+ return result;
+}
diff --git a/apps/web/scripts/backfill-invoice-prefixes.ts b/apps/web/scripts/backfill-invoice-prefixes.ts
new file mode 100644
index 0000000000..a1d94e1486
--- /dev/null
+++ b/apps/web/scripts/backfill-invoice-prefixes.ts
@@ -0,0 +1,40 @@
+import { generateInvoicePrefix } from "@/lib/api/invoices/utils";
+import { prisma } from "@dub/prisma";
+import "dotenv-flow/config";
+
+async function main() {
+ const workspaces = await prisma.project.findMany({
+ where: {
+ invoicePrefix: null,
+ payoutMethodId: {
+ not: null,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (workspaces.length === 0) {
+ console.log("No workspaces left to update.");
+ return;
+ }
+
+ const invoicePrefixes = await Promise.all(
+ workspaces.map(async () => generateInvoicePrefix()),
+ );
+
+ const updatedWorkspaces = await Promise.all(
+ workspaces.map(async (workspace, index) =>
+ prisma.project.update({
+ where: { id: workspace.id },
+ data: { invoicePrefix: invoicePrefixes[index] },
+ select: { id: true, invoicePrefix: true },
+ }),
+ ),
+ );
+
+ console.log("Updated invoice prefixes for workspaces.", updatedWorkspaces);
+}
+
+main();
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index 511513988e..a1bea390c8 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -12,7 +12,7 @@ model Project {
stripeConnectId String? @unique // for Stripe Integration
payoutMethodId String? // for Stripe Connect payouts
shopifyStoreId String? @unique // for Shopify Integration
- invoicePrefix String? // The prefix for the customer used to generate unique invoice numbers (e.g. "METAINC")
+ invoicePrefix String? @unique // The prefix for the customer used to generate unique invoice numbers
usage Int @default(0)
usageLimit Int @default(1000)