46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import type { CouponPreviewResponse } from '@/types/coupon';
|
|
|
|
function extractErrorMessage(payload: unknown): string {
|
|
if (!payload || typeof payload !== 'object') {
|
|
return 'coupon_error_generic';
|
|
}
|
|
|
|
const data = payload as Record<string, any>;
|
|
|
|
if (data.message && typeof data.message === 'string') {
|
|
return data.message;
|
|
}
|
|
|
|
if (data.errors) {
|
|
const errors = data.errors as Record<string, string[]>;
|
|
const firstKey = Object.keys(errors)[0];
|
|
if (firstKey && Array.isArray(errors[firstKey]) && errors[firstKey][0]) {
|
|
return errors[firstKey][0];
|
|
}
|
|
}
|
|
|
|
return 'coupon_error_generic';
|
|
}
|
|
|
|
export async function previewCoupon(packageId: number, code: string): Promise<CouponPreviewResponse> {
|
|
const response = await fetch('/api/v1/marketing/coupons/preview', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
package_id: packageId,
|
|
code,
|
|
}),
|
|
});
|
|
|
|
const payload = await response.json().catch(() => ({}));
|
|
|
|
if (!response.ok) {
|
|
throw new Error(extractErrorMessage(payload));
|
|
}
|
|
|
|
return payload as CouponPreviewResponse;
|
|
}
|