Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: images activities #244

Merged
merged 7 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 78 additions & 17 deletions apps/admin/app/ui/dashboard/activities/AddActivity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { TimePicker } from '@repo/ui/components/ui/time-picker';
import { cn } from '@repo/ui/lib/utils';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import { Calendar as CalendarIcon, PlusCircle } from 'lucide-react';
import { Calendar as CalendarIcon, Paperclip, PlusCircle } from 'lucide-react';
import { useRouter } from 'next/navigation';
import type React from 'react';
import { useState } from 'react';
Expand All @@ -40,8 +40,12 @@ interface Props {
sports: Sport[];
}

const MAX_FILE_SIZE = 1024 * 1024 * 5;
const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];

function AddActivity({ activities, setActivities, addresses, sports }: Props): JSX.Element {
const [open, setOpen] = useState(false);
const [selectedImage, setSelectedImage] = useState<File | null>(null);
const router = useRouter();
const frenchDays = [
{ id: 'monday', name: 'Lundi' },
Expand Down Expand Up @@ -74,6 +78,14 @@ function AddActivity({ activities, setActivities, addresses, sports }: Props): J
end_time: z.date(),
interval: z.coerce.number({ message: 'Le champ est requis' }).int().min(1, { message: 'Le champ est requis' }),
description: z.string().optional(),
image: z
.any()
.refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
message: `L'image doit faire moins de ${MAX_FILE_SIZE / 1000000} Mo`,
})
.refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
message: "L'image doit être au format jpeg, png ou wepb",
}),
})
.refine((data) => data.min_participants <= data.max_participants, {
message: 'Le nombre minimum de participants doit être inférieur ou égal au nombre maximum de participants',
Expand Down Expand Up @@ -108,40 +120,49 @@ function AddActivity({ activities, setActivities, addresses, sports }: Props): J
start_time: undefined,
end_time: undefined,
interval: 1,
image: undefined,
},
});

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

const formData = new FormData();
formData.append('name', values.name);
if (values.description) {
formData.append('description', values.description);
}
formData.append('min_participants', values.min_participants.toString());
formData.append('max_participants', values.max_participants.toString());
formData.append('frequency', values.frequency);
formData.append('interval', values.interval.toString());
formData.append('start_date', values.start_date.toISOString().split('T')[0] || '');
formData.append('end_date', values.end_date.toISOString().split('T')[0] || '');
formData.append('start_time', values.start_time.toTimeString().split(' ')[0] || '');
formData.append('end_time', values.end_time.toTimeString().split(' ')[0] || '');
if (values.id_sport !== -1) formData.append('id_sport', String(values.id_sport) ?? null);
if (values.id_address !== -1) formData.append('id_address', String(values.id_address) ?? null);
for (const day of values.days) {
if (day) {
formData.append('days_of_week[]', day);
}
}
formData.append('image', values.image[0]);

fetch(`${urlApi}/activities`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('access_token')}`,
},
body: JSON.stringify({
name: values.name,
description: values.description,
min_participants: values.min_participants,
max_participants: values.max_participants,
days_of_week: values.days,
frequency: values.frequency,
interval: values.interval,
start_date: values.start_date.toISOString().split('T')[0],
end_date: values.end_date.toISOString().split('T')[0],
start_time: values.start_time.toTimeString().split(' ')[0],
end_time: values.end_time.toTimeString().split(' ')[0],
id_sport: values.id_sport === -1 ? null : values.id_sport ?? null,
id_address: values.id_address === -1 ? null : values.id_address ?? null,
}),
body: formData,
})
.then(async (response) => {
if (response.status === 403) {
router.push('/');
}
if (response.status !== 201) {
const error = await response.json();
console.log(error);
throw new Error(error.message);
}
return response.json();
Expand Down Expand Up @@ -228,6 +249,46 @@ function AddActivity({ activities, setActivities, addresses, sports }: Props): J
)}
/>
</div>
<div className="grid">
<FormField
control={form.control}
name="image"
render={({ field }) => (
<FormItem>
<Label className="font-bold">Image</Label>
{selectedImage && (
<div>
<img src={URL.createObjectURL(selectedImage)} alt="Selected" />
</div>
)}
<FormControl>
<div>
<Button size="lg" type="button">
<input
type="file"
className="hidden"
id="fileInput"
accept="image/*"
onBlur={field.onBlur}
name={field.name}
onChange={(e) => {
field.onChange(e.target.files);
setSelectedImage(e.target.files?.[0] || null);
}}
ref={field.ref}
/>
<label htmlFor="fileInput" className="inline-flex items-center">
<Paperclip />
<span className="whitespace-nowrap">Choisir une image</span>
</label>
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid">
<FormField
control={form.control}
Expand Down
12 changes: 11 additions & 1 deletion apps/api/src/handlers/activities.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { getOccurencesMonthly, getOccurencesWeekly, getOccurencesYearly } from '../libs/activities.js';
import { deleteFile, uploadFile } from '../libs/storage.js';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import {
Expand Down Expand Up @@ -213,7 +214,12 @@ activities.openapi(createActivity, async (c) => {
end_time,
id_sport,
id_address,
} = c.req.valid('json');
image,
} = c.req.valid('form');

if (image === null) {
return c.json({ error: 'You must provide an image' }, 400);
}

const user = c.get('user');
const roles = user.roles;
Expand Down Expand Up @@ -253,6 +259,8 @@ activities.openapi(createActivity, async (c) => {
return c.json({ error: 'Failed to create activity' }, 500);
}

await uploadFile(`activities/activity_${data.id}`, image, 'image');

return c.json(data, 201);
});

Expand Down Expand Up @@ -315,6 +323,8 @@ activities.openapi(deleteActivity, async (c) => {
return c.json({ error: 'Activity not found' }, 404);
}

await deleteFile(`activities/activity_${id}`, 'image');

return c.json({ message: 'Activity deleted' }, 200);
});

Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/routes/activities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
activityOccurencesSchema,
activitySchema,
activitySchemaReponse,
createActivitySchema,
queryActivitiesExceptionSchema,
} from '../validators/activities.js';
import { badRequestSchema, idParamValidator, notFoundSchema, serverErrorSchema } from '../validators/general.js';
Expand Down Expand Up @@ -124,8 +125,8 @@ export const createActivity = createRoute({
request: {
body: {
content: {
'application/json': {
schema: activitySchema.omit({ id: true }),
'multipart/form-data': {
schema: createActivitySchema,
},
},
},
Expand Down
18 changes: 18 additions & 0 deletions apps/api/src/validators/activities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ export const activitySchema = z.object({
id_address: z.coerce.number().nullable(),
});

export const createActivitySchema = z.object({
name: z.string().max(50),
description: z.string().max(255).optional(),
max_participants: z.coerce.number().min(1),
min_participants: z.coerce.number().min(1),
days_of_week: z
.array(z.enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']))
.optional(),
frequency: z.enum(['weekly', 'monthly', 'yearly', 'daily']),
start_date: z.string().date().optional(),
end_date: z.string().date().optional(),
start_time: z.string().time().optional(),
end_time: z.string().time().optional(),
id_sport: z.coerce.number().optional(),
id_address: z.coerce.number().optional(),
image: z.instanceof(File),
});

export const activitySchemaReponse = z.object({
id: z.coerce.number(),
name: z.string().max(50),
Expand Down
40 changes: 25 additions & 15 deletions apps/api/test/activities.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import app from '../src/index.js';
import { Role } from '../src/validators/general.js';
import { deleteAdmin, insertRole, setValidSubscription } from './utils.js';
Expand Down Expand Up @@ -105,26 +107,34 @@ describe('Activities tests', () => {
const start_date = now.toISOString().split('T')[0];
const end_date = end.toISOString().split('T')[0];

const formData = new FormData();
formData.append('name', 'Activity test');
formData.append('description', 'Description test');
formData.append('max_participants', '10');
formData.append('min_participants', '1');
const daysOfWeek = ['monday', 'tuesday'];
for (const day of daysOfWeek) {
formData.append('days_of_week[]', day);
}
formData.append('start_date', String(start_date));
formData.append('end_date', String(end_date));
formData.append('start_time', String(start_time));
formData.append('end_time', String(end_time));
formData.append('frequency', 'weekly');
formData.append('id_sport', String(id_sport));
formData.append('id_address', String(id_location));

const imagePath = path.join(__dirname, 'files', 'mock_image.png');
const imageBuffer = fs.readFileSync(imagePath);
const imageBlob = new Blob([imageBuffer], { type: 'image/png' });
formData.append('image', imageBlob, 'mock_image.png');

const res = await app.request('/activities', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify({
name: 'Activity test',
description: 'Description test',
max_participants: 10,
min_participants: 1,
days_of_week: ['monday', 'tuesday'],
start_date: start_date,
end_date: end_date,
start_time: start_time,
end_time: end_time,
frequency: 'weekly',
id_sport: id_sport,
id_address: id_location,
}),
body: formData,
});

const activity: { id: number } = await res.json();
Expand Down
Binary file added apps/api/test/files/mock_image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
40 changes: 25 additions & 15 deletions apps/api/test/tasks.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import app from '../src/index.js';
import { Role } from '../src/validators/general.js';
import { deleteAdmin, insertRole, setValidSubscription } from './utils.js';
Expand Down Expand Up @@ -101,26 +103,34 @@ describe('Activities tests', () => {
const start_time = now.toTimeString().split(' ')[0];
const end_time = end.toTimeString().split(' ')[0];

const formData = new FormData();
formData.append('name', 'Activity test');
formData.append('description', 'Description test');
formData.append('max_participants', '10');
formData.append('min_participants', '1');
const daysOfWeek = ['monday', 'tuesday'];
for (const day of daysOfWeek) {
formData.append('days_of_week[]', day);
}
formData.append('start_date', String(start_date));
formData.append('end_date', String(end_date));
formData.append('start_time', String(start_time));
formData.append('end_time', String(end_time));
formData.append('frequency', 'weekly');
formData.append('id_sport', String(id_sport));
formData.append('id_address', String(id_location));

const imagePath = path.join(__dirname, 'files', 'mock_image.png');
const imageBuffer = fs.readFileSync(imagePath);
const imageBlob = new Blob([imageBuffer], { type: 'image/png' });
formData.append('image', imageBlob, 'mock_image.png');

const res = await app.request('/activities', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify({
name: 'Activity test',
description: 'Description test',
max_participants: 10,
min_participants: 1,
days_of_week: ['monday', 'tuesday'],
start_date: start_date,
end_date: end_date,
start_time: start_time,
end_time: end_time,
frequency: 'weekly',
id_sport: id_sport,
id_address: id_location,
}),
body: formData,
});

expect(res.status).toBe(201);
Expand Down
Loading
Loading