totalPayment.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import { router, useFocusEffect, useNavigation } from 'expo-router';
  2. import {
  3. View,
  4. Text,
  5. ScrollView,
  6. Pressable,
  7. StyleSheet,
  8. Image,
  9. BackHandler,
  10. Alert,
  11. Linking,
  12. AppState,
  13. Modal,
  14. ActivityIndicator
  15. } from 'react-native';
  16. import { SafeAreaView } from 'react-native-safe-area-context';
  17. import NormalButton from '../../../../component/global/normal_button';
  18. import { PreviousPageBlackSvg } from '../../../../component/global/SVG';
  19. import { useChargingStore } from '../../../../providers/scan_qr_payload_store';
  20. import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
  21. import useUserInfoStore from '../../../../providers/userinfo_store';
  22. import { chargeStationService } from '../../../../service/chargeStationService';
  23. import { authenticationService } from '../../../../service/authService';
  24. import axios from 'axios';
  25. import sha256 from 'crypto-js/sha256';
  26. import { walletService } from '../../../../service/walletService';
  27. import AsyncStorage from '@react-native-async-storage/async-storage';
  28. const TotalPayment = () => {
  29. const {
  30. promotion_code,
  31. stationID,
  32. sum_of_coupon,
  33. scanned_qr_code,
  34. coupon_detail,
  35. total_power,
  36. processed_coupon_store,
  37. setPromotionCode,
  38. setCouponDetail,
  39. setTotalPower,
  40. setProcessedCouponStore,
  41. setSumOfCoupon,
  42. setCurrentPriceStore
  43. } = useChargingStore();
  44. const [currentPriceTotalPayment, setCurrentPriceTotalPayment] = useState<number | null>(null);
  45. const [walletBalance, setWalletBalance] = useState<number | null>(null);
  46. const [loading, setLoading] = useState(false);
  47. const [outTradeNo, setOutTradeNo] = useState('');
  48. const [isExpectingPayment, setIsExpectingPayment] = useState(false);
  49. const paymentInitiatedTime = useRef(null);
  50. const PAYMENT_CHECK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
  51. const appState = useRef(AppState.currentState);
  52. const [totalPrice, setTotalPrice] = useState<number | null>(null);
  53. const [paymentStatus, setPaymentStatus] = useState(null);
  54. const [loadingModalVisible, setLoadingModalVisible] = useState(false);
  55. //fetch current price based on using coupon or not. use coupon = $3.5
  56. useEffect(() => {
  57. const fetchCurrentPrice = async () => {
  58. try {
  59. //if promotion_code.length > 0, fetch original price, otherwise fetch current price
  60. //then calculate total price for display purpose
  61. if (promotion_code.length > 0) {
  62. const response = await chargeStationService.getOriginalPriceInPay(stationID);
  63. setCurrentPriceTotalPayment(response);
  64. let totalPrice = Number(total_power) * Number(response) - Number(sum_of_coupon);
  65. if (totalPrice < 0) {
  66. totalPrice = 0;
  67. } else {
  68. totalPrice = totalPrice;
  69. }
  70. setTotalPrice(totalPrice);
  71. } else {
  72. const response = await chargeStationService.getCurrentPriceInPay(stationID);
  73. setCurrentPriceTotalPayment(response);
  74. let totalPrice = Number(total_power) * Number(response);
  75. setTotalPrice(totalPrice);
  76. }
  77. } catch (error) {
  78. // More specific error handling
  79. if (axios.isAxiosError(error)) {
  80. const errorMessage = error.response?.data?.message || 'Network error occurred';
  81. Alert.alert('Error', `Unable to fetch price: ${errorMessage}`, [
  82. {
  83. text: 'OK',
  84. onPress: () => {
  85. cleanupData();
  86. router.push('/mainPage');
  87. }
  88. }
  89. ]);
  90. } else {
  91. Alert.alert('Error', 'An unexpected error occurred while fetching the price', [
  92. {
  93. text: 'OK',
  94. onPress: () => {
  95. cleanupData();
  96. router.push('/mainPage');
  97. }
  98. }
  99. ]);
  100. }
  101. }
  102. };
  103. fetchCurrentPrice();
  104. }, []);
  105. // Add this effect to handle Android back button
  106. useFocusEffect(
  107. useCallback(() => {
  108. const onBackPress = () => {
  109. cleanupData();
  110. if (router.canGoBack()) {
  111. router.back();
  112. } else {
  113. router.replace('/scanQrPage');
  114. }
  115. return true;
  116. };
  117. BackHandler.addEventListener('hardwareBackPress', onBackPress);
  118. return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
  119. }, [])
  120. );
  121. //check payment status
  122. useEffect(() => {
  123. const subscription = AppState.addEventListener('change', (nextAppState: any) => {
  124. if (
  125. appState.current.match(/inactive|background/) &&
  126. nextAppState === 'active' &&
  127. isExpectingPayment &&
  128. // outTradeNo &&
  129. paymentInitiatedTime.current
  130. ) {
  131. const currentTime = new Date().getTime();
  132. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  133. checkPaymentStatus();
  134. } else {
  135. // Payment check timeout reached
  136. setIsExpectingPayment(false);
  137. setOutTradeNo('');
  138. paymentInitiatedTime.current = null;
  139. Alert.alert(
  140. 'Payment Timeout',
  141. 'The payment status check has timed out. Please check your payment history.'
  142. );
  143. }
  144. }
  145. appState.current = nextAppState;
  146. });
  147. return () => {
  148. subscription.remove();
  149. };
  150. }, [outTradeNo, isExpectingPayment]);
  151. const navigation = useNavigation();
  152. useLayoutEffect(() => {
  153. navigation.setOptions({
  154. gestureEnabled: false
  155. });
  156. }, [navigation]);
  157. const checkPaymentStatus = async () => {
  158. try {
  159. // console.log('outTradeNo in scanQR Page checkpaymentstatus ', outTradeNo);
  160. const result = await walletService.checkPaymentStatus(outTradeNo);
  161. setPaymentStatus(result);
  162. // console.log('checkPaymentStatus from scan QR checkpaymentStatus', result);
  163. if (result && !result.some((item) => item.errmsg?.includes('處理中'))) {
  164. // Payment successful
  165. // console.log('totalFee', totalFee);
  166. Alert.alert('付款已成功', `你已成功增值。請重新掃描去啟動充電槍。`, [
  167. {
  168. text: '確認',
  169. onPress: async () => {
  170. cleanupData();
  171. router.push('/mainPage');
  172. }
  173. }
  174. ]);
  175. } else {
  176. Alert.alert('付款失敗', '請再試一次。', [
  177. {
  178. text: '確定',
  179. onPress: () => {
  180. cleanupData();
  181. router.push('/mainPage');
  182. }
  183. }
  184. ]);
  185. }
  186. setIsExpectingPayment(false);
  187. setOutTradeNo('');
  188. paymentInitiatedTime.current = null;
  189. } catch (error) {
  190. console.error('Failed to check payment status:', error);
  191. Alert.alert('Error', 'Failed to check payment status. Please check your payment history.');
  192. }
  193. };
  194. const showLoadingAndNavigate = async () => {
  195. setLoadingModalVisible(true);
  196. // Wait for 2 seconds
  197. await new Promise((resolve) => setTimeout(resolve, 2000));
  198. cleanupData();
  199. setLoadingModalVisible(false);
  200. router.navigate('(auth)/(tabs)/(home)/mainPage');
  201. router.push('(auth)/(tabs)/(charging)/chargingPage');
  202. };
  203. const cleanupData = () => {
  204. setPromotionCode([]);
  205. setCouponDetail([]);
  206. setProcessedCouponStore([]);
  207. setSumOfCoupon(0);
  208. setTotalPower(null);
  209. };
  210. const handlePay = async () => {
  211. try {
  212. let car, user_id, walletBalance, price_for_pay;
  213. setLoading(true);
  214. if (currentPriceTotalPayment === null) {
  215. Alert.alert('Please wait', 'Still loading price information...');
  216. return;
  217. }
  218. //fetch car with proper try catch
  219. try {
  220. car = await chargeStationService.getUserDefaultCars();
  221. if (!car?.data?.id) {
  222. Alert.alert('Failed to fetch UDCC', 'Please try again later');
  223. return;
  224. }
  225. } catch (error) {
  226. console.error('Failed to fetch user default car:', error);
  227. Alert.alert('Failed to fetch UDC', 'Please try again later');
  228. return;
  229. }
  230. //fetch user id with proper try catch
  231. try {
  232. user_id = await authenticationService.getUserInfo();
  233. if (!user_id?.data?.id) {
  234. Alert.alert('Failed to fetch userID', 'Please try again later');
  235. return;
  236. }
  237. } catch (error) {
  238. console.error('Failed to fetch user ID:', error);
  239. Alert.alert('Failed to fetch user ID', 'Please try again later');
  240. return;
  241. }
  242. // fetch user wallet with proper try catch
  243. try {
  244. walletBalance = await walletService.getWalletBalance();
  245. } catch (error) {
  246. console.error('Failed to fetch user wallet:', error);
  247. Alert.alert('Failed to fetch user wallet', 'Please try again later');
  248. return;
  249. }
  250. //now i have all information ready, i check penalty reservation
  251. //by first fetching all history, then check if penalty_fee > 0 and penalty_paid_status is false
  252. //if there is any, 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.
  253. try {
  254. const reservationHistories = await chargeStationService.fetchReservationHistories();
  255. // console.log('reservationHistories', reservationHistories);
  256. //here if i successfully fetch the reservationHistories, i will check if there are penalty, if i cannot fetch, i will simply continue the payment flow
  257. if (reservationHistories || Array.isArray(reservationHistories)) {
  258. const unpaidPenalties = reservationHistories.filter(
  259. (reservation: any) => reservation.penalty_fee > 0 && reservation.penalty_paid_status === false
  260. );
  261. const mostRecentUnpaidReservation = unpaidPenalties.reduce((mostRecent: any, current: any) => {
  262. return new Date(mostRecent.created_at) > new Date(current.created_at) ? mostRecent : current;
  263. }, unpaidPenalties[0]);
  264. if (unpaidPenalties.length > 0) {
  265. Alert.alert(
  266. '未付罰款',
  267. '您有未支付的罰款。請先支付罰款後再重新掃描充電。',
  268. [
  269. {
  270. text: '查看詳情',
  271. onPress: () => {
  272. // Navigate to a page showing penalty details
  273. cleanupData();
  274. router.push({
  275. pathname: '(auth)/(tabs)/(home)/penaltyPaymentPage',
  276. params: {
  277. book_time: mostRecentUnpaidReservation.book_time,
  278. end_time: mostRecentUnpaidReservation.end_time,
  279. actual_end_time: mostRecentUnpaidReservation.actual_end_time,
  280. penalty_fee: mostRecentUnpaidReservation.penalty_fee,
  281. format_order_id: mostRecentUnpaidReservation.format_order_id,
  282. id: mostRecentUnpaidReservation.id
  283. }
  284. });
  285. }
  286. },
  287. {
  288. text: '返回',
  289. onPress: () => {
  290. cleanupData();
  291. if (router.canGoBack()) {
  292. router.push('/mainPage');
  293. } else {
  294. router.push('/mainPage');
  295. }
  296. }
  297. }
  298. ],
  299. { cancelable: false }
  300. );
  301. return;
  302. }
  303. }
  304. } catch (error) {
  305. Alert.alert('Error', 'Failed to fetch reservation histories for penalty checking purpose');
  306. }
  307. const now = new Date();
  308. const end_time_map: {
  309. [key: number]: number;
  310. } = {
  311. 20: 25,
  312. 25: 30,
  313. 30: 40,
  314. 40: 45,
  315. 80: 120
  316. };
  317. const end_time = new Date(now.getTime() + end_time_map[total_power] * 60000);
  318. const payloadForPay = {
  319. stationID: stationID,
  320. connector: scanned_qr_code,
  321. user: user_id.data.id,
  322. book_time: now.toISOString(),
  323. end_time: end_time.toISOString(),
  324. total_power: total_power,
  325. total_fee: total_power * currentPriceTotalPayment,
  326. promotion_code: promotion_code,
  327. with_coupon: promotion_code.length > 0 ? true : false,
  328. car: car.data.id,
  329. type: 'walking',
  330. is_ic_call: false
  331. };
  332. // check if user has enough wallet, if not, link to qf pay page
  333. if (totalPrice === null) {
  334. Alert.alert('Error', 'Unable to fetch totalPrice', [
  335. {
  336. text: 'OK',
  337. onPress: () => {
  338. cleanupData();
  339. router.push('/mainPage');
  340. }
  341. }
  342. ]);
  343. return;
  344. }
  345. if (walletBalance < totalPrice) {
  346. const needToPay = totalPrice - walletBalance;
  347. oneTimeCharging(needToPay);
  348. return;
  349. } else {
  350. // if user has enough wallet, proceed to payment
  351. try {
  352. const response = await walletService.newSubmitPayment(
  353. payloadForPay.stationID,
  354. payloadForPay.connector,
  355. payloadForPay.user,
  356. payloadForPay.book_time,
  357. payloadForPay.end_time,
  358. payloadForPay.total_power,
  359. payloadForPay.total_fee,
  360. payloadForPay.promotion_code,
  361. payloadForPay.with_coupon,
  362. payloadForPay.car,
  363. payloadForPay.type,
  364. payloadForPay.is_ic_call
  365. );
  366. if (response.error) {
  367. // Handle error response from the service
  368. Alert.alert('掃描失敗 請稍後再試。', response.message || '未知錯誤', [
  369. {
  370. text: '返回主頁',
  371. onPress: () => {
  372. cleanupData();
  373. router.push('/mainPage');
  374. }
  375. }
  376. ]);
  377. return;
  378. }
  379. if (response === 200 || response === 201) {
  380. Alert.alert('啟動成功', '請按下確認並等待頁面稍後自動跳轉至充電介面', [
  381. {
  382. text: '確認',
  383. onPress: showLoadingAndNavigate
  384. }
  385. ]);
  386. } else {
  387. Alert.alert('掃描失敗 請稍後再試。', response.error_msg || '未知錯誤', [
  388. {
  389. text: '返回主頁',
  390. onPress: () => {
  391. cleanupData();
  392. router.push('/mainPage');
  393. }
  394. }
  395. ]);
  396. }
  397. } catch (error) {
  398. console.error('Payment submission failed:', error);
  399. Alert.alert('錯誤', '付款提交失敗,請稍後再試。', [
  400. {
  401. text: 'OK',
  402. onPress: () => {
  403. cleanupData();
  404. router.push('/mainPage');
  405. }
  406. }
  407. ]);
  408. }
  409. }
  410. } catch (error) {
  411. } finally {
  412. setLoading(false);
  413. }
  414. };
  415. function formatTime(utcTimeString: any) {
  416. // Parse the UTC time string
  417. const date = new Date(utcTimeString);
  418. // Add 8 hours
  419. date.setHours(date.getHours());
  420. // Format the date
  421. const year = date.getFullYear();
  422. const month = String(date.getMonth() + 1).padStart(2, '0');
  423. const day = String(date.getDate()).padStart(2, '0');
  424. const hours = String(date.getHours()).padStart(2, '0');
  425. const minutes = String(date.getMinutes()).padStart(2, '0');
  426. const seconds = String(date.getSeconds()).padStart(2, '0');
  427. // Return the formatted string
  428. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  429. }
  430. const oneTimeCharging = async (inputAmount: number) => {
  431. try {
  432. const response = await walletService.getOutTradeNo();
  433. if (response) {
  434. setOutTradeNo(response);
  435. setIsExpectingPayment(true);
  436. paymentInitiatedTime.current = new Date().getTime();
  437. const now = new Date();
  438. const formattedTime = formatTime(now);
  439. let amount = inputAmount * 100;
  440. const origin = 'https://openapi-hk.qfapi.com/checkstand/#/?';
  441. const obj = {
  442. // appcode: '6937EF25DF6D4FA78BB2285441BC05E9',
  443. appcode: '636E234FB30D43598FC8F0140A1A7282',
  444. goods_name: 'Crazy Charge 錢包增值',
  445. out_trade_no: response,
  446. paysource: 'crazycharge_checkout',
  447. return_url: 'https://crazycharge.com.hk/completed',
  448. failed_url: 'https://crazycharge.com.hk/failed',
  449. notify_url: 'https://api.crazycharge.com.hk/api/v1/clients/qfpay/webhook',
  450. sign_type: 'sha256',
  451. txamt: amount,
  452. txcurrcd: 'HKD',
  453. txdtm: formattedTime
  454. };
  455. const paramStringify = (json, flag?) => {
  456. let str = '';
  457. let keysArr = Object.keys(json);
  458. keysArr.sort().forEach((val) => {
  459. if (!json[val]) return;
  460. str += `${val}=${flag ? encodeURIComponent(json[val]) : json[val]}&`;
  461. });
  462. return str.slice(0, -1);
  463. };
  464. // const api_key = '8F59E31F6ADF4D2894365F2BB6D2FF2C';
  465. const api_key = '3E2727FBA2DA403EA325E73F36B07824';
  466. const params = paramStringify(obj);
  467. const sign = sha256(`${params}${api_key}`).toString();
  468. const url = `${origin}${paramStringify(obj, true)}&sign=${sign}`;
  469. try {
  470. const supported = await Linking.canOpenURL(url);
  471. if (supported) {
  472. Alert.alert('', '偵測到您錢包餘額不足,現在為您跳轉到充值頁面', [
  473. {
  474. text: '確定',
  475. onPress: async () => {
  476. await Linking.openURL(url);
  477. }
  478. }
  479. ]);
  480. } else {
  481. Alert.alert('錯誤', '請稍後再試');
  482. }
  483. } catch (error) {
  484. console.error('Top-up failed:', error);
  485. Alert.alert('Error', '一次性付款失敗,請稍後再試');
  486. }
  487. } else {
  488. Alert.alert('Error', 'failed to fetch outTradeNo.');
  489. }
  490. } catch (error) {
  491. Alert.alert('錯誤', '一次性付款失敗,請稍後再試');
  492. }
  493. };
  494. return (
  495. <SafeAreaView className="flex-1 bg-white" edges={['top', 'left', 'right']}>
  496. <Modal transparent={true} visible={loadingModalVisible} animationType="fade">
  497. <View className="flex-1 justify-center items-center bg-black/50">
  498. <View className="bg-white p-6 rounded-lg items-center">
  499. <ActivityIndicator size="large" color="#02677D" />
  500. <Text className="mt-3">請稍候...</Text>
  501. </View>
  502. </View>
  503. </Modal>
  504. <ScrollView className="flex-1 mx-[5%]" showsVerticalScrollIndicator={false}>
  505. <View style={{ marginTop: 25 }}>
  506. <Pressable
  507. onPress={() => {
  508. if (router.canGoBack()) {
  509. router.back();
  510. } else {
  511. cleanupData();
  512. router.replace('/scanQrPage');
  513. }
  514. }}
  515. >
  516. <PreviousPageBlackSvg />
  517. </Pressable>
  518. </View>
  519. <View style={{ marginTop: 25 }}>
  520. <Text style={{ fontSize: 45, paddingBottom: 12 }}>付款概要</Text>
  521. <View>
  522. <View className="flex-row justify-between">
  523. <Text className="text-base lg:text-lg ">充電費用</Text>
  524. <Text className="text-base lg:text-lg">
  525. HK $ {currentPriceTotalPayment ? currentPriceTotalPayment * total_power : 'Loading...'}
  526. </Text>
  527. </View>
  528. <Text style={styles.grayColor} className="text-sm lg:text-base mt-4">
  529. 結算電度數 : {total_power == 80 ? '充滿停機' : `${total_power} KWh`}
  530. </Text>
  531. <Text style={styles.grayColor} className="text-sm lg:text-base mt-4">
  532. 每度電價錢 : $ {currentPriceTotalPayment ? currentPriceTotalPayment : 'Loading...'}
  533. </Text>
  534. <View className="h-0.5 my-3 bg-[#f4f4f4]" />
  535. {processed_coupon_store && processed_coupon_store.length > 0 && (
  536. <Text className="text-base lg:text-lg mb-4 lg:mb-6">優惠劵</Text>
  537. )}
  538. {processed_coupon_store &&
  539. processed_coupon_store?.map((couponObj: any) => (
  540. <View
  541. key={`${couponObj.coupon_detail.amount}-${couponObj.coupon_detail.expire_date}`}
  542. className="flex flex-row items-center justify-between"
  543. >
  544. <View className="flex flex-row items-start ">
  545. <Image
  546. className="w-6 lg:w-8 xl:w-10 h-6 lg:h-8 xl:h-10"
  547. source={require('../../../../assets/couponlogo.png')}
  548. />
  549. <View key={couponObj.coupon_detail.id} className="flex flex-col ml-2 lg:ml-4 ">
  550. <Text className="text-base lg:text-xl text-[#888888] ">
  551. ${couponObj.coupon_detail.amount} 現金劵
  552. </Text>
  553. <Text className=" text-sm lg:text-base my-1 lg:mt-2 lg:mb-4 text-[#888888]">
  554. 有效期{' '}
  555. <Text className="font-[500] text-[#02677D]">
  556. 至 {couponObj.coupon_detail.expire_date.slice(0, 10)}
  557. </Text>
  558. </Text>
  559. </View>
  560. </View>
  561. {/* x 1 */}
  562. <View className="flex flex-row items-center">
  563. <Text className="text-sm lg:text-base">X {' '}</Text>
  564. <View className="w-8 h-8 rounded-full bg-[#02677D] flex items-center justify-center">
  565. <Text className="text-white text-center text-lg">
  566. {couponObj.frequency}
  567. </Text>
  568. </View>
  569. </View>
  570. </View>
  571. ))}
  572. {processed_coupon_store && processed_coupon_store.length > 0 && (
  573. <View className="h-0.5 my-3 bg-[#f4f4f4]" />
  574. )}
  575. <View className="flex-row justify-between ">
  576. <Text className="text-xl">總計</Text>
  577. <Text className="text-3xl">HK$ {totalPrice !== null ? totalPrice : 'Loading...'}</Text>
  578. </View>
  579. <View className="mt-4 ">
  580. <NormalButton
  581. title={
  582. <Text
  583. style={{
  584. color: 'white',
  585. fontSize: 16,
  586. fontWeight: '800'
  587. }}
  588. >
  589. {loading ? '處理中...' : '付款確認'}
  590. </Text>
  591. }
  592. onPress={handlePay}
  593. extendedStyle={{ padding: 24 }}
  594. />
  595. </View>
  596. <View className="h-8" />
  597. </View>
  598. </View>
  599. </ScrollView>
  600. </SafeAreaView>
  601. );
  602. };
  603. export default TotalPayment;
  604. const styles = StyleSheet.create({
  605. grayColor: {
  606. color: '#888888'
  607. },
  608. greenColor: {
  609. color: '#02677D'
  610. }
  611. });