walletPageComponent.tsx 22 KB

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