gitscope
← marzneshin / v0.5.0 / dashboard/src/features/services/components/tables/inbounds/index.tsx
https://dev.kronoz.win/r/marzneshin.git
dashboard/src/features/services/components/tables/inbounds/index.tsx · TypeScript
Blame Raw
 1import { type FC, useCallback, useEffect, useState } from "react";
 2import { useInboundsQuery } from "@marzneshin/features/inbounds";
 3import { Button, DataTable } from "@marzneshin/components";
 4import { columns } from "./columns";
 5import { type ServiceType, useServicesUpdateMutation } from "@marzneshin/features/services";
 6import { useTranslation } from "react-i18next";
 7import type { RowSelectionState } from "@tanstack/react-table";
 8
 9interface ServiceInboundsTableProps {
10    service: ServiceType;
11}
12
13export const ServiceInboundsTable: FC<ServiceInboundsTableProps> = ({
14    service,
15}) => {
16    const { mutate: updateService } = useServicesUpdateMutation();
17    const { data } = useInboundsQuery();
18    const [selectedInbound, setSelectedInbound] = useState<{
19        [key: number]: boolean;
20    }>({});
21    const { t } = useTranslation();
22
23    useEffect(() => {
24        setSelectedInbound((prevSelected) => {
25            const updatedSelected: RowSelectionState = { ...prevSelected };
26            for (const inboundId of service.inbound_ids) {
27                for (const [i, fetchedInbound] of data.entries()) {
28                    if (fetchedInbound.id === inboundId) {
29                        updatedSelected[i] = true;
30                    }
31                }
32            }
33            return updatedSelected;
34        });
35    }, [data, service.inbound_ids]);
36
37    const handleApply = useCallback(() => {
38        const selectedInboundIds = Object.keys(selectedInbound)
39            .filter((key) => selectedInbound[Number.parseInt(key)])
40            .map((key) => data[Number.parseInt(key)].id);
41        updateService({ ...service, inbound_ids: selectedInboundIds });
42    }, [data, selectedInbound, service, updateService]);
43
44    const disabled = Object.keys(selectedInbound).length < 1;
45
46    return (
47        <div className="flex flex-col gap-4">
48            <DataTable
49                columns={columns}
50                data={data}
51                filteredColumn="tag"
52                selectedRow={selectedInbound}
53                setSelectedRow={setSelectedInbound}
54            />
55
56            <Button onClick={handleApply} disabled={disabled}>
57                {t("apply")}
58            </Button>
59        </div>
60    );
61};