1 import { PlusMini, Trash } from "@medusajs/icons"
2 import { HttpTypes } from "@medusajs/types"
3 import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui"
4 import {
5 ColumnDef,
6 RowSelectionState,
7 createColumnHelper,
8 } from "@tanstack/react-table"
9 import { useMemo, useState } from "react"
10 import { useTranslation } from "react-i18next"
11 import { ActionMenu } from "../../../../../components/common/action-menu"
12 import { _DataTable } from "../../../../../components/table/data-table"
13 import { useUpdateRegion } from "../../../../../hooks/api/regions"
14 import { useDataTable } from "../../../../../hooks/use-data-table"
15 import { useCountries } from "../../../common/hooks/use-countries"
16 import { useCountryTableColumns } from "../../../common/hooks/use-country-table-columns"
17 import { useCountryTableQuery } from "../../../common/hooks/use-country-table-query"
18 import { StaticCountry } from "../../../../../lib/data/countries"
19
20 type RegionCountrySectionProps = {
21 region: HttpTypes.AdminRegion
22 }
23
24 const PREFIX = "c"
25 const PAGE_SIZE = 10
26
27 export const RegionCountrySection = ({ region }: RegionCountrySectionProps) => {
28 const { t } = useTranslation()
29 const prompt = usePrompt()
30
31 const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
32
33 const { searchParams, raw } = useCountryTableQuery({
34 pageSize: PAGE_SIZE,
35 prefix: PREFIX,
36 })
37 const { countries, count } = useCountries({
38 countries: (region.countries || []) as StaticCountry[],
39 ...searchParams,
40 })
41
42 const columns = useColumns()
43
44 const { table } = useDataTable({
45 data: countries || [],
46 columns,
47 count,
48 enablePagination: true,
49 enableRowSelection: true,
50 getRowId: (row) => row.iso_2,
51 pageSize: PAGE_SIZE,
52 rowSelection: {
53 state: rowSelection,
54 updater: setRowSelection,
55 },
56 prefix: PREFIX,
57 meta: {
58 region,
59 },
60 })
61
62 const { mutateAsync } = useUpdateRegion(region.id)
63
64 const handleRemoveCountries = async () => {
65 const ids = Object.keys(rowSelection).filter((k) => rowSelection[k])
66
67 const res = await prompt({
68 title: t("general.areYouSure"),
69 description: t("regions.removeCountriesWarning", {
70 count: ids.length,
71 }),
72 verificationText: t("actions.remove"),
73 verificationInstruction: t("general.typeToConfirm"),
74 cancelText: t("actions.cancel"),
75 confirmText: t("actions.remove"),
76 })
77
78 if (!res) {
79 return
80 }
81
82 const payload = region.countries
83 ?.filter((c) => !ids.includes(c.iso_2!))
84 .map((c) => c.iso_2!)
85
86 await mutateAsync(
87 {
88 countries: payload,
89 },
90 {
91 onSuccess: () => {
92 toast.success(t("regions.toast.countries"))
93 },
94 onError: (e) => {
95 toast.error(e.message)
96 },
97 }
98 )
99 }
100
101 return (
102 <Container className="divide-y p-0">
103 <div className="flex items-center justify-between px-6 py-4">
104 <Heading level="h2">{t("fields.countries")}</Heading>
105 <ActionMenu
106 groups={[
107 {
108 actions: [
109 {
110 label: t("regions.addCountries"),
111 icon: <PlusMini />,
112 to: "countries/add",
113 },
114 ],
115 },
116 ]}
117 />
118 </div>
119 <_DataTable
120 table={table}
121 columns={columns}
122 pageSize={PAGE_SIZE}
123 count={count}
124 orderBy={[
125 { key: "name", label: t("fields.name") },
126 { key: "iso_2", label: t("fields.code") },
127 ]}
128 search
129 pagination
130 queryObject={raw}
131 prefix={PREFIX}
132 commands={[
133 {
134 action: handleRemoveCountries,
135 label: t("actions.remove"),
136 shortcut: "r",
137 },
138 ]}
139 />
140 </Container>
141 )
142 }
143
144 const CountryActions = ({
145 country,
146 region,
147 }: {
148 country: StaticCountry
149 region: HttpTypes.AdminRegion
150 }) => {
151 const { t } = useTranslation()
152 const prompt = usePrompt()
153 const { mutateAsync } = useUpdateRegion(region.id)
154
155 const payload = region.countries
156 ?.filter((c) => c.iso_2 && c.iso_2 !== country.iso_2)
157 .map((c) => c.iso_2!)
158
159 const handleRemove = async () => {
160 const res = await prompt({
161 title: t("general.areYouSure"),
162 description: t("regions.removeCountryWarning", {
163 name: country.display_name,
164 }),
165 verificationText: country.display_name,
166 verificationInstruction: t("general.typeToConfirm"),
167 cancelText: t("actions.cancel"),
168 confirmText: t("actions.remove"),
169 })
170
171 if (!res) {
172 return
173 }
174
175 await mutateAsync(
176 {
177 countries: payload,
178 },
179 {
180 onSuccess: () => {
181 toast.success(t("regions.toast.countries"))
182 },
183 onError: (e) => {
184 toast.error(e.message)
185 },
186 }
187 )
188 }
189
190 return (
191 <ActionMenu
192 groups={[
193 {
194 actions: [
195 {
196 label: t("actions.remove"),
197 onClick: handleRemove,
198 icon: <Trash />,
199 },
200 ],
201 },
202 ]}
203 />
204 )
205 }
206
207 const columnHelper = createColumnHelper<StaticCountry>()
208
209 const useColumns = () => {
210 const base = useCountryTableColumns()
211
212 return useMemo(
213 () => [
214 columnHelper.display({
215 id: "select",
216 header: ({ table }) => {
217 return (
218 <Checkbox
219 checked={
220 table.getIsSomePageRowsSelected()
221 ? "indeterminate"
222 : table.getIsAllPageRowsSelected()
223 }
224 onCheckedChange={(value) =>
225 table.toggleAllPageRowsSelected(!!value)
226 }
227 />
228 )
229 },
230 cell: ({ row }) => {
231 return (
232 <Checkbox
233 checked={row.getIsSelected()}
234 onCheckedChange={(value) => row.toggleSelected(!!value)}
235 onClick={(e) => {
236 e.stopPropagation()
237 }}
238 />
239 )
240 },
241 }),
242 ...base,
243 columnHelper.display({
244 id: "actions",
245 cell: ({ row, table }) => {
246 const { region } = table.options.meta as {
247 region: HttpTypes.AdminRegion
248 }
249
250 return <CountryActions country={row.original} region={region} />
251 },
252 }),
253 ],
254 [base]
255 ) as ColumnDef<StaticCountry>[]
256 }