Compare commits
154 Commits
82b73ddadf
...
main
Author | SHA1 | Date | |
---|---|---|---|
105d2aad88
|
|||
1f2bee0b08
|
|||
86d07570c6
|
|||
906dbeca22
|
|||
60bbe418a6
|
|||
650d77bbfd
|
|||
7f06ac94e8
|
|||
ced5259272
|
|||
d1cdf8cf6d
|
|||
4246266f9f
|
|||
956e9b6ffd
|
|||
590539a979
|
|||
abb5c3c584
|
|||
5e61cabcdc
|
|||
8ba47fe2f0
|
|||
834b1643de
|
|||
55aff5f900
|
|||
afcb5427af
|
|||
0b9df38139
|
|||
20f8fd515f
|
|||
256f0b7684
|
|||
409e13277e
|
|||
0433e4695e
|
|||
29c0a234d1
|
|||
a8182befe5
|
|||
ed019a3ed4
|
|||
b726305a44
|
|||
71b7df0008
|
|||
5143bdc446
|
|||
0a3fe8c243
|
|||
1fbd8ee5c3
|
|||
986649a070
|
|||
39312adc2a
|
|||
76643fcc62
|
|||
8084040aef
|
|||
893e6a9e01
|
|||
3648454da4
|
|||
25ca687448
|
|||
0f16edd8cc
|
|||
3348979738
|
|||
cb1222d9cf
|
|||
979362d012
|
|||
9dfb2ba15d
|
|||
8878a13f4f
|
|||
601b337369
|
|||
9c6dc97d23
|
|||
8b8453b276
|
|||
fd4b0e8cd1
|
|||
dba5b511ae
|
|||
50382079c0
|
|||
57676abb02
|
|||
3d50cee9a9
|
|||
02304527d3
|
|||
4a33963c12
|
|||
458183eba8
|
|||
9e5cdfb132
|
|||
30a687018f
|
|||
1241669c35
|
|||
6dbda9d927
|
|||
4cb2677f45
|
|||
63ad84eb8c
|
|||
47ec3da6df
|
|||
bd5e39094b
|
|||
04f30e3ac2
|
|||
9d0b5cb254
|
|||
db8a8b4b7b
|
|||
ac20baad23
|
|||
291e7ff8a7
|
|||
9543177db6
|
|||
9c7a447e4e
|
|||
e623dad81f
|
|||
bfc6069a87
|
|||
a4a0981b2c
|
|||
246dae446f
|
|||
38117ade07
|
|||
33ee18d7e2
|
|||
54a7806316
|
|||
af14cfb11d
|
|||
49c320b2db
|
|||
db560c401a
|
|||
61b0cd51ae
|
|||
c28097d443
|
|||
7aa9dde5a9
|
|||
d1adba04da
|
|||
9176eb014f
|
|||
bdd53eb8bb
|
|||
db7a0b970d
|
|||
1c52ff5a10
|
|||
b0c17db233
|
|||
363dfa5c74
|
|||
72862da3a6
|
|||
4da75e310e
|
|||
48845c70c2
|
|||
8f29169381
|
|||
a98b2b56ec
|
|||
7becd396d3
|
|||
ead2a91410
|
|||
ff85c8bd51
|
|||
1f4cfe0b77
|
|||
4be37ac303
|
|||
62559810b0
|
|||
32460062b8
|
|||
a9cb1ec425
|
|||
c08fbb762a
|
|||
4a4233925d
|
|||
a0fd6ca6ab
|
|||
20b4f2e7e8
|
|||
33689d9c76
|
|||
50a9f3369c
|
|||
31c44eab6e
|
|||
23081e0220
|
|||
3eea3a7409
|
|||
4c157ff67f
|
|||
a1b5fccc98
|
|||
8681752888
|
|||
481400d404
|
|||
77b33144f6
|
|||
83d3a573ca
|
|||
3af1e498ac
|
|||
b93b8b4c04
|
|||
0d96b78c33
|
|||
65576fc5b1
|
|||
c6da328023
|
|||
b44ffcd380
|
|||
6a0b4049b6
|
|||
7fd2c4d7fe
|
|||
11ab6f66f7
|
|||
99bd7a88a5
|
|||
e052b06c83
|
|||
4349a1b61a
|
|||
ab2d07cd18
|
|||
65d5ce3bc2
|
|||
0a89676b7e
|
|||
97d61497bc
|
|||
54e002e1f8
|
|||
d902e05fdd
|
|||
c82d39c009
|
|||
572a04130f
|
|||
faae6b0b93
|
|||
fc1773b5a6
|
|||
7750c1b75c
|
|||
138ff1df65
|
|||
86427bb41b
|
|||
1ae6b6634c
|
|||
45a1cebcf9
|
|||
376c297eda
|
|||
4486e99225
|
|||
9b3fe93f4f
|
|||
15e0263559
|
|||
2ad2063339
|
|||
ab180a12ce
|
|||
d08dcb9720
|
|||
91963e378d
|
|||
1ce5045871
|
15
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"sqltools.connections": [
|
||||
{
|
||||
"previewLimit": 50,
|
||||
"server": "localhost",
|
||||
"port": 5432,
|
||||
"driver": "PostgreSQL",
|
||||
"name": "Traintrape-moi",
|
||||
"database": "traintrape-moi",
|
||||
"username": "traintrapemoi",
|
||||
"socketPath": "/run/postgresql/.s.PGSQL.5432"
|
||||
}
|
||||
],
|
||||
"sqltools.useNodeRuntime": true
|
||||
}
|
@ -1 +1,6 @@
|
||||
# Public variables
|
||||
EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER=https://traintrapemoi.luemy.eu/api
|
||||
EXPO_PUBLIC_TRAINTRAPE_MOI_SOCKET=https://traintrapemoi.luemy.eu/
|
||||
|
||||
# Build variables
|
||||
ANDROID_HOME=/opt/android-sdk
|
2
client/.env.development
Normal file
@ -0,0 +1,2 @@
|
||||
EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER=http://localhost:3000/
|
||||
EXPO_PUBLIC_TRAINTRAPE_MOI_SOCKET=http://localhost:3000/
|
5
client/.gitignore
vendored
@ -9,6 +9,11 @@ dist/
|
||||
web-build/
|
||||
expo-env.d.ts
|
||||
|
||||
# Android output
|
||||
*.aab
|
||||
*.apk
|
||||
*.apks
|
||||
|
||||
# Native
|
||||
*.orig.*
|
||||
*.jks
|
||||
|
@ -1,22 +1,32 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "Traintrape-moi",
|
||||
"slug": "traintrape-moi",
|
||||
"version": "1.0.0",
|
||||
"slug": "traintrape-moi-client",
|
||||
"version": "1.1.1",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"scheme": "myapp",
|
||||
"scheme": "traintrapemoi",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"newArchEnabled": true,
|
||||
"ios": {
|
||||
"bundleIdentifier": "traintrapemoi",
|
||||
"supportsTablet": true
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/images/adaptive-icon.png",
|
||||
"backgroundColor": "#ffffff"
|
||||
"backgroundColor": "#0033fe"
|
||||
},
|
||||
"package": "eu.luemy.traintrapemoi"
|
||||
"package": "eu.luemy.traintrapemoi",
|
||||
"permissions": [
|
||||
"android.permission.ACCESS_COARSE_LOCATION",
|
||||
"android.permission.ACCESS_FINE_LOCATION",
|
||||
"android.permission.ACCESS_BACKGROUND_LOCATION",
|
||||
"android.permission.FOREGROUND_SERVICE",
|
||||
"android.permission.FOREGROUND_SERVICE_LOCATION",
|
||||
"android.permission.RECEIVE_BOOT_COMPLETED",
|
||||
"android.permission.WAKE_LOCK"
|
||||
]
|
||||
},
|
||||
"web": {
|
||||
"bundler": "metro",
|
||||
@ -24,19 +34,6 @@
|
||||
"favicon": "./assets/images/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"image": "./assets/images/splash-icon.png",
|
||||
"imageWidth": 200,
|
||||
"resizeMode": "contain",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@maplibre/maplibre-react-native"
|
||||
],
|
||||
[
|
||||
"expo-location",
|
||||
{
|
||||
@ -44,7 +41,22 @@
|
||||
"isIosBackgroundLocationEnabled": true,
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow $(PRODUCT_NAME) to use your location."
|
||||
}
|
||||
]
|
||||
],
|
||||
"expo-router",
|
||||
"expo-secure-store",
|
||||
"expo-share-intent",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"image": "./assets/images/splash-icon.png",
|
||||
"imageWidth": 128,
|
||||
"resizeMode": "contain",
|
||||
"backgroundColor": "#0033fe"
|
||||
}
|
||||
],
|
||||
"expo-task-manager",
|
||||
"expo-updates",
|
||||
"@maplibre/maplibre-react-native"
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true
|
||||
@ -56,6 +68,12 @@
|
||||
"eas": {
|
||||
"projectId": "1898a5de-1db1-41f7-b883-1b02885f750a"
|
||||
}
|
||||
},
|
||||
"runtimeVersion": {
|
||||
"policy": "appVersion"
|
||||
},
|
||||
"updates": {
|
||||
"url": "https://u.expo.dev/1898a5de-1db1-41f7-b883-1b02885f750a"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,18 +1,19 @@
|
||||
import { Tabs } from 'expo-router'
|
||||
import React from 'react'
|
||||
|
||||
import { Colors } from '@/constants/Colors'
|
||||
import { useColorScheme } from '@/hooks/useColorScheme'
|
||||
import { FontAwesome6, MaterialIcons } from '@expo/vector-icons'
|
||||
import TabBar from '@/components/ui/TabBar'
|
||||
import TabsHeader from '@/components/ui/TabsHeader'
|
||||
|
||||
export default function TabLayout() {
|
||||
const colorScheme = useColorScheme();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tabs
|
||||
tabBar={(props) => <TabBar {...props} />}
|
||||
screenOptions={{
|
||||
tabBarActiveTintColor: Colors[colorScheme ?? 'light'].tint,
|
||||
}}>
|
||||
tabBarHideOnKeyboard: true,
|
||||
header: (props) => <TabsHeader navProps={props} children={undefined} />,
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
@ -24,15 +25,15 @@ export default function TabLayout() {
|
||||
<Tabs.Screen
|
||||
name="challenges"
|
||||
options={{
|
||||
title: 'Challenges',
|
||||
headerTitleStyle: {fontSize: 32},
|
||||
title: 'Défi en cours',
|
||||
headerShown: false,
|
||||
tabBarIcon: ({ color }) => <FontAwesome6 name="coins" size={24} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="train"
|
||||
options={{
|
||||
title: 'Ajouter un trajet',
|
||||
title: 'Trains',
|
||||
headerTitleStyle: {fontSize: 32},
|
||||
tabBarIcon: ({ color }) => <FontAwesome6 name="train" size={24} color={color} />,
|
||||
}}
|
||||
@ -45,6 +46,15 @@ export default function TabLayout() {
|
||||
tabBarIcon: ({ color }) => <MaterialIcons name="history" size={24} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="settings"
|
||||
options={{
|
||||
title: 'Paramètres',
|
||||
headerTitleStyle: {fontSize: 32},
|
||||
tabBarIcon: ({ color }) => <MaterialIcons name="settings" size={24} color={color} />,
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
);
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
@ -1,14 +1,145 @@
|
||||
import { ScrollView } from 'react-native';
|
||||
import ChallengeCard from '@/components/ChallengeCard'
|
||||
import PenaltyBanner from '@/components/PenalyBanner'
|
||||
import { useDrawRandomChallengeMutation, useEndChallenge } from '@/hooks/mutations/useChallengeMutation'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useChallengeActions } from '@/hooks/useChallengeActions'
|
||||
import { useChallenges } from '@/hooks/useChallenges'
|
||||
import { useGame } from '@/hooks/useGame'
|
||||
import { FontAwesome6, MaterialCommunityIcons } from '@expo/vector-icons'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useRouter } from 'expo-router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { View } from 'react-native'
|
||||
import { ActivityIndicator, Appbar, Banner, FAB, MD3Colors, Snackbar, Surface, Text, TouchableRipple } from 'react-native-paper'
|
||||
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
function ChallengeScreenHeader() {
|
||||
const router = useRouter()
|
||||
return <>
|
||||
<Appbar.Header>
|
||||
<Appbar.Content title={"Défi en cours"} />
|
||||
<Appbar.Action icon='format-list-bulleted' onPress={() => router.navigate('/challenges-list')} />
|
||||
</Appbar.Header>
|
||||
<PenaltyBanner />
|
||||
</>
|
||||
}
|
||||
|
||||
function ChallengeScreenBody() {
|
||||
const queryClient = useQueryClient()
|
||||
const auth = useAuth()
|
||||
const game = useGame()
|
||||
const challengeActions = useChallengeActions()
|
||||
const challenges = useChallenges()
|
||||
const currentChallengeAction = useMemo(() => {
|
||||
if (!game.activeChallengeId)
|
||||
return null
|
||||
return challengeActions.find((action) => action.id === game.activeChallengeId)
|
||||
}, [game, challengeActions])
|
||||
const currentChallenge = useMemo(() => {
|
||||
if (!currentChallengeAction)
|
||||
return null
|
||||
return challenges.find((challenge) => challenge.id === currentChallengeAction.challengeId)
|
||||
}, [currentChallengeAction, challenges])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [successSnackbarVisible, setSuccessSnackbarVisible] = useState(false)
|
||||
const [errorVisible, setErrorVisible] = useState(false)
|
||||
const [error, setError] = useState([200, ""])
|
||||
const drawRandomChallengeMutation = useDrawRandomChallengeMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setLoading(true)
|
||||
setSuccessSnackbarVisible(true)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' || query.queryKey[0] === 'get-player' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const endChallenge = useEndChallenge({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setLoading(true)
|
||||
setSuccessSnackbarVisible(true)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' || query.queryKey[0] === 'get-player' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
useEffect(() => {
|
||||
if (challengeActions)
|
||||
setLoading(false)
|
||||
}, [challengeActions])
|
||||
|
||||
return <>
|
||||
{loading &&
|
||||
<View style={{ flexGrow: 1, justifyContent: 'center', alignItems: 'center' }}>
|
||||
<ActivityIndicator size={'large'} />
|
||||
</View>}
|
||||
{!loading && currentChallenge &&
|
||||
<ChallengeCard
|
||||
challenge={currentChallenge}
|
||||
onSuccess={() => { setLoading(true); endChallenge.mutate({ success: true }) }}
|
||||
onFail={() => endChallenge.mutate({ success: false })}
|
||||
style={{ flex: 1, margin: 20 }} />}
|
||||
{!loading && !game.penaltyEnd && !currentChallenge && game.currentRunner && <>
|
||||
<Banner
|
||||
elevation={4}
|
||||
visible={!currentChallenge && game.currentRunner && !loading}
|
||||
icon='vanish'>
|
||||
Aucun défi n'est en cours. Veuillez tirer un défi en cliquant sur le bouton central.
|
||||
Pour rappel, il faut être hors d'un train pour tirer un défi.
|
||||
</Banner>
|
||||
<View style={{ flexGrow: 1, justifyContent: 'center', alignItems: 'center' }}>
|
||||
<FAB
|
||||
label='Tirer un défi'
|
||||
icon='cards'
|
||||
disabled={drawRandomChallengeMutation.isPending}
|
||||
visible={!currentChallenge && game.currentRunner && !loading}
|
||||
onPress={() => drawRandomChallengeMutation.mutate()}
|
||||
variant='tertiary'
|
||||
customSize={64} />
|
||||
</View>
|
||||
</>}
|
||||
<Banner
|
||||
visible={!loading && game.gameStarted && !game.currentRunner}
|
||||
icon={({ size }) => <FontAwesome6 name='cat' size={size} color={'pink'} />}
|
||||
style={{ backgroundColor: MD3Colors.secondary30 }}>
|
||||
Vous êtes poursuiveuse, et n'avez donc pas de défi à accomplir.
|
||||
</Banner>
|
||||
<Snackbar
|
||||
key='success-snackbar'
|
||||
visible={successSnackbarVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setSuccessSnackbarVisible(false)}
|
||||
onIconPress={() => setSuccessSnackbarVisible(false)}>
|
||||
Jeu actualisé
|
||||
</Snackbar>
|
||||
<Snackbar
|
||||
key='error-snackbar'
|
||||
visible={errorVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setErrorVisible(false)}
|
||||
onIconPress={() => setErrorVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
Erreur {error[0]} : {error[1]}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
</>
|
||||
}
|
||||
|
||||
export default function ChallengesScreen() {
|
||||
return (
|
||||
<ScrollView>
|
||||
<ThemedView>
|
||||
<ThemedText>Ici on aura la gestion des challenges</ThemedText>
|
||||
</ThemedView>
|
||||
</ScrollView>
|
||||
);
|
||||
<Surface style={{ flex: 1 }}>
|
||||
<ChallengeScreenHeader />
|
||||
<ChallengeScreenBody />
|
||||
</Surface>
|
||||
)
|
||||
}
|
||||
|
@ -1,14 +1,190 @@
|
||||
import { ScrollView } from 'react-native';
|
||||
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { useDeleteChallengeActionMutation } from '@/hooks/mutations/useChallengeMutation'
|
||||
import { useGameRepairMutation } from '@/hooks/mutations/useGameMutation'
|
||||
import { useDeleteTrainMutation } from '@/hooks/mutations/useTrainMutation'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useChallengeActions } from '@/hooks/useChallengeActions'
|
||||
import { useChallenges } from '@/hooks/useChallenges'
|
||||
import { useMoneyUpdates } from '@/hooks/useMoneyUpdates'
|
||||
import { useTrain } from '@/hooks/useTrain'
|
||||
import { MoneyUpdate } from '@/utils/features/moneyUpdates/moneyUpdatesSlice'
|
||||
import { FontAwesome6 } from '@expo/vector-icons'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { FlatList } from 'react-native'
|
||||
import { Button, Dialog, Divider, List, MD3Colors, Portal, Snackbar, Surface, Text } from 'react-native-paper'
|
||||
|
||||
export default function HistoryScreen() {
|
||||
return (
|
||||
<ScrollView>
|
||||
<ThemedView>
|
||||
<ThemedText>Ici on aura la gestion de l'historique des trains empruntés et des challenges effectués</ThemedText>
|
||||
</ThemedView>
|
||||
</ScrollView>
|
||||
);
|
||||
const auth = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const moneyUpdates = useMoneyUpdates()
|
||||
const [deletingMoneyUpdate, setDeletingMoneyUpdate] = useState<MoneyUpdate | null>(null)
|
||||
|
||||
const [successVisible, setSuccessVisible] = useState(false)
|
||||
const [successMessage, setSuccessMessage] = useState("")
|
||||
const [errorVisible, setErrorVisible] = useState(false)
|
||||
const [error, setError] = useState([200, ""])
|
||||
|
||||
const deleteTrainMutation = useDeleteTrainMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setDeletingMoneyUpdate(null)
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Train supprimé")
|
||||
gameRepairMutation.mutate()
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-money-updates' || query.queryKey[0] === 'get-trains' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const deleteChallengeActionMutation = useDeleteChallengeActionMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setDeletingMoneyUpdate(null)
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Réalisation du défi supprimée")
|
||||
gameRepairMutation.mutate()
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-money-updates' || query.queryKey[0] === 'get-challenges' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const gameRepairMutation = useGameRepairMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-player' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
|
||||
function deleteMoneyUpdate(): void {
|
||||
if (!deletingMoneyUpdate)
|
||||
return
|
||||
switch (deletingMoneyUpdate.reason) {
|
||||
case 'BUY_TRAIN':
|
||||
if (!deletingMoneyUpdate.tripId) return
|
||||
deleteTrainMutation.mutate(deletingMoneyUpdate.tripId)
|
||||
break
|
||||
case 'CHALLENGE':
|
||||
if (!deletingMoneyUpdate.actionId) return
|
||||
deleteChallengeActionMutation.mutate(deletingMoneyUpdate.actionId)
|
||||
break
|
||||
}
|
||||
setDeletingMoneyUpdate(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<Surface style={{ flex :1 }}>
|
||||
<FlatList
|
||||
data={moneyUpdates}
|
||||
keyExtractor={(moneyUpdate) => `money-update-list-item-${moneyUpdate.id}`}
|
||||
ItemSeparatorComponent={() => <Divider />}
|
||||
renderItem={(item) =>
|
||||
<MoneyUpdateListItem moneyUpdate={item.item}
|
||||
onDelete={['START', 'NEW_RUN'].includes(item.item.reason) ? undefined : () => setDeletingMoneyUpdate(item.item)} />} />
|
||||
<Snackbar
|
||||
key='success-snackbar'
|
||||
visible={successVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setSuccessVisible(false)}
|
||||
onIconPress={() => setSuccessVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
{successMessage}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Snackbar
|
||||
key='error-snackbar'
|
||||
visible={errorVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setErrorVisible(false)}
|
||||
onIconPress={() => setErrorVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
Erreur {error[0]} : {error[1]}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Portal>
|
||||
<Dialog visible={deletingMoneyUpdate !== null} onDismiss={() => setDeletingMoneyUpdate(null)}>
|
||||
<Dialog.Title>Êtes-vous sûre ?</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text>Voulez-vous vraiment supprimer ce mouvement de fonds ?</Text>
|
||||
{deletingMoneyUpdate && <MoneyUpdateListItem moneyUpdate={deletingMoneyUpdate} />}
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setDeletingMoneyUpdate(null)}>Annuler</Button>
|
||||
<Button onPress={() => deleteMoneyUpdate()}>Confirmer</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
</Surface>
|
||||
)
|
||||
}
|
||||
|
||||
function MoneyUpdateListItem({ moneyUpdate, onDelete }: { moneyUpdate: MoneyUpdate, onDelete?: () => void }) {
|
||||
const trains = useTrain()
|
||||
const challengeActions = useChallengeActions()
|
||||
const challenges = useChallenges()
|
||||
|
||||
const icon = useMemo(() => {
|
||||
switch (moneyUpdate.reason) {
|
||||
case 'START': return 'star'
|
||||
case 'NEW_RUN': return 'run'
|
||||
case 'BUY_TRAIN': return 'train'
|
||||
case 'CHALLENGE': return 'cards'
|
||||
}
|
||||
}, [moneyUpdate.reason])
|
||||
|
||||
const title = useMemo(() => {
|
||||
switch (moneyUpdate.reason) {
|
||||
case 'START':
|
||||
return "Début de la partie"
|
||||
case 'NEW_RUN':
|
||||
return "Nouvelle tentative"
|
||||
case 'BUY_TRAIN':
|
||||
const train = trains.find((train) => train.id === moneyUpdate.tripId)
|
||||
if (!train) return "Train"
|
||||
const depDateTime = new Date(train.departureTime)
|
||||
const depTime = depDateTime.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const arrDateTime = new Date(train.arrivalTime)
|
||||
const arrTime = arrDateTime.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
return `${train.from} ${depTime} => ${train.to} ${arrTime}`
|
||||
case 'CHALLENGE':
|
||||
const challengeAction = challengeActions.find((challengeAction) => challengeAction.id === moneyUpdate.actionId)
|
||||
if (!challengeAction) return "Défi"
|
||||
const challenge = challenges.find((challenge) => challenge.id === challengeAction.challengeId)
|
||||
if (!challenge) return "Défi"
|
||||
return challenge.title
|
||||
}
|
||||
}, [moneyUpdate.reason, moneyUpdate.tripId, moneyUpdate.actionId])
|
||||
|
||||
const description = useMemo(() => {
|
||||
const earnDate = new Date(moneyUpdate.timestamp).toLocaleDateString(undefined, { day: '2-digit', month: '2-digit' })
|
||||
const earnTime = new Date(moneyUpdate.timestamp).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const verb = moneyUpdate.amount >= 0 ? "Gagné" : "Dépensé"
|
||||
return <Text>
|
||||
{verb} {Math.abs(moneyUpdate.amount)} <FontAwesome6 name='coins' /> le {earnDate} à {earnTime}
|
||||
</Text>
|
||||
}, [moneyUpdate.amount])
|
||||
|
||||
return (
|
||||
<List.Item
|
||||
left={(props) => <List.Icon {...props} icon={icon} />}
|
||||
title={title}
|
||||
description={description}
|
||||
onLongPress={onDelete} />
|
||||
)
|
||||
}
|
||||
|
@ -1,45 +1,68 @@
|
||||
import { StyleSheet } from 'react-native'
|
||||
import { ThemedView } from '@/components/ThemedView'
|
||||
import { useEffect, useState } from 'react'
|
||||
import "maplibre-gl/dist/maplibre-gl.css"
|
||||
|
||||
import * as Location from 'expo-location'
|
||||
import Map from '@/components/map'
|
||||
import { ThemedText } from '@/components/ThemedText'
|
||||
import { useBackgroundPermissions } from 'expo-location'
|
||||
import Map from '@/components/Map'
|
||||
import { FAB, Surface, Text } from 'react-native-paper'
|
||||
import { useGame } from '@/hooks/useGame'
|
||||
import { FontAwesome6 } from '@expo/vector-icons'
|
||||
import FreeChaseBanner from '@/components/FreeChaseBanner'
|
||||
import { View } from 'react-native'
|
||||
|
||||
export default function MapScreen() {
|
||||
const [location, setLocation] = useState<Location.LocationObject | null>(null)
|
||||
const [locationAccessGranted, setLocationAccessGranted] = useState(false)
|
||||
const [backgroundStatus, requestBackgroundPermission] = useBackgroundPermissions()
|
||||
if (!backgroundStatus?.granted && backgroundStatus?.canAskAgain)
|
||||
requestBackgroundPermission()
|
||||
|
||||
useEffect(() => {
|
||||
async function watchPosition() {
|
||||
let { status } = await Location.requestForegroundPermissionsAsync()
|
||||
if (status !== 'granted') {
|
||||
setLocationAccessGranted(false)
|
||||
alert("Vous devez activer votre géolocalisation pour utiliser l'application.")
|
||||
return
|
||||
}
|
||||
setLocationAccessGranted(true)
|
||||
await Location.watchPositionAsync({accuracy: Location.Accuracy.BestForNavigation}, location => setLocation(location))
|
||||
}
|
||||
watchPosition()
|
||||
}, [])
|
||||
const game = useGame()
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.page}>
|
||||
{locationAccessGranted ? <Map location={location} /> : <ThemedText>La géolocalisation est requise pour utiliser la carte.</ThemedText>}
|
||||
</ThemedView>
|
||||
<Surface style={styles.page}>
|
||||
<View style={styles.container}>
|
||||
{backgroundStatus?.granted ? <Map /> : <Text>La géolocalisation est requise pour utiliser la carte.</Text>}
|
||||
<FAB
|
||||
style={styles.moneyBadge}
|
||||
visible={game.gameStarted || game.money > 0}
|
||||
icon={(props) => <FontAwesome6 {...props} name='coins' size={20} />}
|
||||
color='black'
|
||||
label={`${game.money}`}
|
||||
onPress={() => {}} />
|
||||
<FAB
|
||||
style={styles.statusBadge}
|
||||
visible={game.gameStarted || game.money > 0}
|
||||
size='small'
|
||||
color='black'
|
||||
icon={game.currentRunner ? 'run-fast' : () => <FontAwesome6 name='cat' size={20} />}
|
||||
label={game.currentRunner ? "Coureuse" : "Poursuiveuse"}
|
||||
onPress={() => {}} />
|
||||
</View>
|
||||
<FreeChaseBanner />
|
||||
</Surface>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
flex: 1,
|
||||
},
|
||||
container: {
|
||||
flexGrow: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center'
|
||||
},
|
||||
map: {
|
||||
flex: 1,
|
||||
alignSelf: 'stretch',
|
||||
},
|
||||
});
|
||||
moneyBadge: {
|
||||
position: 'absolute',
|
||||
top: 40,
|
||||
right: 20,
|
||||
backgroundColor: 'orange',
|
||||
},
|
||||
statusBadge: {
|
||||
position: 'absolute',
|
||||
top: 40,
|
||||
left: 20,
|
||||
backgroundColor: 'pink',
|
||||
},
|
||||
})
|
||||
|
206
client/app/(tabs)/settings.tsx
Normal file
@ -0,0 +1,206 @@
|
||||
import { useGameRepairMutation, useGameResetMutation, useGameStartMutation, useGameStopMutation, useGameSwitchPlayerMutation } from '@/hooks/mutations/useGameMutation'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useGame, useSetLocationAccuracy, useUpdateGameState } from '@/hooks/useGame'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useRouter } from 'expo-router'
|
||||
import { useState } from 'react'
|
||||
import { Button, Dialog, List, MD3Colors, Portal, Snackbar, Surface, Text } from 'react-native-paper'
|
||||
import { Dropdown } from 'react-native-paper-dropdown'
|
||||
import { Accuracy } from 'expo-location'
|
||||
|
||||
export default function HistoryScreen() {
|
||||
const [successVisible, setSuccessVisible] = useState(false)
|
||||
const [successMessage, setSuccessMessage] = useState("")
|
||||
const [errorVisible, setErrorVisible] = useState(false)
|
||||
const [error, setError] = useState([200, ""])
|
||||
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const auth = useAuth()
|
||||
const game = useGame()
|
||||
const updateGameState = useUpdateGameState()
|
||||
const setLocationAccuracy = useSetLocationAccuracy()
|
||||
|
||||
const accuracyArrayList = [
|
||||
{ value: Accuracy.BestForNavigation.toString(), label: "Navigation" },
|
||||
{ value: Accuracy.Highest.toString(), label: "Plus haute" },
|
||||
{ value: Accuracy.High.toString(), label: "Haute" },
|
||||
{ value: Accuracy.Balanced.toString(), label: "Équilibrée" },
|
||||
{ value: Accuracy.Low.toString(), label: "Basse" },
|
||||
{ value: Accuracy.Lowest.toString(), label: "Plus basse" },
|
||||
{ value: 'null', label: "Désactivée" },
|
||||
]
|
||||
|
||||
const gameStartMutation = useGameStartMutation({
|
||||
auth,
|
||||
updateGameState,
|
||||
onPostSuccess: () => {
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Jeu démarré avec succès")
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-game' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const gameStopMutation = useGameStopMutation({
|
||||
auth,
|
||||
updateGameState,
|
||||
onPostSuccess: () => {
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Jeu arrêté avec succès")
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-game' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const gameSwitchMutation = useGameSwitchPlayerMutation({
|
||||
auth,
|
||||
updateGameState,
|
||||
onPostSuccess: () => {
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Échange de joueuse en course réalisé avec succès")
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-game' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const gameRepairMutation = useGameRepairMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Réparation du jeu effectuée avec succès")
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-game' })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-player' })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'money-updates' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const gameResetMutation = useGameResetMutation({
|
||||
auth,
|
||||
updateGameState,
|
||||
onPostSuccess: () => {
|
||||
setSuccessVisible(true)
|
||||
setSuccessMessage("Jeu réinitialisé avec succès")
|
||||
queryClient.invalidateQueries()
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
|
||||
const [resetConfirmVisible, setResetConfirmVisible] = useState(false)
|
||||
|
||||
return (
|
||||
<Surface
|
||||
style={{ flex: 1 }}>
|
||||
<List.Section title={"Paramètres"}>
|
||||
<List.Item
|
||||
key={"login"}
|
||||
title="Connexion au serveur"
|
||||
description={auth.loggedIn ? "Vous êtes déjà connecté⋅e" : "Vous n'êtes pas connecté⋅e"}
|
||||
right={() => <List.Icon icon="login" />}
|
||||
onPress={() => router.navigate('/login')} />
|
||||
<List.Item
|
||||
key={"location-accuracy"}
|
||||
title="Précision de la géolocalisation"
|
||||
description="Réglez le niveau de précision de la géolocalisation. Une valeur élevée indique une consommation de batterie accrue."
|
||||
right={() => <Dropdown label={"Géolocalisation"} hideMenuHeader={true} options={accuracyArrayList} value={game.settings.locationAccuracy?.toString() ?? 'null'} onSelect={(value) => setLocationAccuracy(!value || value == 'null' ? null : +value)} />} />
|
||||
</List.Section>
|
||||
<List.Section title={"Gestion du jeu"}>
|
||||
<List.Item
|
||||
key={"start"}
|
||||
title="Démarrer le jeu"
|
||||
disabled={game.gameStarted}
|
||||
right={() => <List.Icon icon="play" color={!game.gameStarted ? undefined : MD3Colors.secondary30} />}
|
||||
onPress={() => gameStartMutation.mutate()} />
|
||||
<List.Item
|
||||
key={"stop"}
|
||||
title="Arrêter le jeu"
|
||||
disabled={!game.gameStarted}
|
||||
right={() => <List.Icon icon="stop" color={game.gameStarted ? undefined : MD3Colors.secondary30} />}
|
||||
onPress={() => gameStopMutation.mutate()} />
|
||||
<List.Item
|
||||
key={"switch"}
|
||||
title="Changer de joueur⋅se en course"
|
||||
description="À utiliser après une capture"
|
||||
disabled={!game.gameStarted}
|
||||
right={() => <List.Icon icon="exit-run" color={game.gameStarted ? undefined : MD3Colors.secondary30} />}
|
||||
onPress={() => gameSwitchMutation.mutate()} />
|
||||
</List.Section>
|
||||
<List.Section title={"Avancé"}>
|
||||
<List.Item
|
||||
key={"repair"}
|
||||
title="Réparer"
|
||||
description="Permet de réparer les soldes des joueur⋅ses à partir des défis réalisés et des trains emprunter. À manipuler avec précaution."
|
||||
right={() => <List.Icon icon='tools' color={MD3Colors.error60} />}
|
||||
onPress={() => gameRepairMutation.mutate()} />
|
||||
<List.Item
|
||||
key={"reset"}
|
||||
title="Réinitialiser les données de jeu"
|
||||
description="Permet de détruire toutes les données. À manipuler avec précaution."
|
||||
right={() => <List.Icon icon="reload-alert" color={MD3Colors.error60} />}
|
||||
onPress={() => setResetConfirmVisible(true)} />
|
||||
</List.Section>
|
||||
<Snackbar
|
||||
key='success-snackbar'
|
||||
visible={successVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setSuccessVisible(false)}
|
||||
onIconPress={() => setSuccessVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
{successMessage}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Snackbar
|
||||
key='error-snackbar'
|
||||
visible={errorVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setErrorVisible(false)}
|
||||
onIconPress={() => setErrorVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
Erreur {error[0]} : {error[1]}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Portal>
|
||||
<Dialog key="confirmReset" visible={resetConfirmVisible} onDismiss={() => setResetConfirmVisible(false)}>
|
||||
<Dialog.Title>Confirmer</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text variant="bodyMedium">
|
||||
Cette action va réinitialiser TOUTES les données de jeu : l'historique des positions, les défis réalisés et les trains empruntés.
|
||||
Êtes-vous réellement sûr⋅e de vouloir tout supprimer ?
|
||||
</Text>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setResetConfirmVisible(false)}>Annuler</Button>
|
||||
<Button onPress={() => { setResetConfirmVisible(false); gameResetMutation.mutate() }}>Confirmer</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
</Surface>
|
||||
)
|
||||
}
|
@ -1,14 +1,148 @@
|
||||
import { ScrollView } from 'react-native';
|
||||
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import PenaltyBanner from '@/components/PenalyBanner'
|
||||
import { useAddTrainMutation } from '@/hooks/mutations/useTrainMutation'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useTrain } from '@/hooks/useTrain'
|
||||
import { TrainTrip } from '@/utils/features/train/trainSlice'
|
||||
import { FontAwesome6 } from '@expo/vector-icons'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useShareIntentContext } from 'expo-share-intent'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { FlatList, StyleSheet } from 'react-native'
|
||||
import { Button, Dialog, Divider, FAB, HelperText, List, MD3Colors, Portal, Snackbar, Surface, Text, TextInput } from 'react-native-paper'
|
||||
|
||||
export default function TrainScreen() {
|
||||
return (
|
||||
<ScrollView>
|
||||
<ThemedView>
|
||||
<ThemedText>Ici on aura la page pour ajouter un trajet en train depuis Rail Planner</ThemedText>
|
||||
</ThemedView>
|
||||
</ScrollView>
|
||||
);
|
||||
const [addTrainVisible, setAddTrainVisible] = useState(false)
|
||||
const [addTrainUrl, setAddTrainUrl] = useState("")
|
||||
const trainId = useMemo(() => /[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}/.exec(addTrainUrl)?.[0], [addTrainUrl])
|
||||
|
||||
const [successSnackbarVisible, setSuccessSnackbarVisible] = useState(false)
|
||||
const [errorVisible, setErrorVisible] = useState(false)
|
||||
const [error, setError] = useState([200, ""])
|
||||
|
||||
const auth = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const addTrainMutation = useAddTrainMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setAddTrainVisible(false)
|
||||
setSuccessSnackbarVisible(true)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-trains' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
|
||||
const trains = useTrain()
|
||||
|
||||
|
||||
const { hasShareIntent, shareIntent, resetShareIntent } = useShareIntentContext()
|
||||
useEffect(() => {
|
||||
if (hasShareIntent) {
|
||||
resetShareIntent()
|
||||
if (!shareIntent.text || !shareIntent.text.includes("eurailapp.com/share"))
|
||||
return
|
||||
const parsedTrainId = /[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}/.exec(shareIntent.text)?.[0]
|
||||
if (parsedTrainId)
|
||||
addTrainMutation.mutate(parsedTrainId)
|
||||
else {
|
||||
setErrorVisible(true)
|
||||
setError([400, "Impossible de récupérer l'identifiant du train à ajouter"])
|
||||
}
|
||||
}
|
||||
}, [hasShareIntent])
|
||||
|
||||
return (
|
||||
<Surface style={{ flex: 1 }}>
|
||||
<PenaltyBanner />
|
||||
<FlatList
|
||||
data={trains}
|
||||
keyExtractor={(train) => train.id}
|
||||
ItemSeparatorComponent={() => <Divider />}
|
||||
renderItem={(item) => <TrainListItem train={item.item} />} />
|
||||
<FAB
|
||||
icon='plus'
|
||||
style={styles.addTrainButton}
|
||||
onPress={() => setAddTrainVisible(true)} />
|
||||
<Snackbar
|
||||
key='success-snackbar'
|
||||
visible={successSnackbarVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setSuccessSnackbarVisible(false)}
|
||||
onIconPress={() => setSuccessSnackbarVisible(false)}>
|
||||
Train ajouté avec succès
|
||||
</Snackbar>
|
||||
<Snackbar
|
||||
key='error-snackbar'
|
||||
visible={errorVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setErrorVisible(false)}
|
||||
onIconPress={() => setErrorVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
Erreur {error[0]} : {error[1]}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Portal>
|
||||
<Dialog visible={addTrainVisible} onDismiss={() => setAddTrainVisible(false)}>
|
||||
<Dialog.Title>Ajout d'un train</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<TextInput
|
||||
label="URL de partage RailPlanner"
|
||||
autoComplete='url'
|
||||
inputMode='url'
|
||||
defaultValue={addTrainUrl}
|
||||
multiline={true}
|
||||
onChangeText={setAddTrainUrl}
|
||||
error={!trainId}
|
||||
onEndEditing={() => {
|
||||
if (trainId !== undefined)
|
||||
addTrainMutation.mutate(trainId)
|
||||
}}
|
||||
placeholder="https://eurailapp.com/share/journey?id=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX&type=list&brand=interrail" />
|
||||
<HelperText type='error' visible={!trainId && addTrainVisible}>
|
||||
Le champ doit contenir l'identifiant d'un voyage au format UUID. {trainId}
|
||||
</HelperText>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setAddTrainVisible(false)}>Annuler</Button>
|
||||
<Button onPress={() => {
|
||||
if (trainId !== undefined)
|
||||
addTrainMutation.mutate(trainId)
|
||||
}} disabled={trainId === undefined || addTrainMutation.isPending}>Ajouter</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
</Surface>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
addTrainButton: {
|
||||
position: 'absolute',
|
||||
right: 25,
|
||||
bottom: 25,
|
||||
}
|
||||
})
|
||||
|
||||
function TrainListItem({ train }: { train: TrainTrip }) {
|
||||
const depDateTime = new Date(train.departureTime)
|
||||
const depDate = depDateTime.toLocaleDateString()
|
||||
const depTime = depDateTime.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const arrDateTime = new Date(train.arrivalTime)
|
||||
const arrTime = arrDateTime.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const durationInMinutes = (arrDateTime.getTime() - depDateTime.getTime()) / 1000 / 60
|
||||
const duration = `${Math.floor(durationInMinutes / 60).toString().padStart(2, '0')}:${Math.floor(durationInMinutes % 60).toString().padStart(2, '0')}`
|
||||
const title = `${train.from} ${depTime} => ${train.to} ${arrTime} (${depDate})`
|
||||
const distanceKm = Math.ceil(train.distance / 1000)
|
||||
const cost = 10 * distanceKm
|
||||
return <>
|
||||
<List.Item
|
||||
title={title}
|
||||
description={<><Text>Durée : {duration}, distance : {distanceKm} km, coût : {cost}</Text> <FontAwesome6 name='coins' /></>}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
|
36
client/app/+html.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import Head from 'expo-router/head'
|
||||
import { ScrollViewStyleReset } from 'expo-router/html'
|
||||
import React from 'react'
|
||||
|
||||
export default function Root({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<Head>
|
||||
<title>Traintrape-moi</title>
|
||||
</Head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, shrink-to-fit=no"
|
||||
/>
|
||||
<title>Traintrape-moi</title>
|
||||
<ScrollViewStyleReset />
|
||||
|
||||
{/* Using raw CSS styles as an escape-hatch to ensure the background color never flickers in dark-mode. */}
|
||||
<style dangerouslySetInnerHTML={{ __html: responsiveBackground }} />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
const responsiveBackground = `
|
||||
body {
|
||||
background-color: #fff;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background-color: #000;
|
||||
}
|
||||
}`
|
@ -1,15 +1,69 @@
|
||||
import { useReactNavigationDevTools } from '@dev-plugins/react-navigation'
|
||||
import { useReactQueryDevTools } from '@dev-plugins/react-query'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native'
|
||||
import { Stack } from "expo-router"
|
||||
import { useColorScheme } from '@/hooks/useColorScheme'
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
|
||||
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
|
||||
import { Stack, useNavigationContainerRef } from 'expo-router'
|
||||
import { ShareIntentProvider } from 'expo-share-intent'
|
||||
import { StatusBar } from 'expo-status-bar'
|
||||
import { MD3DarkTheme, MD3LightTheme, PaperProvider } from 'react-native-paper'
|
||||
import { Provider as StoreProvider } from 'react-redux'
|
||||
import GameProvider from '@/components/providers/GameProvider'
|
||||
import GeolocationProvider from '@/components/providers/GeolocationProvider'
|
||||
import LoginProvider from '@/components/providers/LoginProvider'
|
||||
import { useColorScheme } from '@/hooks/useColorScheme'
|
||||
import store from '@/utils/store'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
gcTime: 24 * 60 * 60 * 1000, // 24h
|
||||
staleTime: 2000,
|
||||
retry: 5,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export default function RootLayout() {
|
||||
const colorScheme = useColorScheme()
|
||||
return <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
|
||||
|
||||
const navigationRef = useNavigationContainerRef()
|
||||
useReactNavigationDevTools(navigationRef)
|
||||
useReactQueryDevTools(queryClient)
|
||||
|
||||
const asyncStoragePersister = createAsyncStoragePersister({
|
||||
storage: AsyncStorage,
|
||||
})
|
||||
|
||||
return (
|
||||
<StoreProvider store={store}>
|
||||
<PersistQueryClientProvider
|
||||
client={queryClient}
|
||||
persistOptions={{ persister: asyncStoragePersister }}
|
||||
onSuccess={() => queryClient.resumePausedMutations().then(() => queryClient.invalidateQueries())}>
|
||||
<ShareIntentProvider>
|
||||
<LoginProvider loginRedirect={'/login'}>
|
||||
<GeolocationProvider>
|
||||
<GameProvider>
|
||||
<PaperProvider
|
||||
theme={colorScheme === 'dark' ? MD3DarkTheme : MD3LightTheme} >
|
||||
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
|
||||
<Stack>
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="login" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="challenges-list" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="+not-found" />
|
||||
</Stack>
|
||||
<StatusBar style="auto" />
|
||||
</ThemeProvider>
|
||||
</PaperProvider>
|
||||
</GameProvider>
|
||||
</GeolocationProvider>
|
||||
</LoginProvider>
|
||||
</ShareIntentProvider>
|
||||
</PersistQueryClientProvider>
|
||||
</StoreProvider>
|
||||
)
|
||||
}
|
||||
|
302
client/app/challenges-list.tsx
Normal file
@ -0,0 +1,302 @@
|
||||
import ChallengeCard from "@/components/ChallengeCard"
|
||||
import { useAddChallengeMutation, useAttachNewChallenge, useDeleteChallengeMutation, useEditChallengeMutation } from "@/hooks/mutations/useChallengeMutation"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { useChallengeActions } from "@/hooks/useChallengeActions"
|
||||
import { useChallenges } from "@/hooks/useChallenges"
|
||||
import { useGame } from "@/hooks/useGame"
|
||||
import { Challenge } from "@/utils/features/challenges/challengesSlice"
|
||||
import { FontAwesome6 } from "@expo/vector-icons"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { useRouter } from "expo-router"
|
||||
import React, { ReactNode, useMemo, useState } from "react"
|
||||
import { FlatList, StyleSheet } from "react-native"
|
||||
import { ActivityIndicator, Appbar, Button, Dialog, Divider, FAB, List, MD3Colors, Modal, Portal, Snackbar, Surface, Text, TextInput, Tooltip } from "react-native-paper"
|
||||
|
||||
export default function ChallengesList() {
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const auth = useAuth()
|
||||
const game = useGame()
|
||||
const challenges = useChallenges()
|
||||
const challengeActions = useChallengeActions()
|
||||
const currentChallengeAction = useMemo(() => {
|
||||
if (!game.activeChallengeId)
|
||||
return null
|
||||
return challengeActions.find((action) => action.id === game.activeChallengeId)
|
||||
}, [game, challengeActions])
|
||||
|
||||
const [editChallengeVisible, setEditChallengeVisible] = useState(false)
|
||||
const [editChallengeTitle, setEditChallengeTitle] = useState("")
|
||||
const [editChallengeDescription, setEditChallengeDescription] = useState("")
|
||||
const [editChallengeReward, setEditChallengeReward] = useState(0)
|
||||
const [editChallengeId, setEditChallengeId] = useState<number |null>(null)
|
||||
const [displayedChallenge, setDisplayedChallenge] = useState<Challenge | null>(null)
|
||||
const [confirmDeletedVisible, setConfirmDeleteVisible] = useState(false)
|
||||
const [challengeToAttach, setChallengeToAttach] = useState<Challenge | null>(null)
|
||||
|
||||
const [successSnackbarVisible, setSuccessSnackbarVisible] = useState(false)
|
||||
const [successMessage, setSuccessMessage] = useState("")
|
||||
const [errorVisible, setErrorVisible] = useState(false)
|
||||
const [error, setError] = useState([200, ""])
|
||||
|
||||
const addChallengeMutation = useAddChallengeMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setSuccessMessage("Le défi a bien été ajouté !")
|
||||
setSuccessSnackbarVisible(true)
|
||||
setEditChallengeVisible(false)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
setEditChallengeVisible(false)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const editChallengeMutation = useEditChallengeMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setSuccessMessage("Le défi a bien été modifié !")
|
||||
setSuccessSnackbarVisible(true)
|
||||
setEditChallengeVisible(false)
|
||||
setDisplayedChallenge(null)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
setEditChallengeVisible(false)
|
||||
setDisplayedChallenge(null)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const deleteChallengeMutation = useDeleteChallengeMutation({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setSuccessMessage("Le défi a bien été supprimé !")
|
||||
setDisplayedChallenge(null)
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorVisible(true)
|
||||
setDisplayedChallenge(null)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
const attachNewChallengeMutation = useAttachNewChallenge({
|
||||
auth,
|
||||
onPostSuccess: () => {
|
||||
setChallengeToAttach(null)
|
||||
setSuccessMessage("Le défi en cours a bien été modifié !")
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setChallengeToAttach(null)
|
||||
setErrorVisible(true)
|
||||
if (response)
|
||||
setError([response.statusCode, response.message])
|
||||
else if (error)
|
||||
setError([400, error.message])
|
||||
},
|
||||
})
|
||||
|
||||
function sendEditChallenge() {
|
||||
if (editChallengeId) {
|
||||
editChallengeMutation.mutate({
|
||||
id: editChallengeId,
|
||||
title: editChallengeTitle,
|
||||
description: editChallengeDescription,
|
||||
reward: editChallengeReward,
|
||||
})
|
||||
}
|
||||
else {
|
||||
addChallengeMutation.mutate({
|
||||
title: editChallengeTitle,
|
||||
description: editChallengeDescription,
|
||||
reward: editChallengeReward,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function sendDeleteChallenge() {
|
||||
displayedChallenge && deleteChallengeMutation.mutate(displayedChallenge)
|
||||
}
|
||||
|
||||
function sendAttachNewChallenge() {
|
||||
if (!challengeToAttach || !currentChallengeAction) return
|
||||
attachNewChallengeMutation.mutate({ challengeActionId: currentChallengeAction.id, newChallengeId: challengeToAttach.id })
|
||||
}
|
||||
|
||||
return (
|
||||
<Surface style={{ flex: 1 }}>
|
||||
<Appbar.Header>
|
||||
<Appbar.BackAction onPress={() => router.canGoBack() ? router.back() : router.navigate('/(tabs)/challenges')} />
|
||||
<Appbar.Content title={"Liste des défis"} />
|
||||
</Appbar.Header>
|
||||
<FlatList
|
||||
data={challenges}
|
||||
keyExtractor={(challenge) => `challenge-list-item-${challenge.id}`}
|
||||
ItemSeparatorComponent={() => <Divider />}
|
||||
renderItem={(item) =>
|
||||
<ChallengeListItem challenge={item.item}
|
||||
activeRunner={game.currentRunner}
|
||||
onPress={() => setDisplayedChallenge(item.item)}
|
||||
onLongPress={!currentChallengeAction ? undefined : () => setChallengeToAttach(item.item)} />} />
|
||||
<Snackbar
|
||||
key='success-snackbar'
|
||||
visible={successSnackbarVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setSuccessSnackbarVisible(false)}
|
||||
onIconPress={() => setSuccessSnackbarVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
{successMessage}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<Snackbar
|
||||
key='error-snackbar'
|
||||
visible={errorVisible}
|
||||
icon={'close'}
|
||||
onDismiss={() => setErrorVisible(false)}
|
||||
onIconPress={() => setErrorVisible(false)}>
|
||||
<Text variant='bodyMedium' style={{ color: MD3Colors.secondary0 }}>
|
||||
Erreur {error[0]} : {error[1]}
|
||||
</Text>
|
||||
</Snackbar>
|
||||
<FAB
|
||||
icon='plus'
|
||||
style={{ ...styles.addButton, bottom: errorVisible || successSnackbarVisible ? 80 : styles.addButton.bottom }}
|
||||
onPress={() => {
|
||||
if (editChallengeId) {
|
||||
setEditChallengeTitle("")
|
||||
setEditChallengeDescription("")
|
||||
setEditChallengeReward(0)
|
||||
setEditChallengeId(null)
|
||||
}
|
||||
setEditChallengeVisible(true)
|
||||
}} />
|
||||
<Portal>
|
||||
<Modal
|
||||
visible={displayedChallenge !== null}
|
||||
onDismiss={() => setDisplayedChallenge(null)}
|
||||
contentContainerStyle={{ flex: 1, marginHorizontal: 20, marginVertical: 100 }}>
|
||||
<ChallengeCard
|
||||
challenge={displayedChallenge}
|
||||
onEdit={() => {
|
||||
setEditChallengeTitle(displayedChallenge?.title ?? "")
|
||||
setEditChallengeDescription(displayedChallenge?.description ?? "")
|
||||
setEditChallengeReward(displayedChallenge?.reward ?? 0)
|
||||
setEditChallengeId(displayedChallenge?.id ?? null)
|
||||
setEditChallengeVisible(true)
|
||||
}}
|
||||
onDelete={() => setConfirmDeleteVisible(true)}
|
||||
style={{ flexGrow: 1 }} />
|
||||
</Modal>
|
||||
<Dialog visible={editChallengeVisible} onDismiss={() => setEditChallengeVisible(false)}>
|
||||
<Dialog.Title>{editChallengeId ? "Modification d'un défi" : "Ajout d'un défi"}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<TextInput
|
||||
label="Titre"
|
||||
defaultValue={editChallengeTitle}
|
||||
onChangeText={setEditChallengeTitle}
|
||||
error={!editChallengeTitle} />
|
||||
<TextInput
|
||||
label="Description"
|
||||
defaultValue={editChallengeDescription}
|
||||
multiline={true}
|
||||
onChangeText={setEditChallengeDescription}
|
||||
error={!editChallengeDescription} />
|
||||
<TextInput
|
||||
label="Récompense"
|
||||
defaultValue={editChallengeReward ? editChallengeReward.toString() : ""}
|
||||
inputMode='numeric'
|
||||
onChangeText={(text) => setEditChallengeReward(+text)}
|
||||
error={!editChallengeReward}
|
||||
onEndEditing={() => !addChallengeMutation.isPending && editChallengeMutation.isPending && sendEditChallenge()} />
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setEditChallengeVisible(false)}>Annuler</Button>
|
||||
<Button
|
||||
onPress={sendEditChallenge}
|
||||
disabled={!editChallengeTitle || !editChallengeDescription || !editChallengeReward || addChallengeMutation.isPending || editChallengeMutation.isPending}>
|
||||
{editChallengeId ? "Modifier" : "Ajouter"}
|
||||
</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
<Dialog visible={confirmDeletedVisible} onDismiss={() => setConfirmDeleteVisible(false)}>
|
||||
<Dialog.Title>Êtes-vous sûre ?</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text variant='bodyMedium'>
|
||||
Voulez-vous vraiment supprimer le défi « {displayedChallenge?.title} » ? Cette opération est irréversible !
|
||||
</Text>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setConfirmDeleteVisible(false)}>Annuler</Button>
|
||||
<Button onPress={sendDeleteChallenge} disabled={deleteChallengeMutation.isPending}>Confirmer</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
<Dialog visible={challengeToAttach !== null} onDismiss={() => setChallengeToAttach(null)}>
|
||||
<Dialog.Title>Traiter ce défi</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text variant='bodyMedium'>
|
||||
Voulez-vous vraiment remplacer votre défi actuel par le défi « {challengeToAttach?.title} » ?
|
||||
</Text>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={() => setChallengeToAttach(null)}>Annuler</Button>
|
||||
<Button onPress={sendAttachNewChallenge} disabled={attachNewChallengeMutation.isPending}>Confirmer</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
</Surface>
|
||||
)
|
||||
}
|
||||
|
||||
type ChallengeListItemProps = {
|
||||
challenge: Challenge,
|
||||
activeRunner: boolean,
|
||||
onPress?: () => void,
|
||||
onLongPress?: () => void,
|
||||
}
|
||||
|
||||
function ChallengeListItem({ challenge, activeRunner, onPress, onLongPress }: ChallengeListItemProps) {
|
||||
const challengeActions = useChallengeActions()
|
||||
const attachedAction = challengeActions.find(challengeAction => challengeAction.challengeId === challenge.id)
|
||||
const description = <Text>Récompense : {challenge.reward} <FontAwesome6 name='coins' /></Text>
|
||||
const icon: ReactNode = useMemo(() => {
|
||||
if (!activeRunner)
|
||||
return undefined
|
||||
else if (!attachedAction)
|
||||
return <Tooltip title="Disponible"><List.Icon icon='cards' /></Tooltip>
|
||||
else if (!attachedAction.end)
|
||||
return <Tooltip title="En cours d'accomplissement"><ActivityIndicator /></Tooltip>
|
||||
else if (attachedAction.success)
|
||||
return <Tooltip title="Précédemment réussi"><List.Icon icon='emoticon-happy' /></Tooltip>
|
||||
else
|
||||
return <Tooltip title="Raté"><List.Icon icon='emoticon-sad' /></Tooltip>
|
||||
}, [activeRunner, attachedAction])
|
||||
return (
|
||||
<List.Item
|
||||
title={challenge.title}
|
||||
description={description}
|
||||
right={() => icon}
|
||||
onPress={onPress}
|
||||
onLongPress={attachedAction ? undefined : onLongPress} />
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
addButton: {
|
||||
position: 'absolute',
|
||||
right: 25,
|
||||
bottom: 25,
|
||||
}
|
||||
})
|
92
client/app/login.tsx
Normal file
@ -0,0 +1,92 @@
|
||||
import { useLoginMutation } from "@/hooks/mutations/useLoginMutation"
|
||||
import { useAuth, useAuthLogin, useAuthLogout } from "@/hooks/useAuth"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useRouter } from "expo-router"
|
||||
import { useRef, useState } from "react"
|
||||
import { Appbar, Button, Dialog, Portal, Surface, Text, TextInput } from "react-native-paper"
|
||||
|
||||
export default function Login() {
|
||||
const router = useRouter()
|
||||
|
||||
const auth = useAuth()
|
||||
const authLogin = useAuthLogin()
|
||||
const authLogout = useAuthLogout()
|
||||
|
||||
const isLoggedIn = auth.loggedIn
|
||||
const [name, setName] = useState(auth.name ?? "")
|
||||
const [password, setPassword] = useState("")
|
||||
const [errorDialogVisible, setErrorDialogVisible] = useState(false)
|
||||
const [errorTitle, setErrorTitle] = useState("")
|
||||
const [errorText, setErrorText] = useState("")
|
||||
|
||||
const loginRef = useRef<any | null>()
|
||||
const passwordRef = useRef<any | null>()
|
||||
|
||||
const hideErrorDialog = () => setErrorDialogVisible(false)
|
||||
|
||||
const loginMutation = useLoginMutation({
|
||||
authLogin,
|
||||
onPostSuccess: () => {
|
||||
if (router.canGoBack())
|
||||
router.back()
|
||||
else
|
||||
router.navigate('/')
|
||||
},
|
||||
onError: ({ response, error }) => {
|
||||
setErrorDialogVisible(true)
|
||||
if (response) {
|
||||
setErrorTitle(response.error)
|
||||
setErrorText(response.message)
|
||||
}
|
||||
else {
|
||||
setErrorTitle("Erreur")
|
||||
setErrorText(`Une erreur est survenue lors de la connexion : ${error}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Surface style={{ flex: 1 }}>
|
||||
<Appbar.Header>
|
||||
{isLoggedIn && router.canGoBack() ? <Appbar.BackAction onPress={() => router.back()} /> : undefined}
|
||||
<Appbar.Content title={"Connexion"} />
|
||||
{isLoggedIn ? <Appbar.Action icon={"logout"} onPress={authLogout} /> : undefined}
|
||||
</Appbar.Header>
|
||||
<TextInput
|
||||
ref={loginRef}
|
||||
label="Nom"
|
||||
value={name}
|
||||
onChangeText={setName}
|
||||
onSubmitEditing={() => passwordRef?.current.focus()}
|
||||
style={{ margin: 8 }} />
|
||||
<TextInput
|
||||
ref={passwordRef}
|
||||
label="Mot de passe"
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
onSubmitEditing={() => loginMutation.mutate({ name, password })}
|
||||
secureTextEntry={true}
|
||||
style={{ margin: 8 }} />
|
||||
<Button
|
||||
key={loginMutation.isPending ? "disabledLoginButton" : "loginButton"}
|
||||
onPress={() => loginMutation.mutate({ name, password })}
|
||||
mode={"contained"}
|
||||
icon="login"
|
||||
disabled={loginMutation.isPending}
|
||||
style={{ margin: 8 }}>
|
||||
Se connecter
|
||||
</Button>
|
||||
<Portal>
|
||||
<Dialog visible={errorDialogVisible} onDismiss={hideErrorDialog}>
|
||||
<Dialog.Title>{errorTitle}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text variant="bodyMedium">{errorText}</Text>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={hideErrorDialog}>Ok</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
</Surface>
|
||||
)
|
||||
}
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 13 KiB |
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 5.0 KiB |
Before Width: | Height: | Size: 6.2 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
6
client/babel.config.js
Normal file
@ -0,0 +1,6 @@
|
||||
module.exports = function(api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: ['babel-preset-expo'],
|
||||
}
|
||||
}
|
44
client/components/ChallengeCard.tsx
Normal file
@ -0,0 +1,44 @@
|
||||
import { Challenge } from "@/utils/features/challenges/challengesSlice"
|
||||
import { FontAwesome6 } from "@expo/vector-icons"
|
||||
import { View, ViewStyle } from "react-native"
|
||||
import { Button, Card, IconButton, MD3Colors, Surface, Text } from "react-native-paper"
|
||||
|
||||
export type ChallengeCardProps = {
|
||||
challenge: Challenge | null,
|
||||
onSuccess?: () => void,
|
||||
onFail?: () => void,
|
||||
onDelete?: () => void,
|
||||
onEdit?: () => void,
|
||||
style?: ViewStyle,
|
||||
}
|
||||
|
||||
export default function ChallengeCard({ challenge, onSuccess, onFail, onDelete, onEdit, style }: ChallengeCardProps) {
|
||||
return (
|
||||
<Surface elevation={2} style={{ ...style, borderRadius: 20 }}>
|
||||
<Card.Title
|
||||
title={challenge?.title}
|
||||
titleStyle={{ textAlign: 'center' }}
|
||||
titleVariant='headlineMedium'
|
||||
right={(props) => onEdit ? <IconButton {...props} icon='file-document-edit-outline' onPress={() => onEdit()} /> : <></>} />
|
||||
<View style={{ flexGrow: 1 }}>
|
||||
<Surface elevation={5} mode='flat' style={{ flexGrow: 1, paddingHorizontal: 15, paddingVertical: 20 }}>
|
||||
<Text variant='bodyLarge' style={{ flexGrow: 1 }}>{challenge?.description}</Text>
|
||||
<Text variant='titleMedium'>
|
||||
Récompense : {challenge?.reward} <FontAwesome6 name='coins' />
|
||||
</Text>
|
||||
</Surface>
|
||||
</View>
|
||||
<View style={{ flexWrap: 'wrap', flexDirection: 'row', justifyContent: 'space-around', padding: 15 }}>
|
||||
{onFail && <Button key='failBtn' mode='outlined' icon='cancel' onPress={() => onFail()}>
|
||||
Échouer
|
||||
</Button>}
|
||||
{onSuccess && <Button key='successBtn' mode='contained' icon='check' onPress={() => onSuccess()}>
|
||||
Terminer
|
||||
</Button>}
|
||||
{onDelete && <Button key='deleteBtn' mode='contained' icon='delete' onPress={() => onDelete()} buttonColor={MD3Colors.error60} textColor={MD3Colors.secondary10}>
|
||||
Supprimer
|
||||
</Button>}
|
||||
</View>
|
||||
</Surface>
|
||||
)
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
import { PropsWithChildren, useState } from 'react';
|
||||
import { StyleSheet, TouchableOpacity } from 'react-native';
|
||||
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { IconSymbol } from '@/components/ui/IconSymbol';
|
||||
import { Colors } from '@/constants/Colors';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
|
||||
export function Collapsible({ children, title }: PropsWithChildren & { title: string }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const theme = useColorScheme() ?? 'light';
|
||||
|
||||
return (
|
||||
<ThemedView>
|
||||
<TouchableOpacity
|
||||
style={styles.heading}
|
||||
onPress={() => setIsOpen((value) => !value)}
|
||||
activeOpacity={0.8}>
|
||||
<IconSymbol
|
||||
name="chevron.right"
|
||||
size={18}
|
||||
weight="medium"
|
||||
color={theme === 'light' ? Colors.light.icon : Colors.dark.icon}
|
||||
style={{ transform: [{ rotate: isOpen ? '90deg' : '0deg' }] }}
|
||||
/>
|
||||
|
||||
<ThemedText type="defaultSemiBold">{title}</ThemedText>
|
||||
</TouchableOpacity>
|
||||
{isOpen && <ThemedView style={styles.content}>{children}</ThemedView>}
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
heading: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
},
|
||||
content: {
|
||||
marginTop: 6,
|
||||
marginLeft: 24,
|
||||
},
|
||||
});
|
@ -1,24 +0,0 @@
|
||||
import { Link } from 'expo-router';
|
||||
import { openBrowserAsync } from 'expo-web-browser';
|
||||
import { type ComponentProps } from 'react';
|
||||
import { Platform } from 'react-native';
|
||||
|
||||
type Props = Omit<ComponentProps<typeof Link>, 'href'> & { href: string };
|
||||
|
||||
export function ExternalLink({ href, ...rest }: Props) {
|
||||
return (
|
||||
<Link
|
||||
target="_blank"
|
||||
{...rest}
|
||||
href={href}
|
||||
onPress={async (event) => {
|
||||
if (Platform.OS !== 'web') {
|
||||
// Prevent the default behavior of linking to the default browser on native.
|
||||
event.preventDefault();
|
||||
// Open the link in an in-app browser.
|
||||
await openBrowserAsync(href);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
50
client/components/FreeChaseBanner.tsx
Normal file
@ -0,0 +1,50 @@
|
||||
import { useGame } from "@/hooks/useGame"
|
||||
import { FontAwesome6 } from "@expo/vector-icons"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { View } from "react-native"
|
||||
import { Banner, MD3Colors, ProgressBar, Text } from "react-native-paper"
|
||||
|
||||
export default function FreeChaseBanner() {
|
||||
const game = useGame()
|
||||
const chaseFreeTime = game.chaseFreeTime
|
||||
const chaser = game.gameStarted && !game.currentRunner && chaseFreeTime !== null
|
||||
const chaseFreeDate = useMemo(() => new Date(chaseFreeTime || 0), [chaseFreeTime])
|
||||
const chaseFreePretty = chaseFreeDate.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const [remainingTime, setRemainingTime] = useState(0)
|
||||
const prettyRemainingTime = useMemo(() => `${Math.floor(remainingTime / 60).toString().padStart(2, '0')}:${Math.floor(remainingTime % 60).toString().padStart(2, '0')}`, [remainingTime])
|
||||
const iconName = useMemo(() => {
|
||||
switch (Math.abs(Math.floor(remainingTime) % 4)) {
|
||||
case 0: return 'hourglass-empty'
|
||||
case 1: return 'hourglass-end'
|
||||
case 2: return 'hourglass-half'
|
||||
case 3: return 'hourglass-start'
|
||||
}
|
||||
}, [remainingTime])
|
||||
|
||||
useEffect(() => {
|
||||
const now = new Date().getTime()
|
||||
if (!chaser || (chaseFreeTime < now && remainingTime < 0))
|
||||
return
|
||||
const interval = setInterval(() => setRemainingTime(Math.floor(chaseFreeTime - new Date().getTime()) / 1000), 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [game.gameStarted, game.currentRunner, chaseFreeDate])
|
||||
|
||||
return (
|
||||
<View>
|
||||
<ProgressBar
|
||||
visible={chaser && remainingTime > 0}
|
||||
animatedValue={1 - remainingTime / (45 * 60)}
|
||||
color={'green'}
|
||||
style={{ height: 6 }} />
|
||||
<Banner
|
||||
visible={chaser && remainingTime > 0}
|
||||
icon={({ size }) => <FontAwesome6 name={iconName} size={size} color={MD3Colors.secondary90} />}
|
||||
style={{ backgroundColor: MD3Colors.secondary40 }}>
|
||||
<View>
|
||||
<Text variant='titleMedium'>Vous pourrez commencer la poursuite à {chaseFreePretty}.</Text>
|
||||
<Text variant='titleSmall'>Temps restant : {prettyRemainingTime}</Text>
|
||||
</View>
|
||||
</Banner>
|
||||
</View>
|
||||
)
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
import { BottomTabBarButtonProps } from '@react-navigation/bottom-tabs';
|
||||
import { PlatformPressable } from '@react-navigation/elements';
|
||||
import * as Haptics from 'expo-haptics';
|
||||
|
||||
export function HapticTab(props: BottomTabBarButtonProps) {
|
||||
return (
|
||||
<PlatformPressable
|
||||
{...props}
|
||||
onPressIn={(ev) => {
|
||||
if (process.env.EXPO_OS === 'ios') {
|
||||
// Add a soft haptic feedback when pressing down on the tabs.
|
||||
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
props.onPressIn?.(ev);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
import { StyleSheet } from 'react-native';
|
||||
import Animated, {
|
||||
useSharedValue,
|
||||
useAnimatedStyle,
|
||||
withTiming,
|
||||
withRepeat,
|
||||
withSequence,
|
||||
} from 'react-native-reanimated';
|
||||
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
|
||||
export function HelloWave() {
|
||||
const rotationAnimation = useSharedValue(0);
|
||||
|
||||
rotationAnimation.value = withRepeat(
|
||||
withSequence(withTiming(25, { duration: 150 }), withTiming(0, { duration: 150 })),
|
||||
4 // Run the animation 4 times
|
||||
);
|
||||
|
||||
const animatedStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ rotate: `${rotationAnimation.value}deg` }],
|
||||
}));
|
||||
|
||||
return (
|
||||
<Animated.View style={animatedStyle}>
|
||||
<ThemedText style={styles.text}>👋</ThemedText>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
text: {
|
||||
fontSize: 28,
|
||||
lineHeight: 32,
|
||||
marginTop: -6,
|
||||
},
|
||||
});
|
0
client/components/LoginButton.tsx
Normal file
182
client/components/Map.tsx
Normal file
@ -0,0 +1,182 @@
|
||||
import { FontAwesome5, MaterialIcons } from '@expo/vector-icons'
|
||||
import MapLibreGL, { Camera, FillLayer, LineLayer, MapView, PointAnnotation, RasterLayer, RasterSource, ShapeSource, UserLocation, UserTrackingMode } from '@maplibre/maplibre-react-native'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { circle } from '@turf/circle'
|
||||
import { reverseGeocodeAsync } from 'expo-location'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { StyleSheet } from 'react-native'
|
||||
import { Button, Dialog, FAB, Portal, Text } from 'react-native-paper'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useGame } from '@/hooks/useGame'
|
||||
import { useLastOwnLocation, useLastPlayerLocations } from '@/hooks/useLocation'
|
||||
import { isAuthValid } from '@/utils/features/auth/authSlice'
|
||||
import { Player } from '@/utils/features/game/gameSlice'
|
||||
import { PlayerLocation } from '@/utils/features/location/locationSlice'
|
||||
|
||||
export default function Map() {
|
||||
const [followUser, setFollowUser] = useState(true)
|
||||
|
||||
return (
|
||||
<>
|
||||
<MapWrapper followUser={followUser} setFollowUser={setFollowUser} />
|
||||
<FollowUserButton key={'follow-userr-btn-component'} followUser={followUser} setFollowUser={setFollowUser} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type FollowUserProps = {
|
||||
followUser: boolean,
|
||||
setFollowUser: React.Dispatch<React.SetStateAction<boolean>>,
|
||||
}
|
||||
|
||||
function MapWrapper({ followUser, setFollowUser }: FollowUserProps) {
|
||||
const [displayedPlayerId, setDisplayedPlayerId] = useState<number | null>(null)
|
||||
return (
|
||||
<>
|
||||
<MapComponent followUser={followUser} setFollowUser={setFollowUser} setDisplayedPlayerId={setDisplayedPlayerId} />
|
||||
<Portal>
|
||||
<PlayerLocationDialog displayedPlayerId={displayedPlayerId} onDismiss={() => setDisplayedPlayerId(null)} />
|
||||
</Portal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type MapComponentProps = {
|
||||
followUser?: boolean,
|
||||
setFollowUser: React.Dispatch<React.SetStateAction<boolean>>,
|
||||
setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>>
|
||||
}
|
||||
|
||||
function MapComponent({ followUser, setFollowUser, setDisplayedPlayerId }: MapComponentProps) {
|
||||
MapLibreGL.setAccessToken(null)
|
||||
const userLocation = useLastOwnLocation()
|
||||
return (
|
||||
<MapView
|
||||
logoEnabled={false}
|
||||
compassViewPosition={2}
|
||||
style={styles.map}
|
||||
styleURL="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
|
||||
{userLocation && <Camera
|
||||
defaultSettings={{centerCoordinate: [userLocation?.coords.longitude, userLocation?.coords.latitude], zoomLevel: 15}}
|
||||
followUserLocation={followUser}
|
||||
followUserMode={UserTrackingMode.Follow}
|
||||
followZoomLevel={16}
|
||||
onUserTrackingModeChange={(event) => {
|
||||
if (followUser && !event.nativeEvent.payload.followUserLocation)
|
||||
setFollowUser(false)
|
||||
}} />}
|
||||
|
||||
<RasterSource id="railwaymap-source" tileUrlTemplates={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]}></RasterSource>
|
||||
<RasterLayer id="railwaymap-layer" sourceID="railwaymap-source" style={{rasterOpacity: 0.7}} />
|
||||
|
||||
<UserLocation animated={true} renderMode="native" androidRenderMode="compass" showsUserHeadingIndicator={true} />
|
||||
<PlayerLocationsMarkers setDisplayedPlayerId={setDisplayedPlayerId} />
|
||||
</MapView>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function PlayerLocationsMarkers({ setDisplayedPlayerId }: { setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>> }) {
|
||||
const game = useGame()
|
||||
const lastPlayerLocations = useLastPlayerLocations()
|
||||
return lastPlayerLocations ? lastPlayerLocations
|
||||
.filter(() => !game.currentRunner || !game.gameStarted)
|
||||
.filter(playerLoc => playerLoc.playerId !== game.playerId)
|
||||
.map(playerLoc => <PlayerLocationMarker key={`player-${playerLoc.playerId}-loc`} playerLocation={playerLoc} setDisplayedPlayerId={setDisplayedPlayerId} />) : <></>
|
||||
}
|
||||
|
||||
function PlayerLocationMarker({ playerLocation, setDisplayedPlayerId }: { playerLocation: PlayerLocation, setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>> }) {
|
||||
const accuracyCircle = useMemo(() => circle([playerLocation.longitude, playerLocation.latitude], playerLocation.accuracy, {steps: 64, units: 'meters'}), [playerLocation])
|
||||
return <>
|
||||
<ShapeSource
|
||||
id={`accuracy-radius-${playerLocation.playerId}`}
|
||||
shape={accuracyCircle} />
|
||||
<FillLayer
|
||||
id={`accuracy-radius-fill-${playerLocation.playerId}`}
|
||||
sourceID={`accuracy-radius-${playerLocation.playerId}`}
|
||||
style={{fillOpacity: 0.4, fillColor: 'pink'}}
|
||||
aboveLayerID="railwaymap-layer" />
|
||||
<LineLayer
|
||||
id={`accuracy-radius-border-${playerLocation.playerId}`}
|
||||
sourceID={`accuracy-radius-${playerLocation.playerId}`}
|
||||
style={{lineOpacity: 0.4, lineColor: 'red'}}
|
||||
aboveLayerID={`accuracy-radius-fill-${playerLocation.playerId}`} />
|
||||
<PointAnnotation id={`player-location-marker-${playerLocation.playerId}`}
|
||||
coordinate={[playerLocation.longitude, playerLocation.latitude]}
|
||||
onSelected={() => { setDisplayedPlayerId(playerLocation.playerId) }}>
|
||||
<FontAwesome5 name="map-marker-alt" size={24} color="red" />
|
||||
</PointAnnotation>
|
||||
</>
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
map: {
|
||||
flex: 1,
|
||||
alignSelf: 'stretch',
|
||||
}
|
||||
})
|
||||
|
||||
function FollowUserButton({ followUser, setFollowUser }: FollowUserProps) {
|
||||
return (
|
||||
<FAB
|
||||
key={'follow-user-btn'}
|
||||
style={{ position: 'absolute', right: 25, bottom: 25 }}
|
||||
icon={(props) => <MaterialIcons name={followUser ? 'my-location' : 'location-searching'} {...props} />}
|
||||
onPress={() => setFollowUser(followUser => !followUser)} />
|
||||
)
|
||||
}
|
||||
|
||||
function PlayerLocationDialog({ displayedPlayerId, onDismiss }: { displayedPlayerId: number | null, onDismiss: () => void }) {
|
||||
const auth = useAuth()
|
||||
const lastPlayerLocations = useLastPlayerLocations()
|
||||
const playersQuery = useQuery({
|
||||
queryKey: ['get-players', auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/players/`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth),
|
||||
initialData: { data: [], meta: { currentPage: 0, lastPage: 0, nextPage: 0, prevPage: 0, total: 0, totalPerPage: 0 } },
|
||||
})
|
||||
|
||||
const displayedPlayerLoc = useMemo(() => {
|
||||
return lastPlayerLocations.find(loc => loc.playerId === displayedPlayerId)
|
||||
}, [displayedPlayerId, lastPlayerLocations])
|
||||
|
||||
const displayedPlayerName = useMemo(() => {
|
||||
if (!playersQuery.isSuccess || !displayedPlayerId)
|
||||
return "Chargement…"
|
||||
const player: Player | undefined = playersQuery.data.data.find((player: Player) => player.id === displayedPlayerId)
|
||||
if (!player)
|
||||
return "Chargement…"
|
||||
return player.name
|
||||
}, [displayedPlayerId, playersQuery])
|
||||
|
||||
const [address, setAddress] = useState("Adresse inconnue")
|
||||
useEffect(() => {
|
||||
if (!displayedPlayerLoc)
|
||||
return setAddress("Adresse inconnue")
|
||||
reverseGeocodeAsync(displayedPlayerLoc).then(addresses => setAddress(addresses[0].formattedAddress ?? "Adresse inconnue"))
|
||||
}, [displayedPlayerLoc])
|
||||
|
||||
return (
|
||||
<Dialog visible={displayedPlayerId !== null} onDismiss={onDismiss}>
|
||||
<Dialog.Title>{displayedPlayerName}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Text>
|
||||
Dernière position : {new Date(displayedPlayerLoc?.timestamp ?? 0).toLocaleString()}
|
||||
</Text>
|
||||
<Text>
|
||||
Précision : {displayedPlayerLoc?.accuracy.toPrecision(3)} m
|
||||
</Text>
|
||||
<Text>
|
||||
Adresse estimée : {address}
|
||||
</Text>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={onDismiss}>
|
||||
Fermer
|
||||
</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
77
client/components/Map.web.tsx
Normal file
@ -0,0 +1,77 @@
|
||||
import { useGame } from "@/hooks/useGame"
|
||||
import { useLastOwnLocation, useLastPlayerLocations } from "@/hooks/useLocation"
|
||||
import { PlayerLocation } from "@/utils/features/location/locationSlice"
|
||||
import { circle } from "@turf/circle"
|
||||
import { type Map as MaplibreGLMap } from "maplibre-gl"
|
||||
import { RLayer, RMap, RMarker, RNavigationControl, RSource, useMap } from "maplibre-react-components"
|
||||
import { useMemo, useState } from "react"
|
||||
|
||||
export default function Map() {
|
||||
return (
|
||||
<RMap
|
||||
initialCenter={[2.9, 46.5]}
|
||||
initialZoom={6}
|
||||
mapStyle="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
|
||||
<RNavigationControl position="bottom-right" showCompass={true} showZoom={true} visualizePitch={true} />
|
||||
|
||||
<RSource id="railwaymap-source" type="raster" tiles={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]} />
|
||||
<RLayer id="railwaymap-layer" type="raster" source="railwaymap-source" paint={{"raster-opacity": 0.7}} />
|
||||
|
||||
<UserLocation />
|
||||
<PlayerLocationsMarkers />
|
||||
</RMap>
|
||||
)
|
||||
}
|
||||
|
||||
function UserLocation() {
|
||||
const userLocation = useLastOwnLocation()
|
||||
const [firstUserPositionFetched, setFirstUserPositionFetched] = useState(false)
|
||||
const map: MaplibreGLMap = useMap()
|
||||
if (userLocation != null && !firstUserPositionFetched) {
|
||||
setFirstUserPositionFetched(true)
|
||||
map.flyTo({center: [userLocation.coords.longitude, userLocation.coords.latitude], zoom: 15})
|
||||
}
|
||||
const accuracyCircle = circle([userLocation?.coords.longitude ?? 0, userLocation?.coords.latitude ?? 0], userLocation?.coords.accuracy ?? 0, {steps: 64, units: 'meters'})
|
||||
const marker = userLocation ? <RMarker longitude={userLocation?.coords.longitude} latitude={userLocation?.coords.latitude} /> : <></>
|
||||
return <>
|
||||
<RSource id={'accuracy-radius-own'} type="geojson" data={accuracyCircle} />
|
||||
<RLayer id={'accuracy-radius-fill-own'} type="fill" source='accuracy-radius-own' paint={{"fill-color": "lightblue", "fill-opacity": 0.4}} />
|
||||
<RLayer id={'accuracy-radius-border'} type="line" source='accuracy-radius-own' paint={{"line-color": "blue", "line-opacity": 0.4}} />
|
||||
{marker}
|
||||
</>
|
||||
}
|
||||
|
||||
function PlayerLocationsMarkers() {
|
||||
const game = useGame()
|
||||
const lastPlayerLocations = useLastPlayerLocations()
|
||||
return lastPlayerLocations
|
||||
// .filter(playerLoc => playerLoc.playerId !== game.playerId)
|
||||
.map(playerLoc => <PlayerLocationMarker key={`player-${playerLoc.playerId}-loc`} playerLocation={playerLoc} />)
|
||||
}
|
||||
|
||||
function PlayerLocationMarker({ playerLocation }: { playerLocation: PlayerLocation }) {
|
||||
const map: MaplibreGLMap = useMap()
|
||||
const accuracyCircle = useMemo(() => circle(
|
||||
[playerLocation.longitude, playerLocation.latitude],
|
||||
playerLocation.accuracy,
|
||||
{steps: 64, units: 'meters'}), [playerLocation])
|
||||
return <>
|
||||
<RSource
|
||||
id={`accuracy-radius-${playerLocation.playerId}`}
|
||||
type="geojson"
|
||||
data={accuracyCircle} />
|
||||
<RLayer
|
||||
id={`accuracy-radius-fill-${playerLocation.playerId}`}
|
||||
type="fill" source={`accuracy-radius-${playerLocation.playerId}`}
|
||||
paint={{"fill-color": "pink", "fill-opacity": 0.4}} />
|
||||
<RLayer
|
||||
id={`accuracy-radius-border-${playerLocation.playerId}`}
|
||||
type="line"
|
||||
source={`accuracy-radius-${playerLocation.playerId}`}
|
||||
paint={{"line-color": "red", "line-opacity": 0.4}} />
|
||||
<RMarker
|
||||
key={`marker-player-${playerLocation.playerId}`}
|
||||
longitude={playerLocation.longitude}
|
||||
latitude={playerLocation.latitude} />
|
||||
</>
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
import type { PropsWithChildren, ReactElement } from 'react';
|
||||
import { StyleSheet } from 'react-native';
|
||||
import Animated, {
|
||||
interpolate,
|
||||
useAnimatedRef,
|
||||
useAnimatedStyle,
|
||||
useScrollViewOffset,
|
||||
} from 'react-native-reanimated';
|
||||
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { useBottomTabOverflow } from '@/components/ui/TabBarBackground';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
|
||||
const HEADER_HEIGHT = 250;
|
||||
|
||||
type Props = PropsWithChildren<{
|
||||
headerImage: ReactElement;
|
||||
headerBackgroundColor: { dark: string; light: string };
|
||||
}>;
|
||||
|
||||
export default function ParallaxScrollView({
|
||||
children,
|
||||
headerImage,
|
||||
headerBackgroundColor,
|
||||
}: Props) {
|
||||
const colorScheme = useColorScheme() ?? 'light';
|
||||
const scrollRef = useAnimatedRef<Animated.ScrollView>();
|
||||
const scrollOffset = useScrollViewOffset(scrollRef);
|
||||
const bottom = useBottomTabOverflow();
|
||||
const headerAnimatedStyle = useAnimatedStyle(() => {
|
||||
return {
|
||||
transform: [
|
||||
{
|
||||
translateY: interpolate(
|
||||
scrollOffset.value,
|
||||
[-HEADER_HEIGHT, 0, HEADER_HEIGHT],
|
||||
[-HEADER_HEIGHT / 2, 0, HEADER_HEIGHT * 0.75]
|
||||
),
|
||||
},
|
||||
{
|
||||
scale: interpolate(scrollOffset.value, [-HEADER_HEIGHT, 0, HEADER_HEIGHT], [2, 1, 1]),
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
<Animated.ScrollView
|
||||
ref={scrollRef}
|
||||
scrollEventThrottle={16}
|
||||
scrollIndicatorInsets={{ bottom }}
|
||||
contentContainerStyle={{ paddingBottom: bottom }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.header,
|
||||
{ backgroundColor: headerBackgroundColor[colorScheme] },
|
||||
headerAnimatedStyle,
|
||||
]}>
|
||||
{headerImage}
|
||||
</Animated.View>
|
||||
<ThemedView style={styles.content}>{children}</ThemedView>
|
||||
</Animated.ScrollView>
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
header: {
|
||||
height: HEADER_HEIGHT,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
padding: 32,
|
||||
gap: 16,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
});
|
49
client/components/PenalyBanner.tsx
Normal file
@ -0,0 +1,49 @@
|
||||
import { useGame } from "@/hooks/useGame"
|
||||
import { FontAwesome6 } from "@expo/vector-icons"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { View } from "react-native"
|
||||
import { Banner, MD3Colors, ProgressBar, Text } from "react-native-paper"
|
||||
|
||||
export default function PenaltyBanner() {
|
||||
const game = useGame()
|
||||
const penaltyEnd = game.penaltyEnd
|
||||
const hasPenalty = penaltyEnd !== null
|
||||
const penaltyEndDate = useMemo(() => new Date(penaltyEnd || 0), [penaltyEnd])
|
||||
const penaltyEndPretty = penaltyEndDate.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
|
||||
const [remainingTime, setRemainingTime] = useState(0)
|
||||
const prettyRemainingTime = useMemo(() => `${Math.floor(remainingTime / 60).toString().padStart(2, '0')}:${Math.floor(remainingTime % 60).toString().padStart(2, '0')}`, [remainingTime])
|
||||
const iconName = useMemo(() => {
|
||||
switch (Math.abs(remainingTime % 4)) {
|
||||
case 0: return 'hourglass-empty'
|
||||
case 1: return 'hourglass-end'
|
||||
case 2: return 'hourglass-half'
|
||||
case 3: return 'hourglass-start'
|
||||
}
|
||||
}, [remainingTime])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasPenalty)
|
||||
return
|
||||
const interval = setInterval(() => setRemainingTime(Math.floor((penaltyEndDate.getTime() - new Date().getTime()) / 1000)), 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [hasPenalty, penaltyEndDate])
|
||||
|
||||
return (
|
||||
<View>
|
||||
<Banner
|
||||
visible={hasPenalty}
|
||||
icon={({ size }) => <FontAwesome6 name={iconName} size={size} color={MD3Colors.tertiary80} />}
|
||||
style={{ backgroundColor: MD3Colors.primary30 }}>
|
||||
<View>
|
||||
<Text variant='titleMedium'>Vous avez actuellement une pénalité jusqu'à {penaltyEndPretty}.</Text>
|
||||
<Text variant='titleSmall'>Temps restant : {prettyRemainingTime}</Text>
|
||||
</View>
|
||||
</Banner>
|
||||
<ProgressBar
|
||||
visible={hasPenalty}
|
||||
animatedValue={1 - remainingTime / (30 * 60)}
|
||||
color={MD3Colors.error40}
|
||||
style={{ height: 6 }} />
|
||||
</View>
|
||||
)
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
import { Text, type TextProps, StyleSheet } from 'react-native';
|
||||
|
||||
import { useThemeColor } from '@/hooks/useThemeColor';
|
||||
|
||||
export type ThemedTextProps = TextProps & {
|
||||
lightColor?: string;
|
||||
darkColor?: string;
|
||||
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
|
||||
};
|
||||
|
||||
export function ThemedText({
|
||||
style,
|
||||
lightColor,
|
||||
darkColor,
|
||||
type = 'default',
|
||||
...rest
|
||||
}: ThemedTextProps) {
|
||||
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
|
||||
|
||||
return (
|
||||
<Text
|
||||
style={[
|
||||
{ color },
|
||||
type === 'default' ? styles.default : undefined,
|
||||
type === 'title' ? styles.title : undefined,
|
||||
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
|
||||
type === 'subtitle' ? styles.subtitle : undefined,
|
||||
type === 'link' ? styles.link : undefined,
|
||||
style,
|
||||
]}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
default: {
|
||||
fontSize: 16,
|
||||
lineHeight: 24,
|
||||
},
|
||||
defaultSemiBold: {
|
||||
fontSize: 16,
|
||||
lineHeight: 24,
|
||||
fontWeight: '600',
|
||||
},
|
||||
title: {
|
||||
fontSize: 32,
|
||||
fontWeight: 'bold',
|
||||
lineHeight: 32,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
link: {
|
||||
lineHeight: 30,
|
||||
fontSize: 16,
|
||||
color: '#0a7ea4',
|
||||
},
|
||||
});
|
@ -1,14 +0,0 @@
|
||||
import { View, type ViewProps } from 'react-native';
|
||||
|
||||
import { useThemeColor } from '@/hooks/useThemeColor';
|
||||
|
||||
export type ThemedViewProps = ViewProps & {
|
||||
lightColor?: string;
|
||||
darkColor?: string;
|
||||
};
|
||||
|
||||
export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) {
|
||||
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
|
||||
|
||||
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
|
||||
}
|
@ -1,10 +1,10 @@
|
||||
import * as React from 'react';
|
||||
import renderer from 'react-test-renderer';
|
||||
import * as React from 'react'
|
||||
import renderer from 'react-test-renderer'
|
||||
|
||||
import { ThemedText } from '../ThemedText';
|
||||
import { ThemedText } from '../ThemedText'
|
||||
|
||||
it(`renders correctly`, () => {
|
||||
const tree = renderer.create(<ThemedText>Snapshot test!</ThemedText>).toJSON();
|
||||
const tree = renderer.create(<ThemedText>Snapshot test!</ThemedText>).toJSON()
|
||||
|
||||
expect(tree).toMatchSnapshot();
|
||||
});
|
||||
expect(tree).toMatchSnapshot()
|
||||
})
|
||||
|
@ -21,4 +21,4 @@ exports[`renders correctly 1`] = `
|
||||
>
|
||||
Snapshot test!
|
||||
</Text>
|
||||
`;
|
||||
`
|
||||
|
@ -1,38 +0,0 @@
|
||||
import { StyleSheet, Text } from 'react-native'
|
||||
import MapLibreGL, { Camera, FillLayer, LineLayer, MapView, PointAnnotation, RasterLayer, RasterSource, ShapeSource, UserLocation } from '@maplibre/maplibre-react-native'
|
||||
import { LocationObject } from 'expo-location'
|
||||
import { FontAwesome5 } from '@expo/vector-icons'
|
||||
import { circle } from '@turf/circle'
|
||||
|
||||
export default function Map({ location }: { location: LocationObject | null }) {
|
||||
MapLibreGL.setAccessToken(null)
|
||||
const accuracyCircle = circle([location?.coords.longitude ?? 0, location?.coords.latitude ?? 0], location?.coords.accuracy ?? 0, {steps: 64, units: 'meters'})
|
||||
return (
|
||||
<MapView
|
||||
logoEnabled={true}
|
||||
style={styles.map}
|
||||
styleURL="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
|
||||
{/* FIXME Il faudra pouvoir avoir un bouton de suivi pour activer le suivi de la caméro */}
|
||||
{location && <Camera
|
||||
defaultSettings={{centerCoordinate: [location?.coords.longitude, location?.coords.latitude], zoomLevel: 15}} />}
|
||||
<RasterSource id="railwaymap-source" tileUrlTemplates={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]}></RasterSource>
|
||||
<RasterLayer id="railwaymap-layer" sourceID="railwaymap-source" style={{rasterOpacity: 0.7}} />
|
||||
|
||||
{/* FIXME Il faudra avoir uniquement les positions des autres personnes, puisque sa propre position peut être obtenue nativement */}
|
||||
<ShapeSource id="accuracy-radius" shape={accuracyCircle} />
|
||||
<FillLayer id="accuracy-radius-fill" sourceID="accuracy-radius" style={{fillOpacity: 0.4, fillColor: 'lightblue'}} aboveLayerID="railwaymap-layer" />
|
||||
<LineLayer id="accuracy-radius-border" sourceID="accuracy-radius" style={{lineOpacity: 0.4, lineColor: 'blue'}} aboveLayerID="accuracy-radius-fill" />
|
||||
<PointAnnotation id="current-location" coordinate={[location?.coords.longitude ?? 0, location?.coords.latitude ?? 0]}>
|
||||
<FontAwesome5 name="map-marker-alt" size={24} color="blue" />
|
||||
</PointAnnotation>
|
||||
{/* <UserLocation animated={true} renderMode="native" androidRenderMode="compass" showsUserHeadingIndicator={true} /> */}
|
||||
</MapView>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
map: {
|
||||
flex: 1,
|
||||
alignSelf: 'stretch',
|
||||
}
|
||||
})
|
@ -1,26 +0,0 @@
|
||||
import { circle } from "@turf/circle"
|
||||
import { LocationObject } from "expo-location"
|
||||
import { RLayer, RMap, RMarker, RNavigationControl, RSource } from "maplibre-react-components"
|
||||
|
||||
export default function Map({ location }: { location: LocationObject }) {
|
||||
if (!location)
|
||||
// FIXME On devrait avoir la position qui se centre sur la position une fois qu'elle est établie
|
||||
return <></>
|
||||
const accuracyCircle = circle([location?.coords.longitude ?? 0, location?.coords.latitude ?? 0], location?.coords.accuracy ?? 0, {steps: 64, units: 'meters'})
|
||||
return (
|
||||
<RMap
|
||||
initialCenter={[location?.coords.longitude, location?.coords.latitude]}
|
||||
initialZoom={15}
|
||||
mapStyle="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
|
||||
<RNavigationControl position="bottom-right" showCompass={true} showZoom={true} visualizePitch={true} />
|
||||
|
||||
<RSource id="railwaymap-source" type="raster" tiles={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]} />
|
||||
<RLayer id="railwaymap-layer" type="raster" source="railwaymap-source" paint={{"raster-opacity": 0.7}} />
|
||||
|
||||
<RSource id="accuracy-radius" type="geojson" data={accuracyCircle} />
|
||||
<RLayer id="accuracy-radius-fill" type="fill" source="accuracy-radius" paint={{"fill-color": "lightblue", "fill-opacity": 0.4}} />
|
||||
<RLayer id="accuracy-radius-border" type="line" source="accuracy-radius" paint={{"line-color": "blue", "line-opacity": 0.4}} />
|
||||
{location && <RMarker longitude={location?.coords.longitude} latitude={location?.coords.latitude} />}
|
||||
</RMap>
|
||||
)
|
||||
}
|
126
client/components/providers/GameProvider.tsx
Normal file
@ -0,0 +1,126 @@
|
||||
import { Constants } from '@/constants/Constants'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useChallengeActions, useDownloadChallengeActions } from '@/hooks/useChallengeActions'
|
||||
import { useDownloadChallenges } from '@/hooks/useChallenges'
|
||||
import { useGame, useUpdateActiveChallengeId, useUpdateGameState, useUpdateMoney, useUpdatePenalty } from '@/hooks/useGame'
|
||||
import { useDownloadMoneyUpdates } from '@/hooks/useMoneyUpdates'
|
||||
import { useDownloadTrains } from '@/hooks/useTrain'
|
||||
import { isAuthValid } from '@/utils/features/auth/authSlice'
|
||||
import { ChallengeAction, ChallengeActionPayload } from '@/utils/features/challengeActions/challengeActionsSlice'
|
||||
import { Challenge } from '@/utils/features/challenges/challengesSlice'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { router } from 'expo-router'
|
||||
import { useShareIntentContext } from 'expo-share-intent'
|
||||
import React, { ReactNode, useEffect } from 'react'
|
||||
|
||||
export default function GameProvider({ children }: { children: ReactNode }) {
|
||||
const auth = useAuth()
|
||||
const game = useGame()
|
||||
const challengeActions = useChallengeActions()
|
||||
const updateGameState = useUpdateGameState()
|
||||
const updatePenalty = useUpdatePenalty()
|
||||
const updateMoney = useUpdateMoney()
|
||||
const updateActiveChallengeId = useUpdateActiveChallengeId()
|
||||
const downloadTrains = useDownloadTrains()
|
||||
const downloadChallenges = useDownloadChallenges()
|
||||
const downloadChallengeActions = useDownloadChallengeActions()
|
||||
const downloadMoneyUpdates = useDownloadMoneyUpdates()
|
||||
|
||||
const gameQuery = useQuery({
|
||||
queryKey: ['get-game', auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth),
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (gameQuery.isSuccess && gameQuery.data)
|
||||
updateGameState(gameQuery.data)
|
||||
}, [gameQuery.status, gameQuery.dataUpdatedAt])
|
||||
|
||||
const playerQuery = useQuery({
|
||||
queryKey: ['get-player', game.playerId, auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/players/${game.playerId}/`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth) && !!game.playerId,
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (playerQuery.isSuccess && playerQuery.data) {
|
||||
updateMoney(playerQuery.data.money)
|
||||
updateActiveChallengeId(playerQuery.data.activeChallengeId)
|
||||
}
|
||||
}, [playerQuery.status, playerQuery.dataUpdatedAt])
|
||||
|
||||
const trainsQuery = useQuery({
|
||||
queryKey: ['get-trains', game.playerId, auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/?playerId=${game.playerId}&size=10000`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth) && !!game.playerId,
|
||||
initialData: { data: [], meta: { currentPage: 0, lastPage: 0, nextPage: 0, prevPage: 0, total: 0, totalPerPage: 0 } },
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (trainsQuery.isSuccess && trainsQuery.data)
|
||||
downloadTrains(trainsQuery.data)
|
||||
}, [trainsQuery.status, trainsQuery.dataUpdatedAt])
|
||||
|
||||
const challengesQuery = useQuery({
|
||||
queryKey: ['get-challenges', auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/?size=10000`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth),
|
||||
initialData: { data: [], meta: { currentPage: 0, lastPage: 0, nextPage: 0, prevPage: 0, total: 0, totalPerPage: 0 } },
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (challengesQuery.isSuccess && challengesQuery.data) {
|
||||
downloadChallenges(challengesQuery.data)
|
||||
const dataWithPlayerActions = challengesQuery.data.data.filter(
|
||||
(challenge: (Challenge & {action: ChallengeActionPayload | null})) => challenge.action !== null && challenge.action.playerId === game.playerId)
|
||||
downloadChallengeActions({ data: dataWithPlayerActions })
|
||||
}
|
||||
}, [challengesQuery.status, challengesQuery.dataUpdatedAt])
|
||||
|
||||
const moneyUpdatesQuery = useQuery({
|
||||
queryKey: ['get-money-updates', game.playerId, auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/money-updates/?playerId=${game.playerId}&size=10000`, {
|
||||
headers: { "Authorization": `Bearer ${auth.token}` }}
|
||||
).then(resp => resp.json()),
|
||||
enabled: isAuthValid(auth) && !!game.playerId,
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (moneyUpdatesQuery.isSuccess && moneyUpdatesQuery.data)
|
||||
downloadMoneyUpdates(moneyUpdatesQuery.data)
|
||||
}, [moneyUpdatesQuery.status, moneyUpdatesQuery.dataUpdatedAt])
|
||||
|
||||
useEffect(() => {
|
||||
const now = new Date().getTime()
|
||||
const activeChallenge: ChallengeAction | undefined = challengeActions
|
||||
.find(challengeAction => challengeAction.penaltyStart && challengeAction.penaltyEnd
|
||||
&& challengeAction.penaltyStart <= now && now <= challengeAction.penaltyEnd)
|
||||
if (!activeChallenge || !game.currentRunner || game.runId !== activeChallenge.runId)
|
||||
updatePenalty({ penaltyStart: null, penaltyEnd: null })
|
||||
else if (activeChallenge && (activeChallenge.penaltyStart !== game.penaltyStart || activeChallenge.penaltyEnd)) {
|
||||
updatePenalty({ penaltyStart: activeChallenge.penaltyStart, penaltyEnd: activeChallenge.penaltyEnd })
|
||||
}
|
||||
}, [game.currentRunner, challengeActions])
|
||||
|
||||
const { hasShareIntent, shareIntent, resetShareIntent } = useShareIntentContext()
|
||||
useEffect(() => {
|
||||
if (hasShareIntent) {
|
||||
if (!shareIntent.text || !shareIntent.text.includes("eurailapp.com/share"))
|
||||
return resetShareIntent()
|
||||
router.replace('/train')
|
||||
}
|
||||
}, [hasShareIntent])
|
||||
|
||||
return <>
|
||||
{children}
|
||||
</>
|
||||
}
|
81
client/components/providers/GeolocationProvider.tsx
Normal file
@ -0,0 +1,81 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import React, { ReactNode, useEffect } from 'react'
|
||||
import { Platform } from 'react-native'
|
||||
import { Constants } from '@/constants/Constants'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useSetLocationAccuracy } from '@/hooks/useGame'
|
||||
import { useGeolocationMutation } from '@/hooks/mutations/useGeolocationMutation'
|
||||
import { useQueuedLocations, useSetLastPlayerLocation, useSetLastPlayerLocations, useUnqueueLocation } from '@/hooks/useLocation'
|
||||
import { isAuthValid } from '@/utils/features/auth/authSlice'
|
||||
import { PlayerLocation } from '@/utils/features/location/locationSlice'
|
||||
import { useStartGeolocationServiceEffect } from '@/utils/geolocation'
|
||||
import * as SecureStore from '@/utils/SecureStore'
|
||||
import { socket } from '@/utils/socket'
|
||||
import { Accuracy } from 'expo-location'
|
||||
|
||||
export default function GeolocationProvider({ children }: { children: ReactNode }) {
|
||||
useStartGeolocationServiceEffect()
|
||||
|
||||
const auth = useAuth()
|
||||
const setLocationAccuracy = useSetLocationAccuracy()
|
||||
const geolocationsQueue = useQueuedLocations()
|
||||
const unqueueLocation = useUnqueueLocation()
|
||||
const setLastPlayerLocations = useSetLastPlayerLocations()
|
||||
const setLastPlayerLocation = useSetLastPlayerLocation()
|
||||
const geolocationMutation = useGeolocationMutation({
|
||||
auth,
|
||||
onPostSuccess: (data, variables) => unqueueLocation(variables),
|
||||
onError: ({ response, error }) => console.error(response, error),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
SecureStore.getItemAsync('locationAccuracy').then(locationAccuracyString => {
|
||||
if (!locationAccuracyString)
|
||||
setLocationAccuracy(Accuracy.Balanced)
|
||||
else if (locationAccuracyString === 'null')
|
||||
setLocationAccuracy(null)
|
||||
else
|
||||
setLocationAccuracy(+locationAccuracyString)
|
||||
})
|
||||
}, [])
|
||||
|
||||
if (Platform.OS !== "web") {
|
||||
useEffect(() => {
|
||||
if (geolocationsQueue.length === 0 || geolocationMutation.isPending || !isAuthValid(auth))
|
||||
return
|
||||
const locToSend = geolocationsQueue[0]
|
||||
geolocationMutation.mutate(locToSend)
|
||||
}, [auth, geolocationMutation.status, geolocationsQueue])
|
||||
}
|
||||
|
||||
const lastLocationsQuery = useQuery({
|
||||
queryKey: ['get-last-locations', auth.token],
|
||||
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/last-locations/`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json()),
|
||||
initialData: [],
|
||||
enabled: isAuthValid(auth),
|
||||
refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000,
|
||||
})
|
||||
useEffect(() => {
|
||||
if (lastLocationsQuery.isSuccess && lastLocationsQuery.data)
|
||||
setLastPlayerLocations(lastLocationsQuery.data)
|
||||
}, [lastLocationsQuery.status, lastLocationsQuery.dataUpdatedAt])
|
||||
|
||||
useEffect(() => {
|
||||
const locationListener = async (data: PlayerLocation) => {
|
||||
if (data.playerId)
|
||||
setLastPlayerLocation(data)
|
||||
}
|
||||
socket.on('last-location', locationListener)
|
||||
return () => { socket.off('last-location', locationListener) }
|
||||
}, [])
|
||||
|
||||
return <>
|
||||
{children}
|
||||
</>
|
||||
}
|
77
client/components/providers/LoginProvider.tsx
Normal file
@ -0,0 +1,77 @@
|
||||
import { Href, useRouter } from 'expo-router'
|
||||
import { useRouteInfo } from 'expo-router/build/hooks'
|
||||
import React, { ReactNode, useEffect } from 'react'
|
||||
import { useAuth, useAuthLogin } from '@/hooks/useAuth'
|
||||
import * as SecureStore from '@/utils/SecureStore'
|
||||
import { useLoginMutation } from '@/hooks/mutations/useLoginMutation'
|
||||
import { useGame, useSetPlayerId } from '@/hooks/useGame'
|
||||
|
||||
type Props = {
|
||||
loginRedirect: Href
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export default function LoginProvider({ loginRedirect, children }: Props) {
|
||||
const router = useRouter()
|
||||
const route = useRouteInfo()
|
||||
const auth = useAuth()
|
||||
const authLogin = useAuthLogin()
|
||||
const loginMutation = useLoginMutation({
|
||||
authLogin,
|
||||
onError: ({ response }) => {
|
||||
if (response)
|
||||
authLogin({ name: auth.name ?? "", password: null, token: null })
|
||||
else
|
||||
authLogin({ name: auth.name ?? "", token: null })
|
||||
}
|
||||
})
|
||||
const game = useGame()
|
||||
const setPlayerId = useSetPlayerId()
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const storedName = await SecureStore.getItemAsync('apiName')
|
||||
const storedToken = await SecureStore.getItemAsync('apiToken')
|
||||
if (!auth.loggedIn && storedName !== null && storedName !== auth.name && storedToken !== auth.token) {
|
||||
authLogin({ name: storedName, token: storedToken })
|
||||
return
|
||||
}
|
||||
|
||||
// Si on est pas connecté⋅e, on reste sur la fenêtre de connexion
|
||||
if ((!auth.loggedIn || !auth.token) && route.pathname !== loginRedirect)
|
||||
router.navigate(loginRedirect)
|
||||
})()
|
||||
}, [auth, authLogin, router, route])
|
||||
|
||||
useEffect(() => {
|
||||
// Renouvellement auto du jeton d'authentification
|
||||
const { name, token } = auth
|
||||
const password = SecureStore.getItem('apiPassword')
|
||||
if (name === null || (password === null && token === null) || loginMutation.isPending)
|
||||
return
|
||||
let waitTime = 0
|
||||
if (token !== null && token !== undefined) {
|
||||
const arrayToken = token.split('.')
|
||||
const tokenPayload = JSON.parse(atob(arrayToken[1]))
|
||||
const expTime: number = tokenPayload.exp * 1000
|
||||
const now: number = Math.floor(new Date().getTime())
|
||||
waitTime = expTime - now
|
||||
|
||||
const playerId = tokenPayload.playerId
|
||||
if (playerId !== game.playerId)
|
||||
setPlayerId(playerId)
|
||||
}
|
||||
const timeout = setTimeout(async () => {
|
||||
const password = SecureStore.getItem('apiPassword')
|
||||
if (password)
|
||||
loginMutation.mutate({ name, password })
|
||||
else
|
||||
authLogin({ name: name, token: null })
|
||||
}, waitTime)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [auth, authLogin, loginMutation.status, game, setPlayerId])
|
||||
|
||||
return <>
|
||||
{children}
|
||||
</>
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
import { SymbolView, SymbolViewProps, SymbolWeight } from 'expo-symbols';
|
||||
import { StyleProp, ViewStyle } from 'react-native';
|
||||
|
||||
export function IconSymbol({
|
||||
name,
|
||||
size = 24,
|
||||
color,
|
||||
style,
|
||||
weight = 'regular',
|
||||
}: {
|
||||
name: SymbolViewProps['name'];
|
||||
size?: number;
|
||||
color: string;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
weight?: SymbolWeight;
|
||||
}) {
|
||||
return (
|
||||
<SymbolView
|
||||
weight={weight}
|
||||
tintColor={color}
|
||||
resizeMode="scaleAspectFit"
|
||||
name={name}
|
||||
style={[
|
||||
{
|
||||
width: size,
|
||||
height: size,
|
||||
},
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
// This file is a fallback for using MaterialIcons on Android and web.
|
||||
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { SymbolWeight } from 'expo-symbols';
|
||||
import React from 'react';
|
||||
import { OpaqueColorValue, StyleProp, ViewStyle } from 'react-native';
|
||||
|
||||
// Add your SFSymbol to MaterialIcons mappings here.
|
||||
const MAPPING = {
|
||||
// See MaterialIcons here: https://icons.expo.fyi
|
||||
// See SF Symbols in the SF Symbols app on Mac.
|
||||
'house.fill': 'home',
|
||||
'paperplane.fill': 'send',
|
||||
'chevron.left.forwardslash.chevron.right': 'code',
|
||||
'chevron.right': 'chevron-right',
|
||||
} as Partial<
|
||||
Record<
|
||||
import('expo-symbols').SymbolViewProps['name'],
|
||||
React.ComponentProps<typeof MaterialIcons>['name']
|
||||
>
|
||||
>;
|
||||
|
||||
export type IconSymbolName = keyof typeof MAPPING;
|
||||
|
||||
/**
|
||||
* An icon component that uses native SFSymbols on iOS, and MaterialIcons on Android and web. This ensures a consistent look across platforms, and optimal resource usage.
|
||||
*
|
||||
* Icon `name`s are based on SFSymbols and require manual mapping to MaterialIcons.
|
||||
*/
|
||||
export function IconSymbol({
|
||||
name,
|
||||
size = 24,
|
||||
color,
|
||||
style,
|
||||
}: {
|
||||
name: IconSymbolName;
|
||||
size?: number;
|
||||
color: string | OpaqueColorValue;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
weight?: SymbolWeight;
|
||||
}) {
|
||||
return <MaterialIcons color={color} size={size} name={MAPPING[name]} style={style} />;
|
||||
}
|
49
client/components/ui/TabBar.tsx
Normal file
@ -0,0 +1,49 @@
|
||||
import { BottomTabBarProps } from '@react-navigation/bottom-tabs'
|
||||
import { CommonActions } from '@react-navigation/native'
|
||||
import React from 'react'
|
||||
import { BottomNavigation } from 'react-native-paper'
|
||||
|
||||
const TabBar = (props: BottomTabBarProps) => (
|
||||
<BottomNavigation.Bar
|
||||
shifting
|
||||
navigationState={props.state}
|
||||
safeAreaInsets={props.insets}
|
||||
onTabPress={({ route, preventDefault }) => {
|
||||
const event = props.navigation.emit({
|
||||
type: 'tabPress',
|
||||
target: route.key,
|
||||
canPreventDefault: true,
|
||||
})
|
||||
|
||||
if (event.defaultPrevented) {
|
||||
preventDefault()
|
||||
} else {
|
||||
props.navigation.dispatch({
|
||||
...CommonActions.navigate(route.name, route.params),
|
||||
target: props.state.key,
|
||||
})
|
||||
}
|
||||
}}
|
||||
renderIcon={({ route, focused, color }) => {
|
||||
const { options } = props.descriptors[route.key]
|
||||
if (options.tabBarIcon) {
|
||||
return options.tabBarIcon({ focused, color, size: 24 })
|
||||
}
|
||||
|
||||
return null
|
||||
}}
|
||||
getLabelText={({ route }) => {
|
||||
const { options } = props.descriptors[route.key]
|
||||
const label =
|
||||
options.tabBarLabel !== undefined
|
||||
? options.tabBarLabel.toString()
|
||||
: options.title !== undefined
|
||||
? options.title
|
||||
: route.name
|
||||
|
||||
return label
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
export default TabBar
|
@ -1,22 +0,0 @@
|
||||
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
|
||||
import { BlurView } from 'expo-blur';
|
||||
import { StyleSheet } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
|
||||
export default function BlurTabBarBackground() {
|
||||
return (
|
||||
<BlurView
|
||||
// System chrome material automatically adapts to the system's theme
|
||||
// and matches the native tab bar appearance on iOS.
|
||||
tint="systemChromeMaterial"
|
||||
intensity={100}
|
||||
style={StyleSheet.absoluteFill}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function useBottomTabOverflow() {
|
||||
const tabHeight = useBottomTabBarHeight();
|
||||
const { bottom } = useSafeAreaInsets();
|
||||
return tabHeight - bottom;
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
// This is a shim for web and Android where the tab bar is generally opaque.
|
||||
export default undefined;
|
||||
|
||||
export function useBottomTabOverflow() {
|
||||
return 0;
|
||||
}
|
66
client/components/ui/TabsHeader.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
import { BottomTabHeaderProps } from '@react-navigation/bottom-tabs'
|
||||
import { getHeaderTitle } from '@react-navigation/elements'
|
||||
import React from 'react'
|
||||
import {
|
||||
Appbar,
|
||||
AppbarProps,
|
||||
IconButton,
|
||||
Searchbar,
|
||||
SearchbarProps,
|
||||
Tooltip,
|
||||
} from 'react-native-paper'
|
||||
|
||||
interface TabsHeaderProps extends AppbarProps {
|
||||
navProps: BottomTabHeaderProps
|
||||
withSearchBar?: boolean
|
||||
searchBarProps?: SearchbarProps
|
||||
}
|
||||
|
||||
const TabsHeader = (props: TabsHeaderProps) => {
|
||||
const [query, setQuery] = React.useState('')
|
||||
|
||||
return props.withSearchBar ? (
|
||||
<Appbar.Header {...props}>
|
||||
<Searchbar
|
||||
{...props.searchBarProps}
|
||||
value={query}
|
||||
onChangeText={setQuery}
|
||||
style={{ margin: 8, marginBottom: 16 }}
|
||||
right={(p) => (
|
||||
<Tooltip title="Rechercher">
|
||||
<IconButton
|
||||
{...p}
|
||||
icon="check"
|
||||
onPress={() =>
|
||||
props.searchBarProps?.onChangeText
|
||||
? props.searchBarProps.onChangeText(query)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
/>
|
||||
</Appbar.Header>
|
||||
) : (
|
||||
<Appbar.Header {...props}>
|
||||
{props.navProps.options.headerLeft
|
||||
? props.navProps.options.headerLeft({})
|
||||
: undefined}
|
||||
|
||||
<Appbar.Content
|
||||
title={getHeaderTitle(
|
||||
props.navProps.options,
|
||||
props.navProps.route.name,
|
||||
)}
|
||||
/>
|
||||
|
||||
{props.navProps.options.headerRight
|
||||
? props.navProps.options.headerRight({
|
||||
canGoBack: props.navProps.navigation.canGoBack(),
|
||||
})
|
||||
: undefined}
|
||||
</Appbar.Header>
|
||||
)
|
||||
}
|
||||
|
||||
export default TabsHeader
|
@ -1,26 +0,0 @@
|
||||
/**
|
||||
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
|
||||
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
|
||||
*/
|
||||
|
||||
const tintColorLight = '#0a7ea4';
|
||||
const tintColorDark = '#fff';
|
||||
|
||||
export const Colors = {
|
||||
light: {
|
||||
text: '#11181C',
|
||||
background: '#fff',
|
||||
tint: tintColorLight,
|
||||
icon: '#687076',
|
||||
tabIconDefault: '#687076',
|
||||
tabIconSelected: tintColorLight,
|
||||
},
|
||||
dark: {
|
||||
text: '#ECEDEE',
|
||||
background: '#151718',
|
||||
tint: tintColorDark,
|
||||
icon: '#9BA1A6',
|
||||
tabIconDefault: '#9BA1A6',
|
||||
tabIconSelected: tintColorDark,
|
||||
},
|
||||
};
|
6
client/constants/Constants.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { Accuracy } from 'expo-location'
|
||||
|
||||
export const Constants = {
|
||||
MIN_DELAY_LOCATION_SENT: 20,
|
||||
QUERY_REFETCH_INTERVAL: 15,
|
||||
}
|
@ -6,13 +6,16 @@
|
||||
"build": {
|
||||
"development": {
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
"distribution": "internal",
|
||||
"channel": "development"
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal"
|
||||
"distribution": "internal",
|
||||
"channel": "preview"
|
||||
},
|
||||
"production": {
|
||||
"autoIncrement": true
|
||||
"autoIncrement": true,
|
||||
"channel": "production"
|
||||
}
|
||||
},
|
||||
"submit": {
|
||||
|
230
client/hooks/mutations/useChallengeMutation.ts
Normal file
@ -0,0 +1,230 @@
|
||||
import { AuthState } from "@/utils/features/auth/authSlice"
|
||||
import { Challenge } from "@/utils/features/challenges/challengesSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = () => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type ChallengeActionProps = {
|
||||
auth: AuthState
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
type ChallengeProps = {
|
||||
auth: AuthState
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useDrawRandomChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/draw-random/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useEndChallenge = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async ({ success }: { success: boolean }) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenge-actions/end-current/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
success: success,
|
||||
})
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useAttachNewChallenge = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async ({ challengeActionId, newChallengeId }: { challengeActionId: number, newChallengeId: number }) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenge-actions/${challengeActionId}/`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
challengeId: newChallengeId,
|
||||
})
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useDeleteChallengeActionMutation = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (challengeActionId: number) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenge-actions/${challengeActionId}/`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
},
|
||||
onSuccess: async (resp) => {
|
||||
if (resp.status >= 400) {
|
||||
if (onError)
|
||||
onError({ response: await resp.json() })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useAddChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (challenge: Omit<Challenge, 'id'>) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: challenge.title,
|
||||
description: challenge.description,
|
||||
reward: challenge.reward,
|
||||
})
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useEditChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (challenge: Challenge) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/${challenge.id}/`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: challenge.title,
|
||||
description: challenge.description,
|
||||
reward: challenge.reward,
|
||||
})
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useDeleteChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (challenge: Challenge) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/${challenge.id}/`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
},
|
||||
onSuccess: async (resp) => {
|
||||
if (resp.status >= 400) {
|
||||
if (onError)
|
||||
onError({ response: await resp.json() })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
159
client/hooks/mutations/useGameMutation.ts
Normal file
@ -0,0 +1,159 @@
|
||||
import { AuthState } from "@/utils/features/auth/authSlice"
|
||||
import { GamePayload, GameState } from "@/utils/features/game/gameSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = () => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type GameProps = {
|
||||
updateGameState: (payload: GamePayload) => { payload: GamePayload, type: "game/updateGameState" }
|
||||
auth: AuthState
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useGameStartMutation = ({ auth, updateGameState, onPostSuccess, onError }: GameProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/start/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
updateGameState(data)
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useGameStopMutation = ({ auth, updateGameState, onPostSuccess, onError }: GameProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/stop/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
updateGameState(data)
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useGameSwitchPlayerMutation = ({ auth, updateGameState, onPostSuccess, onError }: GameProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/switch-running-player/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
updateGameState(data)
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useGameRepairMutation = ({ auth, onPostSuccess, onError }: Omit<GameProps, 'updateGameState'>) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/repair/`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useGameResetMutation = ({ auth, updateGameState, onPostSuccess, onError }: GameProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/reset/`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
updateGameState(data)
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
56
client/hooks/mutations/useGeolocationMutation.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import { AuthState } from "@/utils/features/auth/authSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { LocationObject } from "expo-location"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = (data: any, variables: LocationObject, context: unknown) => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type PostProps = {
|
||||
auth: AuthState
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useGeolocationMutation = ({ auth, onPostSuccess, onError }: PostProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (location: LocationObject) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
longitude: location.coords.longitude,
|
||||
latitude: location.coords.latitude,
|
||||
speed: location.coords.speed,
|
||||
accuracy: location.coords.accuracy,
|
||||
altitude: location.coords.altitude,
|
||||
altitudeAccuracy: location.coords.altitudeAccuracy,
|
||||
timestamp: location.timestamp,
|
||||
})
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
networkMode: 'offlineFirst',
|
||||
onSuccess: async (data, location: LocationObject, context: unknown) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess(data, location, context)
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
50
client/hooks/mutations/useLoginMutation.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { AuthPayload } from "@/utils/features/auth/authSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type LoginForm = {
|
||||
name: string
|
||||
password: string
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = () => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type LoginProps = {
|
||||
authLogin: (payload: AuthPayload) => { payload: AuthPayload, type: "auth/login" }
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useLoginMutation = ({ authLogin, onPostSuccess, onError }: LoginProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async ({ name, password }: LoginForm) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/auth/login/`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name, password: password })
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
networkMode: 'always',
|
||||
onSuccess: async (data, { name, password }: LoginForm) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
authLogin({ name: name, password: password, token: data.accessToken })
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
76
client/hooks/mutations/useTrainMutation.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import { AuthState } from "@/utils/features/auth/authSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = () => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type TrainProps = {
|
||||
// addTrain: (payload: TrainPayload) => { payload: GamePayload, type: "train/addTrain" }
|
||||
auth: AuthState
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useAddTrainMutation = ({ auth, onPostSuccess, onError }: TrainProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (trainId: string) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/import/`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
id: trainId,
|
||||
}),
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
if (data.statusCode) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useDeleteTrainMutation = ({ auth, onPostSuccess, onError }: TrainProps) => {
|
||||
return useMutation({
|
||||
mutationFn: async (trainId: string) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/${trainId}/`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth.token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
},
|
||||
onSuccess: async (resp) => {
|
||||
if (resp.status >= 400) {
|
||||
if (onError)
|
||||
onError({ response: await resp.json() })
|
||||
return
|
||||
}
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: async (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
12
client/hooks/useAuth.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
import { AuthPayload, login, logout } from "@/utils/features/auth/authSlice"
|
||||
|
||||
export const useAuth = () => useAppSelector((state) => state.auth)
|
||||
export const useAuthLogin = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (payload: AuthPayload) => dispath(login(payload))
|
||||
}
|
||||
export const useAuthLogout = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return () => dispatch(logout())
|
||||
}
|
8
client/hooks/useChallengeActions.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { ChallengeActionsPayload, downloadChallengeActions } from "@/utils/features/challengeActions/challengeActionsSlice"
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
|
||||
export const useChallengeActions = () => useAppSelector((state) => state.challengeActions.challengeActions)
|
||||
export const useDownloadChallengeActions = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (challengesData: ChallengeActionsPayload) => dispath(downloadChallengeActions(challengesData))
|
||||
}
|
8
client/hooks/useChallenges.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { ChallengesPayload, downloadChallenges } from "@/utils/features/challenges/challengesSlice"
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
|
||||
export const useChallenges = () => useAppSelector((state) => state.challenges.challenges)
|
||||
export const useDownloadChallenges = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (challengesData: ChallengesPayload) => dispath(downloadChallenges(challengesData))
|
||||
}
|
@ -1 +1 @@
|
||||
export { useColorScheme } from 'react-native';
|
||||
export { useColorScheme } from 'react-native'
|
||||
|
@ -1,21 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useColorScheme as useRNColorScheme } from 'react-native';
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useColorScheme as useRNColorScheme } from 'react-native'
|
||||
|
||||
/**
|
||||
* To support static rendering, this value needs to be re-calculated on the client side for web
|
||||
*/
|
||||
export function useColorScheme() {
|
||||
const [hasHydrated, setHasHydrated] = useState(false);
|
||||
const [hasHydrated, setHasHydrated] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setHasHydrated(true);
|
||||
}, []);
|
||||
setHasHydrated(true)
|
||||
}, [])
|
||||
|
||||
const colorScheme = useRNColorScheme();
|
||||
const colorScheme = useRNColorScheme()
|
||||
|
||||
if (hasHydrated) {
|
||||
return colorScheme;
|
||||
return colorScheme
|
||||
}
|
||||
|
||||
return 'light';
|
||||
return 'light'
|
||||
}
|
||||
|
30
client/hooks/useGame.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { Accuracy } from "expo-location"
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
import { GamePayload, PenaltyPayload, setLocationAccuracy, setPlayerId, updateActiveChallengeId, updateGameState, updateMoney, updatePenalty } from "@/utils/features/game/gameSlice"
|
||||
|
||||
export const useGame = () => useAppSelector((state) => state.game)
|
||||
export const useSettings = () => useAppSelector((state) => state.game.settings)
|
||||
export const useSetPlayerId = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (playerId: number) => dispath(setPlayerId(playerId))
|
||||
}
|
||||
export const useUpdateMoney = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (money: number) => dispatch(updateMoney(money))
|
||||
}
|
||||
export const useUpdateActiveChallengeId = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (challengeActionId: number) => dispatch(updateActiveChallengeId(challengeActionId))
|
||||
}
|
||||
export const useUpdateGameState = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (game: GamePayload) => dispatch(updateGameState(game))
|
||||
}
|
||||
export const useUpdatePenalty = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (penalty: PenaltyPayload) => dispatch(updatePenalty(penalty))
|
||||
}
|
||||
export const useSetLocationAccuracy = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (accuracy: Accuracy | null) => dispatch(setLocationAccuracy(accuracy))
|
||||
}
|
24
client/hooks/useLocation.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { LocationObject } from "expo-location"
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
import { PlayerLocation, setLastLocation, setLastPlayerLocation, setLastPlayerLocations, unqueueLocation } from "@/utils/features/location/locationSlice"
|
||||
|
||||
export const useLastOwnLocation = () => useAppSelector((state) => state.location.lastOwnLocation)
|
||||
export const useQueuedLocations = () => useAppSelector((state) => state.location.queuedLocations)
|
||||
export const useLastPlayerLocations = () => useAppSelector((state) => state.location.lastPlayerLocations)
|
||||
|
||||
export const useSetLastLocation = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (location: LocationObject) => dispatch(setLastLocation(location))
|
||||
}
|
||||
export const useUnqueueLocation = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (location: LocationObject) => dispatch(unqueueLocation(location))
|
||||
}
|
||||
export const useSetLastPlayerLocations = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (playerLocations: PlayerLocation[]) => dispatch(setLastPlayerLocations(playerLocations))
|
||||
}
|
||||
export const useSetLastPlayerLocation = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
return (playerLocation: PlayerLocation) => dispatch(setLastPlayerLocation(playerLocation))
|
||||
}
|
8
client/hooks/useMoneyUpdates.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
import { downloadMoneyUpdates, MoneyUpdatesPayload } from "@/utils/features/moneyUpdates/moneyUpdatesSlice"
|
||||
|
||||
export const useMoneyUpdates = () => useAppSelector((state) => state.moneyUpdates.moneyUpdates)
|
||||
export const useDownloadMoneyUpdates = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (moneyUpdatesData: MoneyUpdatesPayload) => dispath(downloadMoneyUpdates(moneyUpdatesData))
|
||||
}
|
5
client/hooks/useStore.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { AppDispatch, RootState } from '@/utils/store'
|
||||
import { useDispatch, useSelector } from 'react-redux'
|
||||
|
||||
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
|
||||
export const useAppSelector = useSelector.withTypes<RootState>()
|
@ -1,21 +0,0 @@
|
||||
/**
|
||||
* Learn more about light and dark modes:
|
||||
* https://docs.expo.dev/guides/color-schemes/
|
||||
*/
|
||||
|
||||
import { Colors } from '@/constants/Colors';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
|
||||
export function useThemeColor(
|
||||
props: { light?: string; dark?: string },
|
||||
colorName: keyof typeof Colors.light & keyof typeof Colors.dark
|
||||
) {
|
||||
const theme = useColorScheme() ?? 'light';
|
||||
const colorFromProps = props[theme];
|
||||
|
||||
if (colorFromProps) {
|
||||
return colorFromProps;
|
||||
} else {
|
||||
return Colors[theme][colorName];
|
||||
}
|
||||
}
|
8
client/hooks/useTrain.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { downloadTrains, TrainsPayload } from "@/utils/features/train/trainSlice"
|
||||
import { useAppDispatch, useAppSelector } from "./useStore"
|
||||
|
||||
export const useTrain = () => useAppSelector((state) => state.train.trains)
|
||||
export const useDownloadTrains = () => {
|
||||
const dispath = useAppDispatch()
|
||||
return (trainsData: TrainsPayload) => dispath(downloadTrains(trainsData))
|
||||
}
|
2180
client/package-lock.json
generated
@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "traintrape-moi-client",
|
||||
"main": "expo-router/entry",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.1",
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"android": "expo run:android",
|
||||
"ios": "expo run:ios",
|
||||
"web": "expo start --web",
|
||||
"test": "jest --watchAll",
|
||||
"lint": "expo lint"
|
||||
@ -14,25 +14,34 @@
|
||||
"preset": "jest-expo"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dev-plugins/react-navigation": "^0.1.0",
|
||||
"@dev-plugins/react-query": "^0.1.0",
|
||||
"@expo/vector-icons": "^14.0.2",
|
||||
"@maplibre/maplibre-react-native": "^10.0.0-alpha.28",
|
||||
"@maplibre/maplibre-react-native": "^10.0.0-beta.8",
|
||||
"@react-native-async-storage/async-storage": "1.23.1",
|
||||
"@react-navigation/bottom-tabs": "^7.0.0",
|
||||
"@react-navigation/native": "^7.0.0",
|
||||
"@reduxjs/toolkit": "^2.4.0",
|
||||
"@tanstack/query-async-storage-persister": "^5.62.7",
|
||||
"@tanstack/react-query": "^5.62.7",
|
||||
"@tanstack/react-query-persist-client": "^5.62.7",
|
||||
"@turf/circle": "^7.1.0",
|
||||
"expo": "~52.0.11",
|
||||
"expo-blur": "~14.0.1",
|
||||
"expo-constants": "~17.0.3",
|
||||
"expo-dev-client": "~5.0.4",
|
||||
"expo-font": "~13.0.1",
|
||||
"expo-haptics": "~14.0.0",
|
||||
"expo-linking": "~7.0.3",
|
||||
"expo-location": "^18.0.2",
|
||||
"expo-router": "~4.0.9",
|
||||
"expo-secure-store": "~14.0.0",
|
||||
"expo-share-intent": "^3.1.1",
|
||||
"expo-splash-screen": "~0.29.13",
|
||||
"expo-status-bar": "~2.0.0",
|
||||
"expo-symbols": "~0.2.0",
|
||||
"expo-system-ui": "~4.0.4",
|
||||
"expo-web-browser": "~14.0.1",
|
||||
"expo-task-manager": "^12.0.3",
|
||||
"expo-updates": "~0.26.10",
|
||||
"maplibre-gl": "^4.7.1",
|
||||
"maplibre-react-components": "^0.1.9",
|
||||
"react": "18.3.1",
|
||||
@ -40,11 +49,13 @@
|
||||
"react-map-gl": "^7.1.7",
|
||||
"react-native": "0.76.3",
|
||||
"react-native-gesture-handler": "~2.20.2",
|
||||
"react-native-reanimated": "~3.16.1",
|
||||
"react-native-safe-area-context": "4.12.0",
|
||||
"react-native-paper": "^5.12.5",
|
||||
"react-native-paper-dropdown": "^2.3.1",
|
||||
"react-native-safe-area-context": "~4.12.0",
|
||||
"react-native-screens": "~4.1.0",
|
||||
"react-native-web": "~0.19.13",
|
||||
"react-native-webview": "13.12.2"
|
||||
"react-redux": "^9.1.2",
|
||||
"socket.io-client": "^4.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.25.2",
|
||||
|
@ -14,5 +14,5 @@
|
||||
".expo/types/**/*.ts",
|
||||
"expo-env.d.ts",
|
||||
"app/(tabs)/index.tsx"
|
||||
]
|
||||
, "babel.config.js" ]
|
||||
}
|
||||
|
3
client/utils/SecureStore.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import { deleteItemAsync, getItem, getItemAsync, setItem, setItemAsync } from 'expo-secure-store'
|
||||
|
||||
export { deleteItemAsync, getItem, getItemAsync, setItem, setItemAsync }
|
19
client/utils/SecureStore.web.ts
Normal file
@ -0,0 +1,19 @@
|
||||
export async function deleteItemAsync(key: string): Promise<void> {
|
||||
return localStorage.removeItem(key)
|
||||
}
|
||||
|
||||
export function getItem(key: string): string | null {
|
||||
return localStorage.getItem(key)
|
||||
}
|
||||
|
||||
export async function getItemAsync(key: string): Promise<string | null> {
|
||||
return localStorage.getItem(key)
|
||||
}
|
||||
|
||||
export function setItem(key: string, value: string): void {
|
||||
localStorage.setItem(key, value)
|
||||
}
|
||||
|
||||
export async function setItemAsync(key: string, value: string): Promise<void> {
|
||||
localStorage.setItem(key, value)
|
||||
}
|
69
client/utils/features/auth/authSlice.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import * as SecureStore from '@/utils/SecureStore'
|
||||
import { Platform } from 'react-native'
|
||||
|
||||
export interface AuthState {
|
||||
loggedIn: boolean,
|
||||
name: string | null,
|
||||
token: string | null,
|
||||
}
|
||||
|
||||
export interface AuthPayload {
|
||||
name: string,
|
||||
password?: string | null,
|
||||
token: string | null,
|
||||
}
|
||||
|
||||
const initialState: AuthState = {
|
||||
loggedIn: false,
|
||||
name: null,
|
||||
token: null,
|
||||
}
|
||||
|
||||
export function isAuthValid({ loggedIn, token }: AuthState): boolean {
|
||||
if (!loggedIn || token === null)
|
||||
return false
|
||||
const arrayToken = token.split('.')
|
||||
const tokenPayload = JSON.parse(atob(arrayToken[1]))
|
||||
const expTime: number = tokenPayload.exp * 1000
|
||||
const now: number = Math.floor(new Date().getTime())
|
||||
return expTime >= now
|
||||
}
|
||||
|
||||
export const authSlice = createSlice({
|
||||
name: 'auth',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
login: (state, action: PayloadAction<AuthPayload>) => {
|
||||
state.loggedIn = action.payload.token !== null
|
||||
state.name = action.payload.name
|
||||
state.token = action.payload.token
|
||||
|
||||
SecureStore.setItem('apiName', action.payload.name)
|
||||
if (action.payload.password !== undefined && Platform.OS !== "web") {
|
||||
// Le stockage navigateur n'est pas sûr, on évite de stocker un mot de passe à l'intérieur
|
||||
if (action.payload.password)
|
||||
SecureStore.setItem('apiPassword', action.payload.password)
|
||||
else
|
||||
SecureStore.deleteItemAsync('apiPassword')
|
||||
}
|
||||
if (action.payload.token)
|
||||
SecureStore.setItem('apiToken', action.payload.token)
|
||||
else
|
||||
SecureStore.deleteItemAsync('apiToken')
|
||||
},
|
||||
logout: (state) => {
|
||||
state.loggedIn = false
|
||||
state.name = null
|
||||
state.token = null
|
||||
|
||||
SecureStore.deleteItemAsync('apiName')
|
||||
SecureStore.deleteItemAsync('apiPassword')
|
||||
SecureStore.deleteItemAsync('apiToken')
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const { login, logout } = authSlice.actions
|
||||
|
||||
export default authSlice.reducer
|
@ -0,0 +1,66 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { Challenge } from '../challenges/challengesSlice'
|
||||
|
||||
export interface ChallengeAction {
|
||||
id: number
|
||||
challengeId: number
|
||||
success: boolean,
|
||||
start: number, // date
|
||||
end: number | null, // date
|
||||
penaltyStart: number | null, // date
|
||||
penaltyEnd: number | null, // date
|
||||
runId: number,
|
||||
}
|
||||
|
||||
export interface ActionsState {
|
||||
challengeActions: ChallengeAction[]
|
||||
}
|
||||
|
||||
const initialState: ActionsState = {
|
||||
challengeActions: []
|
||||
}
|
||||
|
||||
export interface ChallengeActionPayload {
|
||||
id: number
|
||||
playerId: number
|
||||
challengeId: number
|
||||
success: boolean,
|
||||
start: string,
|
||||
end: string | null,
|
||||
penaltyStart: string | null,
|
||||
penaltyEnd: string | null,
|
||||
runId: number,
|
||||
}
|
||||
|
||||
export interface ChallengeActionsPayload {
|
||||
data: (Challenge & { action: ChallengeActionPayload })[]
|
||||
}
|
||||
|
||||
export const challengeActionsSlice = createSlice({
|
||||
name: 'challengeActions',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
|
||||
downloadChallengeActions(state, action: PayloadAction<ChallengeActionsPayload>) {
|
||||
if (state.challengeActions)
|
||||
state.challengeActions = state.challengeActions.filter(challengeAction => action.payload.data.filter(dlChallenge => dlChallenge.action.id === challengeAction.id) === null)
|
||||
for (const dlChallenge of action.payload.data) {
|
||||
state.challengeActions.push({
|
||||
id: dlChallenge.action.id,
|
||||
challengeId: dlChallenge.id,
|
||||
success: dlChallenge.action.success,
|
||||
start: new Date(dlChallenge.action.start).getTime(),
|
||||
end: dlChallenge.action.end ? new Date(dlChallenge.action.end).getTime() : null,
|
||||
penaltyStart: dlChallenge.action.penaltyStart ? new Date(dlChallenge.action.penaltyStart).getTime() : null,
|
||||
penaltyEnd: dlChallenge.action.penaltyEnd ? new Date(dlChallenge.action.penaltyEnd).getTime() : null,
|
||||
runId: dlChallenge.action.runId,
|
||||
})
|
||||
}
|
||||
state.challengeActions.sort((c1, c2) => c2.id - c1.id)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export const { downloadChallengeActions } = challengeActionsSlice.actions
|
||||
|
||||
export default challengeActionsSlice.reducer
|
47
client/utils/features/challenges/challengesSlice.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { PaginationMeta } from '../common'
|
||||
import { ChallengeAction } from '../challengeActions/challengeActionsSlice'
|
||||
|
||||
export interface Challenge {
|
||||
id: number
|
||||
title: string,
|
||||
description: string,
|
||||
reward: number,
|
||||
}
|
||||
|
||||
export interface ChallengesState {
|
||||
challenges: Challenge[]
|
||||
}
|
||||
|
||||
const initialState: ChallengesState = {
|
||||
challenges: []
|
||||
}
|
||||
|
||||
export interface ChallengesPayload {
|
||||
data: (Challenge & { action: ChallengeAction | null })[]
|
||||
meta: PaginationMeta
|
||||
}
|
||||
|
||||
export const challengesSlice = createSlice({
|
||||
name: 'challenges',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
downloadChallenges(state, action: PayloadAction<ChallengesPayload>) {
|
||||
if (state.challenges)
|
||||
state.challenges = state.challenges.filter(challenge => action.payload.data.filter(dlChallenge => dlChallenge.id === challenge.id) === null)
|
||||
for (const dlChallenge of action.payload.data) {
|
||||
state.challenges.push({
|
||||
id: dlChallenge.id,
|
||||
title: dlChallenge.title,
|
||||
description: dlChallenge.description,
|
||||
reward: dlChallenge.reward,
|
||||
})
|
||||
}
|
||||
state.challenges.sort((c1, c2) => c1.title.localeCompare(c2.title))
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export const { downloadChallenges } = challengesSlice.actions
|
||||
|
||||
export default challengesSlice.reducer
|
8
client/utils/features/common.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export interface PaginationMeta {
|
||||
currentPage: number
|
||||
lastPage: number
|
||||
nextPage: number
|
||||
prevPage: number
|
||||
total: number
|
||||
totalPerPage: number
|
||||
}
|
100
client/utils/features/game/gameSlice.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { Accuracy } from 'expo-location'
|
||||
import * as SecureStore from '@/utils/SecureStore'
|
||||
|
||||
export interface RunPayload {
|
||||
id: number
|
||||
gameId: number
|
||||
runnerId: number
|
||||
start: string
|
||||
end: string | null
|
||||
}
|
||||
|
||||
export interface GamePayload {
|
||||
id: number
|
||||
started: boolean
|
||||
currentRunId: number | null
|
||||
currentRun: RunPayload | null
|
||||
}
|
||||
|
||||
export interface PenaltyPayload {
|
||||
penaltyStart: number | null
|
||||
penaltyEnd: number | null
|
||||
}
|
||||
|
||||
export interface Player {
|
||||
id: number
|
||||
name: string
|
||||
money: number
|
||||
activeChallengeId: number | null
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
playerId: number | null
|
||||
runId: number | null
|
||||
gameStarted: boolean
|
||||
money: number
|
||||
currentRunner: boolean
|
||||
activeChallengeId: number | null
|
||||
chaseFreeTime: number | null // date
|
||||
penaltyStart: number | null // date
|
||||
penaltyEnd: number | null //date
|
||||
settings: Settings
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
locationAccuracy: Accuracy | null
|
||||
}
|
||||
|
||||
const initialState: GameState = {
|
||||
playerId: null,
|
||||
runId: null,
|
||||
gameStarted: false,
|
||||
money: 0,
|
||||
currentRunner: false,
|
||||
activeChallengeId: null,
|
||||
chaseFreeTime: null,
|
||||
penaltyStart: null,
|
||||
penaltyEnd: null,
|
||||
settings: {
|
||||
locationAccuracy: Accuracy.Highest,
|
||||
}
|
||||
}
|
||||
|
||||
export const gameSlice = createSlice({
|
||||
name: 'game',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
setPlayerId: (state, action: PayloadAction<number>) => {
|
||||
state.playerId = action.payload
|
||||
},
|
||||
updateMoney: (state, action: PayloadAction<number>) => {
|
||||
state.money = action.payload
|
||||
},
|
||||
updateActiveChallengeId: (state, action: PayloadAction<number | null>) => {
|
||||
state.activeChallengeId = action.payload
|
||||
},
|
||||
updateGameState: (state, action: PayloadAction<GamePayload>) => {
|
||||
const game: GamePayload = action.payload
|
||||
state.gameStarted = game.started
|
||||
state.runId = game.currentRunId
|
||||
state.currentRunner = state.playerId === game.currentRun?.runnerId
|
||||
if (state.currentRunner)
|
||||
state.chaseFreeTime = null
|
||||
else if (game.currentRun)
|
||||
state.chaseFreeTime = new Date(game.currentRun?.start).getTime() + 45 * 60 * 1000
|
||||
},
|
||||
updatePenalty: (state, action: PayloadAction<PenaltyPayload>) => {
|
||||
state.penaltyStart = action.payload.penaltyStart
|
||||
state.penaltyEnd = action.payload.penaltyEnd
|
||||
},
|
||||
setLocationAccuracy: (state, action: PayloadAction<Accuracy | null>) => {
|
||||
state.settings.locationAccuracy = action.payload
|
||||
SecureStore.setItem('locationAccuracy', action.payload?.toString() ?? 'null')
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const { setLocationAccuracy, setPlayerId, updateMoney, updateActiveChallengeId, updateGameState, updatePenalty } = gameSlice.actions
|
||||
|
||||
export default gameSlice.reducer
|
63
client/utils/features/location/locationSlice.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { LocationObject } from 'expo-location'
|
||||
import { Constants } from '@/constants/Constants'
|
||||
|
||||
|
||||
export type PlayerLocation = {
|
||||
id?: number
|
||||
playerId: number
|
||||
longitude: number
|
||||
latitude: number
|
||||
speed: number
|
||||
accuracy: number
|
||||
altitude: number
|
||||
altitudeAccuracy: number
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
interface LocationState {
|
||||
lastOwnLocation: LocationObject | null
|
||||
lastSentLocation: LocationObject | null
|
||||
queuedLocations: LocationObject[]
|
||||
lastPlayerLocations: PlayerLocation[]
|
||||
}
|
||||
|
||||
const initialState: LocationState = {
|
||||
lastOwnLocation: null,
|
||||
lastSentLocation: null,
|
||||
queuedLocations: [],
|
||||
lastPlayerLocations: []
|
||||
}
|
||||
|
||||
export const locationSlice = createSlice({
|
||||
name: 'location',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
setLastLocation: (state, action: PayloadAction<LocationObject>) => {
|
||||
const location: LocationObject = action.payload
|
||||
state.lastOwnLocation = location
|
||||
if (state.lastSentLocation === null || (location.timestamp - state.lastSentLocation.timestamp) >= Constants.MIN_DELAY_LOCATION_SENT * 1000) {
|
||||
state.lastSentLocation = location
|
||||
state.queuedLocations.push(location)
|
||||
}
|
||||
},
|
||||
unqueueLocation: (state, action: PayloadAction<LocationObject>) => {
|
||||
const sentLoc = action.payload
|
||||
state.queuedLocations = state.queuedLocations
|
||||
.filter(loc => new Date(loc.timestamp).getTime() !== sentLoc.timestamp
|
||||
&& loc.coords.latitude !== sentLoc.coords.latitude
|
||||
&& loc.coords.longitude !== sentLoc.coords.longitude)
|
||||
},
|
||||
setLastPlayerLocations: (state, action: PayloadAction<PlayerLocation[]>) => {
|
||||
state.lastPlayerLocations = action.payload
|
||||
},
|
||||
setLastPlayerLocation: (state, action: PayloadAction<PlayerLocation>) => {
|
||||
state.lastPlayerLocations = state.lastPlayerLocations.filter(playerLoc => playerLoc.playerId !== action.payload.playerId)
|
||||
state.lastPlayerLocations.push(action.payload)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const { setLastLocation, unqueueLocation, setLastPlayerLocation, setLastPlayerLocations } = locationSlice.actions
|
||||
|
||||
export default locationSlice.reducer
|
64
client/utils/features/moneyUpdates/moneyUpdatesSlice.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { PaginationMeta } from '../common'
|
||||
|
||||
export interface MoneyUpdate {
|
||||
id: number
|
||||
playerId: number
|
||||
amount: number
|
||||
reason: 'START' | 'NEW_RUN' | 'BUY_TRAIN' | 'CHALLENGE'
|
||||
timestamp: number
|
||||
runId: number | null
|
||||
actionId: number | null
|
||||
tripId: string | null
|
||||
}
|
||||
|
||||
export interface MoneyUpdatesState {
|
||||
moneyUpdates: MoneyUpdate[]
|
||||
}
|
||||
|
||||
const initialState: MoneyUpdatesState = {
|
||||
moneyUpdates: []
|
||||
}
|
||||
|
||||
export interface MoneyUpdatePayload {
|
||||
id: number
|
||||
playerId: number
|
||||
amount: number
|
||||
reason: 'START' | 'NEW_RUN' | 'BUY_TRAIN' | 'CHALLENGE'
|
||||
timestamp: string
|
||||
runId: number | null
|
||||
actionId: number | null
|
||||
tripId: string | null
|
||||
}
|
||||
|
||||
export interface MoneyUpdatesPayload {
|
||||
data: MoneyUpdatePayload[]
|
||||
meta: PaginationMeta
|
||||
}
|
||||
|
||||
export const moneyUpdatesSlice = createSlice({
|
||||
name: 'moneyUpdates',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
downloadMoneyUpdates(state, action: PayloadAction<MoneyUpdatesPayload>) {
|
||||
state.moneyUpdates = state.moneyUpdates.filter(moneyUpdate => action.payload.data.filter(dlMU => dlMU.id === moneyUpdate.id) === null)
|
||||
for (const dlMU of action.payload.data) {
|
||||
state.moneyUpdates.push({
|
||||
id: dlMU.id,
|
||||
playerId: dlMU.playerId,
|
||||
amount: dlMU.amount,
|
||||
reason: dlMU.reason,
|
||||
timestamp: new Date(dlMU.timestamp).getTime(),
|
||||
runId: dlMU.runId,
|
||||
actionId: dlMU.actionId,
|
||||
tripId: dlMU.tripId,
|
||||
})
|
||||
}
|
||||
state.moneyUpdates.sort((mu1, mu2) => mu2.id - mu1.id)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export const { downloadMoneyUpdates } = moneyUpdatesSlice.actions
|
||||
|
||||
export default moneyUpdatesSlice.reducer
|
108
client/utils/features/train/trainSlice.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { PaginationMeta } from '../common'
|
||||
|
||||
export interface InterrailTime {
|
||||
hours: number
|
||||
minutes: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface InterrailDate {
|
||||
day: number
|
||||
month: number
|
||||
year: number
|
||||
}
|
||||
|
||||
export interface InterrailTravelInfo {
|
||||
arrivalTime: InterrailTime
|
||||
date: InterrailDate
|
||||
departureTime: InterrailTime
|
||||
haconVersion: number
|
||||
dataSource: number
|
||||
}
|
||||
|
||||
export interface InterrailStopExtraInfo {
|
||||
departureTime: InterrailTime
|
||||
index: number
|
||||
}
|
||||
|
||||
export interface InterrailStopCoordinates {
|
||||
latitude: number
|
||||
longitude: number
|
||||
}
|
||||
|
||||
export interface InterrailStopStation {
|
||||
coordinates: InterrailStopCoordinates
|
||||
country: string
|
||||
name: string
|
||||
stationId: number
|
||||
}
|
||||
|
||||
export interface InterrailLegInfo {
|
||||
attributeCodes: string[]
|
||||
attributes: object
|
||||
duration: InterrailTime
|
||||
directionStation: string
|
||||
endTime: InterrailTime
|
||||
isSeparateTicket: boolean
|
||||
operationDays: string
|
||||
operator: object
|
||||
dataSource: number
|
||||
startTime: InterrailTime
|
||||
stopExtraInfo: InterrailStopExtraInfo[]
|
||||
trainName: string
|
||||
trainStopStations: InterrailStopStation[]
|
||||
trainType: number
|
||||
}
|
||||
|
||||
export interface TrainTrip {
|
||||
id: string
|
||||
distance: number,
|
||||
from: string,
|
||||
to: string,
|
||||
departureTime: number,
|
||||
arrivalTime: number,
|
||||
infoJson?: string,
|
||||
info?: InterrailLegInfo,
|
||||
}
|
||||
|
||||
export interface TrainsState {
|
||||
trains: TrainTrip[]
|
||||
}
|
||||
|
||||
const initialState: TrainsState = {
|
||||
trains: []
|
||||
}
|
||||
|
||||
export interface TrainsPayload {
|
||||
data: TrainTrip[]
|
||||
meta: PaginationMeta
|
||||
}
|
||||
|
||||
export const trainSlice = createSlice({
|
||||
name: 'train',
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
downloadTrains(state, action: PayloadAction<TrainsPayload>) {
|
||||
if (state.trains)
|
||||
state.trains = state.trains.filter(train => action.payload.data.filter(dlTrain => dlTrain.id === train.id) === null)
|
||||
for (const dlTrain of action.payload.data) {
|
||||
const info = dlTrain.infoJson ? JSON.parse(dlTrain.infoJson) : undefined
|
||||
state.trains.push({
|
||||
id: dlTrain.id,
|
||||
distance: dlTrain.distance,
|
||||
from: dlTrain.from,
|
||||
to: dlTrain.to,
|
||||
departureTime: dlTrain.departureTime,
|
||||
arrivalTime: dlTrain.arrivalTime,
|
||||
info: info,
|
||||
})
|
||||
}
|
||||
state.trains.sort((t1, t2) => t1.departureTime > t2.departureTime ? -1 : t1.departureTime == t2.arrivalTime ? 0 : 1)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const {downloadTrains } = trainSlice.actions
|
||||
|
||||
export default trainSlice.reducer
|
88
client/utils/geolocation.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import * as Location from 'expo-location'
|
||||
import * as TaskManager from 'expo-task-manager'
|
||||
import { Platform } from 'react-native'
|
||||
import { PlayerLocation, setLastLocation } from './features/location/locationSlice'
|
||||
import store from './store'
|
||||
import { useEffect } from 'react'
|
||||
import { socket } from './socket'
|
||||
import { useSettings } from '@/hooks/useGame'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { isAuthValid } from './features/auth/authSlice'
|
||||
|
||||
const LOCATION_TASK = "TRAINTRAPE_MOI_GEOLOCATION"
|
||||
|
||||
TaskManager.defineTask(LOCATION_TASK, async ({ data, error }: any) => {
|
||||
if (error) {
|
||||
console.error(error)
|
||||
return
|
||||
}
|
||||
const { locations } = data
|
||||
const lastLoc: Location.LocationObject = locations.at(-1)
|
||||
if (__DEV__)
|
||||
console.log("Localisation reçue :", lastLoc)
|
||||
store.dispatch(setLastLocation(lastLoc))
|
||||
const playerId = store.getState().game.playerId
|
||||
if (socket.active && playerId) {
|
||||
const lastLocToSend: PlayerLocation = {
|
||||
playerId: playerId,
|
||||
longitude: lastLoc.coords.longitude,
|
||||
latitude: lastLoc.coords.latitude,
|
||||
speed: lastLoc.coords.speed ?? 0,
|
||||
accuracy: lastLoc.coords.accuracy ?? 0,
|
||||
altitude: lastLoc.coords.altitude ?? 0,
|
||||
altitudeAccuracy: lastLoc.coords.altitudeAccuracy ?? 0,
|
||||
timestamp: new Date(lastLoc.timestamp).toISOString(),
|
||||
}
|
||||
socket.emit('last-location', lastLocToSend)
|
||||
}
|
||||
})
|
||||
|
||||
export async function startGeolocationService(locationAccuracy: Location.Accuracy | null): Promise<void | (() => void)> {
|
||||
if (Platform.OS !== "web" && await Location.hasStartedLocationUpdatesAsync(LOCATION_TASK))
|
||||
await Location.stopLocationUpdatesAsync(LOCATION_TASK)
|
||||
|
||||
if (locationAccuracy === null)
|
||||
return
|
||||
|
||||
await Location.enableNetworkProviderAsync().catch(error => alert(error))
|
||||
|
||||
const { status: foregroundStatus } = await Location.requestForegroundPermissionsAsync()
|
||||
if (foregroundStatus !== 'granted')
|
||||
alert("Vous devez activer votre géolocalisation pour utiliser l'application.")
|
||||
|
||||
const { status: backgroundStatus } = await Location.requestBackgroundPermissionsAsync()
|
||||
if (backgroundStatus !== 'granted')
|
||||
alert("Vous devez activer votre géolocalisation en arrière-plan pour utiliser l'application.")
|
||||
|
||||
if (Platform.OS !== "web") {
|
||||
await Location.startLocationUpdatesAsync(LOCATION_TASK, {
|
||||
accuracy: locationAccuracy,
|
||||
activityType: Location.ActivityType.OtherNavigation,
|
||||
distanceInterval: 10,
|
||||
timeInterval: 1000,
|
||||
foregroundService: {
|
||||
killServiceOnDestroy: false,
|
||||
notificationBody: "Géolocalisation activée pour « Traintrape-moi »",
|
||||
notificationTitle: "Traintrape-moi",
|
||||
notificationColor: "#FFFF00",
|
||||
}
|
||||
})
|
||||
return async () => await Location.stopLocationUpdatesAsync(LOCATION_TASK)
|
||||
}
|
||||
else {
|
||||
const locationSubscription = await Location.watchPositionAsync({ accuracy: locationAccuracy }, location_nouveau => store.dispatch(setLastLocation(location_nouveau)))
|
||||
return locationSubscription.remove
|
||||
}
|
||||
}
|
||||
|
||||
export const useStartGeolocationServiceEffect = () => {
|
||||
const auth = useAuth()
|
||||
const settings = useSettings()
|
||||
return useEffect(() => {
|
||||
if (!isAuthValid(auth))
|
||||
return
|
||||
let cleanup: void | (() => void) = () => {}
|
||||
startGeolocationService(settings.locationAccuracy).then(result => cleanup = result)
|
||||
return cleanup
|
||||
}, [auth, settings.locationAccuracy])
|
||||
}
|
3
client/utils/socket.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import { io } from 'socket.io-client'
|
||||
|
||||
export const socket = io(process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SOCKET)
|
25
client/utils/store.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { configureStore } from '@reduxjs/toolkit'
|
||||
import authReducer from './features/auth/authSlice'
|
||||
import challengesReducer from './features/challenges/challengesSlice'
|
||||
import challengeActionsReducer from './features/challengeActions/challengeActionsSlice'
|
||||
import gameReducer from './features/game/gameSlice'
|
||||
import locationReducer from './features/location/locationSlice'
|
||||
import moneyUpdatesReducer from './features/moneyUpdates/moneyUpdatesSlice'
|
||||
import trainReducer from './features/train/trainSlice'
|
||||
|
||||
const store = configureStore({
|
||||
reducer: {
|
||||
auth: authReducer,
|
||||
challenges: challengesReducer,
|
||||
challengeActions: challengeActionsReducer,
|
||||
game: gameReducer,
|
||||
location: locationReducer,
|
||||
moneyUpdates: moneyUpdatesReducer,
|
||||
train: trainReducer,
|
||||
},
|
||||
})
|
||||
|
||||
export default store
|
||||
|
||||
export type RootState = ReturnType<typeof store.getState>
|
||||
export type AppDispatch = typeof store.dispatch
|
4
server/.env.example
Normal file
@ -0,0 +1,4 @@
|
||||
DATABASE_URL="postgres://username:password@localhost:5432/traintrape-moi"
|
||||
JWT_SECRET="CHANGE_ME"
|
||||
API_GLOBAL_PREFIX="api"
|
||||
API_HOSTNAME="traintrape-moi.luemy.eu"
|
@ -21,5 +21,6 @@ module.exports = {
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/semi': 'never',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
9
server/.gitignore
vendored
@ -3,6 +3,10 @@
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Databases
|
||||
*.sqlite3
|
||||
*.sqlite3-journal
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
@ -37,10 +41,7 @@ lerna-debug.log*
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
.env*.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
|
@ -3,6 +3,14 @@
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
"deleteOutDir": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "@nestjs/swagger",
|
||||
"options": {
|
||||
"introspectComments": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
1060
server/package-lock.json
generated
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "traintrape-moi-server",
|
||||
"version": "0.0.1",
|
||||
"version": "1.1.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
@ -21,18 +21,34 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^10.0.0",
|
||||
"@nestjs/core": "^10.0.0",
|
||||
"@nestjs/core": "^10.4.13",
|
||||
"@nestjs/jwt": "^10.2.0",
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/platform-socket.io": "^10.4.15",
|
||||
"@nestjs/platform-ws": "^10.4.15",
|
||||
"@nestjs/swagger": "^8.1.0",
|
||||
"@nestjs/websockets": "^10.4.15",
|
||||
"@prisma/client": "^6.0.1",
|
||||
"bcrypt": "^5.1.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"prisma": "^6.0.1",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"rxjs": "^7.8.1"
|
||||
"rxjs": "^7.8.1",
|
||||
"swagger-ui-express": "^5.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.0.0",
|
||||
"@nestjs/schematics": "^10.0.0",
|
||||
"@nestjs/testing": "^10.0.0",
|
||||
"@nestjs/testing": "^10.4.13",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.2",
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/supertest": "^6.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
||||
"@typescript-eslint/parser": "^8.0.0",
|
||||
@ -65,5 +81,8 @@
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "ts-node prisma/seed.ts"
|
||||
}
|
||||
}
|
||||
|
162
server/prisma/migrations/20241208192715_init/migration.sql
Normal file
@ -0,0 +1,162 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MoneyUpdateType" AS ENUM ('START', 'NEW_RUN', 'WIN_CHALLENGE', 'BUY_TRAIN');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Player" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"password" TEXT NOT NULL,
|
||||
"money" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "Player_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Game" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"started" BOOLEAN NOT NULL DEFAULT false,
|
||||
"currentRunId" INTEGER,
|
||||
|
||||
CONSTRAINT "Game_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PlayerRun" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"gameId" INTEGER NOT NULL,
|
||||
"runnerId" INTEGER NOT NULL,
|
||||
"start" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"end" TIMESTAMPTZ(3),
|
||||
|
||||
CONSTRAINT "PlayerRun_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Geolocation" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"playerId" INTEGER NOT NULL,
|
||||
"longitude" DOUBLE PRECISION NOT NULL,
|
||||
"latitude" DOUBLE PRECISION NOT NULL,
|
||||
"speed" DOUBLE PRECISION NOT NULL,
|
||||
"accuracy" DOUBLE PRECISION NOT NULL,
|
||||
"altitude" DOUBLE PRECISION NOT NULL,
|
||||
"altitudeAccuracy" DOUBLE PRECISION NOT NULL,
|
||||
"timestamp" TIMESTAMPTZ(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Geolocation_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Challenge" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT NOT NULL,
|
||||
"reward" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "Challenge_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChallengeAction" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"playerId" INTEGER NOT NULL,
|
||||
"challengeId" INTEGER NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT false,
|
||||
"success" BOOLEAN NOT NULL DEFAULT false,
|
||||
"start" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"end" TIMESTAMPTZ(3),
|
||||
"penaltyStart" TIMESTAMPTZ(3),
|
||||
"penaltyEnd" TIMESTAMPTZ(3),
|
||||
"runId" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "ChallengeAction_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TrainTrip" (
|
||||
"id" TEXT NOT NULL,
|
||||
"playerId" INTEGER NOT NULL,
|
||||
"distance" DOUBLE PRECISION NOT NULL,
|
||||
"from" TEXT NOT NULL,
|
||||
"to" TEXT NOT NULL,
|
||||
"departureTime" TIMESTAMPTZ(3) NOT NULL,
|
||||
"arrivalTime" TIMESTAMPTZ(3) NOT NULL,
|
||||
"infoJson" JSONB NOT NULL,
|
||||
"runId" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "TrainTrip_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MoneyUpdate" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"playerId" INTEGER NOT NULL,
|
||||
"amount" INTEGER NOT NULL,
|
||||
"reason" "MoneyUpdateType" NOT NULL,
|
||||
"actionId" INTEGER,
|
||||
"tripId" TEXT,
|
||||
"runId" INTEGER,
|
||||
"timestamp" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MoneyUpdate_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Player_name_key" ON "Player"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Game_currentRunId_key" ON "Game"("currentRunId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Challenge_title_key" ON "Challenge"("title");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ChallengeAction_challengeId_key" ON "ChallengeAction"("challengeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MoneyUpdate_actionId_key" ON "MoneyUpdate"("actionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MoneyUpdate_tripId_key" ON "MoneyUpdate"("tripId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MoneyUpdate_runId_key" ON "MoneyUpdate"("runId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Game" ADD CONSTRAINT "Game_currentRunId_fkey" FOREIGN KEY ("currentRunId") REFERENCES "PlayerRun"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlayerRun" ADD CONSTRAINT "PlayerRun_gameId_fkey" FOREIGN KEY ("gameId") REFERENCES "Game"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlayerRun" ADD CONSTRAINT "PlayerRun_runnerId_fkey" FOREIGN KEY ("runnerId") REFERENCES "Player"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Geolocation" ADD CONSTRAINT "Geolocation_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "Player"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChallengeAction" ADD CONSTRAINT "ChallengeAction_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "Player"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChallengeAction" ADD CONSTRAINT "ChallengeAction_challengeId_fkey" FOREIGN KEY ("challengeId") REFERENCES "Challenge"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChallengeAction" ADD CONSTRAINT "ChallengeAction_runId_fkey" FOREIGN KEY ("runId") REFERENCES "PlayerRun"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TrainTrip" ADD CONSTRAINT "TrainTrip_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "Player"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TrainTrip" ADD CONSTRAINT "TrainTrip_runId_fkey" FOREIGN KEY ("runId") REFERENCES "PlayerRun"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "Player"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_actionId_fkey" FOREIGN KEY ("actionId") REFERENCES "ChallengeAction"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_tripId_fkey" FOREIGN KEY ("tripId") REFERENCES "TrainTrip"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_runId_fkey" FOREIGN KEY ("runId") REFERENCES "PlayerRun"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
@ -0,0 +1,18 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `active` on the `ChallengeAction` table. All the data in the column will be lost.
|
||||
- A unique constraint covering the columns `[activeChallengeId]` on the table `Player` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "ChallengeAction" DROP COLUMN "active";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Player" ADD COLUMN "activeChallengeId" INTEGER;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Player_activeChallengeId_key" ON "Player"("activeChallengeId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Player" ADD CONSTRAINT "Player_activeChallengeId_fkey" FOREIGN KEY ("activeChallengeId") REFERENCES "ChallengeAction"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
@ -0,0 +1,41 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "ChallengeAction" DROP CONSTRAINT "ChallengeAction_challengeId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Geolocation" DROP CONSTRAINT "Geolocation_playerId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "MoneyUpdate" DROP CONSTRAINT "MoneyUpdate_actionId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "MoneyUpdate" DROP CONSTRAINT "MoneyUpdate_runId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "MoneyUpdate" DROP CONSTRAINT "MoneyUpdate_tripId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "PlayerRun" DROP CONSTRAINT "PlayerRun_gameId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "PlayerRun" DROP CONSTRAINT "PlayerRun_runnerId_fkey";
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlayerRun" ADD CONSTRAINT "PlayerRun_gameId_fkey" FOREIGN KEY ("gameId") REFERENCES "Game"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlayerRun" ADD CONSTRAINT "PlayerRun_runnerId_fkey" FOREIGN KEY ("runnerId") REFERENCES "Player"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Geolocation" ADD CONSTRAINT "Geolocation_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "Player"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChallengeAction" ADD CONSTRAINT "ChallengeAction_challengeId_fkey" FOREIGN KEY ("challengeId") REFERENCES "Challenge"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_actionId_fkey" FOREIGN KEY ("actionId") REFERENCES "ChallengeAction"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_tripId_fkey" FOREIGN KEY ("tripId") REFERENCES "TrainTrip"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MoneyUpdate" ADD CONSTRAINT "MoneyUpdate_runId_fkey" FOREIGN KEY ("runId") REFERENCES "PlayerRun"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
@ -0,0 +1,14 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- The values [WIN_CHALLENGE] on the enum `MoneyUpdateType` will be removed. If these variants are still used in the database, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterEnum
|
||||
BEGIN;
|
||||
CREATE TYPE "MoneyUpdateType_new" AS ENUM ('START', 'NEW_RUN', 'CHALLENGE', 'BUY_TRAIN');
|
||||
ALTER TABLE "MoneyUpdate" ALTER COLUMN "reason" TYPE "MoneyUpdateType_new" USING ("reason"::text::"MoneyUpdateType_new");
|
||||
ALTER TYPE "MoneyUpdateType" RENAME TO "MoneyUpdateType_old";
|
||||
ALTER TYPE "MoneyUpdateType_new" RENAME TO "MoneyUpdateType";
|
||||
DROP TYPE "MoneyUpdateType_old";
|
||||
COMMIT;
|
3
server/prisma/migrations/migration_lock.toml
Normal file
@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "postgresql"
|
119
server/prisma/schema.prisma
Normal file
@ -0,0 +1,119 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Player {
|
||||
id Int @id @default(autoincrement())
|
||||
name String @unique
|
||||
password String
|
||||
money Int @default(0)
|
||||
activeChallenge ChallengeAction? @relation("ActiveChallenge", fields: [activeChallengeId], references: [id], onDelete: SetNull)
|
||||
activeChallengeId Int? @unique
|
||||
actions ChallengeAction[]
|
||||
geolocations Geolocation[]
|
||||
moneyUpdates MoneyUpdate[]
|
||||
trips TrainTrip[]
|
||||
runs PlayerRun[]
|
||||
}
|
||||
|
||||
model Game {
|
||||
id Int @id @default(autoincrement())
|
||||
started Boolean @default(false)
|
||||
currentRun PlayerRun? @relation("CurrentRun", fields: [currentRunId], references: [id], onDelete: SetNull)
|
||||
currentRunId Int? @unique
|
||||
runs PlayerRun[] @relation("GameRuns")
|
||||
}
|
||||
|
||||
model PlayerRun {
|
||||
id Int @id @default(autoincrement())
|
||||
game Game @relation("GameRuns", fields: [gameId], references: [id], onDelete: Cascade)
|
||||
runningGame Game? @relation("CurrentRun")
|
||||
gameId Int
|
||||
runner Player @relation(fields: [runnerId], references: [id], onDelete: Cascade)
|
||||
runnerId Int
|
||||
start DateTime @default(now()) @db.Timestamptz(3)
|
||||
end DateTime? @db.Timestamptz(3)
|
||||
moneyUpdate MoneyUpdate?
|
||||
challengeActions ChallengeAction[]
|
||||
trains TrainTrip[]
|
||||
}
|
||||
|
||||
model Geolocation {
|
||||
id Int @id @default(autoincrement())
|
||||
player Player @relation(fields: [playerId], references: [id], onDelete: Cascade)
|
||||
playerId Int
|
||||
longitude Float
|
||||
latitude Float
|
||||
speed Float
|
||||
accuracy Float
|
||||
altitude Float
|
||||
altitudeAccuracy Float
|
||||
timestamp DateTime @db.Timestamptz(3)
|
||||
}
|
||||
|
||||
model Challenge {
|
||||
id Int @id @default(autoincrement())
|
||||
title String @unique
|
||||
description String
|
||||
reward Int
|
||||
action ChallengeAction?
|
||||
}
|
||||
|
||||
model ChallengeAction {
|
||||
id Int @id @default(autoincrement())
|
||||
player Player @relation(fields: [playerId], references: [id], onDelete: Restrict)
|
||||
playerId Int
|
||||
challenge Challenge @relation(fields: [challengeId], references: [id], onDelete: Cascade)
|
||||
challengeId Int @unique
|
||||
success Boolean @default(false)
|
||||
start DateTime @default(now()) @db.Timestamptz(3)
|
||||
end DateTime? @db.Timestamptz(3)
|
||||
penaltyStart DateTime? @db.Timestamptz(3)
|
||||
penaltyEnd DateTime? @db.Timestamptz(3)
|
||||
run PlayerRun @relation(fields: [runId], references: [id], onDelete: Restrict)
|
||||
runId Int
|
||||
activePlayer Player? @relation("ActiveChallenge")
|
||||
moneyUpdate MoneyUpdate?
|
||||
}
|
||||
|
||||
model TrainTrip {
|
||||
id String @id
|
||||
player Player @relation(fields: [playerId], references: [id], onDelete: Restrict)
|
||||
playerId Int
|
||||
distance Float
|
||||
from String
|
||||
to String
|
||||
departureTime DateTime @db.Timestamptz(3)
|
||||
arrivalTime DateTime @db.Timestamptz(3)
|
||||
infoJson Json
|
||||
run PlayerRun @relation(fields: [runId], references: [id], onDelete: Restrict)
|
||||
runId Int
|
||||
moneyUpdate MoneyUpdate?
|
||||
}
|
||||
|
||||
model MoneyUpdate {
|
||||
id Int @id @default(autoincrement())
|
||||
player Player @relation(fields: [playerId], references: [id], onDelete: Restrict)
|
||||
playerId Int
|
||||
amount Int
|
||||
reason MoneyUpdateType
|
||||
action ChallengeAction? @relation(fields: [actionId], references: [id], onDelete: Cascade)
|
||||
actionId Int? @unique
|
||||
trip TrainTrip? @relation(fields: [tripId], references: [id], onDelete: Cascade)
|
||||
tripId String? @unique
|
||||
run PlayerRun? @relation(fields: [runId], references: [id], onDelete: Cascade)
|
||||
runId Int? @unique
|
||||
timestamp DateTime @default(now()) @db.Timestamptz(3)
|
||||
}
|
||||
|
||||
enum MoneyUpdateType {
|
||||
START
|
||||
NEW_RUN
|
||||
CHALLENGE
|
||||
BUY_TRAIN
|
||||
}
|
31
server/prisma/seed.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const game = await prisma.game.create({ data: {} })
|
||||
const emmyPassword = await bcrypt.hash("Emmy", 10)
|
||||
const emmy = await prisma.player.upsert({
|
||||
where: { id: 1 },
|
||||
update: { name: 'Emmy' },
|
||||
create: { name: 'Emmy', password: emmyPassword },
|
||||
})
|
||||
|
||||
const taminaPassword = await bcrypt.hash("Tamina", 10)
|
||||
const tamina = await prisma.player.upsert({
|
||||
where: { id: 2 },
|
||||
update: { name: 'Tamina' },
|
||||
create: { name: 'Tamina', password: taminaPassword },
|
||||
})
|
||||
console.log({ game, emmy, tamina })
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
@ -1,22 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
@ -1,12 +0,0 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|