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.

add customer selector

Kiran K77379fda4dab
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
index 5f03f24f4a..5270959abf 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
@@ -4,6 +4,7 @@ import usePartners from "@/lib/swr/use-partners";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { createCommissionSchema } from "@/lib/zod/schemas/commissions";
+import { CustomerSelector } from "@/ui/customers/customer-selector";
import { PartnerLinkSelector } from "@/ui/partners/partner-link-selector";
import { X } from "@/ui/shared/icons";
import { Button, Combobox, Sheet, useMediaQuery } from "@dub/ui";
@@ -40,11 +41,12 @@ function CreateCommissionSheetContent({
formState: { errors },
} = useForm<FormData>();
- const [partnerId, linkId, saleDate, saleAmount] = watch([
+ const [partnerId, linkId, saleDate, saleAmount, customerId] = watch([
"partnerId",
"linkId",
"saleDate",
"saleAmount",
+ "customerId",
]);
const partnerOptions = useMemo(() => {
@@ -217,6 +219,22 @@ function CreateCommissionSheetContent({
</span>
</div>
</div>
+
+ <div>
+ <label htmlFor="name" className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-neutral-900">
+ Customer
+ </h2>
+ </label>
+ <div className="mt-2">
+ <CustomerSelector
+ selectedCustomerId={customerId}
+ setSelectedCustomerId={(id) => {
+ setValue("customerId", id, { shouldDirty: true });
+ }}
+ />
+ </div>
+ </div>
</div>
</div>
</div>
diff --git a/apps/web/ui/customers/customer-selector.tsx b/apps/web/ui/customers/customer-selector.tsx
new file mode 100644
index 0000000000..1ca656432b
--- /dev/null
+++ b/apps/web/ui/customers/customer-selector.tsx
@@ -0,0 +1,102 @@
+import useCustomers from "@/lib/swr/use-customers";
+import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";
+import { Button, Combobox } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useEffect, useMemo, useState } from "react";
+import { useDebounce } from "use-debounce";
+import { useAddCustomerModal } from "../modals/add-customer-modal";
+
+interface CustomerSelectorProps {
+ selectedCustomerId: string;
+ setSelectedCustomerId: (customerId: string) => void;
+}
+
+export function CustomerSelector({
+ selectedCustomerId,
+ setSelectedCustomerId,
+}: CustomerSelectorProps) {
+ const [search, setSearch] = useState("");
+ const [useAsync, setUseAsync] = useState(false);
+ const [debouncedSearch] = useDebounce(search, 500);
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const { customers, loading } = useCustomers({
+ query: useAsync ? { search: debouncedSearch } : undefined,
+ });
+
+ useEffect(() => {
+ if (customers && !useAsync && customers.length >= CUSTOMERS_MAX_PAGE_SIZE) {
+ setUseAsync(true);
+ }
+ }, [customers, useAsync]);
+
+ const { AddCustomerModal, setShowAddCustomerModal } = useAddCustomerModal({
+ onSuccess: (customer) => {
+ setSelectedCustomerId(customer.id);
+ },
+ });
+
+ const customerOptions = useMemo(() => {
+ return customers?.map((customer) => ({
+ value: customer.id,
+ label: customer.name || customer.email || customer.externalId,
+ icon: (
+ <img
+ src={
+ customer.avatar ||
+ `https://api.dub.co/og/avatar?seed=${customer.id}`
+ }
+ className="size-4 rounded-full"
+ />
+ ),
+ }));
+ }, [customers]);
+
+ const selectedOption = useMemo(() => {
+ return customerOptions?.find((o) => o.value === selectedCustomerId) || null;
+ }, [customerOptions, selectedCustomerId]);
+
+ return (
+ <>
+ <AddCustomerModal />
+ <Combobox
+ options={loading ? undefined : customerOptions}
+ setSelected={(option) => {
+ setSelectedCustomerId(option.value);
+ }}
+ selected={selectedOption}
+ caret={true}
+ placeholder="Select customer"
+ searchPlaceholder="Search customer..."
+ onSearchChange={setSearch}
+ shouldFilter={!useAsync}
+ matchTriggerWidth
+ open={openPopover}
+ onOpenChange={setOpenPopover}
+ buttonProps={{
+ className: cn(
+ "w-full justify-start border-neutral-300 px-3",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
+ ),
+ }}
+ emptyState={
+ <div className="flex w-full flex-col items-center gap-2 py-4">
+ No customers found
+ <Button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddCustomerModal(true);
+ }}
+ variant="primary"
+ className="h-7 w-fit px-2"
+ text="Create customer"
+ />
+ </div>
+ }
+ >
+ {selectedOption?.label}
+ </Combobox>
+ </>
+ );
+}
diff --git a/apps/web/ui/modals/add-customer-modal.tsx b/apps/web/ui/modals/add-customer-modal.tsx
new file mode 100644
index 0000000000..f98ef496f9
--- /dev/null
+++ b/apps/web/ui/modals/add-customer-modal.tsx
@@ -0,0 +1,183 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { CustomerProps } from "@/lib/types";
+import { createCustomerBodySchema } from "@/lib/zod/schemas/customers";
+import { Button, Modal } from "@dub/ui";
+import { useCallback, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { z } from "zod";
+
+interface AddCustomerModalProps {
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
+ onSuccess?: (customer: CustomerProps) => void;
+}
+
+type FormData = z.infer<typeof createCustomerBodySchema>;
+
+const AddCustomerModal = ({
+ showModal,
+ setShowModal,
+ onSuccess,
+}: AddCustomerModalProps) => {
+ const { id: workspaceId } = useWorkspace();
+
+ const {
+ register,
+ handleSubmit,
+ watch,
+ formState: { isSubmitting },
+ } = useForm<FormData>({
+ defaultValues: {
+ name: null,
+ email: null,
+ externalId: "",
+ },
+ });
+
+ const onSubmit = async (data: FormData) => {
+ try {
+ const response = await fetch(
+ `/api/customers?workspaceId=${workspaceId}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ },
+ );
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ throw new Error(error.message || "Failed to create customer.");
+ }
+
+ const customer = await response.json();
+ await mutate(`/api/customers?workspaceId=${workspaceId}`);
+ toast.success(
+ `Customer with ID "${customer.externalId}" added successfully!`,
+ );
+ onSuccess?.(customer);
+ setShowModal(false);
+ } catch (error) {
+ toast.error(error.message || "Something went wrong.");
+ }
+ };
+
+ const externalId = watch("externalId");
+
+ return (
+ <Modal showModal={showModal} setShowModal={setShowModal}>
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="text-lg font-medium">Create new customer</h3>
+ </div>
+
+ <div className="bg-neutral-50">
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">
+ <div>
+ <label className="text-sm font-normal text-neutral-500">
+ Name
+ </label>
+ <div className="mt-2 flex rounded-md border border-neutral-300 bg-white">
+ <input
+ type="text"
+ autoComplete="off"
+ className="block w-full rounded-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ placeholder="John Doe"
+ {...register("name", {
+ setValueAs: (value) => (value === "" ? null : value),
+ })}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label className="text-sm font-normal text-neutral-500">
+ Email
+ </label>
+ <div className="mt-2 flex rounded-md border border-neutral-300 bg-white">
+ <input
+ type="email"
+ autoComplete="off"
+ className="block w-full rounded-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ placeholder="[email protected]"
+ {...register("email", {
+ setValueAs: (value) => (value === "" ? null : value),
+ })}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label className="text-sm font-normal text-neutral-500">
+ External ID (Required)
+ </label>
+ <div className="mt-2 flex rounded-md border border-neutral-300 bg-white">
+ <input
+ type="text"
+ required
+ autoComplete="off"
+ className="block w-full rounded-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ placeholder="cust_GWGrkftJdYlZD2mq"
+ {...register("externalId", { required: true })}
+ />
+ </div>
+ <p className="mt-2 text-xs text-neutral-500">
+ This is the customer's unique database ID (or email if no ID)
+ </p>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-9 w-fit"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ type="submit"
+ text="Create customer"
+ className="h-9 w-fit"
+ loading={isSubmitting}
+ disabled={!externalId}
+ />
+ </div>
+ </div>
+ </form>
+ </div>
+ </Modal>
+ );
+};
+
+export function useAddCustomerModal({
+ onSuccess,
+}: {
+ onSuccess?: (customer: CustomerProps) => void;
+} = {}) {
+ const [showAddCustomerModal, setShowAddCustomerModal] = useState(false);
+
+ const AddCustomerModalCallback = useCallback(() => {
+ return (
+ <AddCustomerModal
+ showModal={showAddCustomerModal}
+ setShowModal={setShowAddCustomerModal}
+ onSuccess={onSuccess}
+ />
+ );
+ }, [showAddCustomerModal, setShowAddCustomerModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddCustomerModal,
+ AddCustomerModal: AddCustomerModalCallback,
+ }),
+ [setShowAddCustomerModal, AddCustomerModalCallback],
+ );
+}