Browse Source

perf: 充电模块不显示的问题

zengkunsen 4 months ago
parent
commit
2a11bb9f4a

+ 0 - 579
app/(auth)/(tabs)/(home)/scanQrPage.tsx

@@ -29,93 +29,6 @@ import { useChargingStore } from '../../../../providers/scan_qr_payload_store';
 
 const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
 
-// const ChooseCar = ({ carData, loading, selectedCar, setSelectedCar }) => {
-//     const isLargeScreen = screenHeight >= 800;
-//     const defaultImageUrl = require('../../../../assets/car1.png');
-
-//     return (
-//         <View
-//             style={{
-//                 ...(isLargeScreen
-//                     ? {
-//                           marginTop: '10%',
-//                           marginBottom: '12%',
-//                           paddingBottom: 12
-//                       }
-//                     : {
-//                           flex: 1,
-//                           alignItems: 'center',
-//                           justifyContent: 'center'
-//                       })
-//             }}
-//         >
-//             <View className="justify-center items-center flex-1 ">
-//                 <View
-//                     style={{
-//                         ...(isLargeScreen
-//                             ? {}
-//                             : {
-//                                   backgroundColor: 'rgba(0,0,0,0.7)'
-//                               })
-//                     }}
-//                 >
-//                     {loading ? (
-//                         <View className="w-full">
-//                             <ActivityIndicator color="#34657b" />
-//                         </View>
-//                     ) : (
-//                         <View className="w-screen  bg-[#000000B3]">
-//                             <View className="flex-row items-center justify-between mx-[5%] ">
-//                                 <Pressable
-//                                     className="pt-4 "
-//                                     onPress={() => {
-//                                         if (router.canGoBack()) {
-//                                             router.back();
-//                                         } else {
-//                                             router.replace('mainPage');
-//                                         }
-//                                     }}
-//                                 >
-//                                     <CrossLogoWhiteSvg />
-//                                 </Pressable>
-
-//                                 <Text className="text-base text-white pt-2">選擇充電車輛</Text>
-//                                 <Text className="text-xl text-white pt-2"></Text>
-//                             </View>
-
-//                             <ScrollView
-//                                 horizontal={true}
-//                                 showsHorizontalScrollIndicator={false}
-//                                 contentContainerStyle={{
-//                                     alignItems: 'center',
-//                                     flexDirection: 'row',
-//                                     marginVertical: 12
-//                                 }}
-//                                 className="space-x-2 mx-[5%]"
-//                             >
-//                                 {carData.map((car, index) => (
-//                                     <ChooseCarForChargingRow
-//                                         key={`${car.name}+${index}`}
-//                                         image={car.image}
-//                                         onPress={() => {
-//                                             setSelectedCar(car.id);
-//                                             console.log(car.id);
-//                                         }}
-//                                         isSelected={selectedCar === car.id}
-//                                         // imageUrl={image}
-//                                         VehicleName={car.name}
-//                                         isDefault={car.isDefault}
-//                                     />
-//                                 ))}
-//                             </ScrollView>
-//                         </View>
-//                     )}
-//                 </View>
-//             </View>
-//         </View>
-//     );
-// };
-
 //reminder: scan qr code page, ic call should be false
 const ScanQrPage = () => {
     const { userID, currentPrice, setCurrentPrice } = useUserInfoStore();
@@ -175,41 +88,6 @@ const ScanQrPage = () => {
             };
         }, [])
     );
-    // Effect for fetching user's cars
-    // useEffect(() => {
-    //     const fetchAllCars = async () => {
-    //         try {
-    //             const response = await chargeStationService.getUserCars();
-    //             if (response) {
-    //                 console.log('data', response.data);
-    //                 const carTypes = response.data.map((item: any) => ({
-    //                     id: item.id,
-    //                     name: item.car_typ e.name,
-    //                     image: item.car_type.type_image_url
-    //                 }));
-    //                 // console.log('carTypes', carTypes);
-    //                 // console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', carTypes);
-    //                 let updatedCarTypes = [...carTypes];
-    //                 for (let i = 0; i < carTypes.length; i++) {
-    //                     const car = updatedCarTypes[i];
-    //                     const imageUrl = await chargeStationService.getProcessedImageUrl(car.image);
-    //                     updatedCarTypes[i] = {
-    //                         ...car,
-    //                         image: imageUrl
-    //                     };
-    //                 }
-    //                 setCarData(updatedCarTypes);
-    //                 // console.log('updatedCarTypes', updatedCarTypes);
-    //                 return true;
-    //             }
-    //         } catch (error) {
-    //             console.log(error);
-    //         } finally {
-    //             setLoading(false);
-    //         }
-    //     };
-    //     fetchAllCars();
-    // }, []);
 
     useEffect(() => {
         const fetchDefaultCar = async () => {
@@ -266,126 +144,6 @@ const ScanQrPage = () => {
         full: { duration: 120, displayDuration: '充滿停機', fee: 80 * currentPrice }
     };
 
-    // // Function to handle barcode scanning
-    // const handleBarCodeScanned = async ({ bounds, data, type }: { bounds?: any; data: any; type: any }) => {
-    //     if (
-    //         !bounds ||
-    //         typeof bounds.origin?.x !== 'number' ||
-    //         typeof bounds.origin?.y !== 'number' ||
-    //         typeof bounds.size?.width !== 'number' ||
-    //         typeof bounds.size?.height !== 'number'
-    //     ) {
-    //         // console.log('Invalid or missing bounds data:', bounds);
-    //         // Proceed with scanning logic without bounds checking
-    //         setScanned(true);
-    //         setScannedResult(data);
-    //         setScannedQrCode(data);
-    //         Vibration.vibrate(100);
-    //         // console.log(`type: ${type}   data: ${data}  typeofData ${typeof data}`);
-
-    //         try {
-    //             const price = await fetchCurrentPrice();
-    //             console.log('fetchedCurrentPrice in scanQrPage', price);
-    //             if (!price) {
-    //                 return; // Exit if price fetch failed
-    //             }
-
-    //             const response = await chargeStationService.getTodayReservation();
-    //             if (response) {
-    //                 const now = new Date();
-    //                 const onlyThisConnector = response.filter(
-    //                     (reservation: any) => reservation.connector.ConnectorID === data
-    //                 );
-
-    //                 // Check availability for each duration```````````````````````````````````````````````````````````````````
-    //                 const availability = {
-    //                     // 3: checkAvailability(onlyThisConnector, now, 10) && walletBalance >= 3 * price,
-    //                     25: checkAvailability(onlyThisConnector, now, 40) && walletBalance >= 20 * price,
-    //                     30: checkAvailability(onlyThisConnector, now, 45) && walletBalance >= 25 * price,
-    //                     40: checkAvailability(onlyThisConnector, now, 55) && walletBalance >= 30 * price,
-    //                     45: checkAvailability(onlyThisConnector, now, 60) && walletBalance >= 40 * price,
-    //                     full: checkAvailability(onlyThisConnector, now, 120) && walletBalance >= 80 * price
-    //                 };
-
-    //                 setAvailableSlots(availability);
-    //                 setModalVisible(true);
-    //             } else {
-    //                 Alert.alert('系統錯誤', '無法獲取預約信息。請稍後再試。');
-    //             }
-    //         } catch (error) {
-    //             console.error("Error fetching today's reservations:", error);
-    //             Alert.alert('系統錯誤', '發生未知錯誤。請稍後再試。');
-    //         }
-
-    //         setTimeout(() => {
-    //             setScanned(false);
-    //         }, 2000);
-    //         return;
-    //     }
-    //     // -----------------------------------------------------------------------------------------------------
-    //     const { origin, size } = bounds;
-
-    //     // Calculate the size of the square transparent area
-    //     const transparentAreaSize = Math.min(screenWidth * 0.6, screenHeight * 0.3);
-    //     const transparentAreaX = (screenWidth - transparentAreaSize) / 2;
-    //     const transparentAreaY = (screenHeight - transparentAreaSize) / 2;
-
-    //     // Check if the barcode is within the transparent area
-    //     if (
-    //         origin.x >= transparentAreaX &&
-    //         origin.y >= transparentAreaY &&
-    //         origin.x + size.width <= transparentAreaX + transparentAreaSize &&
-    //         origin.y + size.height <= transparentAreaY + transparentAreaSize
-    //     ) {
-    //         setScanned(true);
-    //         setScannedResult(data);
-    //         setScannedQrCode(data);
-    //         Vibration.vibrate(100);
-    //         // console.log(` type: ${type}   data: ${data}  typeofData ${typeof data}`);
-
-    //         try {
-    //             const price = await fetchCurrentPrice();
-    //             console.log('fetchedCurrentPrice in scanQrPage', price);
-    //             if (!price) {
-    //                 return; // Exit if price fetch failed
-    //             }
-    //             const response = await chargeStationService.getTodayReservation();
-    //             if (response) {
-    //                 const now = new Date();
-    //                 const onlyThisConnector = response.filter(
-    //                     (reservation: any) => reservation.connector.ConnectorID === data
-    //                 );
-    //                 console.log('onlyThisConnector', onlyThisConnector);
-
-    //                 // Check availability for each duration
-    //                 const availability = {
-    //                     // 3: checkAvailability(onlyThisConnector, now, 10) && walletBalance >= 3 * price,
-    //                     25: checkAvailability(onlyThisConnector, now, 40) && walletBalance >= 20 * price,
-    //                     30: checkAvailability(onlyThisConnector, now, 45) && walletBalance >= 25 * price,
-    //                     40: checkAvailability(onlyThisConnector, now, 55) && walletBalance >= 30 * price,
-    //                     45: checkAvailability(onlyThisConnector, now, 60) && walletBalance >= 40 * price,
-    //                     full: checkAvailability(onlyThisConnector, now, 120) && walletBalance >= 80 * price
-    //                 };
-    //                 // console.log('availability', availability);
-
-    //                 // console.log('walletBalance', walletBalance);
-    //                 // console.log('currentPricecurrentPricecurrentPricecurrentPricecurrentPrice', currentPrice);
-    //                 setAvailableSlots(availability);
-    //                 setModalVisible(true);
-    //             } else {
-    //                 Alert.alert('系統錯誤', '無法獲取預約信息。請稍後再試。');
-    //             }
-    //         } catch (error) {
-    //             console.error("Error fetching today's reservations:", error);
-    //             Alert.alert('系統錯誤', '發生未知錯誤。請稍後再試。');
-    //         }
-
-    //         setTimeout(() => {
-    //             setScanned(false);
-    //         }, 2000);
-    //     }
-    // };
-
     // Function to handle barcode scanning
     const handleBarCodeScanned = async ({ bounds, data, type }: { bounds?: any; data: any; type: any }) => {
         if (
@@ -465,31 +223,6 @@ const ScanQrPage = () => {
         }
     };
 
-    // const checkAvailability = (reservations, startTime, duration) => {
-    //     const endTime = new Date(startTime.getTime() + duration * 60000);
-    //     // console.log('now', startTime);
-    //     // console.log('endTime', endTime);
-    //     // console.log('reservations', reservations);
-    //     return !reservations.some((reservation) => {
-    //         // Ignore reservations with status '9' (cancelled)
-    //         if (reservation.status.id === '9' || reservation.status.id === '13') {
-    //             return false;
-    //         }
-
-    //         // For status '8' (early finished), check actual_end_time
-    //         if (reservation.status.id === '8' && reservation.actual_end_time) {
-    //             const actualEndTime = new Date(reservation.actual_end_time);
-    //             if (actualEndTime <= startTime) {
-    //                 return false; // Treat as available if actual end time is before or at start time
-    //             }
-    //         }
-
-    //         const resStart = new Date(reservation.book_time);
-    //         const resEnd = new Date(reservation.end_time);
-    //         return startTime < resEnd && endTime > resStart;
-    //     });
-    // };
-
     const handleDurationSelect = (duration) => {
         setSelectedDuration(duration);
         // console.log(duration);
@@ -552,101 +285,6 @@ const ScanQrPage = () => {
         }
     };
 
-    //below commented is the original WORKING startCharging, if i fucked up, return back to using this!!!
-
-    // const startCharging = async (dataForSubmission) => {
-    //     try {
-    //         const wallet = await walletService.getWalletBalance();
-    //         console.log('wallet in startCharging in scanQrPage', wallet);
-
-    //         const response = await walletService.submitPayment(
-    //             dataForSubmission.stationID,
-    //             dataForSubmission.connector,
-    //             dataForSubmission.user,
-    //             dataForSubmission.book_time,
-    //             dataForSubmission.end_time,
-    //             dataForSubmission.total_power,
-    //             dataForSubmission.total_fee,
-    //             dataForSubmission.promotion_code,
-    //             dataForSubmission.car,
-    //             dataForSubmission.type,
-    //             dataForSubmission.is_ic_call
-    //         );
-    //         if (response.status === 200 || response.status === 201) {
-    //             setSelectedDuration(null);
-    //             console.log('Charging started from startCharging', response);
-    //             setIsConfirmLoading(false);
-    //             // Set a flag in AsyncStorage to indicate charging has started
-
-    //             await AsyncStorage.setItem('chargingStarted', 'true');
-
-    //             Alert.alert('啟動成功', '請稍後等待頁面自動跳轉至充電介面', [
-    //                 {
-    //                     text: 'OK',
-    //                     onPress: async () => {
-    //                         setModalVisible(false);
-    //                         setLoading(true);
-
-    //                         // Wait for 2 seconds
-    //                         await new Promise((resolve) => setTimeout(resolve, 2000));
-
-    //                         // Hide loading spinner and navigate
-    //                         setLoading(false);
-
-    //                         router.push('(auth)/(tabs)/(charging)/chargingPage');
-    //                     }
-    //                 }
-    //             ]);
-
-    //             // Start the navigation attempt loop
-    //             // startNavigationAttempts();
-    //         } else if (response.status === 400) {
-    //             console.log('400 error in paymentSummaryPageComponent');
-    //             Alert.alert('餘額不足', '您的餘額不足,請充值後再試。');
-    //         } else {
-    //             console.log('Failed to start charging:', response);
-    //             Alert.alert('掃描失敗 請稍後再試。', response);
-    //         }
-    //     } catch (error) {
-    //         console.log('Failed to start chasssssssrging:', error);
-    //     }
-    // };
-
-    //below is the new flow for startCharging.
-
-    // useEffect(() => {
-    //     const subscription = AppState.addEventListener('change', (nextAppState) => {
-    //         if (
-    //             appState.current.match(/inactive|background/) &&
-    //             nextAppState === 'active' &&
-    //             isExpectingPayment &&
-    //             // outTradeNo &&
-    //             paymentInitiatedTime.current
-    //         ) {
-    //             const currentTime = new Date().getTime();
-    //             if (currentTime - paymentInitiatedTime.current < PAYMENT_CHECK_TIMEOUT) {
-    //                 checkPaymentStatus();
-    //             } else {
-    //                 // Payment check timeout reached
-    //                 setIsExpectingPayment(false);
-    //                 setOutTradeNo('');
-    //                 paymentInitiatedTime.current = null;
-    //                 Alert.alert(
-    //                     'Payment Timeout',
-    //                     'The payment status check has timed out. Please check your payment history.'
-    //                 );
-    //             }
-    //         }
-    //         appState.current = nextAppState;
-    //     });
-
-    //     return () => {
-    //         subscription.remove();
-    //     };
-    // }, [outTradeNo, isExpectingPayment]);
-
-    //check payment status
-
     useEffect(() => {
         const subscription = AppState.addEventListener('change', (nextAppState) => {
             if (
@@ -918,161 +556,6 @@ const ScanQrPage = () => {
             }
         } catch (error) {}
     };
-
-    // const startNavigationAttempts = () => {
-    //     let attempts = 0;
-    //     const maxAttempts = 10; // Try for about 2.5 minutes (10 * 15 seconds)
-
-    //     const attemptNavigation = async () => {
-    //         try {
-    //             const chargingStarted = await AsyncStorage.getItem('chargingStarted');
-    //             if (chargingStarted === 'true') {
-    //                 // Wait for 2 seconds before navigating
-    //                 await new Promise((resolve) => setTimeout(resolve, 2000));
-    //                 await AsyncStorage.removeItem('chargingStarted');
-    //                 router.push('(auth)/(tabs)/(charging)/chargingPage');
-    //                 // If navigation is successful, clear the flag
-    //             } else {
-    //                 throw new Error('Navigation not ready');
-    //             }
-    //         } catch (error) {
-    //             attempts++;
-    //             if (attempts < maxAttempts) {
-    //                 // If navigation fails, try again after 15 seconds
-    //                 setTimeout(attemptNavigation, 15000);
-    //             } else {
-    //                 // If all attempts fail, show an alert to the user
-    //                 Alert.alert('導航失敗', '無法自動跳轉到充電頁面。請手動導航到充電頁面。', [
-    //                     { text: 'OK', onPress: () => {} }
-    //                 ]);
-    //             }
-    //         }
-    //     };
-
-    //     // Start the first attempt after 15 seconds
-    //     setTimeout(attemptNavigation, 15000);
-    // };
-
-    // return (
-    //     <View style={styles.container} ref={viewRef}>
-    //         {loading ? (
-    //             <View className="flex-1 items-center justify-center">
-    //                 <ActivityIndicator />
-    //             </View>
-    //         ) : (
-    //             <CameraView
-    //                 style={styles.camera}
-    //                 facing="back"
-    //                 barcodeScannerSettings={{
-    //                     barcodeTypes: ['qr']
-    //                 }}
-    //                 onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
-    //                 responsiveOrientationWhenOrientationLocked={true}
-    //             >
-    //                 <View style={styles.overlay}>
-    //                     <View style={styles.topOverlay}>
-    //                         {/* <ChooseCar
-    //                             carData={carData}
-    //                             loading={loading}
-    //                             selectedCar={selectedCar}
-    //                             setSelectedCar={setSelectedCar}
-    //                         /> */}
-    //                         <Pressable
-    //                             // style={styles.closeButton}
-    //                             className="absolute top-20 left-10 z-10 "
-    //                             onPress={() => {
-    //                                 if (router.canGoBack()) {
-    //                                     router.back();
-    //                                 } else {
-    //                                     router.push('/mainPage');
-    //                                 }
-    //                             }}
-    //                         >
-    //                             <CrossLogoWhiteSvg />
-    //                         </Pressable>
-    //                     </View>
-    //                     <View style={styles.centerRow}>
-    //                         <View style={styles.leftOverlay}></View>
-    //                         <View style={styles.transparentArea}></View>
-    //                         <View style={styles.rightOverlay} />
-    //                     </View>
-    //                     <View className="items-center justify-between" style={styles.bottomOverlay}>
-    //                         <View>
-    //                             <Text className="text-white text-lg font-bold mt-2 text-center">
-    //                                 請掃瞄充電座上的二維碼
-    //                             </Text>
-    //                         </View>
-    //                         <View className="flex-row space-x-2 items-center ">
-    //                             <QuestionSvg />
-
-    //                             <Pressable onPress={() => router.push('assistancePage')}>
-    //                                 <Text className="text-white text-base">需要協助?</Text>
-    //                             </Pressable>
-    //                         </View>
-    //                         <View />
-    //                     </View>
-    //                 </View>
-    //             </CameraView>
-    //         )}
-    //         <Modal isVisible={isModalVisible} backdropOpacity={0.5} animationIn="fadeIn" animationOut="fadeOut">
-    //             <View style={styles.modalContent} className="flex flex-col">
-    //                 <Text className="text-xl font-bold mt-2 text-center">請選擇充電時間</Text>
-    //                 <Text className="text-base  m-2 mb-4 text-center">按鈕呈紅色代表該時段已被他人預約</Text>
-    //                 <View className="flex flex-row flex-wrap  ">
-    //                     {Object.entries(availableSlots).map(([duration, available]) => (
-    //                         <NormalButton
-    //                             key={duration}
-    //                             title={
-    //                                 duration === 'full' ? (
-    //                                     <Text className={selectedDuration === duration ? 'text-white' : ''}>
-    //                                         充滿停機
-    //                                     </Text>
-    //                                 ) : (
-    //                                     <Text
-    //                                         className={selectedDuration === duration ? 'text-white' : ''}
-    //                                     >{`${planMap[duration].kWh} 度電 - ${planMap[duration].displayDuration} 分鐘`}</Text>
-    //                                 )
-    //                             }
-    //                             onPress={() => handleDurationSelect(duration)}
-    //                             extendedStyle={[
-    //                                 styles.durationButton,
-    //                                 {
-    //                                     backgroundColor: available
-    //                                         ? selectedDuration === duration
-    //                                             ? '#02677d'
-    //                                             : 'white'
-    //                                         : 'red',
-    //                                     borderColor: available ? 'black' : 'red',
-    //                                     borderWidth: 1
-    //                                 }
-    //                             ]}
-    //                             disabled={!available}
-    //                         />
-    //                     ))}
-    //                 </View>
-    //                 {selectedDuration && (
-    //                     <NormalButton
-    //                         title={
-    //                             isConfirmLoading ? (
-    //                                 <ActivityIndicator color="white" />
-    //                             ) : (
-    //                                 <Text className="text-white">確認</Text>
-    //                             )
-    //                         }
-    //                         onPress={handleConfirm}
-    //                         extendedStyle={styles.confirmButton}
-    //                     />
-    //                 )}
-    //                 <NormalButton
-    //                     title={<Text className="">取消</Text>}
-    //                     onPress={handleCancel}
-    //                     extendedStyle={styles.cancelButton}
-    //                 />
-    //             </View>
-    //         </Modal>
-    //     </View>
-    // );
-    // console.log('availableSlots', availableSlots);
     return (
         <View style={styles.container} ref={viewRef}>
             {!permission ? (
@@ -1139,68 +622,6 @@ const ScanQrPage = () => {
                     </View>
                 </CameraView>
             )}
-            {/* <Modal isVisible={isModalVisible} backdropOpacity={0.5} animationIn="fadeIn" animationOut="fadeOut">
-                <View style={styles.modalContent} className="flex flex-col">
-                    <Text className="text-xl font-bold mt-2 text-center">請選擇充電時間</Text>
-                    {Object.values(availableSlots).some((available) => !available) && (
-                        <Text className="text-base mt-1 text-center">
-                            按鈕呈紅色代表現時錢包餘額不足以支付選擇的充電時間,選擇紅色按鈕並按下確認鍵會進行一次性充值付費
-                        </Text>
-                    )}
-                    <Text className="text-base text-center mb-4"></Text>
-                    <View className="flex flex-row flex-wrap  ">
-                        {Object.entries(availableSlots).map(([duration, available]) => (
-                            <NormalButton
-                                key={duration}
-                                title={
-                                    duration === 'full' ? (
-                                        <Text className={selectedDuration === duration ? 'text-white' : ''}>
-                                            充滿停機 (最多80度電)
-                                        </Text>
-                                    ) : (
-                                        <Text
-                                            className={selectedDuration === duration ? 'text-white' : ''}
-                                        >{`${planMap[duration].kWh} 度電 - ${planMap[duration].displayDuration} 分鐘`}</Text>
-                                    )
-                                }
-                                onPress={() => handleDurationSelect(duration)}
-                                extendedStyle={[
-                                    styles.durationButton,
-                                    {
-                                        backgroundColor: available
-                                            ? selectedDuration === duration
-                                                ? '#02677d'
-                                                : 'white'
-                                            : selectedDuration === duration
-                                            ? '#8B0000' // Darker red when selected
-                                            : 'red', // Normal red when not selected
-                                        borderColor: available ? 'black' : 'red',
-                                        borderWidth: 1
-                                    }
-                                ]}
-                            />
-                        ))}
-                    </View>
-                    {selectedDuration && (
-                        <NormalButton
-                            title={
-                                isConfirmLoading ? (
-                                    <ActivityIndicator color="white" />
-                                ) : (
-                                    <Text className="text-white">確認</Text>
-                                )
-                            }
-                            onPress={handleConfirm}
-                            extendedStyle={styles.confirmButton}
-                        />
-                    )}
-                    <NormalButton
-                        title={<Text className="">取消</Text>}
-                        onPress={handleCancel}
-                        extendedStyle={styles.cancelButton}
-                    />
-                </View>
-            </Modal> */}
         </View>
     );
 };

+ 2 - 1
babel.config.js

@@ -13,7 +13,8 @@ module.exports = function (api) {
                     path: 'factory-env/.env.global.development',
                     allowlist: [
                         'EXPO_PUBLIC_NODE_ENV',
-                        'EXPO_PUBLIC_API_URL'
+                        'EXPO_PUBLIC_API_URL',
+                        'EXPO_PUBLIC_API_IMG_URL',
                     ],
                     blocklist: []
                 }

+ 1 - 1
component/bookingMenuPage/bookingConfirmationPage.tsx

@@ -2,7 +2,7 @@ import { View, Text, ScrollView, Pressable, StyleSheet } from 'react-native';
 import { SafeAreaView } from 'react-native-safe-area-context';
 import { router, useLocalSearchParams } from 'expo-router';
 import NormalButton from '../global/normal_button';
-import { PreviousPageBlackSvg, PreviousPageSvg } from '../global/SVG';
+import { PreviousPageBlackSvg } from '../global/SVG';
 import useCouponStore from '../../providers/coupon_store';
 import { useEffect } from 'react';
 import useBookingStore from '../../providers/booking_store';

+ 3 - 76
component/chargingPage/noChargingOngoingPageComponent.tsx

@@ -10,80 +10,6 @@ import { chargeStationService } from '../../service/chargeStationService';
 // const MAX_RETRIES = 3; // Maximum number of retry attempts
 
 const NoChargingOngoingPageComponent = () => {
-    //fetch charge station info
-    // const [chargeStationInfo, setChargeStationInfo] = useState([]);
-    // const [availableConnectors, setAvailableConnectors] = useState({});
-
-    // useEffect(() => {
-    //     const fetchChargeStationInfo = async () => {
-    //         try {
-    //             const chargeStationInfo = await chargeStationService.fetchAllChargeStations();
-    //             const onlyWaiYipStreetStation = chargeStationInfo.filter(
-    //                 (station) => station.id == '2405311022116801000'
-    //             );
-    //             setChargeStationInfo(onlyWaiYipStreetStation);
-
-    //             // setChargeStationInfo(chargeStationInfo);
-    //         } catch (error) {
-    //             console.error('Error fetching charge station info:', error);
-    //         }
-    //     };
-    //     fetchChargeStationInfo();
-    // }, []);
-
-    // useEffect(() => {
-    //     const fetchChargeStationInfo = async () => {
-    //         try {
-    //             const chargeStationInfo = await chargeStationService.fetchAllChargeStations();
-    //             setChargeStationInfo(chargeStationInfo);
-    //         } catch (error) {
-    //             console.error('Error fetching charge station info:', error);
-    //         }
-    //     };
-    //     fetchChargeStationInfo();
-    // }, []);
-
-    // const fetchConnectorWithRetry = async (stationId, retryCount = 0) => {
-    //     try {
-    //         const response = await chargeStationService.fetchAvailableConnectors(stationId);
-    //         if (response === 500 || !response) {
-    //             throw new Error('Server error');
-    //         }
-    //         return response;
-    //     } catch (error) {
-    //         if (retryCount < MAX_RETRIES) {
-    //             await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
-    //             return fetchConnectorWithRetry(stationId, retryCount + 1);
-    //         }
-    //         // console.error(`Failed to fetch connectors for station ${stationId} after ${MAX_RETRIES} attempts:`, error);
-    //         return null;
-    //     }
-    // };
-
-    // useEffect(() => {
-    //     const fetchAllConnectors = async () => {
-    //         try {
-    //             const connectorData = {};
-    //             for (const station of chargeStationInfo) {
-    //                 const stationConnectors = await fetchConnectorWithRetry(station.id);
-    //                 if (stationConnectors !== null) {
-    //                     connectorData[station.id] = stationConnectors;
-    //                     // Update state immediately for each successful fetch
-    //                     setAvailableConnectors((prev) => ({
-    //                         ...prev,
-    //                         [station.id]: stationConnectors
-    //                     }));
-    //                 }
-    //             }
-    //         } catch (error) {
-    //             console.error('Error fetching connectors:', error);
-    //         }
-    //     };
-
-    //     if (chargeStationInfo.length > 0) {
-    //         fetchAllConnectors();
-    //     }
-    // }, [chargeStationInfo]);
     const [newAvailableConnectors, setNewAvailableConnectors] = useState([]);
     useFocusEffect(
         useCallback(() => {
@@ -134,6 +60,7 @@ const NoChargingOngoingPageComponent = () => {
             '2405311022116801000': require('../../assets/dummyStationPicture.png')
         };
         // const imageSource = stationImages[stationID] || require('../../assets/dummyStationPicture.png');
+        const imgObj = item.image? {uri: item.image} : require('../../assets/dummyStationPicture.png')
         return (
             <Pressable
                 onPress={() => {
@@ -153,7 +80,7 @@ const NoChargingOngoingPageComponent = () => {
                 }}
             >
                 <View className="flex flex-1 flex-row w-full ">
-                    <Image style={styles.image} source={{ uri: item.image }} />
+                    <Image style={styles.image} source={imgObj} />
                     <View className="flex flex-col gap-2 mt-5 mr-2">
                         <Text
                             style={{
@@ -203,7 +130,7 @@ const NoChargingOngoingPageComponent = () => {
                             <View className="">
                                 {newAvailableConnectors?.map((item, index) => (
                                     <View key={index}>
-                                        <View className=" border-b border-gray-200" />
+                                        <View className="border-b border-gray-200" />
                                         <StationRow item={item} key={index} />
                                     </View>
                                 ))}

+ 0 - 3
component/chargingPage/penaltyPaymentPageComponent.tsx

@@ -2,10 +2,7 @@ import { View, Text, ScrollView, Pressable, StyleSheet, Alert } from 'react-nati
 import { SafeAreaView } from 'react-native-safe-area-context';
 import { router, useLocalSearchParams, useNavigation } from 'expo-router';
 import NormalButton from '../global/normal_button';
-import { PreviousPageBlackSvg, PreviousPageSvg } from '../global/SVG';
-import useCouponStore from '../../providers/coupon_store';
 import { useEffect } from 'react';
-import useBookingStore from '../../providers/booking_store';
 import { chargeStationService } from '../../service/chargeStationService';
 import useUserInfoStore from '../../providers/userinfo_store';
 

+ 0 - 2
component/homePage/homePage.tsx

@@ -111,7 +111,6 @@ const HomePage: React.FC<HomePageProps> = () => {
                 fetchCurrentPrice(),
                 fetchMainPromotion()
             ]);
-            console.log('results of all settled', results);
         };
         fetchWithAllSettled();
     }, []);
@@ -267,7 +266,6 @@ const HomePage: React.FC<HomePageProps> = () => {
                                                 return;
                                             }
                                             setShowConfirmationModal(true);
-                                            console.log('showConfirmationModal', showConfirmationModal);
                                         }}
                                     />
                                 </View>

+ 15 - 97
component/resultDetailPage/resultDetailPageComponent.tsx

@@ -105,10 +105,11 @@ const ResultDetailPageComponent = () => {
     const chargeStationName = params.chargeStationName as string;
     const chargeStationAddress = params.chargeStationAddress as string;
     const availableConnectorsFromParams = params.availableConnectors;
-    const imageSource = params.imageSource;
+    const imageSourceProps = params.imageSource;
     const stationLng = params.stationLng as string;
     const stationLat = params.stationLat as string;
     const [isLoading, setIsLoading] = useState(true);
+    const [imageSource, setImageSource] = useState();
     // const chargeStationLat = params.chargeStationLat as string;
     // const chargeStationLng = params.chargeStationLng as string;
     const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
@@ -119,8 +120,20 @@ const ResultDetailPageComponent = () => {
         availableConnectorsFromParams ? Number(availableConnectorsFromParams) : null
     );
     const [newAvailableConnectors, setNewAvailableConnectors] = useState([]);
+    useEffect(() => {
+        const imgObj = imageSourceProps? {uri: imageSourceProps} : require('../../assets/dummyStationPicture.png')
+        setImageSource(imgObj);
+    }, [imageSourceProps])
 
     useEffect(() => {
+        const fetchPrice = async () => {
+            try {
+                const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
+                setPrice(price);
+            } catch (error) {
+                console.error('Error fetching price:', error);
+            }
+        };
         const getCurrentLocation = async () => {
             let { status } = await Location.requestForegroundPermissionsAsync();
             if (status !== 'granted') {
@@ -132,17 +145,6 @@ const ResultDetailPageComponent = () => {
         };
 
         getCurrentLocation();
-    }, []);
-
-    useEffect(() => {
-        const fetchPrice = async () => {
-            try {
-                const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
-                setPrice(price);
-            } catch (error) {
-                console.error('Error fetching price:', error);
-            }
-        };
         fetchPrice();
     }, []);
 
@@ -199,59 +201,12 @@ const ResultDetailPageComponent = () => {
         }
     };
 
-    const handleNavigaationPress = () => {
-        const latitude = chargeStationLat;
-        const longitude = chargeStationLng;
-        console.log('latitude', latitude);
-        console.log('longitude', longitude);
-        const label = encodeURIComponent(chargeStationName);
-
-        // Google Maps App URL
-        const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;
-
-        // Fallback URL for web browser
-        const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;
-
-        Linking.canOpenURL(googleMapsUrl)
-            .then((supported) => {
-                if (supported) {
-                    Linking.openURL(googleMapsUrl);
-                } else {
-                    Linking.openURL(webUrl).catch((err) => {
-                        console.error('An error occurred', err);
-                        Alert.alert(
-                            'Error',
-                            "Unable to open Google Maps. Please make sure it's installed on your device.",
-                            [{ text: 'OK' }],
-                            { cancelable: false }
-                        );
-                    });
-                }
-            })
-            .catch((err) => console.error('An error occurred', err));
-    };
-
-    const handleAddBooking = () => {
-        if (coordinates) {
-            router.push({
-                pathname: 'makingBookingPage',
-                params: {
-                    chargeStationID: chargeStationID,
-                    chargeStationAddress: chargeStationAddress,
-                    chargeStationName: chargeStationName,
-                    chargeStationLat: coordinates.StationLat.toString(),
-                    chargeStationLng: coordinates.StationLng.toString()
-                }
-            });
-        }
-    };
-
     return (
         <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
             <ScrollView className="flex-1 ">
                 <View className="relative">
                     <Image
-                        source={{ uri: imageSource }}
+                        source={ imageSource }
                         resizeMode="cover"
                         style={{ flex: 1, width: '100%', height: 300 }}
                     />
@@ -300,43 +255,6 @@ const ResultDetailPageComponent = () => {
                         <Text>Walk-In</Text>
                         {/* <Text>{distance} </Text> */}
                     </View>
-                    {/* {coordinates ? (
-                        <NormalButton
-                            title={
-                                <View className="pr-2">
-                                    <Text
-                                        style={{
-                                            color: '#FFFFFF',
-                                            fontWeight: 700,
-                                            fontSize: 20
-                                        }}
-                                    >
-                                        + 新增預約
-                                    </Text>
-                                </View>
-                            }
-                            // onPress={() => console.log('ab')}
-                            onPress={handleAddBooking}
-                        />
-                    ) : (
-                        <NormalButton
-                            title={
-                                <View className="pr-2">
-                                    <Text
-                                        style={{
-                                            color: '#FFFFFF',
-                                            fontWeight: 700,
-                                            fontSize: 20
-                                        }}
-                                    >
-                                        <ActivityIndicator />
-                                    </Text>
-                                </View>
-                            }
-                            // onPress={() => console.log('ab')}
-                            onPress={handleAddBooking}
-                        />
-                    )} */}
 
                     <View
                         className="flex-1 flex-row min-h-[20px] border-slate-300 my-6 rounded-2xl"

+ 8 - 8
service/chargeStationService.tsx

@@ -1,7 +1,7 @@
 import axios from 'axios';
 import { Alert } from 'react-native';
 import * as SecureStore from 'expo-secure-store';
-import { EXPO_PUBLIC_API_URL } from '@env';
+import { EXPO_PUBLIC_API_URL, EXPO_PUBLIC_API_IMG_URL } from '@env';
 import { forgetPasswordFormData } from '../types/signup';
 import { CustomerData } from '../types/signUpFormData';
 
@@ -203,30 +203,31 @@ class ChargeStationService {
 
     async NewfetchAvailableConnectors() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/info`, {
+            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/info`, {
                 headers: {
                     Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                 }
             });
-
             if (response.status === 200 && response.data.code === 200) {
+                console.log('sssssss', response.data);
+                console.log('sssssss1', SecureStore.getItemAsync('accessToken'));
                 return response.data.data.map((station: any) => {
                     // const snapshotData = JSON.parse(station.snapshot);
                     const snapshotData = station.snapshot;
 
-                    const availableConnectors = station.Equipments.reduce((count: number, equipment: any) => {
+                    const availableConnectors = station?.Equipments?.reduce((count: number, equipment: any) => {
                         return (
                             count +
                             equipment.ConnectorInfos.filter((connector: any) => connector.Status === '待机').length
                         );
                     }, 0);
-
+                    let imgUrl = station.image? EXPO_PUBLIC_API_IMG_URL + station.image : null
                     return {
                         stationID: snapshotData.StationID,
                         stationName: snapshotData.StationName,
                         availableConnectors: availableConnectors,
                         address: snapshotData.Address,
-                        image: station.image,
+                        image: imgUrl,
                         stationLng: snapshotData.StationLng,
                         stationLat: snapshotData.StationLat
                     };
@@ -328,7 +329,7 @@ class ChargeStationService {
 
     async noImagefetchChargeStationIdByScannedConnectorId(scannedConnectorId: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/simple/info`, {
+            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/simple/info`, {
                 headers: {
                     Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                 }
@@ -487,7 +488,6 @@ class ChargeStationService {
                     Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                 }
             });
-            console.log('Fetching all charge stations:', response.data);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {

+ 0 - 1
service/walletService.tsx

@@ -25,7 +25,6 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            console.log('dqqqqqq',SecureStore.getItemAsync('accessToken'));
             console.error('Error in getCouponForSpecificUser:', error);
             throw error;
         }