68 lines
2.2 KiB
TypeScript
68 lines
2.2 KiB
TypeScript
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
import { Order, OrderStatus, TrackingStep, DeliveryAgent, Location } from '../interfaces';
|
|
|
|
interface OrderState {
|
|
currentOrder: Order | null;
|
|
orders: Order[];
|
|
trackingSteps: TrackingStep[];
|
|
deliveryAgent: DeliveryAgent | null;
|
|
liveLocation: Location | null;
|
|
}
|
|
|
|
const buildTrackingSteps = (status: OrderStatus): TrackingStep[] => {
|
|
const steps: { key: OrderStatus; label: string }[] = [
|
|
{ key: 'placed', label: 'Order Placed' },
|
|
{ key: 'confirmed', label: 'Confirmed' },
|
|
{ key: 'dispatched', label: 'Dispatched' },
|
|
{ key: 'delivered', label: 'Delivered' },
|
|
];
|
|
const currentIndex = steps.findIndex((s) => s.key === status);
|
|
return steps.map((step, index) => ({
|
|
...step,
|
|
isCompleted: index < currentIndex,
|
|
isActive: index === currentIndex,
|
|
}));
|
|
};
|
|
|
|
const initialState: OrderState = {
|
|
currentOrder: null,
|
|
orders: [],
|
|
trackingSteps: [],
|
|
deliveryAgent: null,
|
|
liveLocation: null,
|
|
};
|
|
|
|
const orderSlice = createSlice({
|
|
name: 'order',
|
|
initialState,
|
|
reducers: {
|
|
placeOrder(state, action: PayloadAction<Order>) {
|
|
state.currentOrder = action.payload;
|
|
state.orders.unshift(action.payload);
|
|
state.trackingSteps = buildTrackingSteps('placed');
|
|
},
|
|
updateOrderStatus(state, action: PayloadAction<OrderStatus>) {
|
|
if (state.currentOrder) {
|
|
state.currentOrder.status = action.payload;
|
|
state.trackingSteps = buildTrackingSteps(action.payload);
|
|
const idx = state.orders.findIndex((o) => o.id === state.currentOrder!.id);
|
|
if (idx !== -1) {
|
|
state.orders[idx] = { ...state.orders[idx], status: action.payload };
|
|
}
|
|
}
|
|
},
|
|
setDeliveryAgent(state, action: PayloadAction<DeliveryAgent>) {
|
|
state.deliveryAgent = action.payload;
|
|
},
|
|
updateLiveLocation(state, action: PayloadAction<Location>) {
|
|
state.liveLocation = action.payload;
|
|
},
|
|
addOrder(state, action: PayloadAction<Order>) {
|
|
state.orders.unshift(action.payload);
|
|
},
|
|
},
|
|
});
|
|
|
|
export const { placeOrder, updateOrderStatus, setDeliveryAgent, updateLiveLocation, addOrder } = orderSlice.actions;
|
|
export default orderSlice.reducer;
|