Order History
Relevant source files
The following files were used as context for generating this wiki page:- app/(account)/orders/[id]/page.tsx
- features/orders/components/orders-tab.tsx
- features/orders/components/order-detail-view.tsx
- types/order.types.ts
- features/orders/services/orders.service.ts
- features/orders/hooks/use-orders-query.ts
- app/admin/orders/page.tsx
- app/admin/orders/[id]/page.tsx
- features/orders/utils/index.ts
The Order History feature provides a comprehensive system for both customers and administrators to view and manage e-commerce orders. For customers, it offers a "My Orders" section within their account profile to track past and current purchases. For administrators, it provides a dedicated dashboard to manage all customer orders, update their statuses, and view detailed information.
The implementation follows the project's feature-based architecture, with all core logic, components, and services encapsulated within the features/orders/ directory. This modular design separates data fetching, state management, and UI rendering, promoting code reuse and maintainability. The system relies on a service layer for API communication, React Query for server state management, and distinct components for user-facing and admin-facing interfaces.
Data Models and Types
The foundation of the order system is defined in types/order.types.ts. It establishes the data structures for orders, order items, and related enumerations, ensuring type safety throughout the application.
Entity Relationship Diagram
This diagram shows the relationship between the Order and OrderItem entities. An Order can contain one or more OrderItem records.
Sources: types/order.types.ts:63-73, 29-38
Order Interface
Represents a single customer order.
| Field | Type | Description |
|---|---|---|
id | string | Unique CUID for the order. |
userId | string | CUID of the user who placed the order. |
addressId | string | null | CUID of the shipping address, if specified. |
status | OrderStatus | The current processing status of the order. |
paymentStatus | PaymentStatus | The current payment status of the order. |
totalInt | number | The total order amount in VND. |
items | OrderItem[] | An array of items included in the order. |
createdAt | string | ISO date string of when the order was created. |
updatedAt | string | ISO date string of when the order was last updated. |
| Sources: types/order.types.ts:63-73 |
OrderItem Interface
Represents a single product line item within an order.
| Field | Type | Description |
|---|---|---|
id | string | Unique CUID for the order item. |
orderId | string | CUID of the parent order. |
productId | string | CUID of the product. |
productName | string | A snapshot of the product name at the time of order. |
imageUrls | string[] | A snapshot of the product image URLs. |
quantity | number | The quantity of the product ordered. |
priceInt | number | The unit price in VND at the time of purchase. |
createdAt | string | ISO date string of when the item was added. |
| Sources: types/order.types.ts:29-38 |
Enumerations
The system uses enums to represent the discrete states of an order's lifecycle.
| Enum | Values |
|---|---|
OrderStatus | PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED |
PaymentStatus | UNPAID, PAID |
| Sources: types/order.types.ts:11-22 |
Service Layer (OrdersService)
All communication with the backend order-related API endpoints is handled by the OrdersService class. This service abstracts the details of HTTP requests and response validation, providing a clean, typed interface for the rest of the application.
Sources: features/orders/services/orders.service.ts
Key Methods
| Method | Endpoint | Description |
|---|---|---|
getAll() | GET /orders | Fetches a paginated list of orders for the currently authenticated user. |
getById(id) | GET /orders/:id | Fetches a single order by its ID. |
create(data) | POST /orders | Creates a new order. Automatically includes the userId from the auth store. |
updateStatus(id, data) | PATCH /orders/:id/status | Updates the status and/or payment status of an order (admin only). |
cancel(id) | PATCH /orders/:id/cancel | Cancels an order. |
listAllOrders(query) | GET /orders/admin/all | Fetches a paginated and filterable list of all orders for the admin panel. |
| Sources: features/orders/services/orders.service.ts:43-154 |
Data Fetching Flow
The following diagram illustrates how the service layer fetches an order by its ID.
State Management & Data Fetching (React Query)
Server state for orders is managed using TanStack (React) Query. A set of custom hooks in features/orders/hooks/use-orders-query.ts provides a declarative API for fetching and mutating order data, handling caching, and managing invalidation automatically.
Core Hooks
| Hook | Query/Mutation | Description |
|---|---|---|
useOrders(filters) | useQuery | Fetches a paginated list of orders for the current user. |
useOrder(orderId) | useQuery | Fetches a single order by its ID. |
useCreateOrder() | useMutation | Creates a new order and invalidates order and cart queries on success. |
useUpdateOrderStatus() | useMutation | Updates an order's status and invalidates relevant order queries. |
useCancelOrder() | useMutation | Cancels an order and invalidates relevant order queries. |
| Sources: features/orders/hooks/use-orders-query.ts |
Component Data Flow with useOrder
This diagram shows how a component uses the useOrder hook to fetch and display data.
User-Facing Components
These components are part of the customer's account section, allowing them to view their order history.
Order List (OrdersTab)
The OrdersTab component is displayed in the user's profile and lists all their past orders.
- Functionality: It uses the
useOrdershook (a custom hook that seems to wrapuseState/useEffectrather than the React Query one) to fetch the order list. - Display: Renders a
Tableshowing key order details like ID, date, total price, and status. Each row includes a "Chi tiết" (Details) button to navigate to the order detail page. - Status Badges: Uses
BadgeandPaymentStatusBadgecomponents to visually represent theOrderStatusandPaymentStatus.
Sources: features/orders/components/orders-tab.tsx
Order Detail Page (app/(account)/orders/[id]/page.tsx)
This page provides a detailed view of a single order.
- Data Fetching: It retrieves the
orderIdfrom the URL parameters and usesordersApi.getByIdwithin auseEffecthook to fetch the order data. It also fetches associated address details if anaddressIdis present. - Layout: The page is structured with
Cardcomponents to display:- Order and Payment Status
- General order information (ID, date, total)
- A list of products in the order, including images, names, quantities, and prices.
- Shipping address details.
- A final order summary.
- Protection: The entire page is wrapped in a
<ProtectedRoute>component, ensuring only authenticated users can access it.
Sources: app/(account)/orders/[id]/page.tsx
Admin-Facing Components
The admin panel includes powerful tools for managing all orders in the system.
Order Management Dashboard (app/admin/orders/page.tsx)
This is the main entry point for administrators to manage orders.
- Functionality: It uses the
useOrdersAdminListhook to fetch a paginated list of all orders, with support for filtering by status, payment status, search term, and date range via theOrdersFilterscomponent. - Display: Orders are rendered in the
OrdersListTablecomponent, which defines columns for key data points and an action menu for each order. - Actions: Admins can view order details or trigger a status update directly from the table. Clicking "Update Status" opens the
OrderStatusUpdateDialog.
Sources: app/admin/orders/page.tsx
Admin Order Detail View (app/admin/orders/[id]/page.tsx)
This page allows an admin to view and manage a specific order.
- Data Fetching: It uses the
useQueryhook from@tanstack/react-querywithordersApi.getByIdto fetch the order details. - Component Reuse: It renders the
OrderDetailViewcomponent, which is a shared component also used for displaying order details in other parts of the app. - Status Updates: It includes logic to open the
OrderStatusUpdateDialog. When the admin saves a new status, theuseUpdateOrderStatusmutation is called to persist the change, and React Query automatically handles re-fetching the data.
Sources: app/admin/orders/[id]/page.tsx
Key Workflows
Viewing Order History (User)
This sequence diagram shows the flow when a user views their order history.
Updating Order Status (Admin)
This diagram illustrates the process of an administrator updating an order's status.
Conclusion
The Order History feature is a well-structured module that effectively separates concerns between data, services, state management, and UI. It demonstrates a robust implementation pattern using a dedicated service layer (OrdersService) to interact with the API and React Query hooks to manage server state efficiently. The reuse of components like OrderDetailView for both user and admin contexts highlights a commitment to DRY (Don't Repeat Yourself) principles, making the system both scalable and maintainable.