Skip to content

Commit

Permalink
[ON-2881] Fix delete inventory
Browse files Browse the repository at this point in the history
  • Loading branch information
thehighestprimenumber committed Dec 19, 2024
1 parent 7c3fbe4 commit 2f2784d
Show file tree
Hide file tree
Showing 8 changed files with 123 additions and 18 deletions.
112 changes: 94 additions & 18 deletions app/src/components/Modals/delete-inventory-modal.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,46 @@
"use client";

import { UserDetails } from "@/app/[lng]/[inventory]/settings/page";
import {
Modal,
Badge,
Box,
Button,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Text,
Box,
Badge,
ModalFooter,
useToast,
} from "@chakra-ui/react";
import React, { FC } from "react";
import React, { FC, useState } from "react";

import { FiTrash2 } from "react-icons/fi";
import PasswordInput from "../password-input";
import { useForm } from "react-hook-form";
import { SubmitHandler, useForm } from "react-hook-form";
import { Trans } from "react-i18next/TransWithoutContext";
import { TFunction } from "i18next";
import { InfoOutlineIcon } from "@chakra-ui/icons";
import { UserAttributes } from "@/models/User";
import { api } from "@/services/api";
import { MdCheckCircleOutline } from "react-icons/md";

interface DeleteInventoryModalProps {
isOpen: boolean;
onClose: any;
userData: UserAttributes;
t: TFunction;
lng: string;
inventoryId: string;
}

const DeleteInventoryModal: FC<DeleteInventoryModalProps> = ({
isOpen,
onClose,
userData,
lng,
inventoryId,
t,
}) => {
const {
Expand All @@ -45,6 +49,64 @@ const DeleteInventoryModal: FC<DeleteInventoryModalProps> = ({
formState: { errors, isSubmitting },
setValue,
} = useForm<{ password: string }>();
const [requestPasswordConfirm] = api.useRequestVerificationMutation();
const { data: token } = api.useGetVerifcationTokenQuery({
skip: !userData,
});
const [deleteInventory] = api.useDeleteInventoryMutation();
const [isPasswordCorrect, setIsPasswordCorrect] = useState<boolean>(true);
const toast = useToast();

const onSubmit: SubmitHandler<{ password: string }> = async (data) => {
await requestPasswordConfirm({
password: data.password!,
token: token?.verificationToken!,
}).then(async (res: any) => {
if (res.data?.comparePassword) {
await deleteInventory({
inventoryId,
}).then((res: any) => {
onClose();
setIsPasswordCorrect(true);
toast({
description: t("inventory-deleted"),
status: "success",
duration: 5000,
isClosable: true,
render: () => (
<Box
display="flex"
gap="8px"
color="white"
alignItems="center"
justifyContent="space-between"
p={3}
bg="interactive.primary"
width="600px"
height="60px"
borderRadius="8px"
>
<Box display="flex" gap="8px" alignItems="center">
<MdCheckCircleOutline fontSize="24px" />

<Text
color="base.light"
fontWeight="bold"
lineHeight="52"
fontSize="label.lg"
>
{t("inventory-deleted")}
</Text>
</Box>
</Box>
),
});
});
} else {
setIsPasswordCorrect(false);
}
});
};

return (
<>
Expand Down Expand Up @@ -136,16 +198,29 @@ const DeleteInventoryModal: FC<DeleteInventoryModalProps> = ({
gap="6px"
>
<InfoOutlineIcon color="interactive.secondary" />
<Text
fontSize="body.md"
fontStyle="normal"
lineHeight="20px"
fontFamily="heading"
color="content.tertiary"
letterSpacing="wide"
>
{t("enter-password-info")}
</Text>
{isPasswordCorrect ? (
<Text
fontSize="body.md"
fontStyle="normal"
lineHeight="20px"
fontFamily="heading"
color="content.tertiary"
letterSpacing="wide"
>
{t("enter-password-info")}
</Text>
) : (
<Text
fontSize="body.md"
fontStyle="normal"
lineHeight="20px"
fontFamily="heading"
color="content.tertiary"
letterSpacing="wide"
>
{t("incorrect-password")}
</Text>
)}
</Box>
</Box>
</Box>
Expand Down Expand Up @@ -174,7 +249,8 @@ const DeleteInventoryModal: FC<DeleteInventoryModalProps> = ({
textTransform="uppercase"
fontWeight="semibold"
fontSize="button.md"
type="button"
type="submit"
onClick={handleSubmit(onSubmit)}
p={0}
m={0}
>
Expand Down
6 changes: 6 additions & 0 deletions app/src/components/Tabs/my-inventories-tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ const MyInventoriesTab: FC<MyInventoriesTabProps> = ({
}) => {
const [tabIndex, setTabIndex] = useState(0);
const [cityId, setCityId] = useState<string | undefined>(defaultCityId);
const [inventoryId, setInventoryId] = useState("");

useEffect(() => {
if (!cityId && defaultCityId && defaultCityId !== cityId) {
setCityId(defaultCityId);
Expand Down Expand Up @@ -327,6 +329,9 @@ const MyInventoriesTab: FC<MyInventoriesTabProps> = ({
color: "white",
}}
onClick={() => {
setInventoryId(
inventory.inventoryId,
);
onInventoryDeleteModalOpen();
}}
>
Expand Down Expand Up @@ -363,6 +368,7 @@ const MyInventoriesTab: FC<MyInventoriesTabProps> = ({
</TabPanel>

<DeleteInventoryModal
inventoryId={inventoryId}
isOpen={isInventoryDeleteModalOpen}
onClose={onInventoryDeleteModalClose}
userData={userData}
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/locales/de/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"email-address": "E-Mail",
"remove-user-prompt": "Sind Sie sicher, dass Sie diesen Benutzer <2>dauerhaft entfernen</2> möchten aus Ihrem Team?",
"city-deleted": "Stadt erfolgreich gelöscht",
"inventory-deleted": "Inventar erfolgreich gelöscht",
"delete-file-prompt": "Sind Sie sicher, dass Sie diese Datei <2>dauerhaft löschen</2> möchten aus dem Repository der Stadt?",
"mark-as-completed": "Als abgeschlossen markieren",
"password-required": "Password ist ein Pflichtfeld",
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/locales/en/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"email-address": "Email",
"remove-user-prompt": " Are you sure you want to <2> permanently remove this user </2> from your team?",
"city-deleted": "City deleted successfully",
"inventory-deleted": "Inventory deleted successfully",
"delete-file-prompt": "Are you sure you want to <2> permanently delete </2> this file from the city's repository?",
"mark-as-completed": "Mark as completed",
"password-required": "Password is required",
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/locales/es/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"email-address": "Correo electrónico",
"remove-user-prompt": "¿Está seguro de que desea <2>eliminar permanentemente a este usuario</2> de su equipo?",
"city-deleted": "Ciudad eliminada exitosamente",
"inventory-deleted": "Inventorio eliminado exitosamente",
"delete-file-prompt": "¿Está seguro de que desea <2>eliminar permanentemente</2> este archivo del repositorio de la ciudad?",
"password-required": "Se requiere contraseña",
"min-length": "La longitud mínima debe ser {{length}}",
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/locales/pt/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"email-address": "E-mail",
"remove-user-prompt": "Tem certeza de que deseja <2>remover permanentemente este usuário</2> da sua equipe?",
"city-deleted": "Cidade excluída com sucesso",
"inventory-deleted": "Inventário excluído com sucesso",
"delete-file-prompt": "Tem certeza de que deseja <2>excluir permanentemente</2> este arquivo do repositório da cidade?",
"mark-as-completed": "Marcar como concluído",
"password-required": "A senha é obrigatória",
Expand Down
15 changes: 15 additions & 0 deletions app/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ConnectDataSourceResponse,
EmissionsFactorResponse,
GetDataSourcesResult,
InventoryDeleteQuery,
InventoryProgressResponse,
InventoryResponse,
InventoryUpdateQuery,
Expand Down Expand Up @@ -48,6 +49,7 @@ export const api = createApi({
"SectorBreakdown",
"Inventory",
"CitiesAndInventories",
"Inventories",
],
baseQuery: fetchBaseQuery({ baseUrl: "/api/v0/", credentials: "include" }),
endpoints: (builder) => ({
Expand Down Expand Up @@ -289,6 +291,18 @@ export const api = createApi({
"YearlyReportResults",
],
}),
deleteInventory: builder.mutation<
InventoryAttributes,
InventoryDeleteQuery
>({
query: (data) => ({
url: `/inventory/${data.inventoryId}`,
method: "DELETE",
}),
transformResponse: (response: { data: InventoryAttributes }) =>
response.data,
invalidatesTags: ["InventoryProgress", "InventoryValue", "Inventories"],
}),
deleteInventoryValue: builder.mutation<
InventoryValueAttributes,
InventoryValueInSubSectorDeleteQuery
Expand Down Expand Up @@ -453,6 +467,7 @@ export const api = createApi({
url: `/city/${cityId}/inventory`,
method: "GET",
}),
providesTags: ["Inventories"],
transformResponse: (response: { data: any }) => response.data,
}),
addUserFile: builder.mutation<UserFileResponse, any>({
Expand Down
4 changes: 4 additions & 0 deletions app/src/util/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ export interface InventoryValueInSubSectorDeleteQuery {
inventoryId: string;
}

export interface InventoryDeleteQuery {
inventoryId: string;
}

export interface InventoryUpdateQuery {
inventoryId: string;
data: { isPublic: boolean };
Expand Down

0 comments on commit 2f2784d

Please sign in to comment.