scanQrPage.tsx 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. import { CameraView, useCameraPermissions } from 'expo-camera';
  2. import { useCallback, useEffect, useRef, useState } from 'react';
  3. import {
  4. ActivityIndicator,
  5. Alert,
  6. AppState,
  7. Dimensions,
  8. Linking,
  9. Pressable,
  10. ScrollView,
  11. StyleSheet,
  12. Text,
  13. Vibration,
  14. View
  15. } from 'react-native';
  16. import sha256 from 'crypto-js/sha256';
  17. import ChooseCarForChargingRow from '../../../../component/global/chooseCarForChargingRow';
  18. import { CrossLogoWhiteSvg, QuestionSvg } from '../../../../component/global/SVG';
  19. import { router, useFocusEffect } from 'expo-router';
  20. import { chargeStationService } from '../../../../service/chargeStationService';
  21. import { authenticationService } from '../../../../service/authService';
  22. import { walletService } from '../../../../service/walletService';
  23. import useUserInfoStore from '../../../../providers/userinfo_store';
  24. import Modal from 'react-native-modal';
  25. import NormalButton from '../../../../component/global/normal_button';
  26. import { ceil } from 'lodash';
  27. import AsyncStorage from '@react-native-async-storage/async-storage';
  28. import { useChargingStore } from '../../../../providers/scan_qr_payload_store';
  29. const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
  30. // const ChooseCar = ({ carData, loading, selectedCar, setSelectedCar }) => {
  31. // const isLargeScreen = screenHeight >= 800;
  32. // const defaultImageUrl = require('../../../../assets/car1.png');
  33. // return (
  34. // <View
  35. // style={{
  36. // ...(isLargeScreen
  37. // ? {
  38. // marginTop: '10%',
  39. // marginBottom: '12%',
  40. // paddingBottom: 12
  41. // }
  42. // : {
  43. // flex: 1,
  44. // alignItems: 'center',
  45. // justifyContent: 'center'
  46. // })
  47. // }}
  48. // >
  49. // <View className="justify-center items-center flex-1 ">
  50. // <View
  51. // style={{
  52. // ...(isLargeScreen
  53. // ? {}
  54. // : {
  55. // backgroundColor: 'rgba(0,0,0,0.7)'
  56. // })
  57. // }}
  58. // >
  59. // {loading ? (
  60. // <View className="w-full">
  61. // <ActivityIndicator color="#34657b" />
  62. // </View>
  63. // ) : (
  64. // <View className="w-screen bg-[#000000B3]">
  65. // <View className="flex-row items-center justify-between mx-[5%] ">
  66. // <Pressable
  67. // className="pt-4 "
  68. // onPress={() => {
  69. // if (router.canGoBack()) {
  70. // router.back();
  71. // } else {
  72. // router.replace('mainPage');
  73. // }
  74. // }}
  75. // >
  76. // <CrossLogoWhiteSvg />
  77. // </Pressable>
  78. // <Text className="text-base text-white pt-2">選擇充電車輛</Text>
  79. // <Text className="text-xl text-white pt-2"></Text>
  80. // </View>
  81. // <ScrollView
  82. // horizontal={true}
  83. // showsHorizontalScrollIndicator={false}
  84. // contentContainerStyle={{
  85. // alignItems: 'center',
  86. // flexDirection: 'row',
  87. // marginVertical: 12
  88. // }}
  89. // className="space-x-2 mx-[5%]"
  90. // >
  91. // {carData.map((car, index) => (
  92. // <ChooseCarForChargingRow
  93. // key={`${car.name}+${index}`}
  94. // image={car.image}
  95. // onPress={() => {
  96. // setSelectedCar(car.id);
  97. // console.log(car.id);
  98. // }}
  99. // isSelected={selectedCar === car.id}
  100. // // imageUrl={image}
  101. // VehicleName={car.name}
  102. // isDefault={car.isDefault}
  103. // />
  104. // ))}
  105. // </ScrollView>
  106. // </View>
  107. // )}
  108. // </View>
  109. // </View>
  110. // </View>
  111. // );
  112. // };
  113. //reminder: scan qr code page, ic call should be false
  114. const ScanQrPage = () => {
  115. const { userID, currentPrice, setCurrentPrice } = useUserInfoStore();
  116. const [currentPriceFetchedWhenScanQr, setCurrentPriceFetchedWhenScanQr] = useState(0);
  117. const { scanned_qr_code, setScannedQrCode, stationID, setStationId } = useChargingStore();
  118. const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
  119. const [permission, requestPermission] = useCameraPermissions();
  120. const [scanned, setScanned] = useState(false);
  121. const viewRef = useRef(null);
  122. const [scannedResult, setScannedResult] = useState('');
  123. const [selectedCar, setSelectedCar] = useState('');
  124. const now = new Date();
  125. const [loading, setLoading] = useState(true);
  126. const [loading2, setLoading2] = useState(false);
  127. const [loading3, setLoading3] = useState(false);
  128. const [carData, setCarData] = useState([]);
  129. const [isModalVisible, setModalVisible] = useState(false);
  130. const [isConfirmLoading, setIsConfirmLoading] = useState(false);
  131. const [availableSlots, setAvailableSlots] = useState({
  132. // 3: false,
  133. 25: false,
  134. 30: false,
  135. 40: false,
  136. 45: false,
  137. full: false
  138. });
  139. const [selectedDuration, setSelectedDuration] = useState(null);
  140. const appState = useRef(AppState.currentState);
  141. const [paymentStatus, setPaymentStatus] = useState(null);
  142. const [isExpectingPayment, setIsExpectingPayment] = useState(false);
  143. const paymentInitiatedTime = useRef(null);
  144. const PAYMENT_CHECK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
  145. const [outTradeNo, setOutTradeNo] = useState('');
  146. const [totalFee, setTotalFee] = useState(0);
  147. const [walletBalance, setWalletBalance] = useState(0);
  148. // Effect for requesting camera permissions
  149. useEffect(() => {
  150. (async () => {
  151. const { status } = await requestPermission();
  152. if (status !== 'granted') {
  153. alert(
  154. '我們需要相機權限來掃描機器上的二維碼,以便識別並啟動充電機器。我們不會儲存或共享任何掃描到的資訊。 請前往設定開啟相機權限'
  155. );
  156. }
  157. })();
  158. }, []);
  159. useFocusEffect(
  160. useCallback(() => {
  161. // When screen comes into focus, enable scanning
  162. setScanned(false);
  163. return () => {
  164. // When screen loses focus, disable scanning
  165. setScanned(true);
  166. };
  167. }, [])
  168. );
  169. // Effect for fetching user's cars
  170. // useEffect(() => {
  171. // const fetchAllCars = async () => {
  172. // try {
  173. // const response = await chargeStationService.getUserCars();
  174. // if (response) {
  175. // console.log('data', response.data);
  176. // const carTypes = response.data.map((item: any) => ({
  177. // id: item.id,
  178. // name: item.car_typ e.name,
  179. // image: item.car_type.type_image_url
  180. // }));
  181. // // console.log('carTypes', carTypes);
  182. // // console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', carTypes);
  183. // let updatedCarTypes = [...carTypes];
  184. // for (let i = 0; i < carTypes.length; i++) {
  185. // const car = updatedCarTypes[i];
  186. // const imageUrl = await chargeStationService.getProcessedImageUrl(car.image);
  187. // updatedCarTypes[i] = {
  188. // ...car,
  189. // image: imageUrl
  190. // };
  191. // }
  192. // setCarData(updatedCarTypes);
  193. // // console.log('updatedCarTypes', updatedCarTypes);
  194. // return true;
  195. // }
  196. // } catch (error) {
  197. // console.log(error);
  198. // } finally {
  199. // setLoading(false);
  200. // }
  201. // };
  202. // fetchAllCars();
  203. // }, []);
  204. useEffect(() => {
  205. const fetchDefaultCar = async () => {
  206. try {
  207. const response = await chargeStationService.getUserDefaultCars();
  208. if (response) {
  209. // console.log('default car', response.data.id);
  210. setSelectedCar(response.data.id);
  211. }
  212. } catch (error) {
  213. console.log(error);
  214. } finally {
  215. setLoading(false);
  216. }
  217. };
  218. fetchDefaultCar();
  219. }, []);
  220. useEffect(() => {
  221. const getWalletBalance = async () => {
  222. try {
  223. const response = await walletService.getWalletBalance();
  224. if (response) {
  225. // console.log('walletBalance setting up', response);
  226. setWalletBalance(response);
  227. }
  228. } catch (error) {
  229. console.log(error);
  230. }
  231. };
  232. getWalletBalance();
  233. }, []);
  234. const fetchCurrentPrice = async () => {
  235. try {
  236. const response = await chargeStationService.getCurrentPrice();
  237. if (response) {
  238. setCurrentPriceFetchedWhenScanQr(response);
  239. setCurrentPrice(response);
  240. return response;
  241. }
  242. } catch (error) {
  243. console.error('Error fetching current price:', error);
  244. Alert.alert('錯誤', '無法獲取當前價格,請稍後再試');
  245. return null;
  246. }
  247. };
  248. const planMap = {
  249. // 3: { duration: 10, kWh: 3, displayDuration: 5, fee: 3 * currentPrice },
  250. 25: { duration: 40, kWh: 20, displayDuration: 25, fee: 20 * currentPrice },
  251. 30: { duration: 45, kWh: 25, displayDuration: 30, fee: 25 * currentPrice },
  252. 40: { duration: 55, kWh: 30, displayDuration: 40, fee: 30 * currentPrice },
  253. 45: { duration: 60, kWh: 40, displayDuration: 45, fee: 40 * currentPrice },
  254. full: { duration: 120, displayDuration: '充滿停機', fee: 80 * currentPrice }
  255. };
  256. // // Function to handle barcode scanning
  257. // const handleBarCodeScanned = async ({ bounds, data, type }: { bounds?: any; data: any; type: any }) => {
  258. // if (
  259. // !bounds ||
  260. // typeof bounds.origin?.x !== 'number' ||
  261. // typeof bounds.origin?.y !== 'number' ||
  262. // typeof bounds.size?.width !== 'number' ||
  263. // typeof bounds.size?.height !== 'number'
  264. // ) {
  265. // // console.log('Invalid or missing bounds data:', bounds);
  266. // // Proceed with scanning logic without bounds checking
  267. // setScanned(true);
  268. // setScannedResult(data);
  269. // setScannedQrCode(data);
  270. // Vibration.vibrate(100);
  271. // // console.log(`type: ${type} data: ${data} typeofData ${typeof data}`);
  272. // try {
  273. // const price = await fetchCurrentPrice();
  274. // console.log('fetchedCurrentPrice in scanQrPage', price);
  275. // if (!price) {
  276. // return; // Exit if price fetch failed
  277. // }
  278. // const response = await chargeStationService.getTodayReservation();
  279. // if (response) {
  280. // const now = new Date();
  281. // const onlyThisConnector = response.filter(
  282. // (reservation: any) => reservation.connector.ConnectorID === data
  283. // );
  284. // // Check availability for each duration```````````````````````````````````````````````````````````````````
  285. // const availability = {
  286. // // 3: checkAvailability(onlyThisConnector, now, 10) && walletBalance >= 3 * price,
  287. // 25: checkAvailability(onlyThisConnector, now, 40) && walletBalance >= 20 * price,
  288. // 30: checkAvailability(onlyThisConnector, now, 45) && walletBalance >= 25 * price,
  289. // 40: checkAvailability(onlyThisConnector, now, 55) && walletBalance >= 30 * price,
  290. // 45: checkAvailability(onlyThisConnector, now, 60) && walletBalance >= 40 * price,
  291. // full: checkAvailability(onlyThisConnector, now, 120) && walletBalance >= 80 * price
  292. // };
  293. // setAvailableSlots(availability);
  294. // setModalVisible(true);
  295. // } else {
  296. // Alert.alert('系統錯誤', '無法獲取預約信息。請稍後再試。');
  297. // }
  298. // } catch (error) {
  299. // console.error("Error fetching today's reservations:", error);
  300. // Alert.alert('系統錯誤', '發生未知錯誤。請稍後再試。');
  301. // }
  302. // setTimeout(() => {
  303. // setScanned(false);
  304. // }, 2000);
  305. // return;
  306. // }
  307. // // -----------------------------------------------------------------------------------------------------
  308. // const { origin, size } = bounds;
  309. // // Calculate the size of the square transparent area
  310. // const transparentAreaSize = Math.min(screenWidth * 0.6, screenHeight * 0.3);
  311. // const transparentAreaX = (screenWidth - transparentAreaSize) / 2;
  312. // const transparentAreaY = (screenHeight - transparentAreaSize) / 2;
  313. // // Check if the barcode is within the transparent area
  314. // if (
  315. // origin.x >= transparentAreaX &&
  316. // origin.y >= transparentAreaY &&
  317. // origin.x + size.width <= transparentAreaX + transparentAreaSize &&
  318. // origin.y + size.height <= transparentAreaY + transparentAreaSize
  319. // ) {
  320. // setScanned(true);
  321. // setScannedResult(data);
  322. // setScannedQrCode(data);
  323. // Vibration.vibrate(100);
  324. // // console.log(` type: ${type} data: ${data} typeofData ${typeof data}`);
  325. // try {
  326. // const price = await fetchCurrentPrice();
  327. // console.log('fetchedCurrentPrice in scanQrPage', price);
  328. // if (!price) {
  329. // return; // Exit if price fetch failed
  330. // }
  331. // const response = await chargeStationService.getTodayReservation();
  332. // if (response) {
  333. // const now = new Date();
  334. // const onlyThisConnector = response.filter(
  335. // (reservation: any) => reservation.connector.ConnectorID === data
  336. // );
  337. // console.log('onlyThisConnector', onlyThisConnector);
  338. // // Check availability for each duration
  339. // const availability = {
  340. // // 3: checkAvailability(onlyThisConnector, now, 10) && walletBalance >= 3 * price,
  341. // 25: checkAvailability(onlyThisConnector, now, 40) && walletBalance >= 20 * price,
  342. // 30: checkAvailability(onlyThisConnector, now, 45) && walletBalance >= 25 * price,
  343. // 40: checkAvailability(onlyThisConnector, now, 55) && walletBalance >= 30 * price,
  344. // 45: checkAvailability(onlyThisConnector, now, 60) && walletBalance >= 40 * price,
  345. // full: checkAvailability(onlyThisConnector, now, 120) && walletBalance >= 80 * price
  346. // };
  347. // // console.log('availability', availability);
  348. // // console.log('walletBalance', walletBalance);
  349. // // console.log('currentPricecurrentPricecurrentPricecurrentPricecurrentPrice', currentPrice);
  350. // setAvailableSlots(availability);
  351. // setModalVisible(true);
  352. // } else {
  353. // Alert.alert('系統錯誤', '無法獲取預約信息。請稍後再試。');
  354. // }
  355. // } catch (error) {
  356. // console.error("Error fetching today's reservations:", error);
  357. // Alert.alert('系統錯誤', '發生未知錯誤。請稍後再試。');
  358. // }
  359. // setTimeout(() => {
  360. // setScanned(false);
  361. // }, 2000);
  362. // }
  363. // };
  364. // Function to handle barcode scanning
  365. const handleBarCodeScanned = async ({ bounds, data, type }: { bounds?: any; data: any; type: any }) => {
  366. if (
  367. !bounds ||
  368. typeof bounds.origin?.x !== 'number' ||
  369. typeof bounds.origin?.y !== 'number' ||
  370. typeof bounds.size?.width !== 'number' ||
  371. typeof bounds.size?.height !== 'number'
  372. ) {
  373. setScanned(true);
  374. setScannedQrCode(data);
  375. Vibration.vibrate(100);
  376. //after scanning, immediately fetch the correct station id and push to optionPage
  377. try {
  378. const stationId = await chargeStationService.noImagefetchChargeStationIdByScannedConnectorId(data);
  379. console.log('stationId', stationId);
  380. if (!stationId) {
  381. Alert.alert('錯誤', '無法找到充電站,請稍後再嘗試');
  382. setTimeout(() => {
  383. setScanned(false);
  384. }, 2000);
  385. return;
  386. }
  387. setStationId(stationId);
  388. router.push('/optionPage');
  389. } catch (error) {
  390. console.error('Error fetching station ID:', error);
  391. Alert.alert('錯誤', '無法找到充電站,請稍後再試');
  392. setTimeout(() => {
  393. setScanned(false);
  394. }, 2000);
  395. return;
  396. }
  397. return;
  398. }
  399. // -----------------------------------------------------------------------------------------------------
  400. const { origin, size } = bounds;
  401. // Calculate the size of the square transparent area
  402. const transparentAreaSize = Math.min(screenWidth * 0.6, screenHeight * 0.3);
  403. const transparentAreaX = (screenWidth - transparentAreaSize) / 2;
  404. const transparentAreaY = (screenHeight - transparentAreaSize) / 2;
  405. // Check if the barcode is within the transparent area
  406. if (
  407. origin.x >= transparentAreaX &&
  408. origin.y >= transparentAreaY &&
  409. origin.x + size.width <= transparentAreaX + transparentAreaSize &&
  410. origin.y + size.height <= transparentAreaY + transparentAreaSize
  411. ) {
  412. setScanned(true);
  413. setScannedQrCode(data);
  414. Vibration.vibrate(100);
  415. //after scanning, immediately fetch the correct station id and push to optionPage
  416. try {
  417. const stationId = await chargeStationService.noImagefetchChargeStationIdByScannedConnectorId(data);
  418. console.log('stationId', stationId);
  419. if (!stationId) {
  420. Alert.alert('錯誤', '無法找到充電站,請稍後再嘗試');
  421. setTimeout(() => {
  422. setScanned(false);
  423. }, 2000);
  424. return;
  425. }
  426. setStationId(stationId);
  427. router.push('/optionPage');
  428. } catch (error) {
  429. console.error('Error fetching station ID:', error);
  430. Alert.alert('錯誤', '無法找到充電站,請稍後再試');
  431. setTimeout(() => {
  432. setScanned(false);
  433. }, 2000);
  434. return;
  435. }
  436. return;
  437. }
  438. };
  439. // const checkAvailability = (reservations, startTime, duration) => {
  440. // const endTime = new Date(startTime.getTime() + duration * 60000);
  441. // // console.log('now', startTime);
  442. // // console.log('endTime', endTime);
  443. // // console.log('reservations', reservations);
  444. // return !reservations.some((reservation) => {
  445. // // Ignore reservations with status '9' (cancelled)
  446. // if (reservation.status.id === '9' || reservation.status.id === '13') {
  447. // return false;
  448. // }
  449. // // For status '8' (early finished), check actual_end_time
  450. // if (reservation.status.id === '8' && reservation.actual_end_time) {
  451. // const actualEndTime = new Date(reservation.actual_end_time);
  452. // if (actualEndTime <= startTime) {
  453. // return false; // Treat as available if actual end time is before or at start time
  454. // }
  455. // }
  456. // const resStart = new Date(reservation.book_time);
  457. // const resEnd = new Date(reservation.end_time);
  458. // return startTime < resEnd && endTime > resStart;
  459. // });
  460. // };
  461. const handleDurationSelect = (duration) => {
  462. setSelectedDuration(duration);
  463. // console.log(duration);
  464. };
  465. const handleCancel = () => {
  466. setSelectedDuration(null);
  467. setModalVisible(false);
  468. if (router.canGoBack()) {
  469. router.back();
  470. } else {
  471. router.push('/mainPage');
  472. }
  473. };
  474. const handleConfirm = () => {
  475. if (selectedDuration !== null) {
  476. const now = new Date();
  477. let endTime;
  478. let fee;
  479. let totalPower;
  480. //i create a planMap2 because i want to move the planMap inside this component but i dont wanna move the outside one because i dont wanna make any potential disruptive changes
  481. const planMap2 = {
  482. // 3: { duration: 10, kWh: 3, displayDuration: 5, fee: 3 * currentPriceFetchedWhenScanQr },
  483. 25: { duration: 40, kWh: 20, displayDuration: 25, fee: 20 * currentPriceFetchedWhenScanQr },
  484. 30: { duration: 45, kWh: 25, displayDuration: 30, fee: 25 * currentPriceFetchedWhenScanQr },
  485. 40: { duration: 55, kWh: 30, displayDuration: 40, fee: 30 * currentPriceFetchedWhenScanQr },
  486. 45: { duration: 60, kWh: 40, displayDuration: 45, fee: 40 * currentPriceFetchedWhenScanQr },
  487. full: { duration: 120, displayDuration: '充滿停機', fee: 80 * currentPriceFetchedWhenScanQr }
  488. };
  489. if (selectedDuration === 'full') {
  490. endTime = new Date(now.getTime() + 2 * 60 * 60 * 1000); // 2 hours for "充滿停機"
  491. fee = planMap2.full.fee;
  492. totalPower = 80; // Set to 130 for "充滿停機"
  493. } else {
  494. const durationInMinutes = parseInt(selectedDuration);
  495. endTime = new Date(now.getTime() + durationInMinutes * 60 * 1000);
  496. // console.log('endTime', endTime);
  497. fee = planMap2[selectedDuration].fee;
  498. totalPower = planMap2[selectedDuration].kWh;
  499. }
  500. setTotalFee(fee);
  501. console.log('fee in scanQrPage-- this is the total_fee i send to backend', fee);
  502. const dataForSubmission = {
  503. stationID: '2405311022116801000',
  504. connector: scannedResult,
  505. user: userID,
  506. book_time: now,
  507. end_time: endTime,
  508. total_power: totalPower,
  509. total_fee: fee,
  510. // total_fee: 1,
  511. promotion_code: '',
  512. car: selectedCar,
  513. type: 'walking',
  514. is_ic_call: false
  515. };
  516. startCharging(dataForSubmission);
  517. setIsConfirmLoading(true);
  518. }
  519. };
  520. //below commented is the original WORKING startCharging, if i fucked up, return back to using this!!!
  521. // const startCharging = async (dataForSubmission) => {
  522. // try {
  523. // const wallet = await walletService.getWalletBalance();
  524. // console.log('wallet in startCharging in scanQrPage', wallet);
  525. // const response = await walletService.submitPayment(
  526. // dataForSubmission.stationID,
  527. // dataForSubmission.connector,
  528. // dataForSubmission.user,
  529. // dataForSubmission.book_time,
  530. // dataForSubmission.end_time,
  531. // dataForSubmission.total_power,
  532. // dataForSubmission.total_fee,
  533. // dataForSubmission.promotion_code,
  534. // dataForSubmission.car,
  535. // dataForSubmission.type,
  536. // dataForSubmission.is_ic_call
  537. // );
  538. // if (response.status === 200 || response.status === 201) {
  539. // setSelectedDuration(null);
  540. // console.log('Charging started from startCharging', response);
  541. // setIsConfirmLoading(false);
  542. // // Set a flag in AsyncStorage to indicate charging has started
  543. // await AsyncStorage.setItem('chargingStarted', 'true');
  544. // Alert.alert('啟動成功', '請稍後等待頁面自動跳轉至充電介面', [
  545. // {
  546. // text: 'OK',
  547. // onPress: async () => {
  548. // setModalVisible(false);
  549. // setLoading(true);
  550. // // Wait for 2 seconds
  551. // await new Promise((resolve) => setTimeout(resolve, 2000));
  552. // // Hide loading spinner and navigate
  553. // setLoading(false);
  554. // router.push('(auth)/(tabs)/(charging)/chargingPage');
  555. // }
  556. // }
  557. // ]);
  558. // // Start the navigation attempt loop
  559. // // startNavigationAttempts();
  560. // } else if (response.status === 400) {
  561. // console.log('400 error in paymentSummaryPageComponent');
  562. // Alert.alert('餘額不足', '您的餘額不足,請充值後再試。');
  563. // } else {
  564. // console.log('Failed to start charging:', response);
  565. // Alert.alert('掃描失敗 請稍後再試。', response);
  566. // }
  567. // } catch (error) {
  568. // console.log('Failed to start chasssssssrging:', error);
  569. // }
  570. // };
  571. //below is the new flow for startCharging.
  572. // useEffect(() => {
  573. // const subscription = AppState.addEventListener('change', (nextAppState) => {
  574. // if (
  575. // appState.current.match(/inactive|background/) &&
  576. // nextAppState === 'active' &&
  577. // isExpectingPayment &&
  578. // // outTradeNo &&
  579. // paymentInitiatedTime.current
  580. // ) {
  581. // const currentTime = new Date().getTime();
  582. // if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  583. // checkPaymentStatus();
  584. // } else {
  585. // // Payment check timeout reached
  586. // setIsExpectingPayment(false);
  587. // setOutTradeNo('');
  588. // paymentInitiatedTime.current = null;
  589. // Alert.alert(
  590. // 'Payment Timeout',
  591. // 'The payment status check has timed out. Please check your payment history.'
  592. // );
  593. // }
  594. // }
  595. // appState.current = nextAppState;
  596. // });
  597. // return () => {
  598. // subscription.remove();
  599. // };
  600. // }, [outTradeNo, isExpectingPayment]);
  601. //check payment status
  602. useEffect(() => {
  603. const subscription = AppState.addEventListener('change', (nextAppState) => {
  604. if (
  605. appState.current.match(/inactive|background/) &&
  606. nextAppState === 'active' &&
  607. isExpectingPayment &&
  608. // outTradeNo &&
  609. paymentInitiatedTime.current
  610. ) {
  611. const currentTime = new Date().getTime();
  612. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  613. checkPaymentStatus();
  614. } else {
  615. // Payment check timeout reached
  616. setIsExpectingPayment(false);
  617. setOutTradeNo('');
  618. paymentInitiatedTime.current = null;
  619. Alert.alert(
  620. 'Payment Timeout',
  621. 'The payment status check has timed out. Please check your payment history.'
  622. );
  623. }
  624. }
  625. appState.current = nextAppState;
  626. });
  627. return () => {
  628. subscription.remove();
  629. };
  630. }, [outTradeNo, isExpectingPayment]);
  631. const checkPaymentStatus = async () => {
  632. try {
  633. // console.log('outTradeNo in scanQR Page checkpaymentstatus ', outTradeNo);
  634. const result = await walletService.checkPaymentStatus(outTradeNo);
  635. setPaymentStatus(result);
  636. // console.log('checkPaymentStatus from scan QR checkpaymentStatus', result);
  637. if (result && !result.some((item) => item.errmsg?.includes('處理中'))) {
  638. // Payment successful
  639. // console.log('totalFee', totalFee);
  640. Alert.alert(
  641. '付款已成功',
  642. `你已成功增值HKD $${
  643. Number.isInteger(totalFee) ? totalFee : totalFee.toFixed(1)
  644. }。請重新掃描去啟動充電槍。`,
  645. [
  646. {
  647. text: '確認',
  648. onPress: async () => {
  649. setModalVisible(false);
  650. router.dismiss();
  651. }
  652. }
  653. ]
  654. );
  655. } else {
  656. Alert.alert('付款失敗', '請再試一次。', [
  657. {
  658. text: '確定',
  659. onPress: () => {
  660. setModalVisible(false);
  661. router.dismiss();
  662. }
  663. }
  664. ]);
  665. }
  666. setIsExpectingPayment(false);
  667. setOutTradeNo('');
  668. paymentInitiatedTime.current = null;
  669. } catch (error) {
  670. console.error('Failed to check payment status:', error);
  671. Alert.alert('Error', 'Failed to check payment status. Please check your payment history.');
  672. }
  673. };
  674. function formatTime(utcTimeString) {
  675. // Parse the UTC time string
  676. const date = new Date(utcTimeString);
  677. // Add 8 hours
  678. date.setHours(date.getHours());
  679. // Format the date
  680. const year = date.getFullYear();
  681. const month = String(date.getMonth() + 1).padStart(2, '0');
  682. const day = String(date.getDate()).padStart(2, '0');
  683. const hours = String(date.getHours()).padStart(2, '0');
  684. const minutes = String(date.getMinutes()).padStart(2, '0');
  685. const seconds = String(date.getSeconds()).padStart(2, '0');
  686. // Return the formatted string
  687. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  688. }
  689. const oneTimeCharging = async (inputAmount) => {
  690. try {
  691. const response = await walletService.getOutTradeNo();
  692. // console.log('outtradeno in oneTimeCharging', response);
  693. if (response) {
  694. setOutTradeNo(response);
  695. setIsExpectingPayment(true);
  696. paymentInitiatedTime.current = new Date().getTime();
  697. const now = new Date();
  698. const formattedTime = formatTime(now);
  699. let amount = inputAmount * 100;
  700. const origin = 'https://openapi-hk.qfapi.com/checkstand/#/?';
  701. const obj = {
  702. // appcode: '6937EF25DF6D4FA78BB2285441BC05E9',
  703. appcode: '636E234FB30D43598FC8F0140A1A7282',
  704. goods_name: 'Crazy Charge 錢包增值',
  705. out_trade_no: response,
  706. paysource: 'crazycharge_checkout',
  707. return_url: 'https://crazycharge.com.hk/completed',
  708. failed_url: 'https://crazycharge.com.hk/failed',
  709. notify_url: 'https://api.crazycharge.com.hk/api/v1/clients/qfpay/webhook',
  710. sign_type: 'sha256',
  711. txamt: amount,
  712. txcurrcd: 'HKD',
  713. txdtm: formattedTime
  714. };
  715. const paramStringify = (json, flag?) => {
  716. let str = '';
  717. let keysArr = Object.keys(json);
  718. keysArr.sort().forEach((val) => {
  719. if (!json[val]) return;
  720. str += `${val}=${flag ? encodeURIComponent(json[val]) : json[val]}&`;
  721. });
  722. return str.slice(0, -1);
  723. };
  724. // const api_key = '8F59E31F6ADF4D2894365F2BB6D2FF2C';
  725. const api_key = '3E2727FBA2DA403EA325E73F36B07824';
  726. const params = paramStringify(obj);
  727. const sign = sha256(`${params}${api_key}`).toString();
  728. const url = `${origin}${paramStringify(obj, true)}&sign=${sign}`;
  729. try {
  730. // console.log(url);
  731. const supported = await Linking.canOpenURL(url);
  732. if (supported) {
  733. await Linking.openURL(url);
  734. } else {
  735. Alert.alert('錯誤', '請稍後再試');
  736. }
  737. } catch (error) {
  738. console.error('Top-up failed:', error);
  739. Alert.alert('Error', '一次性付款失敗,請稍後再試');
  740. }
  741. } else {
  742. console.log('nasdasdasdsdfgo');
  743. }
  744. } catch (error) {
  745. console.log(error);
  746. }
  747. };
  748. const startCharging = async (dataForSubmission) => {
  749. try {
  750. //before i start below logic, i need to check if the user has penalty unpaid.
  751. //i will call fetchReservationHistories. and the api will return an array of object, within the object there is a field called "penalty_fee".
  752. //if any reservation has penalty_fee > 0, i will show an alert to the user, and once click the alert it will takes them to a page that show the detail of the reservation.
  753. const reservationHistories = await chargeStationService.fetchReservationHistories();
  754. const unpaidPenalties = reservationHistories.filter(
  755. (reservation) => reservation.penalty_fee > 0 && reservation.penalty_paid_status === false
  756. );
  757. const mostRecentUnpaidReservation = unpaidPenalties.reduce((mostRecent, current) => {
  758. return new Date(mostRecent.created_at) > new Date(current.created_at) ? mostRecent : current;
  759. }, unpaidPenalties[0]);
  760. if (unpaidPenalties.length > 0) {
  761. Alert.alert(
  762. '未付罰款',
  763. '您有未支付的罰款。請先支付罰款後再開始充電。',
  764. [
  765. {
  766. text: '查看詳情',
  767. onPress: () => {
  768. // Navigate to a page showing penalty details
  769. setModalVisible(false);
  770. setLoading(false);
  771. router.push({
  772. pathname: '(auth)/(tabs)/(home)/penaltyPaymentPage',
  773. params: {
  774. book_time: mostRecentUnpaidReservation.book_time,
  775. end_time: mostRecentUnpaidReservation.end_time,
  776. actual_end_time: mostRecentUnpaidReservation.actual_end_time,
  777. penalty_fee: mostRecentUnpaidReservation.penalty_fee,
  778. format_order_id: mostRecentUnpaidReservation.format_order_id,
  779. id: mostRecentUnpaidReservation.id,
  780. stationName:
  781. mostRecentUnpaidReservation.connector.EquipmentID.StationID.snapshot
  782. .StationName,
  783. address:
  784. mostRecentUnpaidReservation.connector.EquipmentID.StationID.snapshot.Address
  785. }
  786. });
  787. }
  788. },
  789. {
  790. text: '返回',
  791. onPress: () => {
  792. setModalVisible(false);
  793. if (router.canGoBack()) {
  794. router.back();
  795. } else {
  796. router.push('/mainPage');
  797. }
  798. }
  799. }
  800. ],
  801. { cancelable: false }
  802. );
  803. return;
  804. }
  805. const wallet = await walletService.getWalletBalance();
  806. if (wallet < dataForSubmission.total_fee) {
  807. oneTimeCharging(dataForSubmission.total_fee);
  808. // const remainingAmount = dataForSubmission.total_fee - wallet;
  809. // oneTimeCharging(remainingAmount);
  810. return;
  811. }
  812. const response = await walletService.submitPayment(
  813. dataForSubmission.stationID,
  814. dataForSubmission.connector,
  815. dataForSubmission.user,
  816. dataForSubmission.book_time,
  817. dataForSubmission.end_time,
  818. dataForSubmission.total_power,
  819. dataForSubmission.total_fee,
  820. dataForSubmission.promotion_code,
  821. dataForSubmission.car,
  822. dataForSubmission.type,
  823. dataForSubmission.is_ic_call
  824. );
  825. if (response.status === 200 || response.status === 201) {
  826. setSelectedDuration(null);
  827. setIsConfirmLoading(false);
  828. await AsyncStorage.setItem('chargingStarted', 'true');
  829. Alert.alert('啟動成功', '請按下確認並等待頁面稍後自動跳轉至充電介面', [
  830. {
  831. text: 'OK',
  832. onPress: async () => {
  833. setModalVisible(false);
  834. setLoading(true);
  835. // Wait for 2 seconds
  836. await new Promise((resolve) => setTimeout(resolve, 2000));
  837. // Hide loading spinner and navigate
  838. setLoading(false);
  839. router.navigate('(auth)/(tabs)/(home)/mainPage');
  840. router.push('(auth)/(tabs)/(charging)/chargingPage');
  841. }
  842. }
  843. ]);
  844. } else if (response.status === 400) {
  845. console.log('400 error in paymentSummaryPageComponent');
  846. Alert.alert('餘額不足', '掃描失敗 請稍後再試。');
  847. } else {
  848. console.log('Failed to start charging:', response);
  849. Alert.alert('掃描失敗 請稍後再試。', response);
  850. }
  851. } catch (error) {
  852. console.log('Failed to start chasssssssrging:', error);
  853. }
  854. };
  855. // const startNavigationAttempts = () => {
  856. // let attempts = 0;
  857. // const maxAttempts = 10; // Try for about 2.5 minutes (10 * 15 seconds)
  858. // const attemptNavigation = async () => {
  859. // try {
  860. // const chargingStarted = await AsyncStorage.getItem('chargingStarted');
  861. // if (chargingStarted === 'true') {
  862. // // Wait for 2 seconds before navigating
  863. // await new Promise((resolve) => setTimeout(resolve, 2000));
  864. // await AsyncStorage.removeItem('chargingStarted');
  865. // router.push('(auth)/(tabs)/(charging)/chargingPage');
  866. // // If navigation is successful, clear the flag
  867. // } else {
  868. // throw new Error('Navigation not ready');
  869. // }
  870. // } catch (error) {
  871. // attempts++;
  872. // if (attempts < maxAttempts) {
  873. // // If navigation fails, try again after 15 seconds
  874. // setTimeout(attemptNavigation, 15000);
  875. // } else {
  876. // // If all attempts fail, show an alert to the user
  877. // Alert.alert('導航失敗', '無法自動跳轉到充電頁面。請手動導航到充電頁面。', [
  878. // { text: 'OK', onPress: () => {} }
  879. // ]);
  880. // }
  881. // }
  882. // };
  883. // // Start the first attempt after 15 seconds
  884. // setTimeout(attemptNavigation, 15000);
  885. // };
  886. // return (
  887. // <View style={styles.container} ref={viewRef}>
  888. // {loading ? (
  889. // <View className="flex-1 items-center justify-center">
  890. // <ActivityIndicator />
  891. // </View>
  892. // ) : (
  893. // <CameraView
  894. // style={styles.camera}
  895. // facing="back"
  896. // barcodeScannerSettings={{
  897. // barcodeTypes: ['qr']
  898. // }}
  899. // onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
  900. // responsiveOrientationWhenOrientationLocked={true}
  901. // >
  902. // <View style={styles.overlay}>
  903. // <View style={styles.topOverlay}>
  904. // {/* <ChooseCar
  905. // carData={carData}
  906. // loading={loading}
  907. // selectedCar={selectedCar}
  908. // setSelectedCar={setSelectedCar}
  909. // /> */}
  910. // <Pressable
  911. // // style={styles.closeButton}
  912. // className="absolute top-20 left-10 z-10 "
  913. // onPress={() => {
  914. // if (router.canGoBack()) {
  915. // router.back();
  916. // } else {
  917. // router.push('/mainPage');
  918. // }
  919. // }}
  920. // >
  921. // <CrossLogoWhiteSvg />
  922. // </Pressable>
  923. // </View>
  924. // <View style={styles.centerRow}>
  925. // <View style={styles.leftOverlay}></View>
  926. // <View style={styles.transparentArea}></View>
  927. // <View style={styles.rightOverlay} />
  928. // </View>
  929. // <View className="items-center justify-between" style={styles.bottomOverlay}>
  930. // <View>
  931. // <Text className="text-white text-lg font-bold mt-2 text-center">
  932. // 請掃瞄充電座上的二維碼
  933. // </Text>
  934. // </View>
  935. // <View className="flex-row space-x-2 items-center ">
  936. // <QuestionSvg />
  937. // <Pressable onPress={() => router.push('assistancePage')}>
  938. // <Text className="text-white text-base">需要協助?</Text>
  939. // </Pressable>
  940. // </View>
  941. // <View />
  942. // </View>
  943. // </View>
  944. // </CameraView>
  945. // )}
  946. // <Modal isVisible={isModalVisible} backdropOpacity={0.5} animationIn="fadeIn" animationOut="fadeOut">
  947. // <View style={styles.modalContent} className="flex flex-col">
  948. // <Text className="text-xl font-bold mt-2 text-center">請選擇充電時間</Text>
  949. // <Text className="text-base m-2 mb-4 text-center">按鈕呈紅色代表該時段已被他人預約</Text>
  950. // <View className="flex flex-row flex-wrap ">
  951. // {Object.entries(availableSlots).map(([duration, available]) => (
  952. // <NormalButton
  953. // key={duration}
  954. // title={
  955. // duration === 'full' ? (
  956. // <Text className={selectedDuration === duration ? 'text-white' : ''}>
  957. // 充滿停機
  958. // </Text>
  959. // ) : (
  960. // <Text
  961. // className={selectedDuration === duration ? 'text-white' : ''}
  962. // >{`${planMap[duration].kWh} 度電 - ${planMap[duration].displayDuration} 分鐘`}</Text>
  963. // )
  964. // }
  965. // onPress={() => handleDurationSelect(duration)}
  966. // extendedStyle={[
  967. // styles.durationButton,
  968. // {
  969. // backgroundColor: available
  970. // ? selectedDuration === duration
  971. // ? '#02677d'
  972. // : 'white'
  973. // : 'red',
  974. // borderColor: available ? 'black' : 'red',
  975. // borderWidth: 1
  976. // }
  977. // ]}
  978. // disabled={!available}
  979. // />
  980. // ))}
  981. // </View>
  982. // {selectedDuration && (
  983. // <NormalButton
  984. // title={
  985. // isConfirmLoading ? (
  986. // <ActivityIndicator color="white" />
  987. // ) : (
  988. // <Text className="text-white">確認</Text>
  989. // )
  990. // }
  991. // onPress={handleConfirm}
  992. // extendedStyle={styles.confirmButton}
  993. // />
  994. // )}
  995. // <NormalButton
  996. // title={<Text className="">取消</Text>}
  997. // onPress={handleCancel}
  998. // extendedStyle={styles.cancelButton}
  999. // />
  1000. // </View>
  1001. // </Modal>
  1002. // </View>
  1003. // );
  1004. // console.log('availableSlots', availableSlots);
  1005. return (
  1006. <View style={styles.container} ref={viewRef}>
  1007. {!permission ? (
  1008. <View />
  1009. ) : !permission.granted ? (
  1010. <View className="flex-1 justify-center items-center">
  1011. <Text style={{ textAlign: 'center' }}>
  1012. 我們需要相機權限來掃描機器上的二維碼,以便識別並啟動充電機器。我們不會儲存或共享任何掃描到的資訊。
  1013. 請前往設定開啟相機權限
  1014. </Text>
  1015. </View>
  1016. ) : loading ? (
  1017. <View className="flex-1 items-center justify-center">
  1018. <ActivityIndicator />
  1019. </View>
  1020. ) : (
  1021. <CameraView
  1022. style={styles.camera}
  1023. facing="back"
  1024. barcodeScannerSettings={{
  1025. barcodeTypes: ['qr']
  1026. }}
  1027. onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
  1028. responsiveOrientationWhenOrientationLocked={true}
  1029. >
  1030. <View style={styles.overlay}>
  1031. <View style={styles.topOverlay}>
  1032. <Pressable
  1033. className="absolute top-20 left-10 z-10 p-4"
  1034. hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }} // Added hitSlop
  1035. onPress={() => {
  1036. if (router.canGoBack()) {
  1037. router.back();
  1038. } else {
  1039. router.push('/mainPage');
  1040. }
  1041. }}
  1042. >
  1043. <View style={{ transform: [{ scale: 1.5 }] }}>
  1044. <CrossLogoWhiteSvg />
  1045. </View>
  1046. </Pressable>
  1047. </View>
  1048. <View style={styles.centerRow}>
  1049. <View style={styles.leftOverlay}></View>
  1050. <View style={styles.transparentArea}></View>
  1051. <View style={styles.rightOverlay} />
  1052. </View>
  1053. <View className="items-center justify-between" style={styles.bottomOverlay}>
  1054. <View>
  1055. <Text className="text-white text-lg font-bold mt-2 text-center">
  1056. 請掃瞄充電座上的二維碼
  1057. </Text>
  1058. </View>
  1059. <View className="flex-row space-x-2 items-center ">
  1060. <QuestionSvg />
  1061. <Pressable onPress={() => router.push('assistancePage')}>
  1062. <Text className="text-white text-base">需要協助?</Text>
  1063. </Pressable>
  1064. </View>
  1065. <View />
  1066. </View>
  1067. </View>
  1068. </CameraView>
  1069. )}
  1070. {/* <Modal isVisible={isModalVisible} backdropOpacity={0.5} animationIn="fadeIn" animationOut="fadeOut">
  1071. <View style={styles.modalContent} className="flex flex-col">
  1072. <Text className="text-xl font-bold mt-2 text-center">請選擇充電時間</Text>
  1073. {Object.values(availableSlots).some((available) => !available) && (
  1074. <Text className="text-base mt-1 text-center">
  1075. 按鈕呈紅色代表現時錢包餘額不足以支付選擇的充電時間,選擇紅色按鈕並按下確認鍵會進行一次性充值付費
  1076. </Text>
  1077. )}
  1078. <Text className="text-base text-center mb-4"></Text>
  1079. <View className="flex flex-row flex-wrap ">
  1080. {Object.entries(availableSlots).map(([duration, available]) => (
  1081. <NormalButton
  1082. key={duration}
  1083. title={
  1084. duration === 'full' ? (
  1085. <Text className={selectedDuration === duration ? 'text-white' : ''}>
  1086. 充滿停機 (最多80度電)
  1087. </Text>
  1088. ) : (
  1089. <Text
  1090. className={selectedDuration === duration ? 'text-white' : ''}
  1091. >{`${planMap[duration].kWh} 度電 - ${planMap[duration].displayDuration} 分鐘`}</Text>
  1092. )
  1093. }
  1094. onPress={() => handleDurationSelect(duration)}
  1095. extendedStyle={[
  1096. styles.durationButton,
  1097. {
  1098. backgroundColor: available
  1099. ? selectedDuration === duration
  1100. ? '#02677d'
  1101. : 'white'
  1102. : selectedDuration === duration
  1103. ? '#8B0000' // Darker red when selected
  1104. : 'red', // Normal red when not selected
  1105. borderColor: available ? 'black' : 'red',
  1106. borderWidth: 1
  1107. }
  1108. ]}
  1109. />
  1110. ))}
  1111. </View>
  1112. {selectedDuration && (
  1113. <NormalButton
  1114. title={
  1115. isConfirmLoading ? (
  1116. <ActivityIndicator color="white" />
  1117. ) : (
  1118. <Text className="text-white">確認</Text>
  1119. )
  1120. }
  1121. onPress={handleConfirm}
  1122. extendedStyle={styles.confirmButton}
  1123. />
  1124. )}
  1125. <NormalButton
  1126. title={<Text className="">取消</Text>}
  1127. onPress={handleCancel}
  1128. extendedStyle={styles.cancelButton}
  1129. />
  1130. </View>
  1131. </Modal> */}
  1132. </View>
  1133. );
  1134. };
  1135. const styles = StyleSheet.create({
  1136. container: {
  1137. flex: 1
  1138. },
  1139. camera: {
  1140. flex: 1
  1141. },
  1142. overlay: {
  1143. flex: 1
  1144. },
  1145. topOverlay: {
  1146. flex: 35,
  1147. alignItems: 'center',
  1148. backgroundColor: 'rgba(0,0,0,0.5)'
  1149. },
  1150. centerRow: {
  1151. flex: 30,
  1152. flexDirection: 'row'
  1153. },
  1154. leftOverlay: {
  1155. flex: 20,
  1156. backgroundColor: 'rgba(0,0,0,0.5)'
  1157. },
  1158. transparentArea: {
  1159. flex: 60,
  1160. aspectRatio: 1,
  1161. position: 'relative'
  1162. },
  1163. rightOverlay: {
  1164. flex: 20,
  1165. backgroundColor: 'rgba(0,0,0,0.5)'
  1166. },
  1167. bottomOverlay: {
  1168. flex: 35,
  1169. backgroundColor: 'rgba(0,0,0,0.5)'
  1170. },
  1171. closeButton: {
  1172. position: 'absolute',
  1173. top: 40,
  1174. left: 20,
  1175. zIndex: 1
  1176. },
  1177. modalContent: {
  1178. backgroundColor: 'white',
  1179. padding: 22,
  1180. alignItems: 'center',
  1181. borderRadius: 4,
  1182. borderColor: 'rgba(0, 0, 0, 0.1)'
  1183. },
  1184. durationButton: { margin: 5 },
  1185. confirmButton: {
  1186. marginTop: 20,
  1187. width: '100%'
  1188. },
  1189. cancelButton: {
  1190. marginTop: 20,
  1191. width: '100%',
  1192. backgroundColor: 'white',
  1193. borderColor: 'black',
  1194. borderWidth: 1,
  1195. color: 'black'
  1196. }
  1197. });
  1198. export default ScanQrPage;