first commit

This commit is contained in:
Romulus21
2024-02-10 14:59:46 +01:00
commit 5bb0b25673
193 changed files with 28660 additions and 0 deletions

18
resources/css/app.css Normal file
View File

@@ -0,0 +1,18 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
.btn {
@apply text-center text-white px-2 py-1 focus:outline-1 border border-white transition duration-300 ease-in-out shadow hover:shadow-lg rounded cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-primary {
@apply btn bg-blue-700 border-blue-700 hover:bg-blue-800 focus:bg-blue-800;
}
.form-control .error-message,
.form-control.invalid-control input,
.form-control.invalid-control select,
.form-control.invalid-control textarea {
@apply text-red-600 border-red-600;
}

12
resources/js/app.tsx Normal file
View File

@@ -0,0 +1,12 @@
import React from 'react';
import './bootstrap';
import {createRoot} from "react-dom/client";
import App from "./pages/App";
import '../css/app.css'
import './utilities/customProperties.ts'
const container = document.getElementById('app')
if (container) {
const root = createRoot(container)
root.render(<App />)
}

32
resources/js/bootstrap.js vendored Normal file
View File

@@ -0,0 +1,32 @@
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
// window.Pusher = Pusher;
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
// wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
// wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
// wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
// forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
// });

View File

@@ -0,0 +1,15 @@
import React, {FC} from "react";
import {PropsWithChildren} from "react";
const Card: FC<PropsWithChildren<CardProps>> = ({children, className = ''}) => {
return <div className={`${className} border m-1 rounded py-1 px-2`}>
{children}
</div>
}
export default Card
interface CardProps {
className?: string
}

View File

@@ -0,0 +1,34 @@
import React, {
FC, HTMLInputTypeAttribute,
ReactElement
} from "react"
const Field: FC<FieldProps> = ({children, type = 'text', className = '', classNameForm = '', ...props}) => {
return <div className={`form-control ${classNameForm}`}>
{children && <label className="block text-gray-900 dark:text-gray-200"
htmlFor={props.id ?? undefined}>
{children}
</label>}
<input className={`${className} w-full mt-2 rounded dark:bg-gray-700`}
type={type}
{...props}/>
<div className={`error-message`} />
</div>
}
export default Field
interface FieldProps {
children?: ReactElement|string,
type?: HTMLInputTypeAttribute,
name: string,
id?: string,
value: any,
placeholder?: string,
autoFocus?: boolean,
className?: string,
classNameForm?: string,
step?: string,
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void,
}

View File

@@ -0,0 +1,30 @@
import React from "react"
import {Link, useLocation} from "react-router-dom"
import useAuthUser from "../hooks/AuthUser";
import Tracker from "./Tracker";
const Header = () => {
const {authUser} = useAuthUser()
const location = useLocation()
console.log(authUser)
return <header className="flex justify-between py-3 px-5 bg-blue-700 text-white text-xl">
<div>
<Link to="/">Ticcat</Link>
</div>
{authUser && <Tracker />}
{authUser
? <span className="flex gap-2">
<Link to="/profile" className={location.pathname === '/profile' ? 'font-bold' : ''}>{authUser.name}</Link>
</span>
: <span className="flex gap-2">
<Link to="/connexion">Connexion</Link>
{/*<Link to="/sinscrire">S'inscrire</Link>*/}
</span>}
</header>
}
export default Header

View File

@@ -0,0 +1,10 @@
import React, {PropsWithChildren} from "react"
const PageLayout = ({children}: PropsWithChildren) => {
return <div className="m-2">
{children}
</div>
}
export default PageLayout

View File

@@ -0,0 +1,43 @@
import React, {useEffect, useState} from "react"
import useTracker from "../hooks/TraskerHook"
import {Link} from "react-router-dom";
const Tracker = () => {
const [timer, setTimer] = useState('')
const {currentTimeTracker, stopCurrentTimeTrack} = useTracker()
useEffect(() => {
setTimer(formatTimer(currentTimeTracker?.start_at))
}, [currentTimeTracker])
useEffect(() => {
setTimeout(() => setTimer(formatTimer(currentTimeTracker?.start_at)), 1000)
}, [timer]);
const formatTimer = (startAt: string|null|undefined) => {
if (!startAt) {
return '--:--'
}
let timer = Math.floor(((new Date()).getTime() - (new Date(startAt)).getTime()) / 1000)
let hours = Math.floor(timer / 3600)
let minutes = Math.floor((timer - hours * 3600) / 60)
let secondes = timer - hours * 3600 - minutes * 60
return `${hours}:${String(minutes).padStart(2, '0')}:${String(secondes).padStart(2, '0')}`
}
return <div>
{currentTimeTracker
? <div className="flex gap-2">
<Link to={`/todos/${currentTimeTracker.to_do.id}`}>
{currentTimeTracker.to_do.name}
</Link>
<span>{timer}</span>
<button onClick={stopCurrentTimeTrack}>Stop</button>
</div>
: <div>--:--</div>
}
</div>
}
export default Tracker

View File

@@ -0,0 +1,74 @@
import React, {FC, useEffect, useState} from "react";
import useAxiosTools from "../../hooks/AxiosTools";
import {toDo} from "../../utilities/types";
import {Link} from "react-router-dom";
import useTracker from "../../hooks/TraskerHook";
import {Simulate} from "react-dom/test-utils";
import load = Simulate.load;
const ToDoIndex: FC<ToDoIndexProps> = ({reload}) => {
const {loading, setLoading, errorCatch, errorLabel, axiosGet, axiosPut} = useAxiosTools(true)
const [toDos, setToDos] = useState<toDo[]>([])
const {startTrackToDo} = useTracker()
useEffect(() => {
fetchToDos()
}, [])
useEffect(() => {
if (reload && !loading) {
fetchToDos()
}
}, [reload]);
const fetchToDos = async () => {
try {
const res = await axiosGet('api/todos')
setToDos(res.data)
} catch (error) {
errorCatch(error)
} finally {
setLoading(false)
}
}
const toggleCheck = async (toDo: toDo) => {
console.log(toDo)
try {
await axiosPut('api/todos/' + toDo.id, {checked: ! toDo.checked})
await fetchToDos()
} catch (error) {
errorCatch(error)
} finally {
setLoading(false)
}
}
return <>
{errorLabel()}
<ul className="my-5">
{toDos.map(toDo => <li key={toDo.id} className="flex gap-2">
<span>Move</span>
<input type={"checkbox"}
checked={toDo.checked}
onChange={() =>toggleCheck(toDo)}
className=""/>
<Link to={"/todos/" + toDo.id}
className={`${toDo.checked ? 'line-through' : ''} flex-1`}>
{toDo.name}
</Link>
{!toDo.checked && <span className="cursor-pointer"
onClick={() => startTrackToDo(toDo)}>
Play
</span>}
</li>)}
</ul>
</>
}
export default ToDoIndex
interface ToDoIndexProps {
reload: Date|null,
}

View File

@@ -0,0 +1,100 @@
import React, {FC, HTMLInputTypeAttribute, ReactElement, useEffect, useState} from "react"
import {useParams} from "react-router-dom";
import useAxiosTools from "../../hooks/AxiosTools";
import {timeTracker, toDo} from "../../utilities/types";
const ToDoShow = () => {
const {id} = useParams()
console.log(id)
const {setLoading, errorCatch, errorLabel, axiosGet, axiosPut} = useAxiosTools(true)
const [toDo, setToDo] = useState<toDo|null>(null)
useEffect(() => {
fetchToDo()
}, [])
const fetchToDo = async () => {
try {
const res = await axiosGet('/api/todos/' + id)
setToDo(res.data)
} catch (error) {
errorCatch(error)
} finally {
setLoading(false)
}
}
return <div>
<h1>{toDo?.name}</h1>
<h1>{toDo?.description}</h1>
{toDo && <ToDoTimeTrackers toDo={toDo} />}
</div>
}
export default ToDoShow
const ToDoTimeTrackers: FC<ToDoTimeTrackers> = ({toDo: toDo}) => {
const {setLoading, errorCatch, errorLabel, axiosGet, axiosPut} = useAxiosTools(true)
const [timeTrackers, setTimeTrackers] = useState<timeTracker[]>([])
useEffect(() => {
fetchTimeTrackers()
}, [])
const fetchTimeTrackers = async () => {
try {
const res = await axiosGet(`/api/todos/${toDo.id}/time-trackers`)
setTimeTrackers(res.data)
} catch (error) {
errorCatch(error)
} finally {
setLoading(false)
}
}
const timeSpend = () => {
let timer = 0
let more = false
timeTrackers.forEach(timeTracker => {
if (! timeTracker.end_at) {
more = true
} else {
timer += ((new Date(timeTracker.end_at)).getTime()) - (new Date(timeTracker.start_at)).getTime()
}
})
timer = Math.floor(timer / 1000)
let hours = Math.floor(timer / 3600)
let minutes = Math.floor((timer - hours * 3600) / 60)
let secondes = timer - hours * 3600 - minutes * 60
return `${more ? '+' : ''} ${hours}:${String(minutes).padStart(2, '0')}:${String(secondes).padStart(2, '0')}`
}
return <div>
<div>Temps passé : {timeSpend()}</div>
<table className="mx-auto">
<thead>
<tr>
<th>Début</th>
<th>Fin</th>
<th>Différence</th>
</tr>
</thead>
<tbody>
{timeTrackers.map(timeTracker => <tr key={timeTracker.id} className="text-center">
<td>{timeTracker.start_at ? (new Date(timeTracker.start_at)).toSmallFrDate() : ''}</td>
<td>{timeTracker.end_at ? (new Date(timeTracker.end_at)).toSmallFrDate() : ''}</td>
<td className="text-right">{timeTracker.start_at && timeTracker.end_at ? (new Date(timeTracker.end_at)).difference(new Date(timeTracker.start_at)) : ''}</td>
</tr>)}
</tbody>
</table>
</div>
}
interface ToDoTimeTrackers {
toDo: toDo,
}

View File

@@ -0,0 +1,41 @@
import React, {FC, FormEvent, useState} from "react"
import Field from "../Field";
import useAxiosTools from "../../hooks/AxiosTools";
const ToDoStore: FC<ToDoStoreProps> = ({setReload}) => {
const [toDo, setToDo] = useState('')
const {errorCatch, errorLabel, axiosPost} = useAxiosTools()
const onSubmit = async (event: FormEvent) => {
event.preventDefault()
try {
await axiosPost('api/todos', {name: toDo})
setToDo('')
setReload(new Date())
} catch (error) {
errorCatch(error)
}
}
return <>
{errorLabel()}
<form className="flex" onSubmit={onSubmit}>
<Field name="todo"
value={toDo}
classNameForm="flex-1"
className="h-10 !mt-0 rounded-r-none px-2"
onChange={event => setToDo(event.target.value)} />
<button type="submit"
className="bg-blue-900 h-10 rounded-r px-5">
Ajouter
</button>
</form>
</>
}
export default ToDoStore
interface ToDoStoreProps {
setReload: (date: Date) => void,
}

View File

@@ -0,0 +1,77 @@
import React, {
createContext,
Dispatch,
PropsWithChildren,
SetStateAction,
useContext,
useEffect,
useState
} from "react";
import axios from "axios";
const AuthUserContext = createContext<AuthUserProps|undefined>(undefined)
interface AuthUserProps {
authUser?: User|null,
setAuthUser: Dispatch<SetStateAction<User | null>>,
loadingAuthUser: boolean,
logout: () => void,
}
export const AuthUserProvider = ({children}: PropsWithChildren) => {
const [authUser, setAuthUser] = useState<User|null>(null)
const [loadingAuthUser, setLoadingAuthUser] = useState(true)
useEffect(() => {
(async () => {
try {
const res = await axios.get('/api/user')
setAuthUser(res.data)
} catch (e) {
// @ts-ignore
if (e.response.status === 401) {
console.info('no user login')
if (!['/connexion', '/inscription'].includes(window.location.pathname)) {
window.location.href = '/connexion'
}
}
} finally {
setLoadingAuthUser(false)
}
})()
}, [])
const logout = async () => {
try {
setLoadingAuthUser(false)
const res = await axios.delete('/api/logout')
setAuthUser(null)
window.location.replace('/')
} catch (e) {
console.error(e)
} finally {
setLoadingAuthUser(false)
}
}
return <AuthUserContext.Provider value={{authUser, setAuthUser, loadingAuthUser, logout}}>
{children}
</AuthUserContext.Provider>
}
const useAuthUser = () => {
const context = useContext(AuthUserContext)
if (context === undefined) {
throw new Error('Add AuthUserProvider to use AuthUserContext')
}
return context
}
export default useAuthUser
interface User {
id: number,
name: string,
email: string,
locations: {id: number, latitude: number, longitude: number}[],
}

View File

@@ -0,0 +1,37 @@
import {useState} from "react";
import axios from "axios";
import React from "react";
import {cleanErrorsForm, displayFormErrors} from "../utilities/form";
const useAxiosTools = (isLoading = false) => {
const [loading, setLoading] = useState(isLoading)
const [error, setError] = useState<string|null>(null)
const axiosGet = axios.get
const axiosPost = axios.post
const axiosPut = axios.put
const axiosDelete = axios.delete
const errorCatch = (error: any) => {
if (error.response && error.response.status === 422) {
displayFormErrors(error)
} else {
setError(error.response?.data.message || error.message)
}
}
const errorLabel = () => {
return error ? <div className="bg-red-600 rounded m-2 text-center text-white px-2 py-1 mx-auto">{error}</div>: null
}
const cleanErrors = () => {
cleanErrorsForm()
setError(null)
}
return {loading, setLoading, error, setError, errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost, axiosPut, axiosDelete}
}
export default useAxiosTools

View File

@@ -0,0 +1,66 @@
import React, {createContext, PropsWithChildren, useContext, useEffect, useState} from "react";
import {timeTracker, toDo} from "../utilities/types";
import useAxiosTools from "./AxiosTools";
const TrackerContext = createContext<TrackerProps|undefined>(undefined)
interface TrackerProps {
currentTimeTracker: timeTracker|null,
startTrackToDo: (toDo: toDo) => void,
stopCurrentTimeTrack: () => void,
isToDoTracked: (toDo: toDo) => boolean,
}
export const TrackerProvider = ({children}: PropsWithChildren) => {
const [currentTimeTracker, setCurrentTimeTracker] = useState(null)
const [toDoTracked, setToDoTracked] = useState<toDo|null>(null)
const {axiosGet, axiosPost, axiosDelete} = useAxiosTools()
useEffect(() => {
fetchCurrentTimeTracker()
}, [])
const fetchCurrentTimeTracker = async () => {
try {
const res = await axiosGet(`/api/time-tracker/user`)
setCurrentTimeTracker(res.data)
} catch (error) {
console.error(error)
}
}
const startTrackToDo = async (toDo: toDo) => {
try {
const res = await axiosPost('/api/time-tracker', {todo_id: toDo.id})
setCurrentTimeTracker(res.data)
} catch (error) {
console.error(error)
}
}
const stopCurrentTimeTrack = async () => {
try {
const res = await axiosDelete(`/api/time-tracker/user`)
setCurrentTimeTracker(null)
} catch (error) {
console.error(error)
}
}
const isToDoTracked = (toDo: toDo) => toDo.id === toDoTracked?.id
return <TrackerContext.Provider value={{currentTimeTracker, startTrackToDo, stopCurrentTimeTrack, isToDoTracked}}>
{children}
</TrackerContext.Provider>
}
const useTracker = () => {
const context = useContext(TrackerContext)
if (context === undefined) {
throw new Error('Add TrackerProvider to use AuthUserContext')
}
return context
}
export default useTracker

View File

@@ -0,0 +1,17 @@
import React from "react"
import Router from "./Router"
import {AuthUserProvider} from "../hooks/AuthUser";
import {TrackerProvider} from "../hooks/TraskerHook";
const App = () => {
return <main className="h-screen overflow-auto dark:bg-gray-900 dark:text-white">
<AuthUserProvider>
<TrackerProvider>
<Router />
</TrackerProvider>
</AuthUserProvider>
</main>
}
export default App

View File

@@ -0,0 +1,45 @@
import React, {FormEvent, SyntheticEvent, useState} from "react"
import Field from "../../components/Field";
import axios from "axios";
import {useNavigate} from "react-router-dom";
import useAuthUser from "../../hooks/AuthUser";
import useAxiosTools from "../../hooks/AxiosTools";
const ForgotPassword = () => {
const [email, setEmail] = useState('')
const [message, setMessage] = useState(false)
const {errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost} = useAxiosTools()
const handleSubmit = async (event: FormEvent) => {
event.preventDefault()
try {
cleanErrors()
await axiosGet('/sanctum/csrf-cookie')
const res = await axiosPost('/api/forgot', {email})
setMessage(true)
} catch (e) {
errorCatch(e)
}
}
return <div>
<form onSubmit={handleSubmit} className="w-96 mx-auto mt-10 border shadow p-3">
<h1 className="text-center">Mot de passe oublié</h1>
{message && <p className="bg-green-600">Un email vous a é envoyé pour modifier le mot de passe.</p>}
{errorLabel()}
<Field type="email"
name="email"
placeholder="Email"
value={email}
onChange={event => setEmail(event.target.value)}
autoFocus>Email</Field>
<button type="submit" className="mt-5 btn-primary w-full block text-lg">Valider</button>
</form>
</div>
}
export default ForgotPassword

View File

@@ -0,0 +1,56 @@
import React, {FormEvent, SyntheticEvent, useState} from "react"
import axios from "axios";
import {Link, useNavigate} from "react-router-dom";
import useAxiosTools from "../../hooks/AxiosTools";
import Field from "../../components/Field";
import useAuthUser from "../../hooks/AuthUser";
import Card from "../../components/Card";
const Login = () => {
const navigate = useNavigate()
const {setAuthUser} = useAuthUser()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const {errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost} = useAxiosTools()
const handleSubmit = async (event: FormEvent) => {
event.preventDefault()
try {
cleanErrors()
await axiosGet('/sanctum/csrf-cookie')
const res = await axiosPost('/api/login', {email, password})
setAuthUser(res.data)
navigate('/')
} catch (e) {
errorCatch(e)
}
}
return <div>
<Card className="w-96 mx-auto mt-10 p-2 overflow-hidden">
<form onSubmit={handleSubmit}>
<h1 className="text-center bg-blue-500 -mx-2 -mt-1 text-lg font-bold px-2 py-1 mb-2">
Connexion
</h1>
{errorLabel()}
<Field type="email"
name="email"
placeholder="Email"
value={email}
onChange={event => setEmail(event.target.value)}
autoFocus>Email</Field>
<Field type="password"
name="password"
placeholder="******"
value={password}
onChange={event => setPassword(event.target.value)}>Mot de passe</Field>
<button type="submit" className="mt-5 btn-primary w-full block text-lg">Valider</button>
<Link to="/mot-de-passe-oubliee" className="mt-2 inline-block">Mot de passe oublié ?</Link>
</form>
</Card>
</div>
}
export default Login

View File

@@ -0,0 +1,77 @@
import React, {FormEvent, useState} from "react"
import useAuthUser from "../../hooks/AuthUser"
import Field from "../../components/Field";
import useAxiosTools from "../../hooks/AxiosTools";
import PageLayout from "../../components/PageLayout";
import Card from "../../components/Card";
const Profile = () => {
const {authUser, setAuthUser, logout} = useAuthUser()
const [latitude, setLatitude] = useState(0)
const [longitude, setLongitude] = useState(0)
const {errorCatch, axiosPost} = useAxiosTools()
const submitLocation = async (event: FormEvent) => {
event.preventDefault()
try {
const res = await axiosPost(`/api/locations`, {latitude, longitude})
setAuthUser(res.data)
} catch (e) {
errorCatch(e)
}
}
return <PageLayout>
<div className="m-1 my-5 flex justify-between">
<h1 className="text-lg font-bold">Profile de l&apos;utilisateur</h1>
<div>
<button type="button" onClick={logout} className="btn-primary text-lg font-bold">Se déconnecter</button>
</div>
</div>
<Card className="mb-5">
<div>Nom : <strong>{authUser?.name}</strong></div>
<div>Email : <strong>{authUser?.email}</strong></div>
</Card>
{/*<div>Update name & email</div>*/}
{/*<div>Change password</div>*/}
{/*<div>Delete Account</div>*/}
<Card>
<h2>Météo</h2>
{authUser?.locations && authUser.locations.length > 0 ? <>
<h3>Emplacements</h3>
<ul>
{authUser?.locations.map(location => <li key={location.id}>{location.latitude} - {location.longitude}</li>)}
</ul>
</> : <form onSubmit={submitLocation}>
<h3>Ajouter un emplacement</h3>
<div className="flex gap-2">
<Field name="latitude"
type="number"
step="0.0001"
value={latitude}
className="h-10"
onChange={event => setLatitude(Number(event.target.value))}>
Latitude
</Field>
<Field name="longitude"
type="number"
step="0.0001"
value={longitude}
className="h-10"
onChange={event => setLongitude(Number(event.target.value))}>
Longitude
</Field>
<div className="self-end">
<button type="submit" className="btn-primary w-24 h-10">Valider</button>
</div>
</div>
</form>}
</Card>
</PageLayout>
}
export default Profile

View File

@@ -0,0 +1,58 @@
import React, {ChangeEvent, FormEvent, SyntheticEvent, useState} from "react"
import Field from "../../components/Field";
import axios from "axios";
import {useNavigate} from "react-router-dom";
import Card from "../../components/Card";
import useAuthUser from "../../hooks/AuthUser";
const Register = () => {
const navigate = useNavigate()
const {setAuthUser} = useAuthUser()
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const handleSubmit = async (event: FormEvent) => {
event.preventDefault()
try {
await axios.get('/sanctum/csrf-cookie')
const res = await axios.post('/api/register', {name, email, password})
setAuthUser(res.data)
navigate('/')
} catch (e) {
console.error(e)
}
}
return <div>
<Card className="w-96 mx-auto mt-10 p-2 overflow-hidden">
<form onSubmit={handleSubmit}>
<h1 className="text-center bg-blue-500 -mx-2 -mt-1 text-lg font-bold px-2 py-1 mb-2">
S'inscrire
</h1>
<Field placeholder="Nom"
name="name"
value={name}
onChange={event => setName(event.target.value)}
autoFocus>Nom</Field>
<Field type="email"
name="email"
placeholder="Email"
value={email}
onChange={event => setEmail(event.target.value)}
autoFocus>Email</Field>
<Field type="password"
name="password"
placeholder="******"
value={password}
onChange={event => setPassword(event.target.value)}
autoFocus>Mot de passe</Field>
<button type="submit" className="mt-5 btn-primary w-full block text-lg">Valider</button>
</form>
</Card>
</div>
}
export default Register

View File

@@ -0,0 +1,58 @@
import Field from "../../components/Field";
import React, {FormEvent, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import useAuthUser from "../../hooks/AuthUser";
import axios from "axios";
import useAxiosTools from "../../hooks/AxiosTools";
const Reset = () => {
let {token} = useParams()
const navigate = useNavigate()
const {setAuthUser} = useAuthUser()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [samePassword, setSamePassword] = useState('')
const {errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost} = useAxiosTools()
const handleSubmit = async (event: FormEvent) => {
event.preventDefault()
try {
cleanErrors()
await axiosGet('/sanctum/csrf-cookie')
const res = await axiosPost('/api/reset', {email, token, password, samePassword})
setAuthUser(res.data.user)
navigate('/connexion')
} catch (e) {
errorCatch(e)
}
}
return <div>
<form onSubmit={handleSubmit} className="w-96 mx-auto mt-10 border shadow p-3">
<h1 className="text-center">Modifier voter mot de passe</h1>
{errorLabel()}
<Field type="email"
name="email"
placeholder="Email"
value={email}
onChange={event => setEmail(event.target.value)}
autoFocus>Email</Field>
<Field type="password"
name="password"
placeholder="******"
value={password}
onChange={event => setPassword(event.target.value)}>Mot de passe</Field>
<Field type="password"
name="same_password"
placeholder="******"
value={samePassword}
onChange={event => setSamePassword(event.target.value)}>Confirmation du mot de passe</Field>
<button type="submit" className="mt-5 btn-primary w-full block text-lg">Valider</button>
</form>
</div>
}
export default Reset

View File

@@ -0,0 +1,21 @@
import React, {useState} from "react"
import useAuthUser from "../hooks/AuthUser";
import ToDoStore from "../components/toDos/ToDoStore";
import ToDoIndex from "../components/toDos/ToDoIndex";
const Home = () => {
const {authUser} = useAuthUser()
const [reload, setReload] = useState<Date|null>(null)
return <div>
{authUser &&
<div className="px-5 pt-10">
<ToDoStore setReload={setReload} />
<ToDoIndex reload={reload} />
</div>
}
</div>
}
export default Home

View File

@@ -0,0 +1,35 @@
import React from "react";
import {BrowserRouter, Route, Routes} from "react-router-dom";
import {Suspense} from "react";
import Profile from "./Auth/Profile";
import Login from "./Auth/Login";
import Header from "../components/Header";
import Home from "./Home";
import useAuthUser from "../hooks/AuthUser";
import Register from "./Auth/Register";
import ToDoShow from "../components/toDos/ToDoShow";
const Router = () => {
console.log('router')
const {authUser, loadingAuthUser, logout} = useAuthUser()
return <>
{loadingAuthUser ? '...loading'
: <BrowserRouter>
<Suspense fallback={'... loading'}>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/connexion" element={<Login />} />
<Route path="/inscription" element={<Register />} />
<Route path="/todos/:id" element={<ToDoShow />} />
</Routes>
</Suspense>
</BrowserRouter>
}
</>
}
export default Router

View File

@@ -0,0 +1,48 @@
interface Number {
pad(n: number, char?: string): string
}
Number.prototype.pad = function(n, char = "0") {
return (new Array(n).join(char) + this).slice(-n)
}
interface Date {
toFrDate(): string,
toFrTime(): string,
toSmallFrDate(): string,
difference(start_at?: Date): string,
}
Date.prototype.toFrDate = function() {
return `${this.getDate()}/${Number(this.getMonth() + 1).pad(2)}/${this.getFullYear()}`
}
Date.prototype.toFrTime = function(separator = 'h') {
return `${this.getHours().pad(2, '0')}${separator}${Number(this.getMinutes()).pad(2)}`
}
Date.prototype.toSmallFrDate = function() {
if ((new Date(this)).toFrDate() === (new Date()).toFrDate()) {
return `${this.toFrTime()}`
}
return `${this.toFrDate()} ${this.toFrTime()}`
}
Date.prototype.difference = function (start_at) {
if (!this) {
return '--:--'
}
let end_at = this
if (!start_at) {
end_at = new Date()
start_at = this
}
let timer = Math.floor((end_at.getTime() - start_at.getTime()) / 1000)
let hours = Math.floor(timer / 3600)
let minutes = Math.floor((timer - hours * 3600) / 60)
let secondes = timer - hours * 3600 - minutes * 60
return `${hours}:${String(minutes).padStart(2, '0')}:${String(secondes).padStart(2, '0')}`
}

View File

@@ -0,0 +1,40 @@
export function displayFormErrors(error: any, form: HTMLElement|null = null) {
if (error.response && error.response.status === 422) {
let errors = error.response.data.errors
const formBase = (form) ? form : document.body
Object.keys(errors).forEach(key => {
displayError(key, errors[key], formBase)
})
}
}
export function displayError(key: string, message: string, form: HTMLElement|null = null) {
const formBase = (form) ? form : document
const input = formBase.querySelector(`input[name="${key}"], select[name="${key}"], textarea[name="${key}"]`)
if (input) {
const formControl = input.closest('.form-control')
if (formControl) {
formControl.classList.add('invalid-control')
const errorMessage: HTMLElement|null = formControl.querySelector('.error-message')
if (errorMessage) {
errorMessage.innerText = message
}
if(key === 'form_info') {
formControl.classList.remove('hidden')
}
}
}
}
export function cleanErrorsForm(form = null) {
const formBase = (form) ? form : document.body
const inputsErrors = formBase.querySelectorAll('.invalid-control')
inputsErrors.forEach(input => {
input.classList.remove('invalid-control')
const errorMessage: HTMLElement|null = input.querySelector('.error-message')
if (errorMessage) {
errorMessage.innerText = ''
}
})
}

View File

@@ -0,0 +1,15 @@
export interface toDo {
id: number,
user_id: number,
name: string,
checked: boolean,
description?: string,
}
export interface timeTracker {
id: number,
to_do_id: number,
start_at: string,
end_at: string,
to_do: toDo,
}

View File

@@ -0,0 +1,5 @@
<?php
return [
'invalid_credentials' => 'Invalid credentials.'
];

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<meta name="description" content="Application de suivi météo">
<!-- Scripts -->
@viteReactRefresh
@vite(['resources/js/app.tsx'])
</head>
<body class="font-sans antialiased">
<div id="app" />
</body>
</html>

View File

@@ -0,0 +1,12 @@
<x-mail::message>
# Nouveau mot de passe
Veuillez cliquer sur le bouton de réinitilisation de votre de mot de passe.
<x-mail::button :url="$link">
Réinitialisation de mot de passe
</x-mail::button>
Merci,<br>
{{ config('app.name') }}
</x-mail::message>