walletPageComponent.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. // 优惠券注释
  194. useEffect(() => {
  195. const fetchData = async () => {
  196. try {
  197. setLoading(true);
  198. const info = await walletService.getCustomerInfo();
  199. const coupon = await walletService.getCouponForSpecificUser(info.id);
  200. const useableConpon = coupon.filter((couponObj: any) => {
  201. const today = new Date();
  202. if (couponObj.expire_date === null) {
  203. return couponObj.is_consumed === false;
  204. }
  205. const expireDate = new Date(couponObj.expire_date);
  206. return expireDate > today && couponObj.is_consumed === false;
  207. });
  208. setCoupons(useableConpon);
  209. } catch (error) {
  210. } finally {
  211. setLoading(false);
  212. }
  213. };
  214. fetchData();
  215. }, []);
  216. //monitor app state
  217. useEffect(() => {
  218. const subscription = AppState.addEventListener('change', (nextAppState) => {
  219. if (
  220. appState.current.match(/inactive|background/) &&
  221. nextAppState === 'active' &&
  222. isExpectingPayment &&
  223. // outTradeNo &&
  224. paymentInitiatedTime.current
  225. ) {
  226. const currentTime = new Date().getTime();
  227. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  228. checkPaymentStatus();
  229. } else {
  230. // Payment check timeout reached
  231. setIsExpectingPayment(false);
  232. setOutTradeNo('');
  233. paymentInitiatedTime.current = null;
  234. Alert.alert(
  235. 'Payment Timeout',
  236. 'The payment status check has timed out. Please check your payment history.'
  237. );
  238. }
  239. }
  240. appState.current = nextAppState;
  241. });
  242. return () => {
  243. subscription.remove();
  244. };
  245. }, [outTradeNo, isExpectingPayment]);
  246. //check payment status
  247. const checkPaymentStatus = async () => {
  248. try {
  249. const result = await walletService.checkPaymentStatus(outTradeNo);
  250. setPaymentStatus(result);
  251. if (result && !result.some((item) => item.errmsg?.includes('處理中'))) {
  252. // Payment successful
  253. Alert.alert('Success', 'Payment was successful!', [
  254. {
  255. text: '成功',
  256. onPress: async () => {
  257. const wallet = await walletService.getWalletBalance();
  258. setWalletBalance(wallet);
  259. }
  260. }
  261. ]);
  262. } else {
  263. Alert.alert('Payment Failed', 'Payment was not successful. Please try again.');
  264. }
  265. setIsExpectingPayment(false);
  266. setOutTradeNo('');
  267. paymentInitiatedTime.current = null;
  268. } catch (error) {
  269. console.error('Failed to check payment status:', error);
  270. Alert.alert('Error', 'Failed to check payment status. Please check your payment history.');
  271. }
  272. };
  273. //fetch customer wallet balance
  274. useEffect(() => {
  275. const fetchData = async () => {
  276. try {
  277. setLoading(true);
  278. const info = await walletService.getCustomerInfo();
  279. const wallet = await walletService.getWalletBalance();
  280. setUserID(info.id);
  281. setWalletBalance(wallet);
  282. // setCoupons(coupon);
  283. } catch (error) {
  284. } finally {
  285. setLoading(false);
  286. }
  287. };
  288. fetchData();
  289. }, []);
  290. const formatMoney = (amount: any) => {
  291. if (amount === null || amount === undefined || isNaN(Number(amount))) {
  292. return 'LOADING';
  293. }
  294. if (typeof amount !== 'number') {
  295. amount = Number(amount);
  296. }
  297. // Check if the number is a whole number
  298. if (Number.isInteger(amount)) {
  299. return amount.toLocaleString('en-US');
  300. }
  301. // For decimal numbers, show one decimal place
  302. return Number(amount)
  303. .toFixed(1)
  304. .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  305. };
  306. const filterPaymentOptions = (options, allowedKeys) => {
  307. return Object.fromEntries(Object.entries(options).filter(([key]) => allowedKeys.includes(key)));
  308. };
  309. function formatTime(utcTimeString) {
  310. // Parse the UTC time string
  311. const date = new Date(utcTimeString);
  312. // Add 8 hours
  313. date.setHours(date.getHours());
  314. // Format the date
  315. const year = date.getFullYear();
  316. const month = String(date.getMonth() + 1).padStart(2, '0');
  317. const day = String(date.getDate()).padStart(2, '0');
  318. const hours = String(date.getHours()).padStart(2, '0');
  319. const minutes = String(date.getMinutes()).padStart(2, '0');
  320. const seconds = String(date.getSeconds()).padStart(2, '0');
  321. // Return the formatted string
  322. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  323. }
  324. useEffect(() => {
  325. const fetchPaymentType = async () => {
  326. const response = await walletService.selectPaymentType();
  327. // console.log('response', response);
  328. const filteredPaymentTypes = filterPaymentOptions(response, ['union_pay_wap_payment', 'payme_wap_payment']);
  329. setPaymentType(filteredPaymentTypes);
  330. };
  331. fetchPaymentType();
  332. }, []);
  333. const handleAmountConfirm = async (inputAmount) => {
  334. setAmountModalVisible(false);
  335. try {
  336. const response = await walletService.getOutTradeNo();
  337. if (response) {
  338. setOutTradeNo(response);
  339. setIsExpectingPayment(true);
  340. paymentInitiatedTime.current = new Date().getTime();
  341. const now = new Date();
  342. const formattedTime = formatTime(now);
  343. const out_trade_no = response;
  344. let amount = inputAmount * 100;
  345. const origin = 'https://openapi-hk.qfapi.com/checkstand/#/?';
  346. const obj = {
  347. // appcode: '6937EF25DF6D4FA78BB2285441BC05E9',
  348. appcode: '636E234FB30D43598FC8F0140A1A7282',
  349. goods_name: 'Crazy Charge 錢包增值',
  350. out_trade_no: response,
  351. paysource: 'crazycharge_checkout',
  352. return_url: 'https://www.google.com',
  353. failed_url: 'https://www.google.com',
  354. notify_url: 'https://api.crazycharge.com.hk/api/v1/clients/qfpay/webhook',
  355. sign_type: 'sha256',
  356. txamt: amount,
  357. txcurrcd: 'HKD',
  358. txdtm: formattedTime
  359. };
  360. const paramStringify = (json, flag?) => {
  361. let str = '';
  362. let keysArr = Object.keys(json);
  363. keysArr.sort().forEach((val) => {
  364. if (!json[val]) return;
  365. str += `${val}=${flag ? encodeURIComponent(json[val]) : json[val]}&`;
  366. });
  367. return str.slice(0, -1);
  368. };
  369. // const api_key = '8F59E31F6ADF4D2894365F2BB6D2FF2C';
  370. const api_key = '3E2727FBA2DA403EA325E73F36B07824';
  371. const params = paramStringify(obj);
  372. const sign = sha256(`${params}${api_key}`).toString();
  373. const url = `${origin}${paramStringify(obj, true)}&sign=${sign}`;
  374. try {
  375. const supported = await Linking.canOpenURL(url);
  376. if (supported) {
  377. await Linking.openURL(url);
  378. } else {
  379. Alert.alert('錯誤', '請稍後再試');
  380. }
  381. } catch (error) {
  382. console.error('Top-up failed:', error);
  383. Alert.alert('Error', 'Failed to process top-up. Please try again.');
  384. }
  385. } else {
  386. }
  387. } catch (error) {}
  388. };
  389. // const handleCouponClick = async (clickedCoupon: string) => {
  390. // Alert.alert(
  391. // '立即使用優惠券', // Title
  392. // '按確認打開相機,掃描充電站上的二維碼以使用優惠券', // Message
  393. // [
  394. // {
  395. // text: '取消',
  396. // style: 'cancel'
  397. // },
  398. // {
  399. // text: '確認',
  400. // onPress: () => router.push('scanQrPage')
  401. // }
  402. // ]
  403. // );
  404. // };
  405. const handleCouponClick = async (couponName: string, couponDescription: string) => {
  406. router.push({
  407. pathname: '/couponDetailPage',
  408. params: {
  409. couponName: couponName,
  410. couponDescription: couponDescription
  411. }
  412. });
  413. };
  414. const formattedAmount = formatMoney(walletBalance);
  415. return (
  416. <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
  417. <ScrollView className="flex-1 ">
  418. <View className="flex-1 mx-[5%]">
  419. <View style={{ marginTop: 25 }}>
  420. <Pressable
  421. onPress={() => {
  422. // if (router.canGoBack()) {
  423. // router.back();
  424. // } else {
  425. // router.replace('/accountMainPage');
  426. // }
  427. router.replace('/accountMainPage');
  428. }}
  429. >
  430. <CrossLogoSvg />
  431. </Pressable>
  432. <Text style={{ fontSize: 45, marginVertical: 25 }}>錢包</Text>
  433. </View>
  434. <View>
  435. <ImageBackground
  436. className="flex-col-reverse shadow-lg"
  437. style={{ height: 200 }}
  438. source={require('../../assets/walletCard1.png')}
  439. resizeMode="contain"
  440. >
  441. <View className="mx-[5%] pb-6">
  442. <Text className="text-white text-xl">餘額 (HKD)</Text>
  443. <View className="flex-row items-center justify-between ">
  444. <Text style={{ fontSize: 52 }} className=" text-white font-bold">
  445. {loading ? (
  446. <View className="items-center justify-center">
  447. <ActivityIndicator />
  448. </View>
  449. ) : (
  450. <>
  451. <Text>$</Text>
  452. {formattedAmount === 'LOADING' || amount == null ? (
  453. <ActivityIndicator />
  454. ) : (
  455. `${formattedAmount}`
  456. )}
  457. </>
  458. )}
  459. </Text>
  460. <Pressable
  461. className="rounded-2xl items-center justify-center p-3 px-5 pr-6 "
  462. style={{
  463. backgroundColor: 'rgba(231, 242, 248, 0.2)'
  464. }}
  465. onPress={() => {
  466. setAmountModalVisible(true);
  467. }}
  468. >
  469. <Text className="text-white font-bold">+ 增值</Text>
  470. </Pressable>
  471. </View>
  472. </View>
  473. </ImageBackground>
  474. </View>
  475. <View className="flex-row-reverse mt-2 mb-6">
  476. <Pressable
  477. onPress={() => {
  478. router.push({
  479. pathname: '/paymentRecord',
  480. params: { walletBalance: formatMoney(walletBalance) }
  481. });
  482. }}
  483. >
  484. <Text className="text-[#02677D] text-lg underline">訂單紀錄</Text>
  485. </Pressable>
  486. </View>
  487. </View>
  488. <View className="w-full h-1 bg-[#DBE4E8]" />
  489. <View className="flex-row justify-between mx-[5%] pt-6 pb-3">
  490. <Text className="text-xl">優惠券</Text>
  491. <Pressable onPress={() => router.push('couponPage')}>
  492. <Text className="text-xl text-[#888888]">顯示所有</Text>
  493. </Pressable>
  494. </View>
  495. <View className="flex-1 flex-col mx-[5%]">
  496. {loading ? (
  497. <View className="items-center justify-center">
  498. <ActivityIndicator />
  499. </View>
  500. ) : (
  501. <View>
  502. {coupons
  503. .filter(
  504. (coupon) =>
  505. coupon.is_consumed === false && new Date(coupon.expire_date) > new Date()
  506. )
  507. .slice(0, 2)
  508. .map((coupon, index) => (
  509. <IndividualCouponComponent
  510. key={index}
  511. title={coupon.coupon.name}
  512. price={coupon.coupon.amount}
  513. detail={coupon.coupon.description}
  514. date={formatCouponDate(coupon.expire_date)}
  515. noCircle={true}
  516. onCouponClick={() =>
  517. handleCouponClick(coupon.coupon.name, coupon.coupon.description)
  518. }
  519. />
  520. ))}
  521. </View>
  522. )}
  523. </View>
  524. </ScrollView>
  525. <AmountInputModal
  526. visible={amountModalVisible}
  527. onClose={() => setAmountModalVisible(false)}
  528. onConfirm={handleAmountConfirm}
  529. />
  530. </SafeAreaView>
  531. );
  532. };
  533. export default WalletPageComponent;