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.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // @flow
  2. import * as React from 'react';
  3. import {Button, Caption, Card, Headline, Subheading, withTheme} from 'react-native-paper';
  4. import {StackNavigationProp} from "@react-navigation/stack";
  5. import type {CustomTheme} from "../../../managers/ThemeManager";
  6. import type {Device} from "./EquipmentListScreen";
  7. import {BackHandler, View} from "react-native";
  8. import * as Animatable from "react-native-animatable";
  9. import i18n from "i18n-js";
  10. import {CalendarList} from "react-native-calendars";
  11. import LoadingConfirmDialog from "../../../components/Dialogs/LoadingConfirmDialog";
  12. import ErrorDialog from "../../../components/Dialogs/ErrorDialog";
  13. import {
  14. generateMarkedDates,
  15. getFirstEquipmentAvailability,
  16. getISODate,
  17. getRelativeDateString,
  18. getValidRange,
  19. isEquipmentAvailable
  20. } from "../../../utils/EquipmentBooking";
  21. import ConnectionManager from "../../../managers/ConnectionManager";
  22. import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
  23. type Props = {
  24. navigation: StackNavigationProp,
  25. route: {
  26. params?: {
  27. item?: Device,
  28. },
  29. },
  30. theme: CustomTheme,
  31. }
  32. type State = {
  33. dialogVisible: boolean,
  34. errorDialogVisible: boolean,
  35. markedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } },
  36. currentError: number,
  37. }
  38. class EquipmentRentScreen extends React.Component<Props, State> {
  39. state = {
  40. dialogVisible: false,
  41. errorDialogVisible: false,
  42. markedDates: {},
  43. currentError: 0,
  44. }
  45. item: Device | null;
  46. bookedDates: Array<string>;
  47. bookRef: { current: null | Animatable.View }
  48. canBookEquipment: boolean;
  49. lockedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } }
  50. constructor(props: Props) {
  51. super(props);
  52. this.resetSelection();
  53. this.bookRef = React.createRef();
  54. this.canBookEquipment = false;
  55. this.bookedDates = [];
  56. if (this.props.route.params != null) {
  57. if (this.props.route.params.item != null)
  58. this.item = this.props.route.params.item;
  59. else
  60. this.item = null;
  61. }
  62. const item = this.item;
  63. if (item != null) {
  64. this.lockedDates = {};
  65. for (let i = 0; i < item.booked_at.length; i++) {
  66. const range = getValidRange(new Date(item.booked_at[i].begin), new Date(item.booked_at[i].end), null);
  67. this.lockedDates = {
  68. ...this.lockedDates,
  69. ...generateMarkedDates(
  70. false,
  71. this.props.theme,
  72. range
  73. )
  74. };
  75. }
  76. }
  77. }
  78. /**
  79. * Captures focus and blur events to hook on android back button
  80. */
  81. componentDidMount() {
  82. this.props.navigation.addListener(
  83. 'focus',
  84. () =>
  85. BackHandler.addEventListener(
  86. 'hardwareBackPress',
  87. this.onBackButtonPressAndroid
  88. )
  89. );
  90. this.props.navigation.addListener(
  91. 'blur',
  92. () =>
  93. BackHandler.removeEventListener(
  94. 'hardwareBackPress',
  95. this.onBackButtonPressAndroid
  96. )
  97. );
  98. }
  99. /**
  100. * Overrides default android back button behaviour to deselect date if any is selected.
  101. *
  102. * @return {boolean}
  103. */
  104. onBackButtonPressAndroid = () => {
  105. if (this.bookedDates.length > 0) {
  106. this.resetSelection();
  107. this.updateMarkedSelection();
  108. return true;
  109. } else
  110. return false;
  111. };
  112. /**
  113. * Selects a new date on the calendar.
  114. * If both start and end dates are already selected, unselect all.
  115. *
  116. * @param day The day selected
  117. */
  118. selectNewDate = (day: { dateString: string, day: number, month: number, timestamp: number, year: number }) => {
  119. const selected = new Date(day.dateString);
  120. const start = this.getBookStartDate();
  121. if (!(this.lockedDates.hasOwnProperty(day.dateString))) {
  122. if (start === null) {
  123. this.updateSelectionRange(selected, selected);
  124. this.enableBooking();
  125. } else if (start.getTime() === selected.getTime()) {
  126. this.resetSelection();
  127. } else if (this.bookedDates.length === 1) {
  128. this.updateSelectionRange(start, selected);
  129. this.enableBooking();
  130. } else
  131. this.resetSelection();
  132. this.updateMarkedSelection();
  133. }
  134. }
  135. updateSelectionRange(start: Date, end: Date) {
  136. this.bookedDates = getValidRange(start, end, this.item);
  137. }
  138. updateMarkedSelection() {
  139. this.setState({
  140. markedDates: generateMarkedDates(
  141. true,
  142. this.props.theme,
  143. this.bookedDates
  144. ),
  145. });
  146. }
  147. enableBooking() {
  148. if (!this.canBookEquipment) {
  149. this.showBookButton();
  150. this.canBookEquipment = true;
  151. }
  152. }
  153. resetSelection() {
  154. if (this.canBookEquipment)
  155. this.hideBookButton();
  156. this.canBookEquipment = false;
  157. this.bookedDates = [];
  158. }
  159. /**
  160. * Shows the book button by plying a fade animation
  161. */
  162. showBookButton() {
  163. if (this.bookRef.current != null) {
  164. this.bookRef.current.fadeInUp(500);
  165. }
  166. }
  167. /**
  168. * Hides the book button by plying a fade animation
  169. */
  170. hideBookButton() {
  171. if (this.bookRef.current != null) {
  172. this.bookRef.current.fadeOutDown(500);
  173. }
  174. }
  175. showDialog = () => {
  176. this.setState({dialogVisible: true});
  177. }
  178. showErrorDialog = (error: number) => {
  179. this.setState({
  180. errorDialogVisible: true,
  181. currentError: error,
  182. });
  183. }
  184. onDialogDismiss = () => {
  185. this.setState({dialogVisible: false});
  186. }
  187. onErrorDialogDismiss = () => {
  188. this.setState({errorDialogVisible: false});
  189. }
  190. /**
  191. * Sends the selected data to the server and waits for a response.
  192. * If the request is a success, navigate to the recap screen.
  193. * If it is an error, display the error to the user.
  194. *
  195. * @returns {Promise<R>}
  196. */
  197. onDialogAccept = () => {
  198. return new Promise((resolve) => {
  199. const item = this.item;
  200. const start = this.getBookStartDate();
  201. const end = this.getBookEndDate();
  202. if (item != null && start != null && end != null) {
  203. console.log({
  204. "device": item.id,
  205. "begin": getISODate(start),
  206. "end": getISODate(end),
  207. })
  208. ConnectionManager.getInstance().authenticatedRequest(
  209. "location/booking",
  210. {
  211. "device": item.id,
  212. "begin": getISODate(start),
  213. "end": getISODate(end),
  214. })
  215. .then(() => {
  216. this.onDialogDismiss();
  217. this.props.navigation.replace("equipment-confirm", {
  218. item: this.item,
  219. dates: [getISODate(start), getISODate(end)]
  220. });
  221. resolve();
  222. })
  223. .catch((error: number) => {
  224. this.onDialogDismiss();
  225. this.showErrorDialog(error);
  226. resolve();
  227. });
  228. } else {
  229. this.onDialogDismiss();
  230. resolve();
  231. }
  232. });
  233. }
  234. getBookStartDate() {
  235. return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
  236. }
  237. getBookEndDate() {
  238. const length = this.bookedDates.length;
  239. return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
  240. }
  241. render() {
  242. const item = this.item;
  243. const start = this.getBookStartDate();
  244. const end = this.getBookEndDate();
  245. if (item != null) {
  246. const isAvailable = isEquipmentAvailable(item);
  247. const firstAvailability = getFirstEquipmentAvailability(item);
  248. return (
  249. <View style={{flex: 1}}>
  250. <CollapsibleScrollView>
  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('screens.equipment.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('screens.equipment.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('screens.equipment.booking')
  287. : end != null && start.getTime() !== end.getTime()
  288. ? i18n.t('screens.equipment.bookingPeriod', {
  289. begin: getRelativeDateString(start),
  290. end: getRelativeDateString(end)
  291. })
  292. : i18n.t('screens.equipment.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. </CollapsibleScrollView>
  356. <LoadingConfirmDialog
  357. visible={this.state.dialogVisible}
  358. onDismiss={this.onDialogDismiss}
  359. onAccept={this.onDialogAccept}
  360. title={i18n.t('screens.equipment.dialogTitle')}
  361. titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
  362. message={i18n.t('screens.equipment.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('screens.equipment.bookButton')}
  395. </Button>
  396. </Animatable.View>
  397. </View>
  398. )
  399. } else
  400. return <View/>;
  401. }
  402. }
  403. export default withTheme(EquipmentRentScreen);