Application Android et IOS pour l'amicale des élèves https://play.google.com/store/apps/details?id=fr.amicaleinsat.application
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EquipmentRentScreen.tsx 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Copyright (c) 2019 - 2020 Arnaud Vergnet.
  3. *
  4. * This file is part of Campus INSAT.
  5. *
  6. * Campus INSAT is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Campus INSAT is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import React, { useCallback, useRef, useState } from 'react';
  20. import {
  21. Button,
  22. Caption,
  23. Card,
  24. Headline,
  25. Subheading,
  26. useTheme,
  27. } from 'react-native-paper';
  28. import { StackNavigationProp, StackScreenProps } from '@react-navigation/stack';
  29. import { BackHandler, StyleSheet, View } from 'react-native';
  30. import * as Animatable from 'react-native-animatable';
  31. import i18n from 'i18n-js';
  32. import { CalendarList, PeriodMarking } from 'react-native-calendars';
  33. import LoadingConfirmDialog from '../../../components/Dialogs/LoadingConfirmDialog';
  34. import ErrorDialog from '../../../components/Dialogs/ErrorDialog';
  35. import {
  36. generateMarkedDates,
  37. getFirstEquipmentAvailability,
  38. getISODate,
  39. getRelativeDateString,
  40. getValidRange,
  41. isEquipmentAvailable,
  42. } from '../../../utils/EquipmentBooking';
  43. import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
  44. import { MainStackParamsList } from '../../../navigation/MainNavigator';
  45. import GENERAL_STYLES from '../../../constants/Styles';
  46. import { ApiRejectType } from '../../../utils/WebData';
  47. import { REQUEST_STATUS } from '../../../utils/Requests';
  48. import { useFocusEffect } from '@react-navigation/core';
  49. import { useNavigation } from '@react-navigation/native';
  50. import { useAuthenticatedRequest } from '../../../context/loginContext';
  51. type Props = StackScreenProps<MainStackParamsList, 'equipment-rent'>;
  52. export type MarkedDatesObjectType = {
  53. [key: string]: PeriodMarking;
  54. };
  55. const styles = StyleSheet.create({
  56. titleContainer: {
  57. marginLeft: 'auto',
  58. marginRight: 'auto',
  59. flexDirection: 'row',
  60. flexWrap: 'wrap',
  61. },
  62. title: {
  63. textAlign: 'center',
  64. },
  65. caption: {
  66. textAlign: 'center',
  67. lineHeight: 35,
  68. marginLeft: 10,
  69. },
  70. card: {
  71. margin: 5,
  72. },
  73. subtitle: {
  74. textAlign: 'center',
  75. marginBottom: 10,
  76. minHeight: 50,
  77. },
  78. calendar: {
  79. marginBottom: 50,
  80. },
  81. buttonContainer: {
  82. position: 'absolute',
  83. bottom: 0,
  84. left: 0,
  85. width: '100%',
  86. flex: 1,
  87. transform: [{ translateY: 100 }],
  88. },
  89. button: {
  90. width: '80%',
  91. flex: 1,
  92. marginLeft: 'auto',
  93. marginRight: 'auto',
  94. marginBottom: 20,
  95. borderRadius: 10,
  96. },
  97. });
  98. function EquipmentRentScreen(props: Props) {
  99. const theme = useTheme();
  100. const navigation = useNavigation<StackNavigationProp<any>>();
  101. const [currentError, setCurrentError] = useState<ApiRejectType>({
  102. status: REQUEST_STATUS.SUCCESS,
  103. });
  104. const [markedDates, setMarkedDates] = useState<MarkedDatesObjectType>({});
  105. const [dialogVisible, setDialogVisible] = useState(false);
  106. const item = props.route.params.item;
  107. const bookedDates = useRef<Array<string>>([]);
  108. const canBookEquipment = useRef(false);
  109. const bookRef = useRef<Animatable.View & View>(null);
  110. let lockedDates: {
  111. [key: string]: PeriodMarking;
  112. } = {};
  113. if (item) {
  114. item.booked_at.forEach((date: { begin: string; end: string }) => {
  115. const range = getValidRange(
  116. new Date(date.begin),
  117. new Date(date.end),
  118. null
  119. );
  120. lockedDates = {
  121. ...lockedDates,
  122. ...generateMarkedDates(false, theme, range),
  123. };
  124. });
  125. }
  126. useFocusEffect(
  127. useCallback(() => {
  128. BackHandler.addEventListener(
  129. 'hardwareBackPress',
  130. onBackButtonPressAndroid
  131. );
  132. return () => {
  133. BackHandler.removeEventListener(
  134. 'hardwareBackPress',
  135. onBackButtonPressAndroid
  136. );
  137. };
  138. // eslint-disable-next-line react-hooks/exhaustive-deps
  139. }, [])
  140. );
  141. /**
  142. * Overrides default android back button behaviour to deselect date if any is selected.
  143. *
  144. * @return {boolean}
  145. */
  146. const onBackButtonPressAndroid = (): boolean => {
  147. if (bookedDates.current.length > 0) {
  148. resetSelection();
  149. updateMarkedSelection();
  150. return true;
  151. }
  152. return false;
  153. };
  154. const showDialog = () => setDialogVisible(true);
  155. const onDialogDismiss = () => setDialogVisible(false);
  156. const onErrorDialogDismiss = () =>
  157. setCurrentError({ status: REQUEST_STATUS.SUCCESS });
  158. const getBookStartDate = (): Date | null => {
  159. return bookedDates.current.length > 0
  160. ? new Date(bookedDates.current[0])
  161. : null;
  162. };
  163. const getBookEndDate = (): Date | null => {
  164. const { length } = bookedDates.current;
  165. return length > 0 ? new Date(bookedDates.current[length - 1]) : null;
  166. };
  167. const start = getBookStartDate();
  168. const end = getBookEndDate();
  169. const request = useAuthenticatedRequest(
  170. 'location/booking',
  171. item && start && end
  172. ? {
  173. device: item.id,
  174. begin: getISODate(start),
  175. end: getISODate(end),
  176. }
  177. : undefined
  178. );
  179. /**
  180. * Sends the selected data to the server and waits for a response.
  181. * If the request is a success, navigate to the recap screen.
  182. * If it is an error, display the error to the user.
  183. *
  184. * @returns {Promise<void>}
  185. */
  186. const onDialogAccept = (): Promise<void> => {
  187. return new Promise((resolve: () => void) => {
  188. if (item != null && start != null && end != null) {
  189. request()
  190. .then(() => {
  191. onDialogDismiss();
  192. navigation.replace('equipment-confirm', {
  193. item: item,
  194. dates: [getISODate(start), getISODate(end)],
  195. });
  196. resolve();
  197. })
  198. .catch((error: ApiRejectType) => {
  199. onDialogDismiss();
  200. setCurrentError(error);
  201. resolve();
  202. });
  203. } else {
  204. onDialogDismiss();
  205. resolve();
  206. }
  207. });
  208. };
  209. /**
  210. * Selects a new date on the calendar.
  211. * If both start and end dates are already selected, unselect all.
  212. *
  213. * @param day The day selected
  214. */
  215. const selectNewDate = (day: {
  216. dateString: string;
  217. day: number;
  218. month: number;
  219. timestamp: number;
  220. year: number;
  221. }) => {
  222. const selected = new Date(day.dateString);
  223. if (!lockedDates[day.dateString] != null) {
  224. if (start === null) {
  225. updateSelectionRange(selected, selected);
  226. enableBooking();
  227. } else if (start.getTime() === selected.getTime()) {
  228. resetSelection();
  229. } else if (bookedDates.current.length === 1) {
  230. updateSelectionRange(start, selected);
  231. enableBooking();
  232. } else {
  233. resetSelection();
  234. }
  235. updateMarkedSelection();
  236. }
  237. };
  238. const showBookButton = () => {
  239. if (bookRef.current && bookRef.current.fadeInUp) {
  240. bookRef.current.fadeInUp(500);
  241. }
  242. };
  243. const hideBookButton = () => {
  244. if (bookRef.current && bookRef.current.fadeOutDown) {
  245. bookRef.current.fadeOutDown(500);
  246. }
  247. };
  248. const enableBooking = () => {
  249. if (!canBookEquipment.current) {
  250. showBookButton();
  251. canBookEquipment.current = true;
  252. }
  253. };
  254. const resetSelection = () => {
  255. if (canBookEquipment.current) {
  256. hideBookButton();
  257. }
  258. canBookEquipment.current = false;
  259. bookedDates.current = [];
  260. };
  261. const updateSelectionRange = (s: Date, e: Date) => {
  262. if (item) {
  263. bookedDates.current = getValidRange(s, e, item);
  264. } else {
  265. bookedDates.current = [];
  266. }
  267. };
  268. const updateMarkedSelection = () => {
  269. setMarkedDates(generateMarkedDates(true, theme, bookedDates.current));
  270. };
  271. let subHeadingText;
  272. if (start == null) {
  273. subHeadingText = i18n.t('screens.equipment.booking');
  274. } else if (end != null && start.getTime() !== end.getTime()) {
  275. subHeadingText = i18n.t('screens.equipment.bookingPeriod', {
  276. begin: getRelativeDateString(start),
  277. end: getRelativeDateString(end),
  278. });
  279. } else {
  280. subHeadingText = i18n.t('screens.equipment.bookingDay', {
  281. date: getRelativeDateString(start),
  282. });
  283. }
  284. if (item) {
  285. const isAvailable = isEquipmentAvailable(item);
  286. const firstAvailability = getFirstEquipmentAvailability(item);
  287. return (
  288. <View style={GENERAL_STYLES.flex}>
  289. <CollapsibleScrollView>
  290. <Card style={styles.card}>
  291. <Card.Content>
  292. <View style={GENERAL_STYLES.flex}>
  293. <View style={styles.titleContainer}>
  294. <Headline style={styles.title}>{item.name}</Headline>
  295. <Caption style={styles.caption}>
  296. ({i18n.t('screens.equipment.bail', { cost: item.caution })})
  297. </Caption>
  298. </View>
  299. </View>
  300. <Button
  301. icon={isAvailable ? 'check-circle-outline' : 'update'}
  302. color={
  303. isAvailable ? theme.colors.success : theme.colors.primary
  304. }
  305. mode="text"
  306. >
  307. {i18n.t('screens.equipment.available', {
  308. date: getRelativeDateString(firstAvailability),
  309. })}
  310. </Button>
  311. <Subheading style={styles.subtitle}>{subHeadingText}</Subheading>
  312. </Card.Content>
  313. </Card>
  314. <CalendarList
  315. // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
  316. minDate={new Date()}
  317. // Max amount of months allowed to scroll to the past. Default = 50
  318. pastScrollRange={0}
  319. // Max amount of months allowed to scroll to the future. Default = 50
  320. futureScrollRange={3}
  321. // Enable horizontal scrolling, default = false
  322. horizontal
  323. // Enable paging on horizontal, default = false
  324. pagingEnabled
  325. // Handler which gets executed on day press. Default = undefined
  326. onDayPress={selectNewDate}
  327. // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
  328. firstDay={1}
  329. // Hide month navigation arrows.
  330. hideArrows={false}
  331. // Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
  332. markingType={'period'}
  333. markedDates={{ ...lockedDates, ...markedDates }}
  334. theme={{
  335. 'backgroundColor': theme.colors.agendaBackgroundColor,
  336. 'calendarBackground': theme.colors.background,
  337. 'textSectionTitleColor': theme.colors.agendaDayTextColor,
  338. 'selectedDayBackgroundColor': theme.colors.primary,
  339. 'selectedDayTextColor': '#ffffff',
  340. 'todayTextColor': theme.colors.text,
  341. 'dayTextColor': theme.colors.text,
  342. 'textDisabledColor': theme.colors.agendaDayTextColor,
  343. 'dotColor': theme.colors.primary,
  344. 'selectedDotColor': '#ffffff',
  345. 'arrowColor': theme.colors.primary,
  346. 'monthTextColor': theme.colors.text,
  347. 'indicatorColor': theme.colors.primary,
  348. 'textDayFontFamily': 'monospace',
  349. 'textMonthFontFamily': 'monospace',
  350. 'textDayHeaderFontFamily': 'monospace',
  351. 'textDayFontWeight': '300',
  352. 'textMonthFontWeight': 'bold',
  353. 'textDayHeaderFontWeight': '300',
  354. 'textDayFontSize': 16,
  355. 'textMonthFontSize': 16,
  356. 'textDayHeaderFontSize': 16,
  357. 'stylesheet.day.period': {
  358. base: {
  359. overflow: 'hidden',
  360. height: 34,
  361. width: 34,
  362. alignItems: 'center',
  363. },
  364. },
  365. }}
  366. style={styles.calendar}
  367. />
  368. </CollapsibleScrollView>
  369. <LoadingConfirmDialog
  370. visible={dialogVisible}
  371. onDismiss={onDialogDismiss}
  372. onAccept={onDialogAccept}
  373. title={i18n.t('screens.equipment.dialogTitle')}
  374. titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
  375. message={i18n.t('screens.equipment.dialogMessage')}
  376. />
  377. <ErrorDialog
  378. visible={currentError.status !== REQUEST_STATUS.SUCCESS}
  379. onDismiss={onErrorDialogDismiss}
  380. status={currentError.status}
  381. code={currentError.code}
  382. />
  383. <Animatable.View
  384. ref={bookRef}
  385. useNativeDriver
  386. style={styles.buttonContainer}
  387. >
  388. <Button
  389. icon="bookmark-check"
  390. mode="contained"
  391. onPress={showDialog}
  392. style={styles.button}
  393. >
  394. {i18n.t('screens.equipment.bookButton')}
  395. </Button>
  396. </Animatable.View>
  397. </View>
  398. );
  399. }
  400. return null;
  401. }
  402. export default EquipmentRentScreen;