Skip to content

Commit

Permalink
[Event] fix committee event creation (#2941)
Browse files Browse the repository at this point in the history
* [Event] fix committee event creation

* Fix tests
  • Loading branch information
ottaviano authored Mar 29, 2024
1 parent 71508b9 commit e7dd099
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 147 deletions.
60 changes: 4 additions & 56 deletions src/api/events.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,7 @@
import { newPaginatedResult } from '~/api/pagination'
import { Event, EventCategory, EventGroupCategory } from '~/domain/event'
import { Event } from '~/domain/event'
import { apiClient, apiClientPublic } from '~/services/networking/client'

const eventToJson = event => ({
name: event.name,
category: event.categoryId,
visibility: event.visibility,
description: event.description,
begin_at: event.beginAt,
finish_at: event.finishAt,
capacity: parseInt(event.capacity),
visio_url: event.visioUrl,
post_address: {
address: event.post_address.address,
postal_code: event.post_address?.postal_code,
city_name: event.post_address?.city_name,
country: event.post_address?.country,
},
time_zone: event.timezone,
live_url: event.liveUrl,
mode: event.mode,
})

export const getEvents = async ({ pageParam: page = 1, onlyMine = false }) => {
const data = await apiClient.get(
`/api/v3/events?order[beginAt]=desc&page=${page}&page_size=20${onlyMine ? '&only_mine' : ''}`
Expand Down Expand Up @@ -58,48 +38,16 @@ export const getEvent = async id => {
return Event.fromApi(event)
}

export const formatCategories = rawCategories => {
const categoriesByGroup = rawCategories.reduce((acc, category) => {
const categoriesOfCurrentGroup = acc[category.event_group_category.slug] || []
return {
...acc,
[category.event_group_category.slug]: categoriesOfCurrentGroup.concat(
new EventCategory(
category.slug,
category.name,
category.event_group_category.slug,
category.event_group_category.name,
category.event_group_category.description
)
),
}
}, {})

return Object.keys(categoriesByGroup).map(eventGroupSlug => {
const eventGroupCategory = rawCategories.find(c => c.event_group_category.slug === eventGroupSlug)
const { slug, name } = eventGroupCategory.event_group_category
return new EventGroupCategory(slug, name, categoriesByGroup[eventGroupSlug])
})
}

export const getCategoriesWithGroups = async () => {
const rawCategories = await apiClientPublic('get', '/api/event_categories')
return formatCategories(rawCategories)
}

export const getCategories = async () => {
const rawCategories = await apiClientPublic('get', '/api/event_categories')
return rawCategories
}
export const getCategories = async () => await apiClientPublic('get', '/api/event_categories')

export const deleteEvent = id => apiClient.delete(`/api/v3/events/${id}`)
export const cancelEvent = id => apiClient.put(`/api/v3/events/${id}/cancel`)
export const createEvent = async ({ event }) => {
const data = await apiClient.post('/api/v3/events', eventToJson(event))
const data = await apiClient.post('/api/v3/events', event)
return data.uuid
}
export const updateEvent = async ({ event }) => {
const data = await apiClient.put(`/api/v3/events/${event.id}`, eventToJson(event))
const data = await apiClient.put(`/api/v3/events/${event.id}`, event)
return data.uuid
}
export const uploadImage = async ({ eventId, image }) => {
Expand Down
45 changes: 0 additions & 45 deletions src/api/events.test.js

This file was deleted.

2 changes: 1 addition & 1 deletion src/components/Elections/ElectionFilters.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const ElectionFilters = ({ filterValues, handleTypeSelection, handleDetailSelect
<Grid item>
<Contact>
{messages.help}&nbsp;
<a href="mailto:techsupport@en-marche.fr">{messages.mail}</a>
<a href="mailto:techsupport@parti-renaissance.fr">{messages.mail}</a>
</Contact>
</Grid>
</Grid>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Events/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const EventRoute = () => (
<Route path={paths.create} element={<CreateOrEditEvent />} />

{/* Edit an event */}
<Route path={`${paths.update}/:eventId`} element={<CreateOrEditEvent editable={true} />} />
<Route path={`${paths.update}/:eventId`} element={<CreateOrEditEvent />} />
</Routes>
)

Expand Down
64 changes: 31 additions & 33 deletions src/components/Events/pages/createOrEdit/CreateOrEditEvent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
createEvent as createEventApi,
deleteImage as deleteImageApi,
getEvent,
updateEvent,
updateEvent as updateEventApi,
uploadImage as imageUploadApi,
} from '~/api/events'
import BlockForm from '~/components/Events/pages/createOrEdit/components/BlockForm/BlockForm'
Expand All @@ -36,7 +36,7 @@ import UploadImage from '~/components/Events/pages/createOrEdit/components/forms
import FormGroup from '~/components/Events/pages/createOrEdit/components/FormGroup/FormGroup'
import { Box } from '@mui/system'

import timezones from '~/components/Events/timezones.json'
import timezones from '~/shared/timezones.json'
import { useCustomSnackbar } from '~/components/shared/notification/hooks'
import { useErrorHandler } from '~/components/shared/error/hooks'
import { notifyVariants } from '~/components/shared/notification/constants'
Expand All @@ -45,23 +45,22 @@ import { useBlocker } from 'react-router-dom'
import ModalBeforeLeave from '../../Components/ModalBeforeLeave'
import { formatDateTimeWithTimezone } from '~/components/Events/shared/helpers'
import TextFieldPlaces from '~/components/Events/pages/createOrEdit/components/TextFieldPlaces'
import { useSelector } from 'react-redux'
import { getCurrentScope } from '~/redux/user/selectors'
import type { Scope } from '~/domain/scope'
import paths from '~/shared/paths'
import { paths as eventPaths } from '~/components/Events/shared/paths'

interface CreateOrEditEventProps {
editable: boolean
}

const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
const { editable } = props

const CreateOrEditEvent = () => {
const { eventId } = useParams()

const navigate = useNavigate()
const editable = !!eventId
const currentScope = useSelector(getCurrentScope) as Scope
const { enqueueSnackbar } = useCustomSnackbar()

const [blockerOpen, setBlockerOpen] = useState(false)

const { data } = useQueryWithScope(['event', eventId], () => getEvent(eventId), {
enabled: !!editable && !!eventId,
enabled: editable,
})

const event = data as Event
Expand Down Expand Up @@ -103,7 +102,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
cityName: event?.address?.cityName || '',
country: event?.address?.country || '',
},
liveUrl: event?.visioUrl || '',
liveUrl: event?.liveUrl || '',
},
}),
defaultValues: {
Expand All @@ -122,7 +121,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
},
})

const { mutate: mutation, isLoading } = useMutation(editable ? updateEvent : createEventApi, {
const { mutate: mutation, isLoading } = useMutation(editable ? updateEventApi : createEventApi, {
onSuccess: async uuid => {
const image = watch('image')

Expand All @@ -133,7 +132,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
notifyVariants.success
)

navigate(`/evenements/${uuid}`)
navigate(`${paths.events}/${uuid}`)
},
onError: ({
response: { data },
Expand Down Expand Up @@ -173,7 +172,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
if (
isDirty &&
isSubmitting &&
!nextLocation.pathname.startsWith(`/evenement/${editable ? 'modifier/' : 'creer'}`)
!nextLocation.pathname.startsWith(`${paths.events}/${editable ? eventPaths.update : eventPaths.create}`)
) {
setBlockerOpen(true)
return true
Expand All @@ -191,36 +190,34 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {

const convertFinishAt = new Date(finishAt ? finishAt : beginAt)

const committee =
Array.isArray(currentScope.getCommittees()) && currentScope.getCommittees().length
? currentScope.getCommittees()[0].uuid
: null

const data = {
id: event?.id,
name: getValues('name'),
categoryId: getValues('categoryId'),
category: getValues('categoryId'),
visibility: getValues('visibility'),
beginAt: formatDateTimeWithTimezone(beginAt, timeBeginAt),
finishAt: formatDateTimeWithTimezone(watch('severalDays') ? convertFinishAt : beginAt, timeFinishAt),
timezone: getValues('timezone'),
begin_at: formatDateTimeWithTimezone(beginAt, timeBeginAt),
finish_at: formatDateTimeWithTimezone(watch('severalDays') ? convertFinishAt : beginAt, timeFinishAt),
time_zone: getValues('timezone'),
description: getValues('description'),
visioUrl: getValues('visioUrl'),
visio_url: getValues('visioUrl'),
live_url: getValues('liveUrl'),
mode: watch('isVirtual') ? 'online' : null,
capacity: getValues('capacity'),
mode: watch('isVirtual') ? 'online' : 'meeting',
capacity: parseInt(getValues('capacity') as string),
post_address: {
address: getValues('address.address') || null,
postal_code: getValues('address.postalCode') || null,
city_name: getValues('address.cityName') || null,
country: getValues('address.country') || null,
},
...(committee ? { type: 'committee', committee } : {}),
}

if (editable) {
mutation({
event: data,
})
} else {
mutation({
event: data,
})
}
mutation({ event: data })
}

return (
Expand All @@ -230,7 +227,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
</Grid>

<Breadcrumbs separator=">" aria-label="breadcrumb">
<Link underline="hover" color="black" href="/evenements">
<Link underline="hover" color="black" href={paths.events}>
{messages.title}
</Link>

Expand Down Expand Up @@ -377,6 +374,7 @@ const CreateOrEditEvent = (props: CreateOrEditEventProps) => {
onChange={(_, value) => {
setValue('timezone', timezones.find(option => option.value === value)?.key || 'Europe/Paris')
}}
defaultValue={timezones.find(option => option.key === 'Europe/Paris')?.value}
options={timezones.map(option => option.value)}
sx={{ width: '100%' }}
renderInput={params => (
Expand Down
9 changes: 2 additions & 7 deletions src/components/Events/pages/list/ListEvents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, ButtonGroup, Container, Grid, Stack } from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { getCategoriesWithGroups, getEvents, getMyEvents } from '~/api/events'
import { getEvents, getMyEvents } from '~/api/events'
import PageHeader from '~/ui/PageHeader'
import { messages, ONE_DAY } from '~/components/Events/shared/constants'
import { messages } from '~/components/Events/shared/constants'
import { paths as eventsPath } from '~/components/Events/shared/paths'
import TabsComponent, { TabProps } from '~/components/Events/Components/Tabs'
import { TabPanel } from '~/components/Events/Components'
Expand All @@ -16,11 +16,6 @@ const ListEvents = () => {

const [selectedTab, setSelectedTab] = useState<number>(0)

useQuery(['categories', { feature: 'Events', view: 'Events' }], () => getCategoriesWithGroups(), {
cacheTime: ONE_DAY,
staleTime: ONE_DAY,
})

const { data: countOnlyMine, isLoading: isLoadingCountOnlyMine } = useQuery(
['countOnlyMine', { feature: 'Events', view: 'Events' }],
() => getMyEvents({ countOnlyMine: true })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Event } from '~/domain/event'
import type { Event as EventType } from '~/components/Events/shared/types'
import { useMutation } from '@tanstack/react-query'
import { notifyVariants } from '~/components/shared/notification/constants'
import { deleteEvent as deleteEventQuery } from '~/api/events'
import { deleteEvent as deleteEventQuery, cancelEvent as cancelEventQuery } from '~/api/events'
import { useCustomSnackbar } from '~/components/shared/notification/hooks'
import { useErrorHandler } from '~/components/shared/error/hooks'

Expand Down Expand Up @@ -50,7 +50,7 @@ const CardEvent = ({ event, refetchEvents }: CardEventProps) => {
onError: handleError,
})

const { mutate: cancelEvent } = useMutation(deleteEventQuery, {
const { mutate: cancelEvent } = useMutation(cancelEventQuery, {
onSuccess: () => {
enqueueSnackbar("L'événement a été annulé avec succès", notifyVariants.success)

Expand Down
2 changes: 0 additions & 2 deletions src/components/Events/shared/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const ONE_DAY = 24 * 60 * 60 * 1000

export const messages = {
title: 'Événements',
update: 'Modifier un événement',
Expand Down
6 changes: 6 additions & 0 deletions src/domain/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import PropTypes from 'prop-types'
import { parseDate } from '~/shared/helpers'
import { z } from 'zod'
import { Place } from '~/domain/place'

export class Attendee {
static propTypes = {
firstName: PropTypes.string.isRequired,
Expand Down Expand Up @@ -81,6 +82,7 @@ export class Event {
}),
isPrivate: PropTypes.bool.isRequired,
visioUrl: PropTypes.string,
liveUrl: PropTypes.string,
mode: PropTypes.string,
image: PropTypes.string,
}
Expand Down Expand Up @@ -110,6 +112,7 @@ export class Event {
e.category ? e.category : null,
e.private,
e.visio_url,
e.live_url,
e.mode,
e.image_url
)
Expand All @@ -134,6 +137,7 @@ export class Event {
this.category,
this.isPrivate,
this.visioUrl,
this.liveUrl,
this.mode,
this.image
)
Expand All @@ -158,6 +162,7 @@ export class Event {
this.category,
newPrivate,
this.visioUrl,
this.liveUrl,
this.mode,
this.image
)
Expand Down Expand Up @@ -195,6 +200,7 @@ export class Event {
},
public isPrivate: boolean,
public visioUrl: string,
public liveUrl: string,
public mode: string,
public image: string
) {}
Expand Down
File renamed without changes.

0 comments on commit e7dd099

Please sign in to comment.