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