No componente a seguir o openConfirmModal deve ser modificado.

1. Na propriedade children termos dois botoes, um embaixo do outro.
O primeiro é para renovar apenas a data de vencimento.
O segundo é para renovar o token e a data de vencimento

2 Ambos os botões devem chamar a função que está no onSubmit

3 o onsumbit deve ser removido


/* eslint-disable no-underscore-dangle */
import React, { useEffect, useRef, useState } from "react";
import {
    RelButton,
    RelCard,
    RelChip,
    RelGrid,
    RelSelect,
    RelStack,
    RelSwitch,
    RelTable,
    RelTableLocalization,
    RelText,
    RelTransitions,
    TData,
    useRelSnackbar,
    useRelTable
} from "@rel/core";
import { v4 } from "uuid";
import { RelIcon } from "@rel/icons";
import { ZodError } from "zod";
import { format, add } from "date-fns";
import { RelServicesApi } from "@rel/services";
import { useTranslation } from "react-i18next";
import { TabExternalProps } from "./interface.ts";
import {
    Active,
    FrequencyExpiration,
    TypeApplication
} from "../../../../interfaces/enums.ts";
import {
    ApplicationExternalForms,
    applicationExternalSchema,
    external
} from "./schema.ts";
import { useModal } from "../../../../hooks/useModal.ts";

export const TabExternalApplications: React.FC<TabExternalProps> = ({
    workspaceId,
    integrationId,
    setBtnSaveDisabled,
    externalApplicationData,
    setExternalApplicationData,
    control,
    getValues,
    setValue,
    setError,
    clearErrors,
    indexRowEdit,
    errors
}) => {
    const { t } = useTranslation();

    const [modalOpen, setModalOpen] = useState(false);

    // Função que abre modal
    const openModal = () => setModalOpen(true);

    // Função que fecha modal
    const closeModal = () => setModalOpen(false);

    const externalApplicationPrevLength = useRef<number>();

    const [enableEditRow, setEnableEditRow] = useState(false);

    const { enqueueSnackbar, closeSnackbar } = useRelSnackbar();

    const { onOpen: openConfirmModal } = useModal("ConfirmModal");

    const addExternalApplicationHandler = () => {
        setEnableEditRow(true);
        const newDate = add(new Date(), { years: 1 });
        const newDateTime = format(newDate, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx");

        const newApplication = {
            ...external,
            id: v4(),
            integrationId: integrationId ?? 0,
            expirationKey: newDateTime
        } as any;
        setExternalApplicationData((prevState: any) => [
            ...prevState,
            newApplication
        ]);
        const applicationsForm = getApplicationsForm();
        applicationsForm.push(newApplication);

        setBtnSaveDisabled(true);
        tableExternalApplication.setColumnVisibility({ key: false });
        setValue("externalApplications", applicationsForm);
    };

    useEffect(() => {
        if (indexRowEdit >= 0) {
            const row = tableExternalApplication?.getRow(
                indexRowEdit.toString()
            ) as any;
            setBtnSaveDisabled(true);
            tableExternalApplication.setEditingRow(row);
            tableExternalApplication.setColumnVisibility({ key: false });
        }
    }, [indexRowEdit]);

    useEffect(() => {
        if (
            externalApplicationData &&
            externalApplicationData?.length > 0 &&
            externalApplicationData.length >
                (externalApplicationPrevLength.current ?? 0)
        ) {
            if (enableEditRow) {
                tableExternalApplication?.setEditingRow(
                    tableExternalApplication?.getRow(
                        (externalApplicationData.length - 1).toString()
                    ) as any
                );
            }
        }
        externalApplicationPrevLength.current = externalApplicationData.length;
    }, [externalApplicationData]);

    const getApplicationsForm = () =>
        (getValues("externalApplications") as ApplicationExternalForms[]) ?? [];

    const deleteExternalApplicationHandle = (
        _event: React.MouseEvent | null,
        row: any
    ) => {
        const applicationDeletedId = row.original.id;
        setExternalApplicationData((prevState) => {
            const externalApplicationDataCopy = [...prevState];
            externalApplicationDataCopy.splice(row.index, 1);
            return externalApplicationDataCopy;
        });
        const applicationsFormFiltered = getApplicationsForm().filter(
            (application) => application.id !== applicationDeletedId
        );
        setValue("externalApplications", applicationsFormFiltered);
    };

    const optionsExpiration: { value: string; label: string }[] = [
        { value: "0", label: t("1 mês") },
        { value: "1", label: t("3 meses") },
        { value: "2", label: t("6 meses") },
        { value: "3", label: t("1 ano") }
    ];

    const renderConnection = ({ cell }: any) => (
        <RelChip
            color={cell.getValue() === Active.Y ? "success" : "error"}
            label={cell.getValue() === Active.Y ? t("Sim") : t("Não")}
        />
    );

    const renderDate = ({ row }: any) => {
        const dateRef = row.original.expirationKey ?? "";
        return format(new Date(dateRef), "dd/MM/yyyy HH:mm:ss");
    };

    const renderStatus = ({ cell }: any) => (
        <RelChip
            color={cell.getValue() === Active.Y ? "success" : "error"}
            label={cell.getValue() === Active.Y ? t("Sim") : t("Não")}
        />
    );

    const renewKeyApplicationHandle = async (index: number, name: string) => {
        const response = await RelServicesApi.getRequest({
            method: "Workspace/GenerateNewKey",
            urlParameters: { name }
        });
        if (response.status === 200) {
            setExternalApplicationData((prevState) => {
                const newArray = [...prevState];
                newArray[index].key = response.data;
                return newArray;
            });
        }
        const expirationKey = new Date();
        expirationKey.setFullYear(expirationKey.getFullYear() + 1);

        setValue(`externalApplications.${index}.key`, response.data);
        setValue(
            `externalApplications.${index}.expirationKey`,
            expirationKey.toISOString()
        );

        setExternalApplicationData((prevState) => {
            const newState = [...prevState];
            newState[index].expirationKey = expirationKey;
            return newState;
        });
    };

    const confirmTokenRenewal = (index: number, applicationName: string) => {
        const newExpirationDate = format(
            add(new Date(), { years: 1 }),
            "dd/MM/yyyy HH:mm:ss"
        );
        openConfirmModal({
            title: t("Renovar Token"),
            icon: "refresh",
            open: modalOpen,
            onClose: closeModal,
            children: (
                <RelGrid>
                    <RelGrid container m={2} justifyContent="center">
                        <RelText textAlign="center">
                            {t(
                                "Deseja realmente atualizar o token da aplicação:"
                            )}
                            &nbsp;
                        </RelText>
                        <RelText textAlign="center" color="error">
                            {applicationName}
                        </RelText>
                        <RelText textAlign="center">&nbsp;?</RelText>
                    </RelGrid>
                    <RelGrid container m={2} justifyContent="center">
                        <RelText sx={{ fontSize: "0.8rem" }} textAlign="center">
                            {t(
                                "A data de validade do token será atualizada para"
                            )}{" "}
                            {`${newExpirationDate}.`}
                        </RelText>
                    </RelGrid>
                </RelGrid>
            ),
            onSubmit: async () =>
                renewKeyApplicationHandle(index, applicationName)
        });
    };

    const cancelRowHandler = ({ row }: any) => {
        const { id, name } = row.original;
        const isNum = /^\d+$/.test(id);

        if (!isNum && name === "") {
            deleteExternalApplicationHandle(null, row);
        }
        clearErrors(`externalApplications.${row.index}`);
        tableExternalApplication.setColumnVisibility({ key: true });
        setBtnSaveDisabled(false);
    };

    const copyToken = (tokenValue: string) => {
        navigator.clipboard.writeText(tokenValue).then(() => {
            const key = v4();
            enqueueSnackbar(t("Token copiado para a área de transferência!"), {
                key,
                variant: "success",
                action: (
                    <RelButton iconButton onClick={() => closeSnackbar(key)}>
                        <RelIcon name="close" />
                    </RelButton>
                )
            });
        });
    };

    const saveExternalApplicationHandle = ({
        exitEditingMode,
        row,
        values
    }: any) => {
        try {
            const dateNow = Date.now();
            let expirationKey = new Date(
                new Date(dateNow).setFullYear(
                    new Date(dateNow).getFullYear() + 1
                )
            );

            if (
                row._valuesCache.expirationOption ===
                FrequencyExpiration.OneMonth.toString()
            )
                expirationKey = new Date(
                    new Date(dateNow).setMonth(new Date(dateNow).getMonth() + 1)
                );
            else if (
                row._valuesCache.expirationOption ===
                FrequencyExpiration.ThreeMonths.toString()
            )
                expirationKey = new Date(
                    new Date(dateNow).setMonth(new Date(dateNow).getMonth() + 3)
                );
            else if (
                row._valuesCache.expirationOption ===
                FrequencyExpiration.SixMonths.toString()
            )
                expirationKey = new Date(
                    new Date(dateNow).setMonth(new Date(dateNow).getMonth() + 6)
                );

            const castedData = applicationExternalSchema.parse({
                ...values,
                workspaceId,
                integrationId: integrationId ?? 0,
                id: row.original.id,
                expirationKey: expirationKey.toISOString(),
                typeApplication: TypeApplication.Client
            }) as any;

            setExternalApplicationData((prevState) => {
                const newState = [...prevState];
                newState[row.index] = castedData;
                return newState;
            });

            const applicationsForm = getApplicationsForm();

            let indexKey = 0;
            let newApplication = true;
            const valuesUpdated =
                (applicationsForm.map((item, index) => {
                    let newItem = item;
                    if (item.id === castedData.id) {
                        newApplication = false;
                        newItem = castedData;
                        indexKey = index;
                    }
                    return newItem;
                }) as ApplicationExternalForms[]) ?? [];

            if (newApplication) valuesUpdated.push(castedData);

            tableExternalApplication.setColumnVisibility({ key: true });
            clearErrors(`externalApplications.${row.index}`);
            setValue("externalApplications", valuesUpdated);
            setBtnSaveDisabled(false);
            setEnableEditRow(false);
            exitEditingMode();

            if (Number.isNaN(castedData.id)) {
                indexKey = newApplication
                    ? externalApplicationData.length - 1
                    : indexKey;
                renewKeyApplicationHandle(indexKey, castedData.name);
            }
        } catch (error: any) {
            if (error instanceof ZodError) {
                error.issues.map((item) =>
                    setError(
                        `externalApplications.${row.index}.${item.path[0]}` as any,
                        {
                            message: item.message
                        }
                    )
                );
            }
        }
    };

    const tableExternalApplication = useRelTable({
        enableColumnActions: false,
        enableSorting: false,
        enableTopToolbar: false,
        enableBottomToolbar: false,
        editDisplayMode: "row",
        enableEditing: true,
        localization: RelTableLocalization.PtBr,
        positionActionsColumn: "last",
        onEditingRowSave: saveExternalApplicationHandle,
        onEditingRowCancel: cancelRowHandler,
        renderRowActions: ({ row, table }) => (
            <RelGrid container spacing={2}>
                <RelGrid>
                    <RelTransitions.Collapse in={row.original.id > 0}>
                        <RelButton
                            iconButton
                            color="warning"
                            onClick={() =>
                                confirmTokenRenewal(
                                    row.index,
                                    row._valuesCache.name
                                )
                            }
                        >
                            <RelIcon name="refresh" size={18} />
                        </RelButton>
                    </RelTransitions.Collapse>
                </RelGrid>
                <RelGrid>
                    <RelButton
                        iconButton
                        color="warning"
                        onClick={() => {
                            table.setEditingRow(row);
                            setBtnSaveDisabled(true);
                            tableExternalApplication.setColumnVisibility({
                                key: false
                            });
                        }}
                    >
                        <RelIcon name="pencil" size={14} />
                    </RelButton>
                </RelGrid>
                <RelGrid>
                    <RelButton
                        color="error"
                        iconButton
                        onClick={(e) => deleteExternalApplicationHandle(e, row)}
                    >
                        <RelIcon name="trash" size={14} />
                    </RelButton>
                </RelGrid>
            </RelGrid>
        ),
        data: (externalApplicationData as TData[]) ?? [],
        columns: [
            {
                id: "name",
                accessorKey: "name",
                header: t("Nome"),
                muiEditTextFieldProps: ({ row }) => ({
                    required: true,
                    error: Boolean(
                        errors.externalApplications &&
                            errors.externalApplications[row.index]?.name
                    ),
                    helperlabel:
                        (errors.externalApplications &&
                            errors.externalApplications[row.index]?.name
                                ?.message) ??
                        "",
                    onFocus: () =>
                        clearErrors(`externalApplications.${row.index}.name`)
                }),
                maxSize: 130
            },
            {
                id: "key",
                accessorKey: "key",
                header: t("Token"),
                Cell: ({ cell }) => (
                    <RelText
                        sx={{
                            maxWidth: 130,
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                            cursor: "pointer"
                        }}
                        title="Clique para copiar o token"
                        onClick={() => copyToken(cell.getValue())}
                    >
                        {cell.getValue() ?? ""}
                    </RelText>
                ),

                muiEditTextFieldProps: ({ row }) => ({
                    required: true,
                    error: Boolean(
                        errors.externalApplications &&
                            errors.externalApplications[row.index]?.key
                    ),
                    helperlabel:
                        (errors.externalApplications &&
                            errors.externalApplications[row.index]?.key
                                ?.message) ??
                        "",
                    onFocus: () =>
                        clearErrors(`externalApplications.${row.index}.key`)
                }),
                maxSize: 130
            },
            {
                id: "active",
                accessorKey: "active",
                header: t("Ativo"),
                muiEditTextFieldProps: ({ row }) => ({
                    required: true,
                    error: Boolean(
                        errors.externalApplications &&
                            errors.externalApplications[row.index]?.active
                    ),
                    onFocus: () =>
                        clearErrors(`externalApplications.${row.index}.key`)
                }),
                filterSelectOptions: [
                    {
                        label: t("Inativo"),
                        value: Active.N.toString()
                    },
                    {
                        label: t("Ativo"),
                        value: Active.Y.toString()
                    }
                ],
                maxSize: 65,
                Cell: renderStatus,
                Edit: ({ cell, row }) => (
                    <RelSwitch
                        control={control}
                        name={`externalApplications.${row.index}.active`}
                        defaultValue={row.original.active}
                        onChange={(e: any) => {
                            row._valuesCache[cell.column.id] = e.target.checked
                                ? Active.Y
                                : Active.N;
                            row.toggleSelected(
                                row._valuesCache[cell.column.id]
                            );
                        }}
                    />
                )
            },
            {
                id: "requiredConnectionToken",
                accessorKey: "requiredConnectionToken",
                header: t("Requer Conexão"),
                muiEditTextFieldProps: ({ row }) => ({
                    required: true,
                    error: Boolean(
                        errors.externalApplications &&
                            errors.externalApplications[row.index]
                                ?.requiredConnectionToken
                    ),
                    onFocus: () =>
                        clearErrors(
                            `externalApplications.${row.index}.requiredConnectionToken`
                        )
                }),
                filterSelectOptions: [
                    {
                        label: t("Não"),
                        value: Active.N.toString()
                    },
                    {
                        label: t("Sim"),
                        value: Active.Y.toString()
                    }
                ],
                maxSize: 50,
                Cell: renderConnection,
                Edit: ({ cell, row }) => (
                    <RelSwitch
                        control={control}
                        name={`externalApplications.${row.index}.requiredConnectionToken`}
                        defaultValue={row.original.requiredConnectionToken}
                        onChange={(e: any) => {
                            row._valuesCache[cell.column.id] = e.target.checked
                                ? Active.Y
                                : Active.N;
                            row.toggleSelected(
                                row._valuesCache[cell.column.id]
                            );
                        }}
                    />
                )
            },
            {
                id: "expirationOption",
                accessorKey: "expirationOption",
                header: t("Expiração"),
                muiEditTextFieldProps: ({ row }) => ({
                    required: true,
                    error: Boolean(
                        errors.externalApplications &&
                            errors.externalApplications[row.index]
                                ?.expirationOption
                    ),
                    onFocus: () =>
                        clearErrors(
                            `externalApplications.${row.index}.expirationOption`
                        )
                }),
                filterSelectOptions: [
                    {
                        label: t("Não"),
                        value: Active.N.toString()
                    },
                    {
                        label: t("Sim"),
                        value: Active.Y.toString()
                    }
                ],
                Cell: renderDate,
                Edit: ({ cell, row }) => (
                    <RelSelect
                        name="expirationOption"
                        control={control}
                        options={optionsExpiration}
                        defaultValue="3"
                        onChange={(e: any) => {
                            row._valuesCache[cell.column.id] = e.target.value;
                        }}
                        required
                        fullWidth
                    />
                ),
                maxSize: 50
            }
        ]
    });

    return (
        <RelStack>
            <RelGrid
                container
                spacing={2}
                alignItems="center"
                justifyContent="center"
            >
                <RelGrid
                    xs={12}
                    container
                    paddingRight={1}
                    justifyContent="flex-end"
                >
                    <RelButton
                        disabled={
                            !tableExternalApplication
                                .getColumn("key")
                                .getIsVisible()
                        }
                        startIcon={<RelIcon name="plus" size={16} />}
                        onClick={addExternalApplicationHandler}
                    >
                        {t("Adicionar")}
                    </RelButton>
                </RelGrid>
                <RelGrid
                    xs={12}
                    sx={{ height: "calc(100vh - 310px)", overflow: "auto" }}
                >
                    <RelCard.Root>
                        <RelTable table={tableExternalApplication} />
                    </RelCard.Root>
                </RelGrid>
            </RelGrid>
        </RelStack>
    );
};