Skip to content

Commit

Permalink
added the currency change api and added the button for it and changes…
Browse files Browse the repository at this point in the history
… CSS
  • Loading branch information
ka8540 committed Apr 20, 2024
1 parent d877593 commit 509d216
Show file tree
Hide file tree
Showing 7 changed files with 228 additions and 61 deletions.
223 changes: 180 additions & 43 deletions PCP/Retailer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,42 @@ import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Image, ScrollView, Button, ActivityIndicator, TouchableOpacity, TextInput } from 'react-native';
import { useRoute } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { Picker } from '@react-native-picker/picker';
import { ActionSheetIOS } from 'react-native';
const ProductDetails = () => {
const [productDescription, setProductDescription] = useState('');
const [product, setProduct] = useState(null);
const [retailers, setRetailers] = useState([]);
const [priceInfo, setPriceInfo] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [selectedCurrency, setSelectedCurrency] = useState('USD');
const [convertedPrice, setConvertedPrice] = useState('');
const [quantity, setQuantity] = useState('1'); // Default quantity
const route = useRoute();
const { ProductID } = route.params;


const showCurrencyOptions = () => {
const options = ['USD', 'CAD', 'INR', 'Cancel'];
const cancelButtonIndex = options.length - 1;

ActionSheetIOS.showActionSheetWithOptions(
{
options: options,
cancelButtonIndex: cancelButtonIndex,
userInterfaceStyle: 'light' // This should make it have the silver background
},
(buttonIndex) => {
if (buttonIndex !== cancelButtonIndex) {
setSelectedCurrency(options[buttonIndex]);
}
}
);
};

useEffect(() => {
const fetchProductDetails = async () => {

try {
const productResponse = await fetch(`http://127.0.0.1:5000/products/${ProductID}`);
const productData = await productResponse.json();
Expand Down Expand Up @@ -45,6 +67,36 @@ const ProductDetails = () => {
fetchProductDetails();
}, [ProductID]);

useEffect(() => {
const fetchConvertedPrice = async () => {
if (selectedCurrency === 'USD' || !priceInfo.Price) return;

const endpoint = selectedCurrency === 'CAD' ? '/cad_price' : '/inr_price';
const url = `http://127.0.0.1:5000${endpoint}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: { 'Price': priceInfo.Price.toString() },
});
if (!response.ok) throw new Error('Price conversion failed');
const result = await response.json();

// Check the selected currency and set the state accordingly
if (selectedCurrency === 'CAD') {
setConvertedPrice(result.price_cad);
} else if (selectedCurrency === 'INR') {
setConvertedPrice(result.price_inr);
}

console.log(result); // This will log the correct value
} catch (error) {
setError(`Failed to convert price: ${error.message}`);
}
};

fetchConvertedPrice();
}, [priceInfo, selectedCurrency]);

const handleAddToFavorites = async () => {
const sessionKey = await AsyncStorage.getItem('sessionKey');
if (!sessionKey) {
Expand Down Expand Up @@ -112,25 +164,40 @@ const ProductDetails = () => {
keyboardType="numeric"
placeholder="Quantity"
/>
<Button
title="Add to Favorite"

<TouchableOpacity
onPress={handleAddToFavorites}
color="#ff4444"
/>
<Button
title="Add to Cart"
style={styles.buttonFavorite}
>
<Text style={styles.buttonText}>Add to Favorite</Text>
</TouchableOpacity>

<TouchableOpacity
onPress={handleAddToCart}
color="#008000"
/>
style={styles.buttonCart}
>
<Text style={styles.buttonText}>Add to Cart</Text>
</TouchableOpacity>

<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10 }}>
<TouchableOpacity
onPress={showCurrencyOptions}
style={styles.currencyButton}
>
<Text style={styles.buttonText}>Choose Currency</Text>
</TouchableOpacity>
</View>
<Text style={styles.productDescription}>{productDescription}</Text>
{retailers.map(retailer => (
<View key={retailer.RetailerID} style={styles.retailerContainer}>
<TouchableOpacity onPress={() => {/* navigation logic to retailer */}}>
{retailers.map((retailer) => (
<View key={retailer.RetailerID} style={styles.retailerContainer}>
<Text style={styles.retailerName}>{retailer.RetailerName}</Text>
{priceInfo && <Text style={styles.productPrice}>{priceInfo.Currency} {priceInfo.Price}</Text>}
</TouchableOpacity>
</View>
))}
<Text style={styles.productPrice}>
{selectedCurrency === 'USD' ? priceInfo.Price : convertedPrice}
</Text>
</View>
))}


</>
)}
</ScrollView>
Expand All @@ -140,57 +207,127 @@ const ProductDetails = () => {
const styles = StyleSheet.create({
container: {
flexGrow: 1,
justifyContent: 'center',
justifyContent: 'flex-start', // Aligns content to the top of the screen
alignItems: 'center',
backgroundColor: '#f0f0f0', // Soft background color
padding: 20,
},
centered: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
productTitle: {
fontSize: 24,
fontSize: 28, // Larger font size for product title
fontWeight: 'bold',
marginBottom: 20,
color: '#333', // Darker color for better readability
marginTop: 20,
textAlign: 'center', // Center-align the text
},
productImage: {
width: '100%',
height: 300,
height: 250, // Adjusted for proportionate display
resizeMode: 'contain',
marginBottom: 20,
borderRadius: 10, // Rounded corners for the image
marginTop: 20,
},
productDescription: {
quantityInput: {
fontSize: 18,
height: 50, // Taller touch area
width: '80%', // Consistent width with the buttons
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5, // Rounded corners for the input field
padding: 10,
backgroundColor: '#fff', // White background to stand out from container
marginBottom: 20,
marginTop:20,
},
productPrice: {
fontSize: 15,
color: 'green',
buttonFavorite: {
backgroundColor: '#ff4444', // Red for the favorite button
paddingVertical: 15, // Slightly more padding for a larger button
width: '90%', // Set a consistent width
borderRadius: 10, // Rounded corners
alignSelf: 'center', // Center the button
marginTop: 10, // Space from the top element
marginBottom: 5, // Space from the bottom element
elevation: 2, // Drop shadow for Android (optional)
shadowColor: '#000', // Black color for the shadow
shadowOffset: { width: 0, height: 2 }, // Positioning of the shadow
shadowOpacity: 0.25, // Opacity of the shadow
shadowRadius: 3.84,
marginBottom: 10,
},
buttonCart: {
backgroundColor: '#008000', // Green for the cart button
paddingVertical: 15, // Slightly more padding for a larger button
width: '90%', // Set a consistent width
borderRadius: 10, // Rounded corners
alignSelf: 'center', // Center the button
marginTop: 5, // Space from the top element
marginBottom: 10, // Space from the bottom element
elevation: 2, // Drop shadow for Android (optional)
shadowColor: '#000', // Black color for the shadow
shadowOffset: { width: 0, height: 2 }, // Positioning of the shadow
shadowOpacity: 0.25, // Opacity of the shadow
shadowRadius: 3.84, // Blur radius of the shadow
marginBottom: 15,
},
buttonText: {
color: '#ffffff', // White text color
fontSize: 18, // Slightly larger font size
fontWeight: '600', // Medium font weight
textAlign: 'center', // Center text
fontSize: 20,
},
productDescription: {
fontSize: 18,
color: '#666', // Dark grey for readability
textAlign: 'justify', // Justified text for cleaner presentation
marginBottom: 20,
paddingHorizontal: 10, // Padding to prevent text from touching screen edges
},
retailerContainer: {
padding: 10,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%'
padding: 10,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
width: '100%',
marginBottom: 10,
},
retailerName: {
fontSize: 22,
color: '#007bff'
fontSize: 20,
fontWeight: '600',
color: '#007bff', // Slightly darker for better visibility
},
quantityInput: {
priceContainer: { // Create a new style for the price container
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
},
productPrice: {
fontSize: 18,
height: 40,
width: '50%',
fontWeight: '600', // Bold for the price
color: '#008000', // Green for the price
marginLeft: 4, // Space between the retailer name and the price
},
pickerContainer: {
borderColor: '#ccc',
borderWidth: 1,
padding: 10,
marginBottom: 10
}
borderRadius: 5,
width: '80%', // Consistent width with other elements
marginBottom: 20,
backgroundColor: '#fff',
},
currencyButton: {
backgroundColor: '#dcdcdc', // Silver background color
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 5,
marginHorizontal: 5,
elevation: 2, // Optional for Android shadow
shadowColor: '#000', // Optional for iOS shadow
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.22,
shadowRadius: 2.22,
},
});

export default ProductDetails;
10 changes: 10 additions & 0 deletions PCP/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions PCP/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@expo/vector-icons": "^14.0.0",
"@react-native-async-storage/async-storage": "^1.22.3",
"@react-native-community/masked-view": "^0.1.11",
"@react-native-picker/picker": "^2.7.5",
"@react-navigation/bottom-tabs": "^6.5.14",
"@react-navigation/drawer": "^6.6.9",
"@react-navigation/native": "^6.1.12",
Expand Down
27 changes: 20 additions & 7 deletions PCP/server/src/api/price_conversion_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,25 @@

class Canadian(Resource):
def get(self):
price_usd = request.headers.get('Price')
price_cad = get_convert_price_to_canadian(price_usd)
return price_cad

price_usd_str = request.headers.get('Price')
print(price_usd_str, "USD Prices!!")
try:
price_usd = float(price_usd_str)
price_cad = get_convert_price_to_canadian(price_usd)
print(price_cad,"price_result!!")
print(jsonify({'price_cad': price_cad}))
return jsonify({'price_cad': price_cad})
except (ValueError, TypeError):
return make_response(jsonify({'error': 'Invalid price value'}), 400)

class Indian(Resource):
def get(self):
price_usd = request.headers.get('Price')
price_inr = get_convert_price_to_canadian(price_usd)
return price_inr
price_usd_str = request.headers.get('Price')
try:
price_usd = float(price_usd_str)
print(price_usd)
price_inr = get_convert_price_to_indian(price_usd)
print("INR PRICE RESULT:",price_inr)
return jsonify({'price_inr': price_inr})
except (ValueError, TypeError):
return make_response(jsonify({'error': 'Invalid price value'}), 400)
17 changes: 6 additions & 11 deletions PCP/server/src/db/price_conversion.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
def get_convert_price_to_canadian(price_usd):
# Current exchange rate from USD to CAD
exchange_rate = 1.38 # Example rate, replace with actual rate
# Convert price to CAD
exchange_rate = 1.38
price_cad = price_usd * exchange_rate

return price_cad


print(price_cad)
return round(price_cad, 2) # Assuming you want to round to 2 decimal places

def get_convert_price_to_indian(price_usd):
# Current exchange rate from USD to INR
exchange_rate = 83.60 # Example rate, replace with actual rate
# Convert price to CAD
exchange_rate = 83.60
price_inr = price_usd * exchange_rate
return price_inr
print(price_inr,"INR PRICE")
return round(price_inr, 2)
Loading

0 comments on commit 509d216

Please sign in to comment.