walletPageComponent.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import {
  2. View,
  3. Image,
  4. Text,
  5. ScrollView,
  6. AppState,
  7. Pressable,
  8. ImageBackground,
  9. ActivityIndicator,
  10. Modal,
  11. Alert,
  12. TextInput,
  13. Linking,
  14. Dimensions
  15. } from 'react-native';
  16. import { SafeAreaView } from 'react-native-safe-area-context';
  17. import { router } from 'expo-router';
  18. import { CrossLogoSvg } from '../global/SVG';
  19. import { useEffect, useRef, useState } from 'react';
  20. import { walletService } from '../../service/walletService';
  21. // import UnionPayImage from '../../assets/unionpay.png';
  22. // import PayMeImage from '../../assets/payme.png';
  23. import { formatCouponDate, formatDate } from '../../util/lib';
  24. import { set } from 'date-fns';
  25. import { reloadAppAsync } from 'expo';
  26. import sha256 from 'crypto-js/sha256';
  27. import { useCallback } from 'react';
  28. import { useChargingStore } from '../../providers/scan_qr_payload_store';
  29. const AmountInputModal = ({ visible, onClose, onConfirm }) => {
  30. const amounts = [
  31. // { amount: 1, percentage: 0 },
  32. { amount: 200, percentage: 0 },
  33. { amount: 500, percentage: 5 },
  34. { amount: 1000, percentage: 10 },
  35. { amount: 2000, percentage: 15 }
  36. ];
  37. const getFontSize = () => {
  38. const { width } = Dimensions.get('window');
  39. if (width < 320) return 8;
  40. if (width < 350) return 10; //super small phones
  41. if (width < 375) return 12; // Smaller phones
  42. if (width < 414) return 14; // Average phones
  43. return 16; // Larger phones
  44. };
  45. return (
  46. <Modal animationType="fade" transparent={true} visible={visible} onRequestClose={onClose}>
  47. <View
  48. style={{
  49. flex: 1,
  50. justifyContent: 'center',
  51. alignItems: 'center',
  52. backgroundColor: 'rgba(0,0,0,0.5)'
  53. }}
  54. >
  55. <View
  56. style={{
  57. backgroundColor: 'white',
  58. padding: 20,
  59. borderRadius: 10,
  60. width: '80%'
  61. }}
  62. >
  63. <Text style={{ fontSize: 20, marginBottom: 20 }}>選擇增值金額</Text>
  64. <View
  65. style={{
  66. flexDirection: 'row',
  67. flexWrap: 'wrap',
  68. justifyContent: 'space-between',
  69. marginBottom: 20
  70. }}
  71. >
  72. {amounts.map((amount) => (
  73. <Pressable
  74. key={amount.amount}
  75. onPress={() => onConfirm(amount.amount)}
  76. style={{
  77. backgroundColor: '#02677D',
  78. padding: 10,
  79. borderRadius: 5,
  80. width: '48%',
  81. alignItems: 'center',
  82. marginBottom: 10
  83. }}
  84. >
  85. <Text style={{ color: 'white', fontSize: getFontSize() }}>
  86. ${amount.amount}
  87. {amount.percentage > 0 ? ` (+${amount.percentage}%) ` : ''}
  88. </Text>
  89. </Pressable>
  90. ))}
  91. </View>
  92. <Text>*括號為回贈比例</Text>
  93. <Pressable onPress={onClose} style={{ padding: 10, alignItems: 'center', marginTop: 10 }}>
  94. <Text style={{ color: 'red' }}>取消</Text>
  95. </Pressable>
  96. </View>
  97. </View>
  98. </Modal>
  99. );
  100. };
  101. export const IndividualCouponComponent = ({
  102. title,
  103. price,
  104. detail,
  105. date,
  106. setOpacity,
  107. redeem_code,
  108. onCouponClick,
  109. noCircle
  110. }: {
  111. title: string;
  112. price: string;
  113. detail: string;
  114. onCouponClick?: (clickedCoupon: string, clickedCouponDescription: string) => void;
  115. date: string;
  116. setOpacity?: boolean;
  117. redeem_code?: string;
  118. noCircle?: boolean;
  119. }) => {
  120. const { promotion_code } = useChargingStore();
  121. return (
  122. <ImageBackground
  123. source={require('../../assets/empty_coupon.png')}
  124. resizeMode="contain"
  125. style={{ width: '100%', aspectRatio: 16 / 5, justifyContent: 'center' }}
  126. className={`mb-3 lg:mb-4
  127. ${setOpacity ? 'opacity-50' : ''}`}
  128. >
  129. {/* largest container */}
  130. <Pressable
  131. className="flex-row w-full h-full "
  132. onPress={setOpacity ? () => {} : () => onCouponClick(redeem_code)}
  133. >
  134. {/* price column on the left */}
  135. <View className="flex-row items-center w-[31%] items-center justify-center">
  136. <Text className="pl-1 lg:pl-2 text-[#02677D] text-base md:text-lg lg:text-xl">$</Text>
  137. <Text className="text-3xl lg:text-4xl text-[#02677D] font-[600]">{price}</Text>
  138. </View>
  139. {/* this is a hack for good coupon display */}
  140. <View className="w-[7%] " />
  141. {/* detail column on the right */}
  142. <View className=" w-[62%] flex flex-col justify-evenly">
  143. <View className="flex flex-row justify-between items-center w-[90%]">
  144. <Text className="text-base lg:text-lg xl:text-xl">{title}</Text>
  145. {/* if opacity is true=used coupon= no circle */}
  146. {noCircle ? (
  147. <></>
  148. ) : (
  149. <View
  150. style={{
  151. width: 24,
  152. height: 24,
  153. borderRadius: 12,
  154. borderWidth: 2,
  155. borderColor: '#02677D',
  156. justifyContent: 'center',
  157. alignItems: 'center'
  158. }}
  159. className={`${promotion_code?.includes(redeem_code) ? 'bg-[#02677D]' : 'bg-white'}`}
  160. >
  161. <Text className="text-white">{promotion_code?.indexOf(redeem_code) + 1}</Text>
  162. </View>
  163. )}
  164. </View>
  165. <Text numberOfLines={2} ellipsizeMode="tail" className="text-xs w-[90%]">
  166. {detail}
  167. </Text>
  168. <View className="flex flex-row">
  169. <Text className="text-sm lg:text-base xl:text-lg">有效期至 {' '}</Text>
  170. <Text className="text-sm lg:text-base xl:text-lg font-bold text-[#02677D]">{date}</Text>
  171. </View>
  172. </View>
  173. </Pressable>
  174. </ImageBackground>
  175. );
  176. };
  177. const WalletPageComponent = () => {
  178. const [walletBalance, setWalletBalance] = useState<string | null>(null);
  179. const [loading, setLoading] = useState<boolean>(false);
  180. const [modalVisible, setModalVisible] = useState(false);
  181. const [coupons, setCoupons] = useState([]);
  182. const [paymentType, setPaymentType] = useState({});
  183. const [userID, setUserID] = useState('');
  184. const [selectedPaymentType, setSelectedPaymentType] = useState<string | null>(null);
  185. const [amount, setAmount] = useState<number>(0);
  186. const [amountModalVisible, setAmountModalVisible] = useState(false);
  187. const [outTradeNo, setOutTradeNo] = useState('');
  188. const PAYMENT_CHECK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
  189. const [paymentStatus, setPaymentStatus] = useState(null);
  190. const [isExpectingPayment, setIsExpectingPayment] = useState(false);
  191. const appState = useRef(AppState.currentState);
  192. const paymentInitiatedTime = useRef(null);
  193. useEffect(() => {
  194. const fetchData = async () => {
  195. try {
  196. setLoading(true);
  197. const info = await walletService.getCustomerInfo();
  198. const coupon = await walletService.getCouponForSpecificUser(info.id);
  199. const useableConpon = coupon.filter((couponObj: any) => {
  200. const today = new Date();
  201. if (couponObj.expire_date === null) {
  202. return couponObj.is_consumed === false;
  203. }
  204. const expireDate = new Date(couponObj.expire_date);
  205. return expireDate > today && couponObj.is_consumed === false;
  206. });
  207. setCoupons(useableConpon);
  208. } catch (error) {
  209. } finally {
  210. setLoading(false);
  211. }
  212. };
  213. fetchData();
  214. }, []);
  215. //monitor app state
  216. useEffect(() => {
  217. const subscription = AppState.addEventListener('change', (nextAppState) => {
  218. if (
  219. appState.current.match(/inactive|background/) &&
  220. nextAppState === 'active' &&
  221. isExpectingPayment &&
  222. // outTradeNo &&
  223. paymentInitiatedTime.current
  224. ) {
  225. const currentTime = new Date().getTime();
  226. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  227. checkPaymentStatus();
  228. } else {
  229. // Payment check timeout reached
  230. setIsExpectingPayment(false);
  231. setOutTradeNo('');
  232. paymentInitiatedTime.current = null;
  233. Alert.alert(
  234. 'Payment Timeout',
  235. 'The payment status check has timed out. Please check your payment history.'
  236. );
  237. }
  238. }
  239. appState.current = nextAppState;
  240. });
  241. return () => {
  242. subscription.remove();
  243. };
  244. }, [outTradeNo, isExpectingPayment]);
  245. //check payment status
  246. const checkPaymentStatus = async () => {
  247. try {
  248. const result = await walletService.checkPaymentStatus(outTradeNo);
  249. setPaymentStatus(result);
  250. if (result && !result.some((item) => item.errmsg?.includes('處理中'))) {
  251. // Payment successful
  252. Alert.alert('Success', 'Payment was successful!', [
  253. {
  254. text: '成功',
  255. onPress: async () => {
  256. const wallet = await walletService.getWalletBalance();
  257. setWalletBalance(wallet);
  258. }
  259. }
  260. ]);
  261. } else {
  262. Alert.alert('Payment Failed', 'Payment was not successful. Please try again.');
  263. }
  264. setIsExpectingPayment(false);
  265. setOutTradeNo('');
  266. paymentInitiatedTime.current = null;
  267. } catch (error) {
  268. console.error('Failed to check payment status:', error);
  269. Alert.alert('Error', 'Failed to check payment status. Please check your payment history.');
  270. }
  271. };
  272. //fetch customer wallet balance
  273. useEffect(() => {
  274. const fetchData = async () => {
  275. try {
  276. setLoading(true);
  277. const info = await walletService.getCustomerInfo();
  278. const wallet = await walletService.getWalletBalance();
  279. setUserID(info.id);
  280. setWalletBalance(wallet);
  281. setCoupons(coupon);
  282. } catch (error) {
  283. } finally {
  284. setLoading(false);
  285. }
  286. };
  287. fetchData();
  288. }, []);
  289. const formatMoney = (amount: any) => {
  290. if (amount === null || amount === undefined || isNaN(Number(amount))) {
  291. return 'LOADING';
  292. }
  293. if (typeof amount !== 'number') {
  294. amount = Number(amount);
  295. }
  296. // Check if the number is a whole number
  297. if (Number.isInteger(amount)) {
  298. return amount.toLocaleString('en-US');
  299. }
  300. // For decimal numbers, show one decimal place
  301. return Number(amount)
  302. .toFixed(1)
  303. .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  304. };
  305. const filterPaymentOptions = (options, allowedKeys) => {
  306. return Object.fromEntries(Object.entries(options).filter(([key]) => allowedKeys.includes(key)));
  307. };
  308. function formatTime(utcTimeString) {
  309. // Parse the UTC time string
  310. const date = new Date(utcTimeString);
  311. // Add 8 hours
  312. date.setHours(date.getHours());
  313. // Format the date
  314. const year = date.getFullYear();
  315. const month = String(date.getMonth() + 1).padStart(2, '0');
  316. const day = String(date.getDate()).padStart(2, '0');
  317. const hours = String(date.getHours()).padStart(2, '0');
  318. const minutes = String(date.getMinutes()).padStart(2, '0');
  319. const seconds = String(date.getSeconds()).padStart(2, '0');
  320. // Return the formatted string
  321. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  322. }
  323. useEffect(() => {
  324. const fetchPaymentType = async () => {
  325. const response = await walletService.selectPaymentType();
  326. // console.log('response', response);
  327. const filteredPaymentTypes = filterPaymentOptions(response, ['union_pay_wap_payment', 'payme_wap_payment']);
  328. setPaymentType(filteredPaymentTypes);
  329. };
  330. fetchPaymentType();
  331. }, []);
  332. const handleAmountConfirm = async (inputAmount) => {
  333. setAmountModalVisible(false);
  334. try {
  335. const response = await walletService.getOutTradeNo();
  336. if (response) {
  337. setOutTradeNo(response);
  338. setIsExpectingPayment(true);
  339. paymentInitiatedTime.current = new Date().getTime();
  340. const now = new Date();
  341. const formattedTime = formatTime(now);
  342. const out_trade_no = response;
  343. let amount = inputAmount * 100;
  344. const origin = 'https://openapi-hk.qfapi.com/checkstand/#/?';
  345. const obj = {
  346. // appcode: '6937EF25DF6D4FA78BB2285441BC05E9',
  347. appcode: '636E234FB30D43598FC8F0140A1A7282',
  348. goods_name: 'Crazy Charge 錢包增值',
  349. out_trade_no: response,
  350. paysource: 'crazycharge_checkout',
  351. return_url: 'https://www.google.com',
  352. failed_url: 'https://www.google.com',
  353. notify_url: 'https://api.crazycharge.com.hk/api/v1/clients/qfpay/webhook',
  354. sign_type: 'sha256',
  355. txamt: amount,
  356. txcurrcd: 'HKD',
  357. txdtm: formattedTime
  358. };
  359. const paramStringify = (json, flag?) => {
  360. let str = '';
  361. let keysArr = Object.keys(json);
  362. keysArr.sort().forEach((val) => {
  363. if (!json[val]) return;
  364. str += `${val}=${flag ? encodeURIComponent(json[val]) : json[val]}&`;
  365. });
  366. return str.slice(0, -1);
  367. };
  368. // const api_key = '8F59E31F6ADF4D2894365F2BB6D2FF2C';
  369. const api_key = '3E2727FBA2DA403EA325E73F36B07824';
  370. const params = paramStringify(obj);
  371. const sign = sha256(`${params}${api_key}`).toString();
  372. const url = `${origin}${paramStringify(obj, true)}&sign=${sign}`;
  373. try {
  374. const supported = await Linking.canOpenURL(url);
  375. if (supported) {
  376. await Linking.openURL(url);
  377. } else {
  378. Alert.alert('錯誤', '請稍後再試');
  379. }
  380. } catch (error) {
  381. console.error('Top-up failed:', error);
  382. Alert.alert('Error', 'Failed to process top-up. Please try again.');
  383. }
  384. } else {
  385. }
  386. } catch (error) {}
  387. };
  388. // const handleCouponClick = async (clickedCoupon: string) => {
  389. // Alert.alert(
  390. // '立即使用優惠券', // Title
  391. // '按確認打開相機,掃描充電站上的二維碼以使用優惠券', // Message
  392. // [
  393. // {
  394. // text: '取消',
  395. // style: 'cancel'
  396. // },
  397. // {
  398. // text: '確認',
  399. // onPress: () => router.push('scanQrPage')
  400. // }
  401. // ]
  402. // );
  403. // };
  404. const handleCouponClick = async (couponName: string, couponDescription: string) => {
  405. router.push({
  406. pathname: '/couponDetailPage',
  407. params: {
  408. couponName: couponName,
  409. couponDescription: couponDescription
  410. }
  411. });
  412. };
  413. const formattedAmount = formatMoney(walletBalance);
  414. return (
  415. <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
  416. <ScrollView className="flex-1 ">
  417. <View className="flex-1 mx-[5%]">
  418. <View style={{ marginTop: 25 }}>
  419. <Pressable
  420. onPress={() => {
  421. if (router.canGoBack()) {
  422. router.back();
  423. } else {
  424. router.replace('/accountMainPage');
  425. }
  426. }}
  427. >
  428. <CrossLogoSvg />
  429. </Pressable>
  430. <Text style={{ fontSize: 45, marginVertical: 25 }}>錢包</Text>
  431. </View>
  432. <View>
  433. <ImageBackground
  434. className="flex-col-reverse shadow-lg"
  435. style={{ height: 200 }}
  436. source={require('../../assets/walletCard1.png')}
  437. resizeMode="contain"
  438. >
  439. <View className="mx-[5%] pb-6">
  440. <Text className="text-white text-xl">餘額 (HKD)</Text>
  441. <View className="flex-row items-center justify-between ">
  442. <Text style={{ fontSize: 52 }} className=" text-white font-bold">
  443. {loading ? (
  444. <View className="items-center justify-center">
  445. <ActivityIndicator />
  446. </View>
  447. ) : (
  448. <>
  449. <Text>$</Text>
  450. {formattedAmount === 'LOADING' || amount == null ? (
  451. <ActivityIndicator />
  452. ) : (
  453. `${formattedAmount}`
  454. )}
  455. </>
  456. )}
  457. </Text>
  458. <Pressable
  459. className="rounded-2xl items-center justify-center p-3 px-5 pr-6 "
  460. style={{
  461. backgroundColor: 'rgba(231, 242, 248, 0.2)'
  462. }}
  463. onPress={() => {
  464. setAmountModalVisible(true);
  465. }}
  466. >
  467. <Text className="text-white font-bold">+ 增值</Text>
  468. </Pressable>
  469. </View>
  470. </View>
  471. </ImageBackground>
  472. </View>
  473. <View className="flex-row-reverse mt-2 mb-6">
  474. <Pressable
  475. onPress={() => {
  476. router.push({
  477. pathname: '/paymentRecord',
  478. params: { walletBalance: formatMoney(walletBalance) }
  479. });
  480. }}
  481. >
  482. <Text className="text-[#02677D] text-lg underline">訂單紀錄</Text>
  483. </Pressable>
  484. </View>
  485. </View>
  486. <View className="w-full h-1 bg-[#DBE4E8]" />
  487. <View className="flex-row justify-between mx-[5%] pt-6 pb-3">
  488. <Text className="text-xl">優惠券</Text>
  489. <Pressable onPress={() => router.push('couponPage')}>
  490. <Text className="text-xl text-[#888888]">顯示所有</Text>
  491. </Pressable>
  492. </View>
  493. <View className="flex-1 flex-col mx-[5%]">
  494. {loading ? (
  495. <View className="items-center justify-center">
  496. <ActivityIndicator />
  497. </View>
  498. ) : (
  499. <View>
  500. {coupons
  501. .filter(
  502. (coupon) =>
  503. coupon.is_consumed === false && new Date(coupon.expire_date) > new Date()
  504. )
  505. .slice(0, 2)
  506. .map((coupon, index) => (
  507. <IndividualCouponComponent
  508. key={index}
  509. title={coupon.coupon.name}
  510. price={coupon.coupon.amount}
  511. detail={coupon.coupon.description}
  512. date={formatCouponDate(coupon.expire_date)}
  513. noCircle={true}
  514. onCouponClick={() =>
  515. handleCouponClick(coupon.coupon.name, coupon.coupon.description)
  516. }
  517. />
  518. ))}
  519. </View>
  520. )}
  521. </View>
  522. </ScrollView>
  523. {/* <TopUpModal
  524. visible={modalVisible}
  525. onClose={() => setModalVisible(false)}
  526. onSelect={handleTopUp}
  527. paymentOptions={paymentType}
  528. /> */}
  529. <AmountInputModal
  530. visible={amountModalVisible}
  531. onClose={() => setAmountModalVisible(false)}
  532. onConfirm={handleAmountConfirm}
  533. />
  534. </SafeAreaView>
  535. );
  536. };
  537. export default WalletPageComponent;