The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
WIP bounty logic
Tim Wilson11e6bd053d91
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsxindex aeef2c7854..124e99b4d4 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx@@ -5,6 +5,7 @@ import {createBountySchema,SUBMISSION_REQUIREMENTS,} from "@/lib/zod/schemas/bounties";+import { BountyLogic } from "@/ui/partners/bounties/bounty-logic";import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";import {ProgramSheetAccordion,@@ -23,11 +24,15 @@ import {Sheet,SmartDateTimePicker,Switch,- Trophy,} from "@dub/ui";import { cn } from "@dub/utils";import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";-import { Controller, useForm } from "react-hook-form";+import {+ Controller,+ FormProvider,+ useForm,+ useFormContext,+} from "react-hook-form";import { toast } from "sonner";import { z } from "zod";@@ -37,6 +42,8 @@ type BountySheetProps = {type FormData = z.infer<typeof createBountySchema>;+export const useAddEditBountyForm = () => useFormContext<FormData>();+type SubmissionRequirement = (typeof SUBMISSION_REQUIREMENTS)[number];const BOUNTY_TYPES: CardSelectorOption[] = [@@ -67,6 +74,19 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);const { makeRequest, isSubmitting } = useApiMutation<BountyProps>();+ const form = useForm<FormData>({+ defaultValues: {+ // TODO: Edit existing values (and handle currency / 100)++ type: "performance",+ performanceLogic: {+ activity: undefined,+ operator: "gte",+ value: undefined,+ },+ },+ });+const {handleSubmit,watch,@@ -74,11 +94,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {control,register,formState: { errors },- } = useForm<FormData>({- defaultValues: {- type: "performance",- },- });+ } = form;const [startsAt, rewardAmount, type, name, description] = watch(["startsAt",@@ -164,313 +180,309 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {</div></div>- <div className="flex-1 overflow-y-auto">- <div className="p-6">- <ProgramSheetAccordion- type="multiple"- value={openAccordions}- onValueChange={setOpenAccordions}- className="space-y-6"- >- <ProgramSheetAccordionItem value="bounty-type">- <ProgramSheetAccordionTrigger>- Bounty type- </ProgramSheetAccordionTrigger>- <ProgramSheetAccordionContent>- <div className="space-y-4">- <p className="text-content-default text-sm">- Set how the bounty will be completed- </p>- <CardSelector- options={BOUNTY_TYPES}- value={watch("type")}- onChange={(value: FormData["type"]) =>- setValue("type", value)- }- name="bounty-type"- />- </div>- </ProgramSheetAccordionContent>- </ProgramSheetAccordionItem>-- <ProgramSheetAccordionItem value="bounty-details">- <ProgramSheetAccordionTrigger>- Bounty details- </ProgramSheetAccordionTrigger>- <ProgramSheetAccordionContent>- <div className="space-y-6">- <p className="text-content-default text-sm">- Set the schedule, reward and additional details- </p>-- <div>- <SmartDateTimePicker- value={watch("startsAt")}- onChange={(date) => {- setValue("startsAt", date as Date, {- shouldDirty: true,- });- }}- label="Start date"- placeholder='E.g. "2024-03-01", "Last Thursday", "2 hours ago"'+ <FormProvider {...form}>+ <div className="flex-1 overflow-y-auto">+ <div className="p-6">+ <ProgramSheetAccordion+ type="multiple"+ value={openAccordions}+ onValueChange={setOpenAccordions}+ className="space-y-6"+ >+ <ProgramSheetAccordionItem value="bounty-type">+ <ProgramSheetAccordionTrigger>+ Bounty type+ </ProgramSheetAccordionTrigger>+ <ProgramSheetAccordionContent>+ <div className="space-y-4">+ <p className="text-content-default text-sm">+ Set how the bounty will be completed+ </p>+ <CardSelector+ options={BOUNTY_TYPES}+ value={watch("type")}+ onChange={(value: FormData["type"]) =>+ setValue("type", value)+ }+ name="bounty-type"/></div>+ </ProgramSheetAccordionContent>+ </ProgramSheetAccordionItem>++ <ProgramSheetAccordionItem value="bounty-details">+ <ProgramSheetAccordionTrigger>+ Bounty details+ </ProgramSheetAccordionTrigger>+ <ProgramSheetAccordionContent>+ <div className="space-y-6">+ <p className="text-content-default text-sm">+ Set the schedule, reward and additional details+ </p>- <AnimatedSizeContainer- height- transition={{ ease: "easeInOut", duration: 0.2 }}- className={!hasEndDate ? "hidden" : ""}- style={{ display: !hasEndDate ? "none" : "block" }}- >- <div className="flex items-center gap-4">- <Switch- fn={setHasEndDate}- checked={hasEndDate}- trackDimensions="w-8 h-4"- thumbDimensions="w-3 h-3"- thumbTranslate="translate-x-4"+ <div>+ <SmartDateTimePicker+ value={watch("startsAt")}+ onChange={(date) => {+ setValue("startsAt", date as Date, {+ shouldDirty: true,+ });+ }}+ label="Start date"+ placeholder='E.g. "2024-03-01", "Last Thursday", "2 hours ago"'/>- <div className="flex flex-col gap-1">- <h3 className="text-sm font-medium text-neutral-700">- Add end date- </h3>- </div></div>- {hasEndDate && (- <div className="mt-6 p-px">- <SmartDateTimePicker- value={watch("endsAt")}- onChange={(date) => {- setValue("endsAt", date, {- shouldDirty: true,- });- }}- label="End date"- placeholder='E.g. "in 3 months"'+ <AnimatedSizeContainer+ height+ transition={{ ease: "easeInOut", duration: 0.2 }}+ className={!hasEndDate ? "hidden" : ""}+ style={{ display: !hasEndDate ? "none" : "block" }}+ >+ <div className="flex items-center gap-4">+ <Switch+ fn={setHasEndDate}+ checked={hasEndDate}+ trackDimensions="w-8 h-4"+ thumbDimensions="w-3 h-3"+ thumbTranslate="translate-x-4"/>+ <div className="flex flex-col gap-1">+ <h3 className="text-sm font-medium text-neutral-700">+ Add end date+ </h3>+ </div></div>- )}- </AnimatedSizeContainer>- <div>- <label- htmlFor="rewardAmount"- className="text-sm font-medium text-neutral-800"- >- Reward- </label>- <div className="mt-2">- <Controller- name="rewardAmount"- control={control}- rules={{- required: true,- min: 0,- }}- render={({ field }) => (- <AmountInput- {...field}- id="rewardAmount"- amountType="flat"- placeholder="200"- error={errors.rewardAmount?.message}- value={- field.value == null || isNaN(field.value)- ? ""- : field.value- }- onChange={(e) => {- const val = e.target.value;-- field.onChange(- val === "" ? null : parseFloat(val),- );+ {hasEndDate && (+ <div className="mt-6 p-px">+ <SmartDateTimePicker+ value={watch("endsAt")}+ onChange={(date) => {+ setValue("endsAt", date, {+ shouldDirty: true,+ });}}+ label="End date"+ placeholder='E.g. "in 3 months"'/>- )}- />+ </div>+ )}+ </AnimatedSizeContainer>++ <div>+ <label+ htmlFor="rewardAmount"+ className="text-sm font-medium text-neutral-800"+ >+ Reward+ </label>+ <div className="mt-2">+ <Controller+ name="rewardAmount"+ control={control}+ rules={{+ required: true,+ min: 0,+ }}+ render={({ field }) => (+ <AmountInput+ {...field}+ id="rewardAmount"+ amountType="flat"+ placeholder="200"+ error={errors.rewardAmount?.message}+ value={+ field.value == null || isNaN(field.value)+ ? ""+ : field.value+ }+ onChange={(e) => {+ const val = e.target.value;++ field.onChange(+ val === "" ? null : parseFloat(val),+ );+ }}+ />+ )}+ />+ </div></div>- </div>- {type === "submission" && (+ {type === "submission" && (+ <div>+ <label+ htmlFor="name"+ className="text-sm font-medium text-neutral-800"+ >+ Name+ </label>+ <div className="mt-2">+ <input+ id="name"+ type="text"+ maxLength={100}+ className={cn(+ "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",+ errors.name &&+ "border-red-600 focus:border-red-500 focus:ring-red-600",+ )}+ placeholder="Create a YouTube video about..."+ {...register("name", {+ setValueAs: (value) =>+ value === "" ? null : value,+ })}+ />+ <div className="mt-1 text-left">+ <span className="text-xs text-neutral-400">+ {name?.length || 0}/100+ </span>+ </div>+ </div>+ </div>+ )}++ {type === "performance" && (+ <div>+ <span className="text-sm font-medium text-neutral-800">+ Logic+ </span>+ <BountyLogic className="mt-2" />+ </div>+ )}+<div><label- htmlFor="name"+ htmlFor="description"className="text-sm font-medium text-neutral-800">- Name+ Details+ <span className="ml-1 font-normal text-neutral-500">+ (optional)+ </span></label><div className="mt-2">- <input- id="name"- type="text"- maxLength={100}+ <textarea+ id="description"+ rows={3}+ maxLength={500}className={cn(- "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",- errors.name &&+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",+ errors.description &&"border-red-600 focus:border-red-500 focus:ring-red-600",)}- placeholder="Create a YouTube video about..."- {...register("name", {+ placeholder="Provide any bounty requirements to the partner"+ {...register("description", {setValueAs: (value) =>value === "" ? null : value,})}/><div className="mt-1 text-left"><span className="text-xs text-neutral-400">- {name?.length || 0}/100+ {description?.length || 0}/500</span></div></div></div>- )}-- {type === "performance" && (- <div>- <span className="text-sm font-medium text-neutral-800">- Logic- </span>- <div className="mt-2 block flex w-full items-center gap-1.5 rounded-md border border-neutral-300 px-3 py-2">- <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">- <Trophy className="size-4 text-neutral-800" />+ </div>+ </ProgramSheetAccordionContent>+ </ProgramSheetAccordionItem>++ <ProgramSheetAccordionItem value="submission-requirements">+ <ProgramSheetAccordionTrigger>+ Submission requirements+ </ProgramSheetAccordionTrigger>+ <ProgramSheetAccordionContent>+ <div className="space-y-6">+ <p className="text-content-default text-sm">+ Set how partners should submit proof of their work. By+ default an open text field is provided.+ </p>++ <div className="space-y-4">+ <div className="flex items-center gap-4">+ <Switch+ fn={setRequireImage}+ checked={requireImage}+ trackDimensions="w-8 h-4"+ thumbDimensions="w-3 h-3"+ thumbTranslate="translate-x-4"+ />+ <div className="flex flex-col gap-1">+ <h3 className="text-sm font-medium text-neutral-700">+ Require at least one image+ </h3></div>- <span className="text-content-emphasis text-sm font-medium leading-relaxed">- When- </span></div>- </div>- )}- <div>- <label- htmlFor="description"- className="text-sm font-medium text-neutral-800"- >- Details- <span className="ml-1 font-normal text-neutral-500">- (optional)- </span>- </label>- <div className="mt-2">- <textarea- id="description"- rows={3}- maxLength={500}- className={cn(- "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",- errors.description &&- "border-red-600 focus:border-red-500 focus:ring-red-600",- )}- placeholder="Provide any bounty requirements to the partner"- {...register("description", {- setValueAs: (value) => (value === "" ? null : value),- })}- />- <div className="mt-1 text-left">- <span className="text-xs text-neutral-400">- {description?.length || 0}/500- </span>+ <div className="flex items-center gap-4">+ <Switch+ fn={setRequireUrl}+ checked={requireUrl}+ trackDimensions="w-8 h-4"+ thumbDimensions="w-3 h-3"+ thumbTranslate="translate-x-4"+ />+ <div className="flex flex-col gap-1">+ <h3 className="text-sm font-medium text-neutral-700">+ Require at least one URL+ </h3>+ </div></div></div></div>- </div>- </ProgramSheetAccordionContent>- </ProgramSheetAccordionItem>-- <ProgramSheetAccordionItem value="submission-requirements">- <ProgramSheetAccordionTrigger>- Submission requirements- </ProgramSheetAccordionTrigger>- <ProgramSheetAccordionContent>- <div className="space-y-6">- <p className="text-content-default text-sm">- Set how partners should submit proof of their work. By- default an open text field is provided.- </p>-- <div className="space-y-4">- <div className="flex items-center gap-4">- <Switch- fn={setRequireImage}- checked={requireImage}- trackDimensions="w-8 h-4"- thumbDimensions="w-3 h-3"- thumbTranslate="translate-x-4"- />- <div className="flex flex-col gap-1">- <h3 className="text-sm font-medium text-neutral-700">- Require at least one image- </h3>- </div>- </div>-- <div className="flex items-center gap-4">- <Switch- fn={setRequireUrl}- checked={requireUrl}- trackDimensions="w-8 h-4"- thumbDimensions="w-3 h-3"- thumbTranslate="translate-x-4"+ </ProgramSheetAccordionContent>+ </ProgramSheetAccordionItem>++ <ProgramSheetAccordionItem value="groups">+ <ProgramSheetAccordionTrigger>+ Groups+ </ProgramSheetAccordionTrigger>+ <ProgramSheetAccordionContent>+ <Controller+ control={control}+ name="groupIds"+ render={({ field }) => (+ <GroupsMultiSelect+ selectedGroupIds={field.value}+ setSelectedGroupIds={(ids) => field.onChange(ids)}/>- <div className="flex flex-col gap-1">- <h3 className="text-sm font-medium text-neutral-700">- Require at least one URL- </h3>- </div>- </div>- </div>- </div>- </ProgramSheetAccordionContent>- </ProgramSheetAccordionItem>-- <ProgramSheetAccordionItem value="groups">- <ProgramSheetAccordionTrigger>- Groups- </ProgramSheetAccordionTrigger>- <ProgramSheetAccordionContent>- <Controller- control={control}- name="groupIds"- render={({ field }) => (- <GroupsMultiSelect- selectedGroupIds={field.value}- setSelectedGroupIds={(ids) => field.onChange(ids)}- />- )}- />- </ProgramSheetAccordionContent>- </ProgramSheetAccordionItem>- </ProgramSheetAccordion>+ )}+ />+ </ProgramSheetAccordionContent>+ </ProgramSheetAccordionItem>+ </ProgramSheetAccordion>+ </div></div>- </div>- <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">- <div className="flex items-center justify-end gap-2 p-5">- <Button- type="button"- variant="secondary"- onClick={() => setIsOpen(false)}- text="Cancel"- className="w-fit"- disabled={isSubmitting}- />-- <Button- type="submit"- variant="primary"- text="Create bounty"- className="w-fit"- loading={isSubmitting}- disabled={shouldDisableSubmit}- disabledTooltip={- shouldDisableSubmit- ? "Please fill all required fields."- : undefined- }- />+ <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">+ <div className="flex items-center justify-end gap-2 p-5">+ <Button+ type="button"+ variant="secondary"+ onClick={() => setIsOpen(false)}+ text="Cancel"+ className="w-fit"+ disabled={isSubmitting}+ />++ <Button+ type="submit"+ variant="primary"+ text="Create bounty"+ className="w-fit"+ loading={isSubmitting}+ disabled={shouldDisableSubmit}+ disabledTooltip={+ shouldDisableSubmit+ ? "Please fill all required fields."+ : undefined+ }+ />+ </div></div>- </div>+ </FormProvider></form>);}diff --git a/apps/web/lib/swr/use-groups.ts b/apps/web/lib/swr/use-groups.tsindex b086788a4a..0245f75b42 100644--- a/apps/web/lib/swr/use-groups.ts+++ b/apps/web/lib/swr/use-groups.ts@@ -11,15 +11,17 @@ const partialQuerySchema = getGroupsQuerySchema.partial();export default function useGroups<T extends GroupProps>({query,includeParams,+ enabled = true,}: {query?: z.infer<typeof partialQuerySchema>;includeParams?: boolean;+ enabled?: boolean;} = {}) {const { id: workspaceId, defaultProgramId } = useWorkspace();const { getQueryString } = useRouterStuff();const { data, isLoading, error } = useSWR<T[]>(- defaultProgramId+ enabled && defaultProgramId? `/api/groups${// TODO: standardize how we handle params in useSWR hooks – it's a bit all over the place rnincludeParamsdiff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.tsindex 2b727db40e..d5f514ef9b 100644--- a/apps/web/lib/zod/schemas/bounties.ts+++ b/apps/web/lib/zod/schemas/bounties.ts@@ -8,6 +8,25 @@ import { parseDateSchema } from "./utils";export const SUBMISSION_REQUIREMENTS = ["image", "url"] as const;+export const PERFORMANCE_ACTIVITIES = [+ "earnings",+ "revenue",+ "clicks",+ "click earnings",+ "leads",+ "lead earnings",+ "sales",+ "sale earnings",+] as const;++export const PERFORMANCE_CURRENCY_ACTIVITIES = [+ "click earnings",+ "lead earnings",+ "sale earnings",+ "earnings",+ "revenue",+];+export const createBountySchema = z.object({name: z.string()@@ -28,6 +47,13 @@ export const createBountySchema = z.object({.min(0).max(2).nullish(),+ performanceLogic: z+ .object({+ activity: z.enum(PERFORMANCE_ACTIVITIES),+ operator: z.enum(["gte"]).default("gte"),+ value: z.number().min(0, "Logic value must be at least 0"),+ })+ .nullish(),groupIds: z.array(z.string()).nullable(),});diff --git a/apps/web/ui/partners/bounties/bounty-logic.tsx b/apps/web/ui/partners/bounties/bounty-logic.tsxnew file mode 100644index 0000000000..56cb35a02b--- /dev/null+++ b/apps/web/ui/partners/bounties/bounty-logic.tsx@@ -0,0 +1,125 @@+import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";+import {+ PERFORMANCE_ACTIVITIES,+ PERFORMANCE_CURRENCY_ACTIVITIES,+} from "@/lib/zod/schemas/bounties";+import {+ InlineBadgePopover,+ InlineBadgePopoverContext,+ InlineBadgePopoverMenu,+} from "@/ui/shared/inline-badge-popover";+import { Trophy } from "@dub/ui/icons";+import { cn, currencyFormatter } from "@dub/utils";+import { useAddEditBountyForm } from "app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet";+import { useContext } from "react";+import { Controller } from "react-hook-form";++export function BountyLogic({ className }: { className?: string }) {+ const { control, watch } = useAddEditBountyForm();++ const [activity, value] = watch([+ "performanceLogic.activity",+ "performanceLogic.value",+ ]);++ const isCurrency = PERFORMANCE_CURRENCY_ACTIVITIES.includes(activity);++ return (+ <div+ className={cn(+ "block flex w-full items-center gap-1.5 rounded-md border border-neutral-300 px-3 py-2",+ className,+ )}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">+ <Trophy className="size-4 text-neutral-800" />+ </div>+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">+ When partner{" "}+ <Controller+ control={control}+ name="performanceLogic.activity"+ render={({ field }) => (+ <InlineBadgePopover+ text={field.value ?? "activity"}+ invalid={!field.value}+ >+ <InlineBadgePopoverMenu+ selectedValue={field.value}+ onSelect={field.onChange}+ items={PERFORMANCE_ACTIVITIES.map((activity) => ({+ text: activity,+ value: activity,+ }))}+ />+ </InlineBadgePopover>+ )}+ />+ {activity && (+ <>+ {" "}+ is at least{" "}+ <InlineBadgePopover+ text={+ value+ ? isCurrency+ ? currencyFormatter(value)+ : value+ : "amount"+ }+ invalid={!value}+ >+ <ValueInput />+ </InlineBadgePopover>+ </>+ )}+ </span>+ </div>+ );+}++function ValueInput() {+ const { watch, register } = useAddEditBountyForm();++ const activity = watch("performanceLogic.activity");++ const isCurrency = PERFORMANCE_CURRENCY_ACTIVITIES.includes(activity);++ const { setIsOpen } = useContext(InlineBadgePopoverContext);++ return (+ <div className="relative rounded-md shadow-sm">+ {isCurrency && (+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">+ $+ </span>+ )}+ <input+ className={cn(+ "block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",+ isCurrency ? "pl-4 pr-12" : "pr-7",+ )}+ {...register("performanceLogic.value", {+ required: true,+ setValueAs: (value: string) => (value === "" ? undefined : +value),+ min: 0,+ onChange: handleMoneyInputChange,+ })}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ setIsOpen(false);+ return;+ }++ handleMoneyKeyDown(e);+ }}+ />+ {isCurrency && (+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">+ USD+ </span>+ )}+ </div>+ );+}diff --git a/apps/web/ui/shared/inline-badge-popover.tsx b/apps/web/ui/shared/inline-badge-popover.tsxindex 66b7cd14cf..6080098f7a 100644--- a/apps/web/ui/shared/inline-badge-popover.tsx+++ b/apps/web/ui/shared/inline-badge-popover.tsx@@ -212,8 +212,9 @@ export const InlineBadgePopoverInputs = ({// Kinda nasty but allows the component to only receive/return the values array without needing external IDsuseEffect(() => {- const currentValues = values.map((item) => item.value);+ const currentValues = values.map(({ value }) => value);if (JSON.stringify(currentValues) !== JSON.stringify(valuesProp)) {+ // Values have changed: generate new IDssetValues(valuesProp.map((value) => ({ id: uuid(), value })));}}, [valuesProp, values]);@@ -223,7 +224,7 @@ export const InlineBadgePopoverInputs = ({item.id === id ? { ...item, value: newValue } : item,);setValues(updatedValues);- onChange(updatedValues.map((item) => item.value));+ onChange(updatedValues.map(({ value }) => value));};const handleDelete = (id: string) => {