canina/frontend/application/lib/services/orderService.ts

97 lines
2.4 KiB
TypeScript

import api from './api';
export interface OrderItem {
id: string;
orderId: string;
productId: string | null;
quantity: number;
product?: Record<string, unknown>;
}
export interface Order {
id: string;
userId: string;
couponId: string | null;
totalAmount: number;
charityDonation: number;
status: string;
trackingNumber: string | null;
createdAt: string;
orderItems: OrderItem[];
}
interface ApiErr {
response?: {
data?: {
message?: string | string[];
};
};
}
export class OrderService {
private static instance: OrderService;
private constructor() {}
public static getInstance(): OrderService {
if (!OrderService.instance) {
OrderService.instance = new OrderService();
}
return OrderService.instance;
}
/**
* Create a new order on the backend
*/
public async createOrder(orderData: {
petId?: string;
couponCode?: string;
prescriptionUrl?: string;
charityDonation?: number;
paymentMethod?: string;
isRefill?: boolean;
refillIntervalDays?: number;
shippingAddress?: string;
items: { productId: string; quantity: number }[];
}): Promise<Order> {
try {
const response = await api.post('/orders', orderData);
return response.data;
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در ثبت سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get all orders for the current user
*/
public async getUserOrders(): Promise<Order[]> {
try {
const response = await api.get('/orders');
return response.data.data;
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get order details by ID
*/
public async getOrderById(id: string): Promise<Order> {
try {
const response = await api.get(`/orders/${id}`);
return response.data;
} catch (error) {
const err = error as ApiErr;
const message = err.response?.data?.message || 'خطا در دریافت جزئیات سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
}
export const orderService = OrderService.getInstance();