Skip to content

Commit

Permalink
fix: undefined id and disable button when no mats (#274)
Browse files Browse the repository at this point in the history
* fix: undefined id and disable button when no mats

* fix: materials

---------

Co-authored-by: Simon ZHANG <102216594+userMeh@users.noreply.github.com>
  • Loading branch information
Jayllyz and userMeh committed Jul 20, 2024
1 parent 3dbbc8d commit 0d1d8d8
Show file tree
Hide file tree
Showing 15 changed files with 162 additions and 189 deletions.
25 changes: 5 additions & 20 deletions apps/admin/app/(dashboard)/dashboard/materials/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import type { Address, Material } from '@/app/lib/type/Materials';
import AddMaterial from '@/app/ui/dashboard/materials/AddMaterial';
import AddNewMaterial from '@/app/ui/dashboard/materials/AddNewMaterial';
import DeleteMaterial from '@/app/ui/dashboard/materials/DeleteMaterial';
Expand All @@ -11,31 +12,15 @@ import { ScrollArea } from '@repo/ui/components/ui/scroll-area';
import { useRouter } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

type MaterialData = {
interface MaterialData {
data: Material[];
count: number;
};

type Address = {
id: number;
road: string;
number: number;
complement: string | null;
name: string | null;
};
}

type AddressData = {
interface AddressData {
data: Address[];
count: number;
};
}

function ShowContent({ addresses }: { addresses: Address[] }): JSX.Element {
const router = useRouter();
Expand Down
17 changes: 17 additions & 0 deletions apps/admin/app/lib/type/Materials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export type Material = {
addresses: {
id_address: number;
quantity: number;
}[];
id: number;
name: string;
weight_grams: number | null;
};

export type Address = {
id: number;
road: string;
number: number;
complement: string | null;
name: string | null;
};
25 changes: 25 additions & 0 deletions apps/admin/app/lib/utils/Materials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use server';

import { cookies } from 'next/headers';

const urlApi = process.env.ATHLONIX_API_URL;

export async function addMaterial(
id_material: number,
id_address: number,
quantity: number,
): Promise<{ status: number }> {
const res = await fetch(`${urlApi}/materials/${id_material}/add`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cookies().get('access_token')?.value}`,
},
body: JSON.stringify({
id_address: id_address,
quantity: quantity,
}),
});

return { status: res.status };
}
1 change: 0 additions & 1 deletion apps/admin/app/ui/dashboard/activities/AddActivity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,6 @@ function AddActivity({ activities, setActivities, addresses, sports }: Props): J
}
if (response.status !== 201) {
const error = await response.json();
console.log(error);
throw new Error(error.message);
}
return response.json();
Expand Down
9 changes: 1 addition & 8 deletions apps/admin/app/ui/dashboard/materials/AddMaterial.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import type { Material } from '@/app/lib/type/Materials';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@repo/ui/components/ui/button';
import {
Expand All @@ -21,14 +22,6 @@ import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

interface Props {
materials: Material[];
setMaterials: React.Dispatch<React.SetStateAction<Material[]>>;
Expand Down
63 changes: 23 additions & 40 deletions apps/admin/app/ui/dashboard/materials/AddMaterialLocation.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use client';

import type { Material } from '@/app/lib/type/Materials';
import { addMaterial } from '@/app/lib/utils/Materials';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@repo/ui/components/ui/button';
import {
Expand All @@ -22,14 +24,6 @@ import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

interface Props {
materials: Material[];
id_address: number;
Expand All @@ -41,7 +35,7 @@ function AddMaterialLocation({ materials, id_address, setMaterials }: Props): JS
const router = useRouter();

const formSchema = z.object({
id_material: z.number({ message: 'Le champ est requis' }).min(1, { message: 'Le champ est requis' }),
id_material: z.coerce.number({ message: 'Le champ est requis' }).min(1, { message: 'Le champ est requis' }),
quantity: z.coerce.number().min(1, { message: 'Le champ est requis' }),
});

Expand All @@ -54,37 +48,26 @@ function AddMaterialLocation({ materials, id_address, setMaterials }: Props): JS
});

async function submit(values: z.infer<typeof formSchema>) {
const urlApi = process.env.NEXT_PUBLIC_API_URL;

fetch(`${urlApi}/materials/${values.id_material}/add`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('access_token')}`,
},
body: JSON.stringify({
id_address: id_address,
quantity: values.quantity,
}),
})
.then(async (response) => {
if (response.status === 403) {
router.push('/');
}
if (response.status !== 201) {
throw new Error(await response.text());
}
return response.json();
})
.then((data) => {
toast.success('Matériel ajouté', { duration: 2000, description: 'Le Matériel a été ajouté avec succès' });
setMaterials([...materials, data]);
setOpen(false);
form.reset();
})
.catch((error: Error) => {
toast.error('Erreur', { duration: 20000, description: error.message });
});
const { status } = await addMaterial(values.id_material, id_address, values.quantity);
if (status === 403) {
router.push('/');
}
if (status !== 201) {
toast.error('Erreur', { duration: 20000, description: 'Une erreur est survenue' });
return;
}
toast.success('Matériel ajouté', { duration: 2000, description: 'Le matériel a été ajouté avec succès' });
setMaterials((prevMaterials) =>
prevMaterials.map((material) =>
material.id === values.id_material
? {
...material,
addresses: [...material.addresses, { id_address: id_address, quantity: values.quantity }],
}
: material,
),
);
setOpen(false);
}

return (
Expand Down
47 changes: 15 additions & 32 deletions apps/admin/app/ui/dashboard/materials/AddNewMaterial.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import type { Address, Material } from '@/app/lib/type/Materials';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@repo/ui/components/ui/button';
import {
Expand All @@ -22,22 +23,6 @@ import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

type Address = {
id: number;
road: string;
number: number;
complement: string | null;
name: string | null;
};

interface Props {
materials: Material[];
addresses: Address[];
Expand All @@ -48,8 +33,6 @@ function AddNewMaterial({ materials, addresses, setMaterials }: Props): JSX.Elem
const [open, setOpen] = useState(false);
const router = useRouter();

const usedAddresses = materials?.map((material) => material.id_address);

const formSchema = z.object({
id_material: z.coerce.number({ message: 'Le champ est requis' }).min(1, { message: 'Le champ est requis' }),
id_address: z.coerce.number({ message: 'Le champ est requis' }).min(1, { message: 'Le champ est requis' }),
Expand Down Expand Up @@ -102,7 +85,7 @@ function AddNewMaterial({ materials, addresses, setMaterials }: Props): JSX.Elem
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="flex gap-2">
<Button className="flex gap-2" disabled={materials.length === 0}>
<PlusCircle />
<div>Ajouter du matériel à une adresse</div>
</Button>
Expand All @@ -128,14 +111,11 @@ function AddNewMaterial({ materials, addresses, setMaterials }: Props): JSX.Elem
</SelectTrigger>
</FormControl>
<SelectContent>
{addresses.map(
(address) =>
!usedAddresses.includes(address.id) && (
<SelectItem key={address.id} value={address.id.toString()}>
{address.name ?? `${address.number}, ${address.road}`}
</SelectItem>
),
)}
{addresses.map((address) => (
<SelectItem key={address.id} value={address.id.toString()}>
{address.name ?? `${address.number}, ${address.road}`}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
Expand All @@ -157,11 +137,14 @@ function AddNewMaterial({ materials, addresses, setMaterials }: Props): JSX.Elem
</SelectTrigger>
</FormControl>
<SelectContent>
{materials?.map((material) => (
<SelectItem key={material.id} value={material.id.toString()}>
{material.name}
</SelectItem>
))}
{materials?.map(
(material) =>
material?.id && (
<SelectItem key={material.id} value={String(material.id)}>
{material.name}
</SelectItem>
),
)}
</SelectContent>
</Select>
<FormMessage />
Expand Down
9 changes: 1 addition & 8 deletions apps/admin/app/ui/dashboard/materials/DeleteMaterial.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Material } from '@/app/lib/type/Materials';
import { Button } from '@repo/ui/components/ui/button';
import {
Dialog,
Expand All @@ -12,14 +13,6 @@ import { CircleX } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

interface Props {
material: Material;
setMaterials: React.Dispatch<React.SetStateAction<Material[]>>;
Expand Down
29 changes: 16 additions & 13 deletions apps/admin/app/ui/dashboard/materials/DeleteMaterialLocation.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Material } from '@/app/lib/type/Materials';
import { Button } from '@repo/ui/components/ui/button';
import {
Dialog,
Expand All @@ -12,33 +13,26 @@ import { CircleX } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

interface Props {
material: Material;
id_material: number;
id_address: number;
setMaterials: React.Dispatch<React.SetStateAction<Material[]>>;
}

function DeleteMaterial({ material, setMaterials }: Props): JSX.Element {
function DeleteMaterial({ id_material, id_address, setMaterials }: Props): JSX.Element {
const [open, setOpen] = useState(false);
const router = useRouter();

function deleteMaterial() {
const urlApi = process.env.NEXT_PUBLIC_API_URL;

fetch(`${urlApi}/materials/${material.id}/remove`, {
fetch(`${urlApi}/materials/${id_material}/remove`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('access_token')}`,
},
body: JSON.stringify({ id_address: material.id_address }),
body: JSON.stringify({ id_address: id_address }),
})
.then(async (response) => {
if (response.status === 403) {
Expand All @@ -51,8 +45,17 @@ function DeleteMaterial({ material, setMaterials }: Props): JSX.Element {
})
.then(() => {
toast.success('Matériel supprimé', { duration: 2000, description: 'Le Matériel a été supprimé avec succès' });
setMaterials((prevMaterials) => prevMaterials.filter((m) => m.id !== material.id));
setOpen(false);
setMaterials((prevMaterials) =>
prevMaterials.map((material) =>
material.id === id_material
? {
...material,
addresses: material.addresses.filter((address) => address.id_address !== id_address),
}
: material,
),
);
})
.catch((error: Error) => {
toast.error('Erreur', { duration: 20000, description: error.message });
Expand Down
9 changes: 1 addition & 8 deletions apps/admin/app/ui/dashboard/materials/EditMaterial.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import type { Material } from '@/app/lib/type/Materials';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@repo/ui/components/ui/button';
import {
Expand All @@ -21,14 +22,6 @@ import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

type Material = {
id_address: number;
quantity: number;
id: number;
name: string;
weight_grams: number | null;
};

interface Props {
material: Material;
materials: Material[];
Expand Down
Loading

0 comments on commit 0d1d8d8

Please sign in to comment.