1 import { zodResolver } from "@hookform/resolvers/zod"
2 import { AdminCampaign, HttpTypes } from "@medusajs/types"
3 import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
4 import { keepPreviousData } from "@tanstack/react-query"
5 import {
6 OnChangeFn,
7 RowSelectionState,
8 createColumnHelper,
9 } from "@tanstack/react-table"
10 import { useMemo, useState } from "react"
11 import { useForm } from "react-hook-form"
12 import { useTranslation } from "react-i18next"
13 import * as zod from "zod"
14 import { RouteFocusModal, useRouteModal } from "../../../../components/modals"
15 import { _DataTable } from "../../../../components/table/data-table"
16 import { KeyboundForm } from "../../../../components/utilities/keybound-form"
17 import { useAddOrRemoveCampaignPromotions } from "../../../../hooks/api/campaigns"
18 import { usePromotions } from "../../../../hooks/api/promotions"
19 import { usePromotionTableColumns } from "../../../../hooks/table/columns/use-promotion-table-columns"
20 import { usePromotionTableFilters } from "../../../../hooks/table/filters/use-promotion-table-filters"
21 import { usePromotionTableQuery } from "../../../../hooks/table/query/use-promotion-table-query"
22 import { useDataTable } from "../../../../hooks/use-data-table"
23
24 type AddCampaignPromotionsFormProps = {
25 campaign: AdminCampaign
26 }
27
28 const AddCampaignPromotionsSchema = zod.object({
29 promotion_ids: zod.array(zod.string()).min(1),
30 })
31
32 const PAGE_SIZE = 50
33
34 export const AddCampaignPromotionsForm = ({
35 campaign,
36 }: AddCampaignPromotionsFormProps) => {
37 const { t } = useTranslation()
38 const { handleSuccess } = useRouteModal()
39
40 const form = useForm<zod.infer<typeof AddCampaignPromotionsSchema>>({
41 defaultValues: { promotion_ids: [] },
42 resolver: zodResolver(AddCampaignPromotionsSchema),
43 })
44
45 const { setValue } = form
46 const { mutateAsync, isPending } = useAddOrRemoveCampaignPromotions(
47 campaign.id
48 )
49 const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
50
51 const updater: OnChangeFn<RowSelectionState> = (fn) => {
52 const state = typeof fn === "function" ? fn(rowSelection) : fn
53 const ids = Object.keys(state)
54
55 setValue("promotion_ids", ids, {
56 shouldDirty: true,
57 shouldTouch: true,
58 })
59
60 setRowSelection(state)
61 }
62
63 const { searchParams, raw } = usePromotionTableQuery({ pageSize: PAGE_SIZE })
64 const {
65 promotions,
66 count,
67 isPending: isLoading,
68 } = usePromotions({ ...searchParams }, { placeholderData: keepPreviousData })
69
70 const columns = useColumns()
71 const filters = usePromotionTableFilters()
72
73 const { table } = useDataTable({
74 data: promotions ?? [],
75 columns,
76 enableRowSelection: (row) => {
77 return row.original.campaign_id !== campaign.id
78 },
79 enablePagination: true,
80 getRowId: (row) => row.id,
81 pageSize: PAGE_SIZE,
82 count,
83 rowSelection: {
84 state: rowSelection,
85 updater,
86 },
87 meta: {
88 campaignId: campaign.id,
89 currencyCode: campaign?.budget?.currency_code,
90 budgetType: campaign?.budget?.type,
91 },
92 })
93
94 const handleSubmit = form.handleSubmit(async (values) => {
95 await mutateAsync(
96 { add: values.promotion_ids },
97 {
98 onSuccess: () => {
99 toast.success(
100 t("campaigns.promotions.toast.success", {
101 count: values.promotion_ids.length,
102 })
103 )
104 handleSuccess()
105 },
106 onError: (error) => toast.error(error.message),
107 }
108 )
109 })
110
111 return (
112 <RouteFocusModal.Form form={form}>
113 <KeyboundForm
114 onSubmit={handleSubmit}
115 className="flex h-full flex-col overflow-hidden"
116 >
117 <RouteFocusModal.Header>
118 <div className="flex items-center justify-end gap-x-2">
119 {form.formState.errors.promotion_ids && (
120 <Hint variant="error">
121 {form.formState.errors.promotion_ids.message}
122 </Hint>
123 )}
124 </div>
125 </RouteFocusModal.Header>
126 <RouteFocusModal.Body className="flex size-full flex-col overflow-y-auto">
127 <_DataTable
128 table={table}
129 count={count}
130 columns={columns}
131 pageSize={PAGE_SIZE}
132 isLoading={isLoading}
133 filters={filters}
134 orderBy={[
135 { key: "code", label: t("fields.code") },
136 { key: "type", label: t("fields.type") },
137 { key: "created_at", label: t("fields.createdAt") },
138 { key: "updated_at", label: t("fields.updatedAt") },
139 ]}
140 queryObject={raw}
141 layout="fill"
142 pagination
143 search="autofocus"
144 noRecords={{
145 message: t("campaigns.promotions.add.list.noRecordsMessage"),
146 }}
147 />
148 </RouteFocusModal.Body>
149 <RouteFocusModal.Footer>
150 <div className="flex items-center justify-end gap-x-2">
151 <RouteFocusModal.Close asChild>
152 <Button size="small" variant="secondary">
153 {t("actions.cancel")}
154 </Button>
155 </RouteFocusModal.Close>
156 <Button size="small" type="submit" isLoading={isPending}>
157 {t("actions.save")}
158 </Button>
159 </div>
160 </RouteFocusModal.Footer>
161 </KeyboundForm>
162 </RouteFocusModal.Form>
163 )
164 }
165
166 const columnHelper = createColumnHelper<HttpTypes.AdminPromotion>()
167
168 const useColumns = () => {
169 const base = usePromotionTableColumns()
170 const { t } = useTranslation()
171
172 return useMemo(
173 () => [
174 columnHelper.display({
175 id: "select",
176 header: ({ table }) => {
177 return (
178 <Checkbox
179 checked={
180 table.getIsSomePageRowsSelected()
181 ? "indeterminate"
182 : table.getIsAllPageRowsSelected()
183 }
184 onCheckedChange={(value) => table.toggleAllRowsSelected(!!value)}
185 />
186 )
187 },
188 cell: ({ row, table }) => {
189 const { campaignId, currencyCode, budgetType } = table.options
190 .meta as {
191 campaignId: string
192 currencyCode: string
193 budgetType: string
194 }
195
196 const isTypeSpend = budgetType === "spend"
197 const isAdded = row.original.campaign_id === campaignId
198 const isAddedToADiffCampaign =
199 !!row.original.campaign_id &&
200 row.original.campaign_id !== campaignId
201 const currencyMismatch =
202 isTypeSpend &&
203 row.original.application_method?.currency_code !== currencyCode
204 const isSelected = row.getIsSelected() || isAdded
205 const isIndeterminate = currencyMismatch || isAddedToADiffCampaign
206
207 const Component = (
208 <Checkbox
209 checked={isIndeterminate ? "indeterminate" : isSelected}
210 disabled={isAdded || isAddedToADiffCampaign || currencyMismatch}
211 onCheckedChange={(value) => row.toggleSelected(!!value)}
212 onClick={(e) => {
213 e.stopPropagation()
214 }}
215 />
216 )
217
218 if (isAddedToADiffCampaign) {
219 return (
220 <Tooltip
221 content={t("campaigns.promotions.alreadyAddedDiffCampaign", {
222 name: row.original?.campaign?.name!,
223 })}
224 side="right"
225 >
226 {Component}
227 </Tooltip>
228 )
229 }
230
231 if (currencyMismatch) {
232 return (
233 <Tooltip
234 content={t("campaigns.promotions.currencyMismatch")}
235 side="right"
236 >
237 {Component}
238 </Tooltip>
239 )
240 }
241
242 if (isAdded) {
243 return (
244 <Tooltip
245 content={t("campaigns.promotions.alreadyAdded")}
246 side="right"
247 >
248 {Component}
249 </Tooltip>
250 )
251 }
252
253 return Component
254 },
255 }),
256 ...base,
257 ],
258 [t, base]
259 )
260 }