1 import { PencilSquare, Trash } from "@medusajs/icons"
2 import { AdminCampaign, AdminPromotion } from "@medusajs/types"
3 import { Button, Checkbox, Container, Heading, usePrompt } from "@medusajs/ui"
4 import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
5 import { useMemo, useState } from "react"
6 import { useTranslation } from "react-i18next"
7 import { Link } from "react-router-dom"
8
9 import { ActionMenu } from "../../../../../components/common/action-menu"
10 import { _DataTable } from "../../../../../components/table/data-table"
11 import { useAddOrRemoveCampaignPromotions } from "../../../../../hooks/api/campaigns"
12 import { usePromotions } from "../../../../../hooks/api/promotions"
13 import { usePromotionTableColumns } from "../../../../../hooks/table/columns/use-promotion-table-columns"
14 import { usePromotionTableFilters } from "../../../../../hooks/table/filters/use-promotion-table-filters"
15 import { usePromotionTableQuery } from "../../../../../hooks/table/query/use-promotion-table-query"
16 import { useDataTable } from "../../../../../hooks/use-data-table"
17
18 type CampaignPromotionSectionProps = {
19 campaign: AdminCampaign
20 }
21
22 const PAGE_SIZE = 10
23
24 export const CampaignPromotionSection = ({
25 campaign,
26 }: CampaignPromotionSectionProps) => {
27 const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
28 const { t } = useTranslation()
29 const prompt = usePrompt()
30 const columns = useColumns()
31 const filters = usePromotionTableFilters()
32 const { searchParams, raw } = usePromotionTableQuery({ pageSize: PAGE_SIZE })
33 const { promotions, count, isLoading, isError, error } = usePromotions({
34 ...searchParams,
35 campaign_id: campaign.id,
36 })
37
38 const { table } = useDataTable({
39 data: promotions ?? [],
40 columns,
41 count,
42 getRowId: (row) => row.id,
43 enablePagination: true,
44 enableRowSelection: true,
45 pageSize: PAGE_SIZE,
46 rowSelection: {
47 state: rowSelection,
48 updater: setRowSelection,
49 },
50 meta: { campaignId: campaign.id },
51 })
52
53 if (isError) {
54 throw error
55 }
56
57 const { mutateAsync } = useAddOrRemoveCampaignPromotions(campaign.id)
58
59 const handleRemove = async () => {
60 const keys = Object.keys(rowSelection)
61
62 const res = await prompt({
63 title: t("campaigns.promotions.remove.title", { count: keys.length }),
64 description: t("campaigns.promotions.remove.description", {
65 count: keys.length,
66 }),
67 confirmText: t("actions.continue"),
68 cancelText: t("actions.cancel"),
69 })
70
71 if (!res) {
72 return
73 }
74
75 await mutateAsync(
76 { remove: keys },
77 { onSuccess: () => setRowSelection({}) }
78 )
79 }
80
81 return (
82 <Container className="divide-y p-0">
83 <div className="flex items-center justify-between px-6 py-4">
84 <Heading level="h2">{t("promotions.domain")}</Heading>
85 <Link to={`/campaigns/${campaign.id}/add-promotions`}>
86 <Button variant="secondary" size="small">
87 {t("general.add")}
88 </Button>
89 </Link>
90 </div>
91
92 <_DataTable
93 table={table}
94 columns={columns}
95 pageSize={PAGE_SIZE}
96 isLoading={isLoading}
97 count={count}
98 navigateTo={(row) => `/promotions/${row.id}`}
99 filters={filters}
100 search
101 pagination
102 orderBy={[
103 { key: "code", label: t("fields.code") },
104 { key: "type", label: t("fields.type") },
105 { key: "created_at", label: t("fields.createdAt") },
106 { key: "updated_at", label: t("fields.updatedAt") },
107 ]}
108 queryObject={raw}
109 commands={[
110 {
111 action: handleRemove,
112 label: t("actions.remove"),
113 shortcut: "r",
114 },
115 ]}
116 noRecords={{
117 message: t("campaigns.promotions.list.noRecordsMessage"),
118 }}
119 />
120 </Container>
121 )
122 }
123
124 export const PromotionActions = ({
125 promotion,
126 campaignId,
127 }: {
128 promotion: AdminPromotion
129 campaignId: string
130 }) => {
131 const { t } = useTranslation()
132 const { mutateAsync } = useAddOrRemoveCampaignPromotions(campaignId)
133
134 const prompt = usePrompt()
135
136 const handleRemove = async () => {
137 const res = await prompt({
138 title: t("campaigns.promotions.remove.title", {
139 count: 1,
140 }),
141 description: t("campaigns.promotions.remove.description", {
142 count: 1,
143 }),
144 confirmText: t("actions.continue"),
145 cancelText: t("actions.cancel"),
146 })
147
148 if (!res) {
149 return
150 }
151
152 await mutateAsync({
153 remove: [promotion.id],
154 })
155 }
156
157 return (
158 <ActionMenu
159 groups={[
160 {
161 actions: [
162 {
163 icon: <PencilSquare />,
164 label: t("actions.edit"),
165 to: `/promotions/${promotion.id}/edit`,
166 },
167 ],
168 },
169 {
170 actions: [
171 {
172 icon: <Trash />,
173 label: t("actions.remove"),
174 onClick: handleRemove,
175 },
176 ],
177 },
178 ]}
179 />
180 )
181 }
182
183 const columnHelper = createColumnHelper<AdminPromotion>()
184
185 const useColumns = () => {
186 const columns = usePromotionTableColumns()
187
188 return useMemo(
189 () => [
190 columnHelper.display({
191 id: "select",
192 header: ({ table }) => {
193 return (
194 <Checkbox
195 checked={
196 table.getIsSomePageRowsSelected()
197 ? "indeterminate"
198 : table.getIsAllPageRowsSelected()
199 }
200 onCheckedChange={(value) =>
201 table.toggleAllPageRowsSelected(!!value)
202 }
203 />
204 )
205 },
206 cell: ({ row }) => {
207 return (
208 <Checkbox
209 checked={row.getIsSelected()}
210 onCheckedChange={(value) => row.toggleSelected(!!value)}
211 onClick={(e) => {
212 e.stopPropagation()
213 }}
214 />
215 )
216 },
217 }),
218 ...columns,
219 columnHelper.display({
220 id: "actions",
221 cell: ({ row, table }) => {
222 const { campaignId } = table.options.meta as {
223 campaignId: string
224 }
225
226 return (
227 <PromotionActions
228 promotion={row.original}
229 campaignId={campaignId}
230 />
231 )
232 },
233 }),
234 ],
235 [columns]
236 )
237 }