chore: init
This commit is contained in:
199 files changed
+27919
No files matched your search
@@ -0,0 +1,8 @@
|
||||
> Why do I have a folder named ".expo" in my project?
|
||||
The ".expo" folder is created when an Expo project is started using "expo start" command.
|
||||
> What do the files contain?
|
||||
- "devices.json": contains information about devices that have recently opened this project. This is used to populate the "Development sessions" list in your development builds.
|
||||
- "settings.json": contains the server configuration that is used to serve the application manifest.
|
||||
> Should I commit the ".expo" folder?
|
||||
No, you should not share the ".expo" folder. It does not contain any information that is relevant for other developers working on the project, it is specific to your machine.
|
||||
Upon project creation, the ".expo" folder is already added to your ".gitignore" file.
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"devices": []
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"hostType": "lan",
|
||||
"lanType": "ip",
|
||||
"dev": true,
|
||||
"minify": false,
|
||||
"urlRandomness": null,
|
||||
"https": false,
|
||||
"scheme": null
|
||||
}
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
/* eslint-disable */
|
||||
import * as Router from 'expo-router';
|
||||
|
||||
export * from 'expo-router';
|
||||
|
||||
declare module 'expo-router' {
|
||||
export namespace ExpoRouter {
|
||||
export interface __routes<T extends string | object = string> {
|
||||
hrefInputParams: { pathname: Router.RelativePathString, params?: Router.UnknownInputParams } | { pathname: Router.ExternalPathString, params?: Router.UnknownInputParams } | { pathname: `/api`; params?: Router.UnknownInputParams; } | { pathname: `/`; params?: Router.UnknownInputParams; } | { pathname: `/_sitemap`; params?: Router.UnknownInputParams; } | { pathname: `/components/ActiveOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/CancelledOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/Category`; params?: Router.UnknownInputParams; } | { pathname: `/components/CompletedOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/ContactUsCenter`; params?: Router.UnknownInputParams; } | { pathname: `/components/FaqCenter`; params?: Router.UnknownInputParams; } | { pathname: `/components/FavoriteButton`; params?: Router.UnknownInputParams; } | { pathname: `/components/FlashSales`; params?: Router.UnknownInputParams; } | { pathname: `/components/HomeCarousel`; params?: Router.UnknownInputParams; } | { pathname: `/components/ItemCard`; params?: Router.UnknownInputParams; } | { pathname: `/components/ProductQuantityInput`; params?: Router.UnknownInputParams; } | { pathname: `/constants/clothColor`; params?: Router.UnknownInputParams; } | { pathname: `/constants/couponData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/flashSalesData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/myCartData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/paymentData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/recentData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/subShipping`; params?: Router.UnknownInputParams; } | { pathname: `/constants/usersData`; params?: Router.UnknownInputParams; } | { pathname: `/constants/wishlistData`; params?: Router.UnknownInputParams; } | { pathname: `/context/CartContext`; params?: Router.UnknownInputParams; } | { pathname: `/screens/AccessLocation`; params?: Router.UnknownInputParams; } | { pathname: `/screens/AddCardScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/CheckOutScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ChooseShippingScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/CompleteYourProfileScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ConfirmPayment`; params?: Router.UnknownInputParams; } | { pathname: `/screens/CouponScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/FashionScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/FilterScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/FlashSalesScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/HelpCenterScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/HomeScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/InviteFriendsScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/JacketScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/LeaveReviewScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/LocationScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/MyCartScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/NewPasswordScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/NotificationScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/OnboardingScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/OrderScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/PasswordManagerScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/PaymentMethodScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/PaymentSuccess`; params?: Router.UnknownInputParams; } | { pathname: `/screens/PrivacyPolicyScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ProductDetails`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ProductDetailsScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ProfileScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/RegisterScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/SearchResultScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/SearchScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/SettingScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/ShippingAddressScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/SignInScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/TrackOrderScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/VerifyCodeScreen`; params?: Router.UnknownInputParams; } | { pathname: `/screens/WellcomeScreen`; params?: Router.UnknownInputParams; } | { pLine truncated
|
||||
hrefOutputParams: { pathname: Router.RelativePathString, params?: Router.UnknownOutputParams } | { pathname: Router.ExternalPathString, params?: Router.UnknownOutputParams } | { pathname: `/api`; params?: Router.UnknownOutputParams; } | { pathname: `/`; params?: Router.UnknownOutputParams; } | { pathname: `/_sitemap`; params?: Router.UnknownOutputParams; } | { pathname: `/components/ActiveOrder`; params?: Router.UnknownOutputParams; } | { pathname: `/components/CancelledOrder`; params?: Router.UnknownOutputParams; } | { pathname: `/components/Category`; params?: Router.UnknownOutputParams; } | { pathname: `/components/CompletedOrder`; params?: Router.UnknownOutputParams; } | { pathname: `/components/ContactUsCenter`; params?: Router.UnknownOutputParams; } | { pathname: `/components/FaqCenter`; params?: Router.UnknownOutputParams; } | { pathname: `/components/FavoriteButton`; params?: Router.UnknownOutputParams; } | { pathname: `/components/FlashSales`; params?: Router.UnknownOutputParams; } | { pathname: `/components/HomeCarousel`; params?: Router.UnknownOutputParams; } | { pathname: `/components/ItemCard`; params?: Router.UnknownOutputParams; } | { pathname: `/components/ProductQuantityInput`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/clothColor`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/couponData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/flashSalesData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/myCartData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/paymentData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/recentData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/subShipping`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/usersData`; params?: Router.UnknownOutputParams; } | { pathname: `/constants/wishlistData`; params?: Router.UnknownOutputParams; } | { pathname: `/context/CartContext`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/AccessLocation`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/AddCardScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/CheckOutScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ChooseShippingScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/CompleteYourProfileScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ConfirmPayment`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/CouponScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/FashionScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/FilterScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/FlashSalesScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/HelpCenterScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/HomeScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/InviteFriendsScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/JacketScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/LeaveReviewScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/LocationScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/MyCartScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/NewPasswordScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/NotificationScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/OnboardingScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/OrderScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/PasswordManagerScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/PaymentMethodScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/PaymentSuccess`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/PrivacyPolicyScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ProductDetails`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ProductDetailsScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ProfileScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/RegisterScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/SearchResultScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/SearchScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/SettingScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/ShippingAddressScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/SignInScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/TrackOrderScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/screens/VerifyCodeScreen`; params?: Router.UnknownOutputParams; } | { pathname: `/scree
Line truncated
|
||||
href: Router.RelativePathString | Router.ExternalPathString | `/api${`?${string}` | `#${string}` | ''}` | `/${`?${string}` | `#${string}` | ''}` | `/_sitemap${`?${string}` | `#${string}` | ''}` | `/components/ActiveOrder${`?${string}` | `#${string}` | ''}` | `/components/CancelledOrder${`?${string}` | `#${string}` | ''}` | `/components/Category${`?${string}` | `#${string}` | ''}` | `/components/CompletedOrder${`?${string}` | `#${string}` | ''}` | `/components/ContactUsCenter${`?${string}` | `#${string}` | ''}` | `/components/FaqCenter${`?${string}` | `#${string}` | ''}` | `/components/FavoriteButton${`?${string}` | `#${string}` | ''}` | `/components/FlashSales${`?${string}` | `#${string}` | ''}` | `/components/HomeCarousel${`?${string}` | `#${string}` | ''}` | `/components/ItemCard${`?${string}` | `#${string}` | ''}` | `/components/ProductQuantityInput${`?${string}` | `#${string}` | ''}` | `/constants/clothColor${`?${string}` | `#${string}` | ''}` | `/constants/couponData${`?${string}` | `#${string}` | ''}` | `/constants/flashSalesData${`?${string}` | `#${string}` | ''}` | `/constants/myCartData${`?${string}` | `#${string}` | ''}` | `/constants/paymentData${`?${string}` | `#${string}` | ''}` | `/constants/recentData${`?${string}` | `#${string}` | ''}` | `/constants/subShipping${`?${string}` | `#${string}` | ''}` | `/constants/usersData${`?${string}` | `#${string}` | ''}` | `/constants/wishlistData${`?${string}` | `#${string}` | ''}` | `/context/CartContext${`?${string}` | `#${string}` | ''}` | `/screens/AccessLocation${`?${string}` | `#${string}` | ''}` | `/screens/AddCardScreen${`?${string}` | `#${string}` | ''}` | `/screens/CheckOutScreen${`?${string}` | `#${string}` | ''}` | `/screens/ChooseShippingScreen${`?${string}` | `#${string}` | ''}` | `/screens/CompleteYourProfileScreen${`?${string}` | `#${string}` | ''}` | `/screens/ConfirmPayment${`?${string}` | `#${string}` | ''}` | `/screens/CouponScreen${`?${string}` | `#${string}` | ''}` | `/screens/FashionScreen${`?${string}` | `#${string}` | ''}` | `/screens/FilterScreen${`?${string}` | `#${string}` | ''}` | `/screens/FlashSalesScreen${`?${string}` | `#${string}` | ''}` | `/screens/HelpCenterScreen${`?${string}` | `#${string}` | ''}` | `/screens/HomeScreen${`?${string}` | `#${string}` | ''}` | `/screens/InviteFriendsScreen${`?${string}` | `#${string}` | ''}` | `/screens/JacketScreen${`?${string}` | `#${string}` | ''}` | `/screens/LeaveReviewScreen${`?${string}` | `#${string}` | ''}` | `/screens/LocationScreen${`?${string}` | `#${string}` | ''}` | `/screens/MyCartScreen${`?${string}` | `#${string}` | ''}` | `/screens/NewPasswordScreen${`?${string}` | `#${string}` | ''}` | `/screens/NotificationScreen${`?${string}` | `#${string}` | ''}` | `/screens/OnboardingScreen${`?${string}` | `#${string}` | ''}` | `/screens/OrderScreen${`?${string}` | `#${string}` | ''}` | `/screens/PasswordManagerScreen${`?${string}` | `#${string}` | ''}` | `/screens/PaymentMethodScreen${`?${string}` | `#${string}` | ''}` | `/screens/PaymentSuccess${`?${string}` | `#${string}` | ''}` | `/screens/PrivacyPolicyScreen${`?${string}` | `#${string}` | ''}` | `/screens/ProductDetails${`?${string}` | `#${string}` | ''}` | `/screens/ProductDetailsScreen${`?${string}` | `#${string}` | ''}` | `/screens/ProfileScreen${`?${string}` | `#${string}` | ''}` | `/screens/RegisterScreen${`?${string}` | `#${string}` | ''}` | `/screens/SearchResultScreen${`?${string}` | `#${string}` | ''}` | `/screens/SearchScreen${`?${string}` | `#${string}` | ''}` | `/screens/SettingScreen${`?${string}` | `#${string}` | ''}` | `/screens/ShippingAddressScreen${`?${string}` | `#${string}` | ''}` | `/screens/SignInScreen${`?${string}` | `#${string}` | ''}` | `/screens/TrackOrderScreen${`?${string}` | `#${string}` | ''}` | `/screens/VerifyCodeScreen${`?${string}` | `#${string}` | ''}` | `/screens/WellcomeScreen${`?${string}` | `#${string}` | ''}` | `/screens/Wishlist${`?${string}` | `#${string}` | ''}` | `/screens/WishlistScreen${`?${string}` | `#${string}` | ''}` | `/themes/BottomTabBar${`?${string}` | `#${string}` | ''}` | `/themes/TabBar${`?${string}` | `#${string}` | ''}` | { pathname: Router.RelativePathString, params?: Router.UnknownInputParams } | { pathname: Router.ExternalPathString, params?: Router.UnknownInputParams } | { pathname: `/api`; params?: Router.UnknownInputParams; } | { pathname: `/`; params?: Router.UnknownInputParams; } | { pathname: `/_sitemap`; params?: Router.UnknownInputParams; } | { pathname: `/components/ActiveOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/CancelledOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/Category`; params?: Router.UnknownInputParams; } | { pathname: `/components/CompletedOrder`; params?: Router.UnknownInputParams; } | { pathname: `/components/ContactUsCenter`; params?: Router.UnknownInputParams; } | { pathname: `/components/FaqCenter`; params?: Router.UnknownInputParams; } | { pathname: `/components/FavoriteButton
Line truncated
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.9 KiB |
@@ -0,0 +1,6 @@
|
||||
|
||||
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
|
||||
# The following patterns were generated by expo-cli
|
||||
|
||||
expo-env.d.ts
|
||||
# @end expo-cli
|
||||
@@ -0,0 +1,304 @@
|
||||
The Backend has been made, on the django, with the following api urls
|
||||
While it consists of all the get, put, post, and delete..
|
||||
#1 Categories
|
||||
/api/categories ( note it also has id filteration with categories/id( as integer))
|
||||
`sample:
|
||||
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Jackets",
|
||||
"image": "http://127.0.0.1:9000/categories/cowsorus_SDhrdcM.png",
|
||||
"created_at": "2025-04-17T13:22:25.166148Z"
|
||||
}
|
||||
]
|
||||
`
|
||||
if you need all the product within the list same category api/categories/id/products/
|
||||
|
||||
#2 products
|
||||
api/products
|
||||
/products/{id}/rate/` - Rate a product (authenticated users)
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "White Jacket",
|
||||
"description": "White Jacket",
|
||||
"price": "1400.00",
|
||||
"image": "http://127.0.0.1:9000/products/cowsorus_2Aa9x4P.png",
|
||||
"category": 1,
|
||||
"stock": 400,
|
||||
"color": "White",
|
||||
"size": "L",
|
||||
"category_name": "Jackets",
|
||||
"average_rating": 0,
|
||||
"created_at": "2025-04-17T13:24:08.869744Z"
|
||||
}
|
||||
]
|
||||
api/ratings (for both post and get)
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"product": 1,
|
||||
"user": 2,
|
||||
"username": "nurpratap",
|
||||
"rating": 4,
|
||||
"comment": "This is good tho",
|
||||
"created_at": "2025-04-17T13:53:36.055166Z"
|
||||
}
|
||||
]
|
||||
api/orders
|
||||
/orders/{id}/` - Retrieve, update and delete an order
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"user": 2,
|
||||
"user_name": "Nur Pratap Karki",
|
||||
"total_price": "16800.00",
|
||||
"status": "Pending",
|
||||
"shipping_address": "Kohalpur",
|
||||
"created_at": "2025-04-17T13:24:40.322127Z",
|
||||
"order_items": [
|
||||
{
|
||||
"id": 1,
|
||||
"product": 1,
|
||||
"product_name": "White Jacket",
|
||||
"product_image": "http://127.0.0.1:9000/products/cowsorus_2Aa9x4P.png",
|
||||
"quantity": 12,
|
||||
"price": "1400.00",
|
||||
"subtotal": 16800.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
### Cart (Shopping Cart)
|
||||
- `GET api/cart/items/` - View items in cart
|
||||
- `POST api/cart/add_item/` - Add an item to the cart
|
||||
- `POST api/cart/remove_item/` - Remove an item from the cart
|
||||
- `POST api/cart/checkout/` - Complete the order with shipping details
|
||||
|
||||
### Authentication
|
||||
- `api/auth/login/` - Login and obtain session auth
|
||||
- `api/auth/logout/` - Logout
|
||||
|
||||
api/users/( signup )
|
||||
api/users/id/( to get, update and delete the user )
|
||||
sample :
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"first_name": "admin",
|
||||
"last_name": "admin",
|
||||
"email": "admin@admin.com",
|
||||
"phone": null,
|
||||
"address": "",
|
||||
"created_at": "2025-04-17T13:18:35.496122Z"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"username": "nurpratap",
|
||||
"first_name": "Nur Pratap",
|
||||
"last_name": "Karki",
|
||||
"email": "nurpratap@gmail.com",
|
||||
"phone": null,
|
||||
"address": "",
|
||||
"created_at": "2025-04-17T13:19:53.037348Z"
|
||||
}
|
||||
]
|
||||
|
||||
## Cart API
|
||||
|
||||
The cart system uses a model-based approach with one-to-one relationship between User and Cart, and one-to-many relationship between Cart and Product through CartItem.
|
||||
|
||||
### Endpoints
|
||||
|
||||
#### Get Cart Items
|
||||
```
|
||||
GET /api/cart/items/
|
||||
```
|
||||
Returns all items in the authenticated user's cart.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"user": 1,
|
||||
"items": [
|
||||
{
|
||||
"id": 1,
|
||||
"product": 1,
|
||||
"product_name": "Product Name",
|
||||
"product_price": "10.00",
|
||||
"quantity": 2,
|
||||
"subtotal": "20.00",
|
||||
"created_at": "2024-04-23T12:00:00Z",
|
||||
"updated_at": "2024-04-23T12:00:00Z"
|
||||
}
|
||||
],
|
||||
"total": "20.00",
|
||||
"created_at": "2024-04-23T12:00:00Z",
|
||||
"updated_at": "2024-04-23T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Add Item to Cart
|
||||
```
|
||||
POST /api/cart/add_item/
|
||||
```
|
||||
Adds a product to the cart.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"product_id": 1,
|
||||
"quantity": 2
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"product": 1,
|
||||
"product_name": "Product Name",
|
||||
"product_price": "10.00",
|
||||
"quantity": 2,
|
||||
"subtotal": "20.00",
|
||||
"created_at": "2024-04-23T12:00:00Z",
|
||||
"updated_at": "2024-04-23T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Remove Item from Cart
|
||||
```
|
||||
POST /api/cart/remove_item/
|
||||
```
|
||||
Removes a product from the cart.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"product_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"message": "Item removed from cart"
|
||||
}
|
||||
```
|
||||
|
||||
#### Update Item Quantity
|
||||
```
|
||||
POST /api/cart/update_quantity/
|
||||
```
|
||||
Updates the quantity of a product in the cart.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"product_id": 1,
|
||||
"quantity": 3
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"product": 1,
|
||||
"product_name": "Product Name",
|
||||
"product_price": "10.00",
|
||||
"quantity": 3,
|
||||
"subtotal": "30.00",
|
||||
"created_at": "2024-04-23T12:00:00Z",
|
||||
"updated_at": "2024-04-23T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Clear Cart
|
||||
```
|
||||
POST /api/cart/clear/
|
||||
```
|
||||
Removes all items from the cart.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"message": "Cart cleared"
|
||||
}
|
||||
```
|
||||
|
||||
#### Checkout
|
||||
```
|
||||
POST /api/cart/checkout/
|
||||
```
|
||||
Converts the cart to an order.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"message": "Order created successfully",
|
||||
"order_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
#### Delete Cart
|
||||
```
|
||||
DELETE /api/cart/delete/
|
||||
```
|
||||
Deletes the entire cart and all its items.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"message": "Cart deleted"
|
||||
}
|
||||
```
|
||||
|
||||
#### Merge Carts
|
||||
```
|
||||
POST /api/cart/merge/
|
||||
```
|
||||
Merges another cart into the current cart. Useful when a user has multiple carts (e.g., from different devices).
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"cart_id": 2
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"message": "Carts merged successfully"
|
||||
}
|
||||
```
|
||||
|
||||
### Authentication
|
||||
All cart endpoints require authentication. Users must be logged in to access their cart.
|
||||
|
||||
### Additional Features
|
||||
|
||||
#### Stock Management
|
||||
- The cart system automatically checks product stock availability when:
|
||||
- Adding items to cart
|
||||
- Updating item quantities
|
||||
- Checking out
|
||||
- If there's insufficient stock, the operation will fail with a 400 Bad Request error
|
||||
|
||||
#### Transaction Safety
|
||||
- Cart operations that modify multiple records (like checkout and merge) use database transactions
|
||||
- This ensures data consistency even if an error occurs during the operation
|
||||
|
||||
#### Error Responses
|
||||
- 400 Bad Request: Invalid input data or insufficient stock
|
||||
- 401 Unauthorized: User not authenticated
|
||||
- 403 Forbidden: Attempting to merge carts from different users
|
||||
- 404 Not Found: Product, cart, or cart item not found
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Vendored
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Generated
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "Shopping",
|
||||
"slug": "Shopping",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"scheme": "myapp",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"newArchEnabled": true,
|
||||
"ios": {
|
||||
"supportsTablet": true
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/images/adaptive-icon.png",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"web": {
|
||||
"bundler": "metro",
|
||||
"output": "static",
|
||||
"favicon": "./assets/images/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"image": "./assets/images/splash-icon.png",
|
||||
"imageWidth": 200,
|
||||
"resizeMode": "contain",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
]
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Stack } from 'expo-router';
|
||||
import { CartProvider } from './context/CartContext';
|
||||
|
||||
// Import your global CSS file
|
||||
import "../global.css";
|
||||
|
||||
export default function Layout() {
|
||||
return (
|
||||
<CartProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</CartProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,954 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import axios from 'axios';
|
||||
import { View, Text } from 'react-native';
|
||||
|
||||
// Utility function to simulate network delay
|
||||
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
// Mock products data for development
|
||||
const mockProducts = [
|
||||
{
|
||||
id: 1,
|
||||
title: "Wireless Headphones",
|
||||
description: "High-quality wireless headphones with noise cancellation",
|
||||
price: 199.99,
|
||||
rating: 4.5,
|
||||
category: "Electronics",
|
||||
image: "headphones.jpg"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: "Smart Watch",
|
||||
description: "Latest smart watch with fitness tracking",
|
||||
price: 299.99,
|
||||
rating: 4.2,
|
||||
category: "Electronics",
|
||||
image: "smartwatch.jpg"
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: "Running Shoes",
|
||||
description: "Comfortable running shoes for all terrains",
|
||||
price: 89.99,
|
||||
rating: 4.7,
|
||||
category: "Sports",
|
||||
image: "shoes.jpg"
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: "Backpack",
|
||||
description: "Durable backpack with laptop compartment",
|
||||
price: 49.99,
|
||||
rating: 4.3,
|
||||
category: "Accessories",
|
||||
image: "backpack.jpg"
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: "Coffee Maker",
|
||||
description: "Programmable coffee maker with timer",
|
||||
price: 79.99,
|
||||
rating: 4.1,
|
||||
category: "Home",
|
||||
image: "coffeemaker.jpg"
|
||||
}
|
||||
];
|
||||
|
||||
// Dummy component to fix Expo Router error
|
||||
export default function Api() {
|
||||
return (
|
||||
<View style={{ display: 'none' }}>
|
||||
<Text>API Service - This component is only to prevent Expo Router errors</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Storage Keys
|
||||
const STORAGE_KEYS = {
|
||||
CART: 'cart',
|
||||
USER_TOKEN: 'userToken',
|
||||
USER_DATA: 'userData',
|
||||
FAVORITES: 'favorites',
|
||||
CSRF_TOKEN: 'csrfToken'
|
||||
};
|
||||
|
||||
// API Configuration8000
|
||||
export const MEDIA_BASE_URL = 'http://192.168.18.3:8000';
|
||||
export const BASE_URL = `${MEDIA_BASE_URL}/api`;
|
||||
|
||||
// Create axios instance with consistent configuration
|
||||
const apiClient = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
timeout: 10000,
|
||||
withCredentials: true, // Important for CSRF cookie handling
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
// Function to fetch CSRF token
|
||||
export const fetchCSRFToken = async () => {
|
||||
try {
|
||||
const response = await axios.get(`${BASE_URL}/get-csrf-token/`, {
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (response.data && response.data.csrfToken) {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.CSRF_TOKEN, response.data.csrfToken);
|
||||
// Also set it in the default headers
|
||||
apiClient.defaults.headers.common['X-CSRFToken'] = response.data.csrfToken;
|
||||
return response.data.csrfToken;
|
||||
}
|
||||
|
||||
console.error('No CSRF token in response:', response.data);
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch CSRF token:', error.response || error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to get stored CSRF token
|
||||
const getCSRFToken = async () => {
|
||||
try {
|
||||
return await AsyncStorage.getItem(STORAGE_KEYS.CSRF_TOKEN);
|
||||
} catch (error) {
|
||||
console.error('Error getting CSRF token from storage:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Add token and CSRF token to requests when available
|
||||
apiClient.interceptors.request.use(
|
||||
async (config) => {
|
||||
// Add auth token if available
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (token) {
|
||||
config.headers.Authorization = `Token ${token}`;
|
||||
}
|
||||
|
||||
// Add CSRF token if available
|
||||
const csrfToken = await getCSRFToken();
|
||||
if (csrfToken) {
|
||||
config.headers['X-CSRFToken'] = csrfToken;
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Handle response errors, especially auth errors
|
||||
apiClient.interceptors.response.use(
|
||||
response => response,
|
||||
async (error) => {
|
||||
// Handle 403 CSRF errors
|
||||
if (error.response && error.response.status === 403) {
|
||||
const errorDetail = error.response.data?.detail || '';
|
||||
if (errorDetail.includes('CSRF') ||
|
||||
(typeof error.response.data === 'string' && error.response.data.includes('CSRF'))) {
|
||||
console.log('CSRF token missing or invalid. Fetching new token...');
|
||||
|
||||
try {
|
||||
// Get a new CSRF token
|
||||
await fetchCSRFToken();
|
||||
|
||||
// Retry the original request with new CSRF token
|
||||
const originalRequest = error.config;
|
||||
const csrfToken = await getCSRFToken();
|
||||
if (csrfToken) {
|
||||
originalRequest.headers['X-CSRFToken'] = csrfToken;
|
||||
return axios(originalRequest);
|
||||
}
|
||||
} catch (csrfError) {
|
||||
console.error('Failed to refresh CSRF token:', csrfError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 401 unauthorized errors
|
||||
if (error.response && error.response.status === 401) {
|
||||
// Clear auth data
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Process image URLs with authentication if needed
|
||||
export const processImageUrl = async (url) => {
|
||||
if (!url) {
|
||||
console.log('No image URL provided, using local fallback');
|
||||
return null; // Return null to indicate no image
|
||||
}
|
||||
|
||||
try {
|
||||
// If the URL is already absolute, use it as is
|
||||
if (url.startsWith('http')) {
|
||||
console.log('Using absolute URL:', url);
|
||||
return url;
|
||||
}
|
||||
|
||||
// Remove any leading / or media/ from url
|
||||
const cleanedUrl = url
|
||||
.replace(/^\/?media\/?/, '') // remove leading "media/" if exists
|
||||
.replace(/^\/+/, ''); // remove any other leading slashes
|
||||
|
||||
// Construct the URL without double-prefixing
|
||||
const finalUrl = `${MEDIA_BASE_URL}/media/${cleanedUrl}`;
|
||||
console.log('Processed image URL:', finalUrl);
|
||||
return finalUrl;
|
||||
} catch (error) {
|
||||
console.error('Error processing image URL:', error);
|
||||
console.error('Original URL:', url);
|
||||
return null; // Return null to indicate error
|
||||
}
|
||||
};
|
||||
|
||||
// CATEGORIES
|
||||
export const fetchCategories = async () => {
|
||||
try {
|
||||
const { data } = await apiClient.get('/categories/');
|
||||
const processedData = await Promise.all(data.map(async category => ({
|
||||
...category,
|
||||
image: await processImageUrl(category.image)
|
||||
})));
|
||||
return processedData;
|
||||
} catch (error) {
|
||||
console.error('Error fetching categories:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchCategoryById = async (id) => {
|
||||
try {
|
||||
const { data } = await apiClient.get(`/categories/${id}/`);
|
||||
return {
|
||||
...data,
|
||||
image: await processImageUrl(data.image)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error fetching category:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchProductsByCategory = async (categoryId) => {
|
||||
try {
|
||||
const { data } = await apiClient.get(`/categories/${categoryId}/products/`);
|
||||
const processedData = await Promise.all(
|
||||
data.map(async (product) => ({
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
}))
|
||||
);
|
||||
return processedData;
|
||||
} catch (error) {
|
||||
console.error('Error fetching products by category:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// PRODUCTS
|
||||
export const fetchProducts = async (searchTerm = '') => {
|
||||
try {
|
||||
// Ensure searchTerm is a string
|
||||
const searchQuery = String(searchTerm || '').trim();
|
||||
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
// Make API call to fetch products
|
||||
const { data } = await apiClient.get('/products/', {
|
||||
params: {
|
||||
search: searchQuery
|
||||
}
|
||||
});
|
||||
|
||||
// Process product images
|
||||
const processedData = await Promise.all(
|
||||
data.map(async (product) => ({
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
}))
|
||||
);
|
||||
|
||||
// Save to recent searches if user is logged in and search term is not empty
|
||||
if (searchQuery) {
|
||||
try {
|
||||
await saveUserRecentSearch(searchQuery);
|
||||
} catch (error) {
|
||||
// Silently fail if user is not logged in
|
||||
console.log('User not logged in, not saving search');
|
||||
}
|
||||
}
|
||||
|
||||
return processedData;
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
// Return empty array instead of throwing error
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchProductById = async (id) => {
|
||||
try {
|
||||
// First try the products endpoint
|
||||
try {
|
||||
const { data } = await apiClient.get(`/products/${id}/`);
|
||||
return {
|
||||
...data,
|
||||
image: await processImageUrl(data.image)
|
||||
};
|
||||
} catch (productsError) {
|
||||
// If products endpoint fails, try the posts endpoint
|
||||
if (productsError.response?.status === 404) {
|
||||
const { data } = await apiClient.get(`/posts/${id}/`);
|
||||
return {
|
||||
...data,
|
||||
image: await processImageUrl(data.image),
|
||||
// Map post fields to product fields if needed
|
||||
name: data.title,
|
||||
price: data.price || 0,
|
||||
rating: data.rating || 0
|
||||
};
|
||||
}
|
||||
throw productsError;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching product:', error);
|
||||
if (error.response?.status === 404) {
|
||||
throw new Error('Product not found');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// CART
|
||||
export const getCart = async () => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
// If not logged in, get from local storage
|
||||
const localCart = await AsyncStorage.getItem(STORAGE_KEYS.CART);
|
||||
return localCart ? JSON.parse(localCart) : { items: [] };
|
||||
}
|
||||
|
||||
const { data } = await apiClient.get('/cart/items/');
|
||||
|
||||
// Process product images and prices
|
||||
if (data && data.items) {
|
||||
const processedItems = await Promise.all(
|
||||
data.items.map(async (item) => {
|
||||
const price = parseFloat(item.product_price);
|
||||
return {
|
||||
...item,
|
||||
product_image: await processImageUrl(item.product_image),
|
||||
product_price: !isNaN(price) ? price : 0,
|
||||
price: !isNaN(price) ? price : 0
|
||||
};
|
||||
})
|
||||
);
|
||||
return {
|
||||
...data,
|
||||
items: processedItems
|
||||
};
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error getting cart:', error);
|
||||
if (error.response?.status === 401) {
|
||||
// If unauthorized, try to get from local storage
|
||||
const localCart = await AsyncStorage.getItem(STORAGE_KEYS.CART);
|
||||
return localCart ? JSON.parse(localCart) : { items: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// Global refresh function
|
||||
let globalRefreshCart = null;
|
||||
|
||||
export const setGlobalRefreshCart = (refreshFunction) => {
|
||||
globalRefreshCart = refreshFunction;
|
||||
};
|
||||
|
||||
export const addToCart = async (productId, quantity = 1) => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
// If not logged in, use local storage
|
||||
const localCart = await AsyncStorage.getItem(STORAGE_KEYS.CART);
|
||||
const currentCart = localCart ? JSON.parse(localCart) : { items: [] };
|
||||
|
||||
// Check if product already exists in cart
|
||||
const existingItem = currentCart.items.find(item => item.product === productId);
|
||||
if (existingItem) {
|
||||
existingItem.quantity += quantity;
|
||||
} else {
|
||||
currentCart.items.push({
|
||||
product: productId,
|
||||
quantity,
|
||||
product_price: 0, // Will be updated when user logs in
|
||||
product_image: null
|
||||
});
|
||||
}
|
||||
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.CART, JSON.stringify(currentCart));
|
||||
|
||||
// Trigger cart refresh if available
|
||||
if (globalRefreshCart) {
|
||||
globalRefreshCart();
|
||||
}
|
||||
|
||||
return currentCart;
|
||||
}
|
||||
|
||||
const { data } = await apiClient.post('/cart/add_item/', {
|
||||
product_id: productId,
|
||||
quantity
|
||||
});
|
||||
|
||||
// Process product images and prices
|
||||
if (data && data.items) {
|
||||
const processedItems = await Promise.all(
|
||||
data.items.map(async (item) => {
|
||||
const price = parseFloat(item.product_price);
|
||||
return {
|
||||
...item,
|
||||
product_image: await processImageUrl(item.product_image),
|
||||
product_price: !isNaN(price) ? price : 0,
|
||||
price: !isNaN(price) ? price : 0
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Trigger cart refresh if available
|
||||
if (globalRefreshCart) {
|
||||
globalRefreshCart();
|
||||
}
|
||||
|
||||
return {
|
||||
...data,
|
||||
items: processedItems
|
||||
};
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error adding to cart:', error);
|
||||
if (error.response?.status === 401) {
|
||||
// If unauthorized, try to add to local storage
|
||||
return await addToCart(productId, quantity);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateCartItemQuantity = async (itemId, quantity) => {
|
||||
try {
|
||||
const { data } = await apiClient.post('/cart/update_quantity/', {
|
||||
item_id: itemId,
|
||||
quantity: quantity
|
||||
});
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error updating cart quantity:', error);
|
||||
if (error.response?.status === 401) {
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
throw new Error('Session expired. Please login again.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteCartItem = async (itemId) => {
|
||||
try {
|
||||
console.log('Attempting to delete cart item with ID:', itemId);
|
||||
// First get the cart item to get the product ID
|
||||
const cartResponse = await apiClient.get('/cart/items/');
|
||||
const cartItem = cartResponse.data.items.find(item => item.id === itemId);
|
||||
|
||||
if (!cartItem) {
|
||||
throw new Error('Cart item not found');
|
||||
}
|
||||
|
||||
const response = await apiClient.post('/cart/remove_item/', {
|
||||
product_id: cartItem.product
|
||||
});
|
||||
console.log('Delete response:', response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error removing cart item:', error);
|
||||
console.error('Error response:', error.response?.data);
|
||||
console.error('Error status:', error.response?.status);
|
||||
if (error.response?.status === 401) {
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
throw new Error('Session expired. Please login again.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const checkoutCart = async (shippingDetails) => {
|
||||
try {
|
||||
const { data } = await apiClient.post('/cart/checkout/', shippingDetails);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error checking out:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// AUTH - Fixed to match Django URLs
|
||||
export const loginUser = async (credentials) => {
|
||||
try {
|
||||
// First ensure we have a CSRF token
|
||||
const csrfToken = await fetchCSRFToken();
|
||||
if (!csrfToken) {
|
||||
console.error('Failed to get CSRF token before login');
|
||||
return { success: false, error: 'Failed to establish secure connection' };
|
||||
}
|
||||
|
||||
// Use the correct endpoint from your Django URLs
|
||||
const response = await apiClient.post('/token-auth/', credentials);
|
||||
const data = response.data;
|
||||
|
||||
if (data && data.token) {
|
||||
// Store token
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.USER_TOKEN, data.token);
|
||||
|
||||
// Set the token in axios defaults
|
||||
apiClient.defaults.headers.common['Authorization'] = `Token ${data.token}`;
|
||||
|
||||
// Store user data
|
||||
if (data.user) {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(data.user));
|
||||
}
|
||||
|
||||
return { success: true, user: data.user };
|
||||
}
|
||||
|
||||
return { success: false, error: data?.message || 'Invalid credentials' };
|
||||
} catch (error) {
|
||||
console.error('Login Error:', error.response?.data || error);
|
||||
|
||||
// Handle specific error cases
|
||||
if (error.response) {
|
||||
if (error.response.status === 401) {
|
||||
return { success: false, error: 'Invalid username or password' };
|
||||
} else if (error.response.status === 403) {
|
||||
// CSRF token might be invalid, try to refresh it
|
||||
await fetchCSRFToken();
|
||||
return { success: false, error: 'Please try again' };
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.message || 'Login failed'
|
||||
};
|
||||
}
|
||||
|
||||
// Network or other errors
|
||||
return {
|
||||
success: false,
|
||||
error: error.message || 'Network error. Please check your connection.'
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const registerUser = async (userData) => {
|
||||
try {
|
||||
// Ensure we have a CSRF token
|
||||
await fetchCSRFToken();
|
||||
|
||||
const { data } = await apiClient.post('/users/', userData);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Registration Error:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const logoutUser = async () => {
|
||||
try {
|
||||
// Try to logout on server using the correct endpoint
|
||||
try {
|
||||
await apiClient.post('/logout/');
|
||||
} catch (apiError) {
|
||||
console.log('API logout failed, continuing with local logout:', apiError);
|
||||
}
|
||||
|
||||
// Clear local storage
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_DATA);
|
||||
|
||||
// Clear API client headers
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Error during logout:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
export const getCurrentUser = async () => {
|
||||
try {
|
||||
// Check if we have a token
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) return null;
|
||||
|
||||
// Get user data from API
|
||||
const { data } = await apiClient.get('/users/me/');
|
||||
|
||||
// Store updated data
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(data));
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error getting current user:', error);
|
||||
|
||||
// Fallback to cached data
|
||||
const userData = await AsyncStorage.getItem(STORAGE_KEYS.USER_DATA);
|
||||
return userData ? JSON.parse(userData) : null;
|
||||
}
|
||||
};
|
||||
|
||||
// ORDERS
|
||||
export const getOrders = async () => {
|
||||
try {
|
||||
const { data } = await apiClient.get('/orders/');
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching orders:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getOrderById = async (orderId) => {
|
||||
try {
|
||||
const { data } = await apiClient.get(`/orders/${orderId}/`);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching order details:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const placeOrder = async (orderData) => {
|
||||
try {
|
||||
const { data } = await apiClient.post('/orders/', orderData);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error placing order:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// FAVORITES
|
||||
export const getFavorites = async () => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
// If not logged in, get from local storage
|
||||
const localFavorites = await AsyncStorage.getItem(STORAGE_KEYS.FAVORITES);
|
||||
return localFavorites ? JSON.parse(localFavorites) : [];
|
||||
}
|
||||
|
||||
const { data } = await apiClient.get('/favorites/');
|
||||
|
||||
// Process images
|
||||
if (Array.isArray(data)) {
|
||||
const processedData = await Promise.all(
|
||||
data.map(async (favorite) => {
|
||||
const product = favorite.product || favorite;
|
||||
return {
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
};
|
||||
})
|
||||
);
|
||||
return processedData;
|
||||
}
|
||||
|
||||
return data || [];
|
||||
} catch (error) {
|
||||
console.error('Error getting favorites:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const toggleFavorite = async (product) => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
// If not logged in, use local storage
|
||||
const localFavorites = await AsyncStorage.getItem(STORAGE_KEYS.FAVORITES);
|
||||
const currentFavorites = localFavorites ? JSON.parse(localFavorites) : [];
|
||||
|
||||
// Check if product exists in favorites
|
||||
const exists = currentFavorites.some(item => item.id === product.id);
|
||||
let updatedFavorites;
|
||||
|
||||
if (exists) {
|
||||
// Remove from favorites
|
||||
updatedFavorites = currentFavorites.filter(item => item.id !== product.id);
|
||||
} else {
|
||||
// Add to favorites
|
||||
const processedProduct = {
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
};
|
||||
updatedFavorites = [...currentFavorites, processedProduct];
|
||||
}
|
||||
|
||||
// Save to local storage
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.FAVORITES, JSON.stringify(updatedFavorites));
|
||||
return updatedFavorites;
|
||||
}
|
||||
|
||||
// If logged in, use API
|
||||
await apiClient.post('/favorites/toggle/', {
|
||||
product_id: product.id
|
||||
});
|
||||
|
||||
// Get updated favorites list
|
||||
return await getFavorites();
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// RATINGS
|
||||
export const rateProduct = async (productId, rating, comment = '') => {
|
||||
try {
|
||||
const { data } = await apiClient.post(`/products/${productId}/rate/`, {
|
||||
rating,
|
||||
comment
|
||||
});
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error rating product:', error);
|
||||
if (error.response?.status === 401) {
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
throw new Error('Session expired. Please login again.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize API - Updated to handle CSRF token
|
||||
export const initializeAPI = async () => {
|
||||
try {
|
||||
console.log('Initializing API...');
|
||||
|
||||
// First fetch CSRF token
|
||||
const csrfToken = await fetchCSRFToken();
|
||||
if (!csrfToken) {
|
||||
console.error('Failed to fetch CSRF token during initialization');
|
||||
return false;
|
||||
}
|
||||
console.log('CSRF token fetched successfully');
|
||||
|
||||
// Then check auth token
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (token) {
|
||||
apiClient.defaults.headers.common['Authorization'] = `Token ${token}`;
|
||||
console.log('Auth token loaded');
|
||||
|
||||
// Verify token is valid
|
||||
try {
|
||||
const response = await apiClient.get('/users/me/');
|
||||
console.log('User authenticated:', response.data);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Token validation error:', error.response?.data || error);
|
||||
if (error.response?.status === 401) {
|
||||
// Token invalid, clear it
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
|
||||
delete apiClient.defaults.headers.common['Authorization'];
|
||||
console.log('Invalid token cleared');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('No auth token found');
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize API:', error.response?.data || error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// For backwards compatibility
|
||||
export const fetchPosts = async (searchTerm) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
// Simulate network delay
|
||||
await delay(500);
|
||||
|
||||
// Filter products based on search term
|
||||
const results = await Promise.all(
|
||||
mockProducts
|
||||
.filter(product =>
|
||||
product.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
product.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
product.category.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
.map(async product => ({
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
}))
|
||||
);
|
||||
|
||||
// Save to recent searches if user is logged in
|
||||
try {
|
||||
await saveUserRecentSearch(searchTerm);
|
||||
} catch (error) {
|
||||
// Silently fail if user is not logged in
|
||||
console.log('User not logged in, not saving search');
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchPostById = async (id) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
await delay(200);
|
||||
const product = mockProducts.find(p => p.id === parseInt(id));
|
||||
if (!product) {
|
||||
throw new Error('Product not found');
|
||||
}
|
||||
return {
|
||||
...product,
|
||||
image: await processImageUrl(product.image)
|
||||
};
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const getUserData = async () => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) return null;
|
||||
|
||||
const { data } = await apiClient.get('/users/me/');
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching user data:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// RECENT SEARCHES
|
||||
export const getUserRecentSearches = async () => {
|
||||
try {
|
||||
const searches = await AsyncStorage.getItem('recentSearches');
|
||||
return searches ? JSON.parse(searches) : [];
|
||||
} catch (error) {
|
||||
console.error('Error getting recent searches:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const saveUserRecentSearch = async (searchTerm) => {
|
||||
try {
|
||||
const searches = await getUserRecentSearches();
|
||||
const updatedSearches = [searchTerm, ...searches.filter(term => term !== searchTerm)].slice(0, 10);
|
||||
await AsyncStorage.setItem('recentSearches', JSON.stringify(updatedSearches));
|
||||
return updatedSearches;
|
||||
} catch (error) {
|
||||
console.error('Error saving recent search:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const removeUserRecentSearch = async (searchTerm) => {
|
||||
try {
|
||||
const searches = await getUserRecentSearches();
|
||||
const updatedSearches = searches.filter(term => term !== searchTerm);
|
||||
await AsyncStorage.setItem('recentSearches', JSON.stringify(updatedSearches));
|
||||
return updatedSearches;
|
||||
} catch (error) {
|
||||
console.error('Error removing recent search:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const clearAllUserRecentSearches = async () => {
|
||||
try {
|
||||
await AsyncStorage.removeItem('recentSearches');
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error clearing recent searches:', error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// FAVORITES
|
||||
export const isProductFavorited = async (productId) => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
// If not logged in, check local storage
|
||||
const localFavorites = await AsyncStorage.getItem(STORAGE_KEYS.FAVORITES);
|
||||
const favorites = localFavorites ? JSON.parse(localFavorites) : [];
|
||||
return {
|
||||
success: true,
|
||||
isFavorited: favorites.some(item => item.id === productId)
|
||||
};
|
||||
}
|
||||
|
||||
// If logged in, check API
|
||||
const { data } = await apiClient.get(`/favorites/check/${productId}/`);
|
||||
return {
|
||||
success: true,
|
||||
isFavorited: data.is_favorited
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking favorite status:', error);
|
||||
return {
|
||||
success: false,
|
||||
isFavorited: false
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Authentication check function
|
||||
export const checkAuthentication = async () => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.USER_TOKEN);
|
||||
if (!token) {
|
||||
throw {
|
||||
response: {
|
||||
status: 401,
|
||||
data: { detail: 'Authentication credentials were not provided.' }
|
||||
}
|
||||
};
|
||||
}
|
||||
return token;
|
||||
} catch (error) {
|
||||
console.error('Authentication check failed:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,527 @@
|
||||
// mock-api.js
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { View, Text } from 'react-native';
|
||||
|
||||
// Dummy component to fix Expo Router error
|
||||
export default function ApiIndex() {
|
||||
return (
|
||||
<View style={{ display: 'none' }}>
|
||||
<Text>API Service - This component is only to prevent Expo Router errors</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Mock product data
|
||||
const mockProducts = [
|
||||
{
|
||||
id: 1,
|
||||
title: "Fjallraven Backpack",
|
||||
price: 109.95,
|
||||
description: "Your perfect pack for everyday use and walks in the forest.",
|
||||
category: "men's clothing",
|
||||
image: "http://example.com/backpack.jpg",
|
||||
rating: { rate: 3.9, count: 120 }
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: "Casual Premium T-Shirt",
|
||||
price: 22.3,
|
||||
description: "Slim-fitting style, contrast raglan long sleeve.",
|
||||
category: "men's clothing",
|
||||
image: "http://example.com/tshirt.jpg",
|
||||
rating: { rate: 4.1, count: 259 }
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: "Cotton Jacket",
|
||||
price: 55.99,
|
||||
description: "Great outerwear jacket for Spring/Autumn/Winter.",
|
||||
category: "men's clothing",
|
||||
image: "http://example.com/jacket.jpg",
|
||||
rating: { rate: 4.7, count: 500 }
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: "Women's Boat Neck T",
|
||||
price: 9.85,
|
||||
description: "95% RAYON 5% SPANDEX, Made in USA or Imported.",
|
||||
category: "women's clothing",
|
||||
image: "http://example.com/womenshirt.jpg",
|
||||
rating: { rate: 4.5, count: 146 }
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: "Women's Snowboard Jacket",
|
||||
price: 56.99,
|
||||
description: "Note: The Jackets is US standard size.",
|
||||
category: "women's clothing",
|
||||
image: "http://example.com/snowjacket.jpg",
|
||||
rating: { rate: 2.6, count: 235 }
|
||||
}
|
||||
];
|
||||
|
||||
// Mock carts data
|
||||
const mockCarts = [
|
||||
{
|
||||
id: 1,
|
||||
userId: 1,
|
||||
date: "2024-04-15T00:00:00.000Z",
|
||||
products: [
|
||||
{ productId: 1, quantity: 2 },
|
||||
{ productId: 3, quantity: 1 }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
userId: 2,
|
||||
date: "2024-04-14T00:00:00.000Z",
|
||||
products: [
|
||||
{ productId: 2, quantity: 3 },
|
||||
{ productId: 5, quantity: 1 }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Mock users data
|
||||
const mockUsers = [
|
||||
{
|
||||
id: 1,
|
||||
username: "johndoe",
|
||||
email: "john@example.com",
|
||||
password: "password123"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
username: "janedoe",
|
||||
email: "jane@example.com",
|
||||
password: "securepass"
|
||||
}
|
||||
];
|
||||
|
||||
// Add delay to simulate network request
|
||||
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
// Helper to simulate authentication in mock API
|
||||
const checkAuthentication = async () => {
|
||||
const token = await AsyncStorage.getItem('userToken');
|
||||
if (!token) {
|
||||
// Simulate 401 error structure
|
||||
throw {
|
||||
response: {
|
||||
status: 401,
|
||||
data: { detail: 'Authentication credentials were not provided.' }
|
||||
}
|
||||
};
|
||||
}
|
||||
return token;
|
||||
};
|
||||
|
||||
// Mock API functions
|
||||
export const fetchPosts = async () => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
// Simulate network delay
|
||||
await delay(300);
|
||||
return [...mockProducts];
|
||||
} catch (error) {
|
||||
if (error.response && error.response.status === 401) {
|
||||
throw error; // Propagate authentication errors
|
||||
}
|
||||
throw new Error('Error fetching products');
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchPostsById = async (id) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
await delay(200);
|
||||
const product = mockProducts.find(p => p.id === parseInt(id));
|
||||
if (!product) {
|
||||
throw new Error('Product not found');
|
||||
}
|
||||
return product;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchCarts = async () => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
await delay(300);
|
||||
return [...mockCarts];
|
||||
} catch (error) {
|
||||
if (error.response && error.response.status === 401) {
|
||||
throw error; // Propagate authentication errors
|
||||
}
|
||||
throw new Error('Error fetching carts');
|
||||
}
|
||||
};
|
||||
|
||||
export const createCarts = async (product, quantity = 1) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
const cartData = await AsyncStorage.getItem('cart');
|
||||
let cart = cartData ? JSON.parse(cartData) : { data: [], totalPrice: 0 };
|
||||
|
||||
const existingProductIndex = cart.data.findIndex(item => item.id === product.id);
|
||||
|
||||
if (existingProductIndex !== -1) {
|
||||
cart.data[existingProductIndex].quantity = quantity;
|
||||
cart.data[existingProductIndex].totalPrice = cart.data[existingProductIndex].quantity * product.price;
|
||||
} else {
|
||||
cart.data.push({
|
||||
id: product.id,
|
||||
title: product.title,
|
||||
price: product.price,
|
||||
description: product.description,
|
||||
category: product.category,
|
||||
image: product.image,
|
||||
rating: {
|
||||
rate: product.rating ? product.rating.rate : 0,
|
||||
count: product.rating ? product.rating.count : 0,
|
||||
},
|
||||
quantity,
|
||||
totalPrice: quantity * product.price
|
||||
});
|
||||
}
|
||||
|
||||
cart.totalPrice = cart.data.reduce((sum, item) => sum + item.totalPrice, 0);
|
||||
await AsyncStorage.setItem('cart', JSON.stringify(cart));
|
||||
|
||||
await delay(200); // Simulate network delay
|
||||
return cart;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const getCart = async () => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
const cart = await AsyncStorage.getItem('cart');
|
||||
await delay(100);
|
||||
return cart ? JSON.parse(cart) : { data: [], totalPrice: 0 };
|
||||
} catch (error) {
|
||||
console.error('Error retrieving cart:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteCartItem = async (productId) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
const cartData = await AsyncStorage.getItem('cart');
|
||||
let cart = cartData ? JSON.parse(cartData) : { data: [], totalPrice: 0 };
|
||||
|
||||
cart.data = cart.data.filter(item => item.id !== productId);
|
||||
cart.totalPrice = cart.data.reduce((sum, item) => sum + item.totalPrice, 0);
|
||||
|
||||
await AsyncStorage.setItem('cart', JSON.stringify(cart));
|
||||
await delay(200);
|
||||
return cart;
|
||||
} catch (error) {
|
||||
console.error('Error deleting item from cart:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// User data with favorites and recent searches
|
||||
const userData = {
|
||||
1: {
|
||||
id: 1,
|
||||
username: 'john_doe',
|
||||
email: 'john@example.com',
|
||||
favorites: [1, 4, 6],
|
||||
recentSearches: ['jacket', 'shoes', 'watch']
|
||||
},
|
||||
2: {
|
||||
id: 2,
|
||||
username: 'jane_smith',
|
||||
email: 'jane@example.com',
|
||||
favorites: [2, 3, 5],
|
||||
recentSearches: ['dress', 'bag', 'sunglasses']
|
||||
}
|
||||
};
|
||||
|
||||
// Current user tracking (simpler than token-based auth)
|
||||
let currentUserId = null;
|
||||
|
||||
// User authentication functions
|
||||
export const loginUser = async (credentials) => {
|
||||
try {
|
||||
// Simulate network delay
|
||||
await delay(500);
|
||||
|
||||
const { username, password } = credentials;
|
||||
|
||||
// For demo purposes, simply find a user with matching username
|
||||
// In a real app, you would verify the password as well
|
||||
const userEntry = Object.entries(userData).find(([_, user]) =>
|
||||
user.username === username
|
||||
);
|
||||
|
||||
if (userEntry) {
|
||||
const [userId, user] = userEntry;
|
||||
currentUserId = parseInt(userId);
|
||||
await AsyncStorage.setItem('currentUserId', userId.toString());
|
||||
return { success: true, user };
|
||||
}
|
||||
|
||||
return { success: false, error: 'Invalid credentials' };
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return { success: false, error: error.message || 'Login failed' };
|
||||
}
|
||||
};
|
||||
|
||||
export const logoutUser = async () => {
|
||||
try {
|
||||
await delay(300);
|
||||
currentUserId = null;
|
||||
await AsyncStorage.removeItem('currentUserId');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
export const getCurrentUser = async () => {
|
||||
if (!currentUserId) {
|
||||
const storedId = await AsyncStorage.getItem('currentUserId');
|
||||
if (storedId) {
|
||||
currentUserId = parseInt(storedId);
|
||||
}
|
||||
}
|
||||
|
||||
return userData[currentUserId] || null;
|
||||
};
|
||||
|
||||
// Favorite functions
|
||||
export const checkIsFavoriteForCurrentUser = async (productId) => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) return false;
|
||||
|
||||
return user.favorites.includes(parseInt(productId));
|
||||
};
|
||||
|
||||
export const toggleFavoriteForCurrentUser = async (productId) => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new Error('User not logged in');
|
||||
|
||||
const id = parseInt(productId);
|
||||
const currentFavorites = [...user.favorites];
|
||||
|
||||
const isFavorite = currentFavorites.includes(id);
|
||||
if (isFavorite) {
|
||||
// Remove from favorites
|
||||
userData[user.id].favorites = currentFavorites.filter(favId => favId !== id);
|
||||
} else {
|
||||
// Add to favorites
|
||||
userData[user.id].favorites = [...currentFavorites, id];
|
||||
}
|
||||
|
||||
return !isFavorite; // Return the new status
|
||||
};
|
||||
|
||||
export const getUserFavorites = async () => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) return [];
|
||||
|
||||
return Promise.all(
|
||||
user.favorites.map(id => fetchProductById(id))
|
||||
);
|
||||
};
|
||||
|
||||
// Recent searches functions
|
||||
export const getUserRecentSearches = async () => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) return [];
|
||||
|
||||
return user.recentSearches;
|
||||
};
|
||||
|
||||
export const saveUserRecentSearch = async (searchTerm) => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new Error('User not logged in');
|
||||
|
||||
// Remove if already exists (to move it to the front)
|
||||
let searches = user.recentSearches.filter(term => term !== searchTerm);
|
||||
|
||||
// Add to beginning
|
||||
searches = [searchTerm, ...searches];
|
||||
|
||||
// Limit to 5 recent searches
|
||||
searches = searches.slice(0, 5);
|
||||
|
||||
userData[user.id].recentSearches = searches;
|
||||
|
||||
return searches;
|
||||
};
|
||||
|
||||
export const removeUserRecentSearch = async (searchTerm) => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new Error('User not logged in');
|
||||
|
||||
userData[user.id].recentSearches = user.recentSearches.filter(
|
||||
term => term !== searchTerm
|
||||
);
|
||||
|
||||
return userData[user.id].recentSearches;
|
||||
};
|
||||
|
||||
export const clearAllUserRecentSearches = async () => {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new Error('User not logged in');
|
||||
|
||||
userData[user.id].recentSearches = [];
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
// Add this function to get current user's favorites
|
||||
export const getFavorites = async () => {
|
||||
try {
|
||||
await delay(300);
|
||||
|
||||
if (currentUserId === null) {
|
||||
const storedId = await AsyncStorage.getItem('currentUserId');
|
||||
if (storedId) {
|
||||
currentUserId = parseInt(storedId);
|
||||
} else {
|
||||
return { success: false, error: 'User not logged in' };
|
||||
}
|
||||
}
|
||||
|
||||
const userFavorites = userData[currentUserId]?.favorites || [];
|
||||
return { success: true, favorites: userFavorites };
|
||||
} catch (error) {
|
||||
console.error('Get favorites error:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// Add function to toggle favorite status
|
||||
export const toggleFavorite = async (productId) => {
|
||||
try {
|
||||
await delay(300);
|
||||
|
||||
if (currentUserId === null) {
|
||||
const storedId = await AsyncStorage.getItem('currentUserId');
|
||||
if (storedId) {
|
||||
currentUserId = parseInt(storedId);
|
||||
} else {
|
||||
return { success: false, error: 'User not logged in' };
|
||||
}
|
||||
}
|
||||
|
||||
const favorites = userData[currentUserId]?.favorites || [];
|
||||
const index = favorites.indexOf(productId);
|
||||
|
||||
if (index !== -1) {
|
||||
// Remove from favorites
|
||||
favorites.splice(index, 1);
|
||||
} else {
|
||||
// Add to favorites
|
||||
favorites.push(productId);
|
||||
}
|
||||
|
||||
// Update the user data
|
||||
userData[currentUserId].favorites = favorites;
|
||||
|
||||
return { success: true, favorites };
|
||||
} catch (error) {
|
||||
console.error('Toggle favorite error:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// Add a function to check if a product is favorited
|
||||
export const isProductFavorited = async (productId) => {
|
||||
try {
|
||||
const { success, favorites, error } = await getFavorites();
|
||||
|
||||
if (!success) {
|
||||
return { success: false, error };
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
isFavorited: favorites.includes(productId)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Check favorite error:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// Update getUserData to use currentUserId
|
||||
export const getUserData = async () => {
|
||||
try {
|
||||
await delay(300);
|
||||
|
||||
if (currentUserId === null) {
|
||||
const storedId = await AsyncStorage.getItem('currentUserId');
|
||||
if (storedId) {
|
||||
currentUserId = parseInt(storedId);
|
||||
} else {
|
||||
return { success: false, error: 'User not logged in' };
|
||||
}
|
||||
}
|
||||
|
||||
const user = userData[currentUserId];
|
||||
|
||||
if (!user) {
|
||||
return { success: false, error: 'User not found' };
|
||||
}
|
||||
|
||||
return { success: true, user };
|
||||
} catch (error) {
|
||||
console.error('Get user data error:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// Search functions
|
||||
export const fetchProducts = async (searchTerm) => {
|
||||
try {
|
||||
// Simulate authentication check
|
||||
await checkAuthentication();
|
||||
|
||||
// Simulate network delay
|
||||
await delay(500);
|
||||
|
||||
// Filter products based on search term
|
||||
const results = mockProducts.filter(product =>
|
||||
product.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
product.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
product.category.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
|
||||
// Save to recent searches if user is logged in
|
||||
try {
|
||||
await saveUserRecentSearch(searchTerm);
|
||||
} catch (error) {
|
||||
// Silently fail if user is not logged in
|
||||
console.log('User not logged in, not saving search');
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import { View, Text, Image, TouchableOpacity, StyleSheet } from 'react-native'
|
||||
import React from 'react'
|
||||
import { useNavigation } from '@react-navigation/native'
|
||||
|
||||
export default function ActiveOrder({ orders = [], navigation: propNavigation }) {
|
||||
// Use provided navigation prop if available, otherwise get from hook
|
||||
const navigation = propNavigation || useNavigation();
|
||||
|
||||
// Safe number formatting helper
|
||||
const formatCurrency = (value) => {
|
||||
if (value === undefined || value === null) return '0.00';
|
||||
if (typeof value === 'number') return value.toFixed(2);
|
||||
if (typeof value === 'string') {
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? '0.00' : num.toFixed(2);
|
||||
}
|
||||
return '0.00';
|
||||
};
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return (
|
||||
<View className="flex-1 justify-center items-center py-10">
|
||||
<Text className="text-gray-500">No active orders found</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className={`mx-4`}>
|
||||
{orders.map((order, index) => {
|
||||
// Each order can have multiple items
|
||||
return (
|
||||
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
|
||||
<View className="bg-gray-100 p-3 border-b border-gray-200">
|
||||
<Text className="font-bold">Order #{order.id}</Text>
|
||||
<Text className="text-gray-500">
|
||||
{new Date(order.created_at || order.date).toLocaleDateString()} |
|
||||
Status: <Text className="text-primary font-medium capitalize">{order.status}</Text>
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{order.items && order.items.map((item, itemIndex) => (
|
||||
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
|
||||
<Image
|
||||
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
|
||||
className="size-[90px] rounded-lg"
|
||||
defaultSource={require('../../assets/images/favicon.png')}
|
||||
/>
|
||||
<View className={`flex-1 flex-col gap-2`}>
|
||||
<Text className={`font-medium text-lg`}>{item.product_name || item.product?.title || 'Product'}</Text>
|
||||
<Text className={`text-sm`}>Qty: {item.quantity}</Text>
|
||||
<View className={`flex-row justify-between items-start`}>
|
||||
<Text className={`text-lg font-bold`}>${formatCurrency(item.price || item.subtotal)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
|
||||
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
|
||||
<TouchableOpacity
|
||||
onPress={() => navigation.navigate('Track Order', { orderId: order.id })}
|
||||
className={`bg-primary rounded-full px-4 py-2`}
|
||||
>
|
||||
<Text className={`text-white font-medium`}>Track Order</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = {
|
||||
itemImage: {
|
||||
width: 90,
|
||||
height: 90,
|
||||
borderRadius: 10,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { View, Text, Image, TouchableOpacity } from 'react-native'
|
||||
import React from 'react'
|
||||
import { useNavigation } from '@react-navigation/native'
|
||||
|
||||
export default function CancelledOrder({ orders = [], navigation: propNavigation }) {
|
||||
// Use provided navigation prop if available, otherwise get from hook
|
||||
const navigation = propNavigation || useNavigation();
|
||||
|
||||
// Safe number formatting helper
|
||||
const formatCurrency = (value) => {
|
||||
if (value === undefined || value === null) return '0.00';
|
||||
if (typeof value === 'number') return value.toFixed(2);
|
||||
if (typeof value === 'string') {
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? '0.00' : num.toFixed(2);
|
||||
}
|
||||
return '0.00';
|
||||
};
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return (
|
||||
<View className="flex-1 justify-center items-center py-10">
|
||||
<Text className="text-gray-500">No cancelled orders found</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className={`mx-4`}>
|
||||
{orders.map((order, index) => {
|
||||
// Each order can have multiple items
|
||||
return (
|
||||
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
|
||||
<View className="bg-gray-100 p-3 border-b border-gray-200">
|
||||
<Text className="font-bold">Order #{order.id}</Text>
|
||||
<Text className="text-gray-500">
|
||||
{new Date(order.created_at || order.date).toLocaleDateString()} |
|
||||
Status: <Text className="text-red-500 font-medium capitalize">{order.status}</Text>
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{order.items && order.items.map((item, itemIndex) => (
|
||||
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
|
||||
<Image
|
||||
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
|
||||
className="size-[90px] rounded-lg"
|
||||
defaultSource={require('../../assets/images/favicon.png')}
|
||||
/>
|
||||
<View className={`flex-1 flex-col gap-2`}>
|
||||
<Text className={`font-medium text-lg`}>{item.product_name || item.product?.title || 'Product'}</Text>
|
||||
<Text className={`text-sm`}>Qty: {item.quantity}</Text>
|
||||
<View className={`flex-row justify-between items-start`}>
|
||||
<Text className={`text-lg font-bold`}>${formatCurrency(item.price || item.subtotal)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
|
||||
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
|
||||
<TouchableOpacity
|
||||
onPress={() => navigation.navigate('Home')}
|
||||
className={`bg-primary rounded-full px-4 py-2`}
|
||||
>
|
||||
<Text className={`text-white font-medium`}>Re-Order</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { View, Text, ScrollView, Image, TouchableOpacity } from 'react-native'
|
||||
import React from 'react'
|
||||
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
|
||||
export default function Category({ categories = [] }) {
|
||||
const navigation = useNavigation()
|
||||
|
||||
// Use fallback demo data if no categories are provided
|
||||
const displayCategories = categories.length > 0 ? categories : [
|
||||
{
|
||||
id: 1,
|
||||
name: "T-shirt",
|
||||
image: "https://www.iconarchive.com/download/i97169/iconsmind/outline/T-Shirt.ico"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Pant",
|
||||
image: "https://static.vecteezy.com/system/resources/previews/010/347/283/non_2x/pants-boy-garment-line-icon-illustration-vector.jpg"
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: "Dress",
|
||||
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRQdRkx2psjWSnEJnmPy1-8c40UVYLtDtTINA&s"
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: "Jacket",
|
||||
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTskcACyLVW4kXqpz2KGOAPyoQ7LKURrafxLw&s"
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: "Kids",
|
||||
image: "https://cdn-icons-png.flaticon.com/512/2934/2934315.png"
|
||||
}
|
||||
]
|
||||
|
||||
return (
|
||||
<View className=" flex-col gap-4 mb-6">
|
||||
<View className="flex-row justify-between items-center px-1 mx-4" >
|
||||
<Text className="text-xl font-semibold">Category</Text>
|
||||
<Text className="text-secondary font-medium">See All</Text>
|
||||
</View>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
className="ml-4"
|
||||
>
|
||||
{
|
||||
displayCategories.map((item, index) => {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={item.id}
|
||||
onPress={() => {
|
||||
navigation.navigate('Category', {
|
||||
categoryId: item.id,
|
||||
title: item.name
|
||||
})
|
||||
}}
|
||||
className={`${index + 1 == displayCategories.length ? "mr-4" : " mr-4"} flex-col items-center gap-2`}
|
||||
>
|
||||
<View className="bg-secondary flex justify-center items-center rounded-full" style={{ height: hp('8%'), width: hp('8%') }}>
|
||||
<Image
|
||||
source={{ uri: item.image }}
|
||||
className="size-10"
|
||||
style={{ width: hp('6%'), height: hp('6%'), borderRadius: 30 }}
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center">{item.name}</Text>
|
||||
</TouchableOpacity>
|
||||
)
|
||||
})
|
||||
}
|
||||
</ScrollView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { View, Text, Image, TouchableOpacity } from 'react-native'
|
||||
import React from 'react'
|
||||
import { useNavigation } from '@react-navigation/native'
|
||||
|
||||
export default function CompletedOrder({ orders = [], navigation: propNavigation }) {
|
||||
// Use provided navigation prop if available, otherwise get from hook
|
||||
const navigation = propNavigation || useNavigation();
|
||||
|
||||
// Safe number formatting helper
|
||||
const formatCurrency = (value) => {
|
||||
if (value === undefined || value === null) return '0.00';
|
||||
if (typeof value === 'number') return value.toFixed(2);
|
||||
if (typeof value === 'string') {
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? '0.00' : num.toFixed(2);
|
||||
}
|
||||
return '0.00';
|
||||
};
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return (
|
||||
<View className="flex-1 justify-center items-center py-10">
|
||||
<Text className="text-gray-500">No completed orders found</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className={`mx-4`}>
|
||||
{orders.map((order, index) => {
|
||||
// Each order can have multiple items
|
||||
return (
|
||||
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
|
||||
<View className="bg-gray-100 p-3 border-b border-gray-200">
|
||||
<Text className="font-bold">Order #{order.id}</Text>
|
||||
<Text className="text-gray-500">
|
||||
{new Date(order.created_at || order.date).toLocaleDateString()} |
|
||||
Status: <Text className="text-green-600 font-medium capitalize">{order.status}</Text>
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{order.items && order.items.map((item, itemIndex) => (
|
||||
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
|
||||
<Image
|
||||
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
|
||||
className="size-[90px] rounded-lg"
|
||||
defaultSource={require('../../assets/images/favicon.png')}
|
||||
/>
|
||||
<View className={`flex-1 flex-col gap-2`}>
|
||||
<Text className={`font-medium text-lg`}>{item.product_name || item.product?.title || 'Product'}</Text>
|
||||
<Text className={`text-sm`}>Qty: {item.quantity}</Text>
|
||||
<View className={`flex-row justify-between items-start`}>
|
||||
<Text className={`text-lg font-bold`}>${formatCurrency(item.price || item.subtotal)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
|
||||
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
|
||||
<TouchableOpacity
|
||||
onPress={() => navigation.navigate('Leave Review')}
|
||||
className={`bg-primary rounded-full px-4 py-2`}
|
||||
>
|
||||
<Text className={`text-white font-medium`}>Leave Review</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { View, Text } from 'react-native'
|
||||
import React from 'react'
|
||||
import { ChevronDownIcon, ChevronUpIcon, GlobeAltIcon } from 'react-native-heroicons/outline'
|
||||
import Icon from 'react-native-vector-icons/FontAwesome6';
|
||||
|
||||
export default function ContactUsCenter() {
|
||||
return (
|
||||
<View className={` mt-4 mx-4 `}>
|
||||
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<Icon name='headset' color={"#704f38"} size={25} />
|
||||
<Text className={`text-lg font-semibold`}>Customer Service</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronDownIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
<View className={`border mb-3 rounded-xl border-gray-300`}>
|
||||
<View className={` flex-row items-center justify-between p-4 border-b border-b-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<Icon name='whatsapp' color={"#704f38"} size={25} />
|
||||
<Text className={`text-lg font-semibold`}>WhatsApp</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronUpIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
<Text className={`p-4 text-left mx-9 text-gray-500`}>(480)555-0103</Text>
|
||||
</View>
|
||||
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<GlobeAltIcon color={"#704f38"} size={26} />
|
||||
<Text className={`text-lg font-semibold`}>Website</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronDownIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<Icon name='facebook' color={"#704f38"} size={26} />
|
||||
<Text className={`text-lg font-semibold`}>Facebook</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronDownIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<Icon name='instagram' color={"#704f38"} size={26} />
|
||||
<Text className={`text-lg font-semibold`}>Instagram</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronDownIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
|
||||
<View className={`flex-row items-center gap-4 `}>
|
||||
<Icon name='twitter' color={"#704f38"} size={26} />
|
||||
<Text className={`text-lg font-semibold`}>Twitter</Text>
|
||||
</View>
|
||||
<View className={`justify-center items-center`}>
|
||||
<ChevronDownIcon color={"#704f38"} size={24} />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { View, Text, ScrollView } from 'react-native'
|
||||
import React, { useState } from 'react'
|
||||
import { TouchableOpacity } from 'react-native';
|
||||
import { ChevronDownIcon, ChevronUpIcon } from 'react-native-heroicons/outline';
|
||||
|
||||
export default function FaqCenter() {
|
||||
const faq = ["All", "Services", "General", "Account"]
|
||||
const [faqActive, setfaqActive] = useState(0);
|
||||
return (
|
||||
<View className={`mx-4 mt-5 `} >
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
|
||||
{
|
||||
faq.map((item, index) => {
|
||||
let isActive = index == faqActive;
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={index}
|
||||
onPress={() => setfaqActive(index)}
|
||||
className={`
|
||||
border border-gray-200 bg-gray-200 px-5 mr-4 mb-4 rounded-full py-3
|
||||
${isActive ? "bg-primary" : ""}
|
||||
`}>
|
||||
<Text className={`${isActive ? "text-white " : ""} capitalize font-bold`}>
|
||||
{item}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)
|
||||
})
|
||||
}
|
||||
</ScrollView>
|
||||
<View className={`border border-gray-300 rounded-2xl mb-5`}>
|
||||
<View className={`flex-row justify-between items-center p-3 border-b border-b-gray-300 `}>
|
||||
<Text className={`font-semibold text-lg`}>Can i track my order's delevery status ?</Text>
|
||||
<ChevronUpIcon color={"#704f38"} />
|
||||
</View>
|
||||
<Text className={`p-3`}>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab distinctio nihil assumenda nostrum laboriosam quo,
|
||||
officia eligendi obcaecati accusamus aliquam debitis, voluptatibus excepturi consequatur expedita eius quisquam velit. Rerum, officia?</Text>
|
||||
</View>
|
||||
<View className={`mb-`}>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2 `}>
|
||||
<Text className={`font-semibold text-lg`}>Is there a return policy ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2 `}>
|
||||
<Text className={`font-semibold text-lg`}>Can i save my favorite item for later ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
|
||||
<Text className={`font-semibold text-lg`}>Can i share products with my friends ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
|
||||
<Text className={`font-semibold text-lg`}>How do i contact customer support ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
|
||||
<Text className={`font-semibold text-lg`}>What payment methods are accepted ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
|
||||
<Text className={`font-semibold text-lg`}>How to add review ?</Text>
|
||||
<ChevronDownIcon color={"#704f38"} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { TouchableOpacity, ActivityIndicator } from 'react-native'
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { HeartIcon } from 'react-native-heroicons/outline'
|
||||
import { HeartIcon as HeartSolid } from 'react-native-heroicons/solid'
|
||||
import { getFavorites } from '../api'
|
||||
|
||||
/**
|
||||
* A reusable favorite/wishlist button component
|
||||
*
|
||||
* @param {Object} props Component props
|
||||
* @param {boolean} props.isFavorite Whether the item is in favorites
|
||||
* @param {Function} props.onToggleFavorite Function to call when toggling favorite state
|
||||
* @param {number} props.size Icon size
|
||||
* @param {string} props.activeColor Color when active
|
||||
* @param {string} props.inactiveColor Color when inactive
|
||||
* @param {Object} props.style Additional styles for the container
|
||||
* @param {number} props.productId The ID of the product
|
||||
* @returns {React.Component} Favorite button component
|
||||
*/
|
||||
export default function FavoriteButton({
|
||||
isFavorite = false,
|
||||
onToggleFavorite,
|
||||
size = 24,
|
||||
activeColor = '#ff3b30',
|
||||
inactiveColor = '#000000',
|
||||
style = {},
|
||||
productId
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [favoriteState, setFavoriteState] = useState(isFavorite);
|
||||
|
||||
// Update favorite state when isFavorite prop changes
|
||||
useEffect(() => {
|
||||
setFavoriteState(isFavorite);
|
||||
}, [isFavorite]);
|
||||
|
||||
// Check favorite status when component mounts
|
||||
useEffect(() => {
|
||||
const checkFavoriteStatus = async () => {
|
||||
if (productId) {
|
||||
try {
|
||||
const favorites = await getFavorites();
|
||||
const isFavorited = favorites.some(fav => fav.id === productId);
|
||||
setFavoriteState(isFavorited);
|
||||
} catch (error) {
|
||||
console.error('Error checking favorite status:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkFavoriteStatus();
|
||||
}, [productId]);
|
||||
|
||||
const handlePress = async () => {
|
||||
if (!onToggleFavorite) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
await onToggleFavorite();
|
||||
// Update local state after successful toggle
|
||||
setFavoriteState(!favoriteState);
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={handlePress}
|
||||
disabled={loading}
|
||||
style={style}
|
||||
className="justify-center items-center"
|
||||
>
|
||||
{loading ? (
|
||||
<ActivityIndicator size="small" color={activeColor} />
|
||||
) : favoriteState ? (
|
||||
<HeartSolid size={size} color={activeColor} />
|
||||
) : (
|
||||
<HeartIcon size={size} color={inactiveColor} />
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// demodata //normal case
|
||||
// demoData //camel case ex:iAmAGoodBBoy
|
||||
// demo_data // snake case ex:i_am_a_good_boy
|
||||
|
||||
import { View, Text, ScrollView, TouchableOpacity, Image } from 'react-native'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import MasonryList from '@react-native-seoul/masonry-list';
|
||||
import flashSalesData from '../constants/flashSalesData';
|
||||
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
|
||||
import { StarIcon } from 'react-native-heroicons/solid';
|
||||
import { HeartIcon } from 'react-native-heroicons/outline';
|
||||
import Icon from "react-native-vector-icons/FontAwesome"
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getFavorites, toggleFavorite } from '../api';
|
||||
|
||||
const FlashSales = ({data}) => {
|
||||
const navigation = useNavigation()
|
||||
const saleEnd = "2024-12-20T23:45:30";
|
||||
const [endDate, setEndDate] = useState(calenderLastDate(saleEnd))
|
||||
const [favorites, setFavorites] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
const remainigTime = calenderLastDate(saleEnd)
|
||||
if (remainigTime.total <= 0) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
setEndDate(remainigTime)
|
||||
}, 1000)
|
||||
return () => clearInterval(timer)
|
||||
}, [saleEnd])
|
||||
|
||||
// Load favorites when component mounts
|
||||
useEffect(() => {
|
||||
const loadFavorites = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const favoriteProducts = await getFavorites();
|
||||
setFavorites(favoriteProducts || []);
|
||||
} catch (error) {
|
||||
console.error('Error loading favorites:', error);
|
||||
setFavorites([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
loadFavorites();
|
||||
}, []);
|
||||
|
||||
//Category toggle
|
||||
const subCategory = ["All", "Newest", "Popular", "Mens", "Kids", "Womens"]
|
||||
const [activeSet, setActiveSet] = useState("All")
|
||||
|
||||
const handleSubCategory = (item) => {
|
||||
setActiveSet(item)
|
||||
}
|
||||
|
||||
const handleFavouriteToggle = async (product) => {
|
||||
try {
|
||||
const updatedFavorites = await toggleFavorite(product);
|
||||
setFavorites(updatedFavorites || []);
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const isProductFavorited = (productId) => {
|
||||
if (!Array.isArray(favorites)) return false;
|
||||
return favorites.some(fav => fav.id === productId);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<View className="flex-1 justify-center items-center">
|
||||
<Text>Loading...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View>
|
||||
<View className="flex-row justify-between items-center px-1 mx-4 mb-4">
|
||||
<Text className="text-xl font-semibold">FlashSales</Text>
|
||||
{
|
||||
endDate.total >= 0 ? <View className="flex-row items-center gap-2">
|
||||
<Text className="font-medium text-gray-500">Closing in :</Text>
|
||||
<View className="bg-btnPrimary h-8 w-8 flex justify-center items-center rounded-lg">
|
||||
<Text className="text-primary">{endDate.hours}</Text>
|
||||
</View>
|
||||
<Text>:</Text>
|
||||
<View className="bg-btnPrimary h-8 w-8 flex justify-center items-center rounded-lg">
|
||||
<Text className="text-primary">{endDate.minutes}</Text>
|
||||
</View>
|
||||
<Text>:</Text>
|
||||
<View className="bg-btnPrimary h-8 w-8 flex justify-center items-center rounded-lg">
|
||||
<Text className="text-primary">{endDate.seconds}</Text>
|
||||
</View>
|
||||
</View> : <></>
|
||||
}
|
||||
</View>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
{
|
||||
subCategory.map((item, index) => {
|
||||
let isActive = item == activeSet;
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={() => handleSubCategory(item)}
|
||||
key={index}
|
||||
className={`
|
||||
border border-gray-500 px-4 ml-4 mb-4 rounded-full py-2
|
||||
${isActive ? "bg-primary" : ""}
|
||||
`}>
|
||||
<Text className={`font-bold ${isActive ? "text-white" : ""}`}>
|
||||
{item}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)
|
||||
})
|
||||
}
|
||||
</ScrollView>
|
||||
<MasonryList
|
||||
data={data}
|
||||
keyExtractor={(item) => item.id}
|
||||
numColumns={2}
|
||||
showsVerticalScrollIndicator={false}
|
||||
renderItem={({ item, index }) => (
|
||||
<CardItem
|
||||
item={item}
|
||||
index={index}
|
||||
handleFavouriteToggle={() => handleFavouriteToggle(item)}
|
||||
isFavourite={isProductFavorited(item.id)}
|
||||
navigation={navigation}
|
||||
/>
|
||||
)}
|
||||
className="mx-4"
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const calenderLastDate = (saleEnd) => {
|
||||
const nowDate = new Date();
|
||||
const saleEndDate = new Date(saleEnd)
|
||||
const total = Math.floor(saleEndDate - nowDate)
|
||||
|
||||
const days = Math.floor(total / (1000 * 60 * 60 * 24))
|
||||
const hours = Math.floor(total / (1000 * 60 * 60) % 24)
|
||||
const minutes = Math.floor(total / (1000 * 60) % 60)
|
||||
const seconds = Math.floor(total / (1000) % 60)
|
||||
|
||||
return {
|
||||
total: total,
|
||||
days: Math.max(0, days),
|
||||
hours: Math.max(0, hours),
|
||||
minutes: Math.max(0, minutes),
|
||||
seconds: Math.max(0, seconds),
|
||||
}
|
||||
}
|
||||
|
||||
const CardItem = ({ item, index, handleFavouriteToggle, isFavourite, navigation }) => {
|
||||
let isEven = item.id % 2 == 0
|
||||
|
||||
const getRating = () => {
|
||||
if (item.rating) {
|
||||
if (typeof item.rating === 'object' && item.rating.rate !== undefined) {
|
||||
return item.rating.rate;
|
||||
}
|
||||
if (typeof item.rating === 'number') {
|
||||
return item.rating;
|
||||
}
|
||||
}
|
||||
|
||||
if (item.average_rating !== undefined) {
|
||||
return item.average_rating;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className={`${isEven ? "pl-4" : " pr-4"} flex-col gap-3 mb-4`}>
|
||||
<TouchableOpacity onPress={() => { navigation.navigate('ProductDetails',{id:item.id,}) }} className="relative">
|
||||
<Image source={{ uri: item.image }} height={hp(20)} className=" object-cover rounded-3xl" />
|
||||
<TouchableOpacity
|
||||
onPress={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFavouriteToggle();
|
||||
}}
|
||||
className="absolute right-4 top-4 bg-white/50 p-2 rounded-full"
|
||||
>
|
||||
{
|
||||
isFavourite ?
|
||||
<Icon name='heart' size={16} color={"red"} />
|
||||
:
|
||||
<HeartIcon size={20} color={"white"} />
|
||||
}
|
||||
</TouchableOpacity>
|
||||
</TouchableOpacity>
|
||||
<View className="flex-row justify-between px-1">
|
||||
<Text className={`flex-1`}>{item.name || item.title}</Text>
|
||||
<View className="flex-row gap-1 ">
|
||||
<StarIcon size={20} color={"orange"} />
|
||||
<Text>{getRating()}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="px-1 ">
|
||||
<Text className="font-medium">Rs {item.price}</Text>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default FlashSales
|
||||
@@ -0,0 +1,48 @@
|
||||
import { View, Text, Image } from 'react-native'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import PagerView from 'react-native-pager-view';
|
||||
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
|
||||
|
||||
const HomeCarousel = ({ setPage, slider }) => {
|
||||
return (
|
||||
<PagerView
|
||||
style={{ flex: 1 }}
|
||||
initialPage={0}
|
||||
scrollEnabled={true}
|
||||
|
||||
// overdrag={true}
|
||||
// overScrollMode={'always'}
|
||||
onPageSelected={(e) => setPage(e.nativeEvent.position)}
|
||||
>
|
||||
{
|
||||
slider.map((item, index) => {
|
||||
return (
|
||||
<View key={index} className={`justify-center items-center bg-[#ece4da] mx-4 mb-3 rounded-xl flex-1`} >
|
||||
<View className={`flex-row justify-between flex-1 p-4`}>
|
||||
<View className={`justify-center gap-3 items- w-1/2`}>
|
||||
<Text className={`capitalize font-semibold text-xl`}>{item.title}</Text>
|
||||
<Text className={`capitalize text-[#797979]`}>{item.description}</Text>
|
||||
<View className={`justify-center items-start`}>
|
||||
<View className={`px-3 py-2 bg-primary w-fit rounded-lg`}>
|
||||
<Text className={`text-white font-bold`}>Shop Now</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<Image
|
||||
source={{ uri: "https://cdn.clo3d.com/resource/images/artwork/landing/watermark_landing_sustainably_renewal_1920.png" }}
|
||||
className={`w-1/2 h-full`}
|
||||
style={{}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
</PagerView>
|
||||
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
export default HomeCarousel
|
||||
@@ -0,0 +1,73 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import Icon from 'react-native-vector-icons/FontAwesome';
|
||||
|
||||
const ItemCard = ({ item, onPress, onFavoritePress, isFavourite }) => (
|
||||
<View style={styles.card}>
|
||||
<TouchableOpacity onPress={onPress}>
|
||||
<Image source={{ uri: item.image }} style={styles.image} />
|
||||
<TouchableOpacity
|
||||
style={styles.heartButton}
|
||||
onPress={onFavoritePress}
|
||||
>
|
||||
<Icon
|
||||
name={isFavourite ? "heart" : "heart-o"}
|
||||
size={20}
|
||||
color={isFavourite ? "#ff0000" : "#333"}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.title}>{item.title}</Text>
|
||||
<Text style={styles.price}>${item.price}</Text>
|
||||
<View style={styles.ratingContainer}>
|
||||
<Text style={styles.rating}>{item.rating}</Text>
|
||||
<Icon name="star" size={16} color="#f5a623" />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
backgroundColor: '#fff',
|
||||
margin: 10,
|
||||
borderRadius: 10,
|
||||
elevation: 2,
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
padding: 10,
|
||||
},
|
||||
image: {
|
||||
width: '100%',
|
||||
height: 150,
|
||||
borderRadius: 8,
|
||||
},
|
||||
heartButton: {
|
||||
position: 'absolute',
|
||||
top: 10,
|
||||
right: 10,
|
||||
padding: 5,
|
||||
},
|
||||
title: {
|
||||
fontSize: 16,
|
||||
fontWeight: 'bold',
|
||||
marginTop: 8,
|
||||
},
|
||||
price: {
|
||||
fontWeight: 'bold',
|
||||
fontSize: 16,
|
||||
color: '#555',
|
||||
marginTop: 4,
|
||||
},
|
||||
ratingContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginTop: 4,
|
||||
},
|
||||
rating: {
|
||||
fontSize: 14,
|
||||
marginRight: 4,
|
||||
color: '#f5a623',
|
||||
},
|
||||
});
|
||||
|
||||
export default ItemCard;
|
||||
@@ -0,0 +1,46 @@
|
||||
import { View, Text, TouchableOpacity } from 'react-native'
|
||||
import React from 'react'
|
||||
import { MinusIcon, PlusIcon } from 'react-native-heroicons/outline'
|
||||
|
||||
/**
|
||||
* A reusable component for quantity selection with plus and minus buttons
|
||||
*
|
||||
* @param {Object} props Component props
|
||||
* @param {number} props.quantity Current quantity value
|
||||
* @param {Function} props.onIncrease Function to call when increasing quantity
|
||||
* @param {Function} props.onDecrease Function to call when decreasing quantity
|
||||
* @param {string} props.label Label text to display (optional)
|
||||
* @param {Object} props.containerStyle Additional styles for the container
|
||||
* @returns {React.Component} Quantity selector component
|
||||
*/
|
||||
export default function ProductQuantityInput({
|
||||
quantity = 1,
|
||||
onIncrease,
|
||||
onDecrease,
|
||||
label = "Quantity",
|
||||
containerStyle = {}
|
||||
}) {
|
||||
return (
|
||||
<View style={containerStyle}>
|
||||
{label && <Text className="text-[17px] font-medium mb-2">{label}</Text>}
|
||||
<View className="flex-row items-center">
|
||||
<TouchableOpacity
|
||||
onPress={onDecrease}
|
||||
className={`bg-primary/40 rounded-lg p-1 ${quantity <= 1 ? 'opacity-50' : ''}`}
|
||||
disabled={quantity <= 1}
|
||||
>
|
||||
<MinusIcon color={quantity <= 1 ? "gray" : "black"} size={25} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<Text className="mx-4 text-xl">{quantity}</Text>
|
||||
|
||||
<TouchableOpacity
|
||||
onPress={onIncrease}
|
||||
className="bg-primary rounded-lg p-1"
|
||||
>
|
||||
<PlusIcon color="white" size={25} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
const clothColor = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Brown",
|
||||
color: "#8C6A5E"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "black",
|
||||
color: "#261A1A"
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: "white",
|
||||
color: "#FAFAFA"
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: "green",
|
||||
color: "#01F702"
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: "red",
|
||||
color: "#F70000"
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
name: "pinK",
|
||||
color: "#F766AE"
|
||||
},
|
||||
|
||||
]
|
||||
export default clothColor
|
||||
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user