Newer
Older
import {
Button,
FormControl,
FormControlLabel,
FormGroup,
NativeSelect,
Switch,
TextField,
} from '@mui/material'
import React, { useCallback, useEffect, useState } from 'react'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import { useWhoAmI } from '../../API'
import { getAxiosXSRFHeader } from '../../axios.config'
import { CheckboxType } from '../../enum/checkboxType.enum'
import { ICustomPopup, PopupDuration } from '../../models/customPopup.model'
import { IPartnersInfo } from '../../models/partnersInfo.model'
import { CustomPopupService } from '../../services/customPopup.service'
import { PartnersInfoService } from '../../services/partnersInfo.service'
import { convertStringToEditorState } from '../../utils/editorStateManagement'
import CustomEditor from '../Newsletter/CustomEditor'
const OPTIONS: Option[] = [
{
value: durationEnum.hours,
label: 'Heures',
},
{
value: durationEnum.days,
label: 'Jours',
},
{
value: durationEnum.infinite,
label: 'Indéterminée',
},
]
const { data: user } = useWhoAmI()
const [refreshData, setRefreshData] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [partnersInfo, setPartnersInfo] = useState<IPartnersInfo>({
grdf_failure: false,
enedis_failure: false,
egl_failure: false,
notification_activated: false,
})
const [previousEndDate, setPreviousEndDate] = useState<string>()
const [customPopup, setCustomPopup] = useState<ICustomPopup>({
popupEnabled: false,
title: '',
description: '',
endDate: DateTime.local().toISO(),
})
const [popupDuration, setPopupDuration] = useState<PopupDuration>({
const isPartnerNotificationOn = () =>
partnersInfo.enedis_failure ||
partnersInfo.egl_failure ||
partnersInfo.grdf_failure
/** Only one type of popup can be enabled */
const isPageValid = () =>
!(isPartnerNotificationOn() && customPopup.popupEnabled)
const handleCheckboxChange = (value: boolean, type: CheckboxType): void => {
switch (type) {
case CheckboxType.GRDF:
...prevPartnersInfo,
grdf_failure: value,
}))
break
case CheckboxType.ENEDIS:
...prevPartnersInfo,
enedis_failure: value,
}))
break
case CheckboxType.EGL:
...prevPartnersInfo,
egl_failure: value,
}))
break
case CheckboxType.CUSTOM:
...prev,
popupEnabled: value,
}))
break
default:
throw new Error('Unknown checkbox type')
}
}
const handlePopupChange = (field: 'title' | 'description', value: string) => {
const handleCancel = useCallback(() => {
setRefreshData(true)
}, [setRefreshData])
const resetFields = useCallback(() => {
setPartnersInfo({
grdf_failure: false,
enedis_failure: false,
egl_failure: false,
notification_activated: false,
})
}, [setPartnersInfo])
useEffect(() => {
let subscribed = true
resetFields()
setIsLoading(true)
if (user) {
const partnersInfoService = new PartnersInfoService()
const customPopupService = new CustomPopupService()
const partnersInfoData = await partnersInfoService.getPartnersInfo()
const customPopupData = await customPopupService.getCustomPopupInfo()
if (partnersInfoData) {
setPartnersInfo({
...partnersInfoData,
})
}
if (customPopupData) {
setCustomPopup({
...customPopupData,
})
setPreviousEndDate(customPopupData.endDate || undefined)
}
}
setIsLoading(false)
}
if (subscribed) {
}
return () => {
subscribed = false
setRefreshData(false)
}
}, [user, refreshData, setPartnersInfo, setCustomPopup, resetFields])
const handleSave = async (): Promise<void> => {
if (user) {
const partnersInfoService = new PartnersInfoService()
const customPopupService = new CustomPopupService()
const updatedPartnersInfo = {
egl_failure: partnersInfo.egl_failure,
enedis_failure: partnersInfo.enedis_failure,
grdf_failure: partnersInfo.grdf_failure,
notification_activated: isPartnerNotificationOn(),
}
await partnersInfoService.savePartnersInfo(
updatedPartnersInfo,
getAxiosXSRFHeader(user.xsrftoken)
)
await customPopupService.saveCustomPopup(
customPopup,
getAxiosXSRFHeader(user.xsrftoken)
)
const handleSelectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
...prev,
type: event.target.value as durationType,
}))
}
/**
* Handles duration change
*/
useEffect(() => {
const now = DateTime.local()
let newDate: DateTime
if (popupDuration.type !== durationEnum.infinite) {
newDate = now.plus({
[popupDuration.type]: popupDuration.duration,
})
} else if (popupDuration.type === 'infinite') {
newDate = now.plus({
years: 1,
})
}
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
...prev,
endDate: newDate.toISO(),
}))
}, [popupDuration])
const isPopupOutdated = (date: string) =>
DateTime.local() >= DateTime.fromISO(date)
/**
* Returns "Popup expirée" OR "Temps restant : ..."
*/
const getRemainingDuration = (date: string) => {
if (isPopupOutdated(date)) {
return <p className="endDate">Popup expirée</p>
}
return (
<p className="endDate">
Temps d'activation restant :<br />
{DateTime.fromISO(date)
.diffNow(['days', 'hours', 'minutes', 'seconds'])
.set({ second: 0 })
.toHuman()}
</p>
)
}
<h1>Création de Pop-up</h1>
{isLoading && <Loader />}
{!isLoading && (
<>
<div className="partnersInfo">
<h3>Affichage des pop-up de panne</h3>
<div>
<FormGroup style={{ flexDirection: 'row' }}>
<FormControlLabel
label="Panne Enedis"
labelPlacement="top"
control={
<Switch
disabled={customPopup.popupEnabled}
checked={partnersInfo.enedis_failure}
onChange={event => {
handleCheckboxChange(
event.target.checked,
CheckboxType.ENEDIS
)
}}
/>
}
<FormControlLabel
label="Panne EGL"
labelPlacement="top"
control={
<Switch
disabled={customPopup.popupEnabled}
checked={partnersInfo.egl_failure}
onChange={event => {
handleCheckboxChange(
event.target.checked,
CheckboxType.EGL
)
}}
/>
}
<FormControlLabel
label="Panne GRDF"
labelPlacement="top"
control={
<Switch
disabled={customPopup.popupEnabled}
checked={partnersInfo.grdf_failure}
onChange={event => {
handleCheckboxChange(
event.target.checked,
CheckboxType.GRDF
)
}}
/>
}
</div>
<div className="customPopup">
<h3>Affichage de pop-up personnalisée</h3>
<FormGroup style={{ flexDirection: 'row' }}>
<FormControlLabel
label="Pop-up active"
labelPlacement="top"
control={
<Switch
disabled={isPartnerNotificationOn()}
checked={customPopup.popupEnabled}
}
/>
{customPopup.popupEnabled &&
previousEndDate &&
getRemainingDuration(previousEndDate)}
</FormGroup>
<div className="popupTitle">
<TextField
type="text"
placeholder="Titre de la popup"
fullWidth
label="Titre"
value={customPopup.title}
onChange={event =>
handlePopupChange('title', event.target.value)
}
/>
</div>
<div className="popupDescription">
<CustomEditor
baseState={convertStringToEditorState(
customPopup.description
)}
handleChange={value =>
handlePopupChange('description', value)
}
type="custom_popup"
/>
</div>
<div className="popupEndDate">
<label htmlFor="title">Nouvelle Durée</label>
<div>
<FormControl style={{ flexDirection: 'row', gap: '1rem' }}>
<NativeSelect
inputProps={{
name: 'age',
id: 'uncontrolled-native',
}}
<option key={option.value} value={option.value}>
{popupDuration.type !== 'infinite' && (
<TextField
inputProps={{
inputMode: 'numeric',
pattern: '[0-9]*',
}}
id="outlined-number"
InputLabelProps={{
shrink: true,
}}
...prev,
duration: Number(e.target.value),
}))
}
/>
)}
<Button variant="outlined" onClick={handleCancel}>
</Button>
<Button disabled={!isPageValid()} onClick={handleSave}>
</div>
</>
)}
</div>
</>
)
}