walletPageComponent.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 { formatCouponDate, formatDate } from '../../util/lib';
  25. import { set } from 'date-fns';
  26. import { reloadAppAsync } from 'expo';
  27. import sha256 from 'crypto-js/sha256';
  28. import { useCallback } from 'react';
  29. import { useChargingStore } from '../../providers/scan_qr_payload_store';
  30. const AmountInputModal = ({ visible, onClose, onConfirm }) => {
  31. const amounts = [
  32. // { amount: 1, percentage: 0 },
  33. { amount: 200, percentage: 0 },
  34. { amount: 500, percentage: 25 },
  35. { amount: 1000, percentage: 100 },
  36. { amount: 2000, percentage: 200 }
  37. ];
  38. const getFontSize = () => {
  39. const { width } = Dimensions.get('window');
  40. if (width < 320) return 8;
  41. if (width < 350) return 10; //super small phones
  42. if (width < 375) return 12; // Smaller phones
  43. if (width < 414) return 14; // Average phones
  44. return 16; // Larger phones
  45. };
  46. return (
  47. <Modal animationType="fade" transparent={true} visible={visible} onRequestClose={onClose}>
  48. <View
  49. style={{
  50. flex: 1,
  51. justifyContent: 'center',
  52. alignItems: 'center',
  53. backgroundColor: 'rgba(0,0,0,0.5)'
  54. }}
  55. >
  56. <View
  57. style={{
  58. backgroundColor: 'white',
  59. padding: 20,
  60. borderRadius: 10,
  61. width: '80%'
  62. }}
  63. >
  64. <Text style={{ fontSize: 20, marginBottom: 20 }}>選擇增值金額</Text>
  65. <View
  66. style={{
  67. flexDirection: 'row',
  68. flexWrap: 'wrap',
  69. justifyContent: 'space-between',
  70. marginBottom: 20
  71. }}
  72. >
  73. {amounts.map((amount) => (
  74. <Pressable
  75. key={amount.amount}
  76. onPress={() => onConfirm(amount.amount)}
  77. style={{
  78. backgroundColor: '#02677D',
  79. padding: 10,
  80. borderRadius: 5,
  81. width: '48%',
  82. alignItems: 'center',
  83. marginBottom: 10
  84. }}
  85. >
  86. <Text style={{ color: 'white', fontSize: getFontSize() }}>
  87. ${amount.amount}
  88. {amount.percentage > 0 ? ` (送$${amount.percentage}) ` : ''}
  89. </Text>
  90. </Pressable>
  91. ))}
  92. </View>
  93. <Text>*括號為贈款金額</Text>
  94. <Pressable onPress={onClose} style={{ padding: 10, alignItems: 'center', marginTop: 10 }}>
  95. <Text style={{ color: 'red' }}>取消</Text>
  96. </Pressable>
  97. </View>
  98. </View>
  99. </Modal>
  100. );
  101. };
  102. export const IndividualCouponComponent = ({
  103. title,
  104. price,
  105. detail,
  106. date,
  107. setOpacity,
  108. redeem_code,
  109. onCouponClick,
  110. noCircle
  111. }: {
  112. title: string;
  113. price: string;
  114. detail: string;
  115. onCouponClick?: (clickedCoupon: string, clickedCouponDescription: string) => void;
  116. date: string;
  117. setOpacity?: boolean;
  118. redeem_code?: string;
  119. noCircle?: boolean;
  120. }) => {
  121. const { promotion_code } = useChargingStore();
  122. return (
  123. <ImageBackground
  124. source={require('../../assets/empty_coupon.png')}
  125. resizeMode="contain"
  126. style={{ width: '100%', aspectRatio: 16 / 5, justifyContent: 'center' }}
  127. className={`mb-3 lg:mb-4
  128. ${setOpacity ? 'opacity-50' : ''}`}
  129. >
  130. {/* largest container */}
  131. <Pressable
  132. className="flex-row w-full h-full "
  133. onPress={setOpacity ? () => {} : () => onCouponClick(redeem_code)}
  134. >
  135. {/* price column on the left */}
  136. <View className="flex-row items-center w-[31%] items-center justify-center">
  137. <Text className="pl-1 lg:pl-2 text-[#02677D] text-base md:text-lg lg:text-xl">$</Text>
  138. <Text className="text-3xl lg:text-4xl text-[#02677D] font-[600]">{price}</Text>
  139. </View>
  140. {/* this is a hack for good coupon display */}
  141. <View className="w-[7%] " />
  142. {/* detail column on the right */}
  143. <View className=" w-[62%] flex flex-col justify-evenly">
  144. <View className="flex flex-row justify-between items-center w-[90%]">
  145. <Text className="text-base lg:text-lg xl:text-xl">{title}</Text>
  146. {/* if opacity is true=used coupon= no circle */}
  147. {noCircle ? (
  148. <></>
  149. ) : (
  150. <View
  151. style={{
  152. width: 24,
  153. height: 24,
  154. borderRadius: 12,
  155. borderWidth: 2,
  156. borderColor: '#02677D',
  157. justifyContent: 'center',
  158. alignItems: 'center'
  159. }}
  160. className={`${promotion_code?.includes(redeem_code) ? 'bg-[#02677D]' : 'bg-white'}`}
  161. >
  162. <Text className="text-white">{promotion_code?.indexOf(redeem_code) + 1}</Text>
  163. </View>
  164. )}
  165. </View>
  166. <Text numberOfLines={2} ellipsizeMode="tail" className="text-xs w-[90%]">
  167. {detail}
  168. </Text>
  169. <View className="flex flex-row">
  170. <Text className="text-sm lg:text-base xl:text-lg">有效期至 {' '}</Text>
  171. <Text className="text-sm lg:text-base xl:text-lg font-bold text-[#02677D]">{date}</Text>
  172. </View>
  173. </View>
  174. </Pressable>
  175. </ImageBackground>
  176. );
  177. };
  178. const WalletPageComponent = () => {
  179. const [walletBalance, setWalletBalance] = useState<string | null>(null);
  180. const [loading, setLoading] = useState<boolean>(false);
  181. const [modalVisible, setModalVisible] = useState(false);
  182. const [coupons, setCoupons] = useState([]);
  183. const [paymentType, setPaymentType] = useState({});
  184. const [userID, setUserID] = useState('');
  185. const [selectedPaymentType, setSelectedPaymentType] = useState<string | null>(null);
  186. const [amount, setAmount] = useState<number>(0);
  187. const [amountModalVisible, setAmountModalVisible] = useState(false);
  188. const [outTradeNo, setOutTradeNo] = useState('');
  189. const PAYMENT_CHECK_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds
  190. const [paymentStatus, setPaymentStatus] = useState(null);
  191. const [isExpectingPayment, setIsExpectingPayment] = useState(false);
  192. const appState = useRef(AppState.currentState);
  193. const paymentInitiatedTime = useRef(null);
  194. // 优惠券注释
  195. useEffect(() => {
  196. const fetchData = async () => {
  197. try {
  198. setLoading(true);
  199. const info = await walletService.getCustomerInfo();
  200. const coupon = await walletService.getCouponForSpecificUser(info.id);
  201. const useableConpon = coupon.filter((couponObj: any) => {
  202. const today = new Date();
  203. if (couponObj.expire_date === null) {
  204. return couponObj.is_consumed === false;
  205. }
  206. const expireDate = new Date(couponObj.expire_date);
  207. return expireDate > today && couponObj.is_consumed === false;
  208. });
  209. setCoupons(useableConpon);
  210. } catch (error) {
  211. } finally {
  212. setLoading(false);
  213. }
  214. };
  215. fetchData();
  216. }, []);
  217. //monitor app state
  218. useEffect(() => {
  219. const subscription = AppState.addEventListener('change', (nextAppState) => {
  220. if (
  221. appState.current.match(/inactive|background/) &&
  222. nextAppState === 'active' &&
  223. isExpectingPayment &&
  224. // outTradeNo &&
  225. paymentInitiatedTime.current
  226. ) {
  227. const currentTime = new Date().getTime();
  228. if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
  229. checkPaymentStatus();
  230. } else {
  231. // Payment check timeout reached
  232. setIsExpectingPayment(false);
  233. setOutTradeNo('');
  234. paymentInitiatedTime.current = null;
  235. Alert.alert(
  236. 'Payment Timeout',
  237. 'The payment status check has timed out. Please check your payment history.'
  238. );
  239. }
  240. }
  241. appState.current = nextAppState;
  242. });
  243. return () => {
  244. subscription.remove();
  245. };
  246. }, [outTradeNo, isExpectingPayment]);
  247. //check payment status
  248. const checkPaymentStatus = async () => {
  249. try {
  250. const result = await walletService.checkPaymentStatus(outTradeNo);
  251. setPaymentStatus(result);
  252. if (result && !result.some((item) => item.errmsg?.includes('處理中'))) {
  253. // Payment successful
  254. Alert.alert('Success', 'Payment was successful!', [
  255. {
  256. text: '成功',
  257. onPress: async () => {
  258. const wallet = await walletService.getWalletBalance();
  259. setWalletBalance(wallet);
  260. }
  261. }
  262. ]);
  263. } else {
  264. Alert.alert('Payment Failed', 'Payment was not successful. Please try again.');
  265. }
  266. setIsExpectingPayment(false);
  267. setOutTradeNo('');
  268. paymentInitiatedTime.current = null;
  269. } catch (error) {
  270. console.error('Failed to check payment status:', error);
  271. Alert.alert('Error', 'Failed to check payment status. Please check your payment history.');
  272. }
  273. };
  274. //fetch customer wallet balance
  275. useEffect(() => {
  276. const fetchData = async () => {
  277. try {
  278. setLoading(true);
  279. const info = await walletService.getCustomerInfo();
  280. const wallet = await walletService.getWalletBalance();
  281. setUserID(info.id);
  282. setWalletBalance(wallet);
  283. // setCoupons(coupon);
  284. } catch (error) {
  285. } finally {
  286. setLoading(false);
  287. }
  288. };
  289. fetchData();
  290. }, []);
  291. const formatMoney = (amount: any) => {
  292. if (amount === null || amount === undefined || isNaN(Number(amount))) {
  293. return 'LOADING';
  294. }
  295. if (typeof amount !== 'number') {
  296. amount = Number(amount);
  297. }
  298. // Check if the number is a whole number
  299. if (Number.isInteger(amount)) {
  300. return amount.toLocaleString('en-US');
  301. }
  302. // For decimal numbers, show one decimal place
  303. return Number(amount)
  304. .toFixed(1)
  305. .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  306. };
  307. const filterPaymentOptions = (options, allowedKeys) => {
  308. return Object.fromEntries(Object.entries(options).filter(([key]) => allowedKeys.includes(key)));
  309. };
  310. function formatTime(utcTimeString) {
  311. // Parse the UTC time string
  312. const date = new Date(utcTimeString);
  313. // Add 8 hours
  314. date.setHours(date.getHours());
  315. // Format the date
  316. const year = date.getFullYear();
  317. const month = String(date.getMonth() + 1).padStart(2, '0');
  318. const day = String(date.getDate()).padStart(2, '0');
  319. const hours = String(date.getHours()).padStart(2, '0');
  320. const minutes = String(date.getMinutes()).padStart(2, '0');
  321. const seconds = String(date.getSeconds()).padStart(2, '0');
  322. // Return the formatted string
  323. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  324. }
  325. useEffect(() => {
  326. const fetchPaymentType = async () => {
  327. const response = await walletService.selectPaymentType();
  328. // console.log('response', response);
  329. const filteredPaymentTypes = filterPaymentOptions(response, ['union_pay_wap_payment', 'payme_wap_payment']);
  330. setPaymentType(filteredPaymentTypes);
  331. };
  332. fetchPaymentType();
  333. }, []);
  334. const handleAmountConfirm = async (inputAmount) => {
  335. setAmountModalVisible(false);
  336. try {
  337. const response = await walletService.getOutTradeNo();
  338. if (response) {
  339. setOutTradeNo(response);
  340. setIsExpectingPayment(true);
  341. paymentInitiatedTime.current = new Date().getTime();
  342. const now = new Date();
  343. const formattedTime = formatTime(now);
  344. const out_trade_no = response;
  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, flag?) => {
  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;