Application Android et IOS pour l'amicale des élèves
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.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // @flow
  2. import * as React from 'react';
  3. import {Button, Caption, Card, Headline, Subheading, withTheme} from 'react-native-paper';
  4. import {Collapsible} from "react-navigation-collapsible";
  5. import {withCollapsible} from "../../../utils/withCollapsible";
  6. import {StackNavigationProp} from "@react-navigation/stack";
  7. import type {CustomTheme} from "../../../managers/ThemeManager";
  8. import type {Device} from "./EquipmentListScreen";
  9. import {Animated, BackHandler} from "react-native";
  10. import * as Animatable from "react-native-animatable";
  11. import {View} from "react-native-animatable";
  12. import i18n from "i18n-js";
  13. import {CalendarList} from "react-native-calendars";
  14. import LoadingConfirmDialog from "../../../components/Dialogs/LoadingConfirmDialog";
  15. import ConnectionManager from "../../../managers/ConnectionManager";
  16. import ErrorDialog from "../../../components/Dialogs/ErrorDialog";
  17. import {
  18. generateMarkedDates,
  19. getFirstEquipmentAvailability,
  20. getISODate,
  21. getRelativeDateString,
  22. getValidRange,
  23. isEquipmentAvailable
  24. } from "../../../utils/EquipmentBooking";
  25. type Props = {
  26. navigation: StackNavigationProp,
  27. route: {
  28. params?: {
  29. item?: Device,
  30. },
  31. },
  32. theme: CustomTheme,
  33. collapsibleStack: Collapsible,
  34. }
  35. type State = {
  36. dialogVisible: boolean,
  37. errorDialogVisible: boolean,
  38. markedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } },
  39. currentError: number,
  40. }
  41. class EquipmentRentScreen extends React.Component<Props, State> {
  42. state = {
  43. dialogVisible: false,
  44. errorDialogVisible: false,
  45. markedDates: {},
  46. currentError: 0,
  47. }
  48. item: Device | null;
  49. bookedDates: Array<string>;
  50. bookRef: { current: null | Animatable.View }
  51. canBookEquipment: boolean;
  52. lockedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } }
  53. constructor(props: Props) {
  54. super(props);
  55. this.resetSelection();
  56. this.bookRef = React.createRef();
  57. this.canBookEquipment = false;
  58. this.bookedDates = [];
  59. if (this.props.route.params != null) {
  60. if (this.props.route.params.item != null)
  61. this.item = this.props.route.params.item;
  62. else
  63. this.item = null;
  64. }
  65. const item = this.item;
  66. if (item != null) {
  67. this.lockedDates = {};
  68. for (let i = 0; i < item.booked_at.length; i++) {
  69. const range = getValidRange(new Date(item.booked_at[i].begin), new Date(item.booked_at[i].end), null);
  70. this.lockedDates = {
  71. ...this.lockedDates,
  72. ...generateMarkedDates(
  73. false,
  74. this.props.theme,
  75. range
  76. )
  77. };
  78. }
  79. }
  80. }
  81. /**
  82. * Captures focus and blur events to hook on android back button
  83. */
  84. componentDidMount() {
  85. this.props.navigation.addListener(
  86. 'focus',
  87. () =>
  88. BackHandler.addEventListener(
  89. 'hardwareBackPress',
  90. this.onBackButtonPressAndroid
  91. )
  92. );
  93. this.props.navigation.addListener(
  94. 'blur',
  95. () =>
  96. BackHandler.removeEventListener(
  97. 'hardwareBackPress',
  98. this.onBackButtonPressAndroid
  99. )
  100. );
  101. }
  102. /**
  103. * Overrides default android back button behaviour to deselect date if any is selected.
  104. *
  105. * @return {boolean}
  106. */
  107. onBackButtonPressAndroid = () => {
  108. if (this.bookedDates.length > 0) {
  109. this.resetSelection();
  110. this.updateMarkedSelection();
  111. return true;
  112. } else
  113. return false;
  114. };
  115. /**
  116. * Selects a new date on the calendar.
  117. * If both start and end dates are already selected, unselect all.
  118. *
  119. * @param day The day selected
  120. */
  121. selectNewDate = (day: { dateString: string, day: number, month: number, timestamp: number, year: number }) => {
  122. const selected = new Date(day.dateString);
  123. const start = this.getBookStartDate();
  124. if (!(this.lockedDates.hasOwnProperty(day.dateString))) {
  125. if (start === null) {
  126. this.updateSelectionRange(selected, selected);
  127. this.enableBooking();
  128. } else if (start.getTime() === selected.getTime()) {
  129. this.resetSelection();
  130. } else if (this.bookedDates.length === 1) {
  131. this.updateSelectionRange(start, selected);
  132. this.enableBooking();
  133. } else
  134. this.resetSelection();
  135. this.updateMarkedSelection();
  136. }
  137. }
  138. updateSelectionRange(start: Date, end: Date) {
  139. this.bookedDates = getValidRange(start, end, this.item);
  140. }
  141. updateMarkedSelection() {
  142. this.setState({
  143. markedDates: generateMarkedDates(
  144. true,
  145. this.props.theme,
  146. this.bookedDates
  147. ),
  148. });
  149. }
  150. enableBooking() {
  151. if (!this.canBookEquipment) {
  152. this.showBookButton();
  153. this.canBookEquipment = true;
  154. }
  155. }
  156. resetSelection() {
  157. if (this.canBookEquipment)
  158. this.hideBookButton();
  159. this.canBookEquipment = false;
  160. this.bookedDates = [];
  161. }
  162. /**
  163. * Shows the book button by plying a fade animation
  164. */
  165. showBookButton() {
  166. if (this.bookRef.current != null) {
  167. this.bookRef.current.fadeInUp(500);
  168. }
  169. }
  170. /**
  171. * Hides the book button by plying a fade animation
  172. */
  173. hideBookButton() {
  174. if (this.bookRef.current != null) {
  175. this.bookRef.current.fadeOutDown(500);
  176. }
  177. }
  178. showDialog = () => {
  179. this.setState({dialogVisible: true});
  180. }
  181. showErrorDialog = (error: number) => {
  182. this.setState({
  183. errorDialogVisible: true,
  184. currentError: error,
  185. });
  186. }
  187. onDialogDismiss = () => {
  188. this.setState({dialogVisible: false});
  189. }
  190. onErrorDialogDismiss = () => {
  191. this.setState({errorDialogVisible: false});
  192. }
  193. /**
  194. * Sends the selected data to the server and waits for a response.
  195. * If the request is a success, navigate to the recap screen.
  196. * If it is an error, display the error to the user.
  197. *
  198. * @returns {Promise<R>}
  199. */
  200. onDialogAccept = () => {
  201. return new Promise((resolve) => {
  202. const item = this.item;
  203. const start = this.getBookStartDate();
  204. const end = this.getBookEndDate();
  205. if (item != null && start != null && end != null) {
  206. ConnectionManager.getInstance().authenticatedRequest(
  207. "location/booking",
  208. {
  209. "device": item.id,
  210. "begin": getISODate(start),
  211. "end": getISODate(end),
  212. })
  213. .then(() => {
  214. console.log("Success, replace screen");
  215. resolve();
  216. })
  217. .catch((error: number) => {
  218. this.onDialogDismiss();
  219. this.showErrorDialog(error);
  220. resolve();
  221. });
  222. } else
  223. resolve();
  224. });
  225. }
  226. getBookStartDate() {
  227. return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
  228. }
  229. getBookEndDate() {
  230. const length = this.bookedDates.length;
  231. return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
  232. }
  233. render() {
  234. const {containerPaddingTop, scrollIndicatorInsetTop, onScroll} = this.props.collapsibleStack;
  235. const item = this.item;
  236. const start = this.getBookStartDate();
  237. const end = this.getBookEndDate();
  238. if (item != null) {
  239. const isAvailable = isEquipmentAvailable(item);
  240. const firstAvailability = getFirstEquipmentAvailability(item);
  241. return (
  242. <View style={{flex: 1}}>
  243. <Animated.ScrollView
  244. // Animations
  245. onScroll={onScroll}
  246. contentContainerStyle={{
  247. paddingTop: containerPaddingTop,
  248. minHeight: '100%'
  249. }}
  250. scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}>
  251. <Card style={{margin: 5}}>
  252. <Card.Content>
  253. <View style={{flex: 1}}>
  254. <View style={{
  255. marginLeft: "auto",
  256. marginRight: "auto",
  257. flexDirection: "row",
  258. flexWrap: "wrap",
  259. }}>
  260. <Headline style={{textAlign: "center"}}>
  261. {item.name}
  262. </Headline>
  263. <Caption style={{
  264. textAlign: "center",
  265. lineHeight: 35,
  266. marginLeft: 10,
  267. }}>
  268. ({i18n.t('equipmentScreen.bail', {cost: item.caution})})
  269. </Caption>
  270. </View>
  271. </View>
  272. <Button
  273. icon={isAvailable ? "check-circle-outline" : "update"}
  274. color={isAvailable ? this.props.theme.colors.success : this.props.theme.colors.primary}
  275. mode="text"
  276. >
  277. {i18n.t('equipmentScreen.available', {date: getRelativeDateString(firstAvailability)})}
  278. </Button>
  279. <Subheading style={{
  280. textAlign: "center",
  281. marginBottom: 10,
  282. minHeight: 50
  283. }}>
  284. {
  285. start == null
  286. ? i18n.t('equipmentScreen.booking')
  287. : end != null && start.getTime() !== end.getTime()
  288. ? i18n.t('equipmentScreen.bookingPeriod', {
  289. begin: getRelativeDateString(start),
  290. end: getRelativeDateString(end)
  291. })
  292. : i18n.t('equipmentScreen.bookingDay', {
  293. date: getRelativeDateString(start)
  294. })
  295. }
  296. </Subheading>
  297. </Card.Content>
  298. </Card>
  299. <CalendarList
  300. // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
  301. minDate={new Date()}
  302. // Max amount of months allowed to scroll to the past. Default = 50
  303. pastScrollRange={0}
  304. // Max amount of months allowed to scroll to the future. Default = 50
  305. futureScrollRange={3}
  306. // Enable horizontal scrolling, default = false
  307. horizontal={true}
  308. // Enable paging on horizontal, default = false
  309. pagingEnabled={true}
  310. // Handler which gets executed on day press. Default = undefined
  311. onDayPress={this.selectNewDate}
  312. // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
  313. firstDay={1}
  314. // Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates
  315. disableAllTouchEventsForDisabledDays={true}
  316. // Hide month navigation arrows.
  317. hideArrows={false}
  318. // Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
  319. markingType={'period'}
  320. markedDates={{...this.lockedDates, ...this.state.markedDates}}
  321. theme={{
  322. backgroundColor: this.props.theme.colors.agendaBackgroundColor,
  323. calendarBackground: this.props.theme.colors.background,
  324. textSectionTitleColor: this.props.theme.colors.agendaDayTextColor,
  325. selectedDayBackgroundColor: this.props.theme.colors.primary,
  326. selectedDayTextColor: '#ffffff',
  327. todayTextColor: this.props.theme.colors.text,
  328. dayTextColor: this.props.theme.colors.text,
  329. textDisabledColor: this.props.theme.colors.agendaDayTextColor,
  330. dotColor: this.props.theme.colors.primary,
  331. selectedDotColor: '#ffffff',
  332. arrowColor: this.props.theme.colors.primary,
  333. monthTextColor: this.props.theme.colors.text,
  334. indicatorColor: this.props.theme.colors.primary,
  335. textDayFontFamily: 'monospace',
  336. textMonthFontFamily: 'monospace',
  337. textDayHeaderFontFamily: 'monospace',
  338. textDayFontWeight: '300',
  339. textMonthFontWeight: 'bold',
  340. textDayHeaderFontWeight: '300',
  341. textDayFontSize: 16,
  342. textMonthFontSize: 16,
  343. textDayHeaderFontSize: 16,
  344. 'stylesheet.day.period': {
  345. base: {
  346. overflow: 'hidden',
  347. height: 34,
  348. width: 34,
  349. alignItems: 'center',
  350. }
  351. }
  352. }}
  353. style={{marginBottom: 50}}
  354. />
  355. </Animated.ScrollView>
  356. <LoadingConfirmDialog
  357. visible={this.state.dialogVisible}
  358. onDismiss={this.onDialogDismiss}
  359. onAccept={this.onDialogAccept}
  360. title={i18n.t('equipmentScreen.dialogTitle')}
  361. titleLoading={i18n.t('equipmentScreen.dialogTitleLoading')}
  362. message={i18n.t('equipmentScreen.dialogMessage')}
  363. />
  364. <ErrorDialog
  365. visible={this.state.errorDialogVisible}
  366. onDismiss={this.onErrorDialogDismiss}
  367. errorCode={this.state.currentError}
  368. />
  369. <Animatable.View
  370. ref={this.bookRef}
  371. style={{
  372. position: "absolute",
  373. bottom: 0,
  374. left: 0,
  375. width: "100%",
  376. flex: 1,
  377. transform: [
  378. {translateY: 100},
  379. ]
  380. }}>
  381. <Button
  382. icon="bookmark-check"
  383. mode="contained"
  384. onPress={this.showDialog}
  385. style={{
  386. width: "80%",
  387. flex: 1,
  388. marginLeft: "auto",
  389. marginRight: "auto",
  390. marginBottom: 20,
  391. borderRadius: 10
  392. }}
  393. >
  394. {i18n.t('equipmentScreen.bookButton')}
  395. </Button>
  396. </Animatable.View>
  397. </View>
  398. )
  399. } else
  400. return <View/>;
  401. }
  402. }
  403. export default withCollapsible(withTheme(EquipmentRentScreen));