walletPageComponent.tsx 22 KB

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