|
| 1 | +import type { CouponRequestType } from '@stacksjs/orm' |
| 2 | +import type { CouponsTable, NewCoupon } from '../../../../orm/src/models/Coupon' |
| 3 | +import { db } from '@stacksjs/database' |
| 4 | + |
| 5 | +/** |
| 6 | + * Create a new coupon |
| 7 | + * |
| 8 | + * @param request The coupon data to store |
| 9 | + * @returns The newly created coupon record |
| 10 | + */ |
| 11 | +export async function store(request: CouponRequestType): Promise<CouponsTable | undefined> { |
| 12 | + await request.validate() |
| 13 | + |
| 14 | + const couponData: NewCoupon = { |
| 15 | + code: request.get<string>('code'), |
| 16 | + description: request.get('description'), |
| 17 | + discount_type: request.get<string>('discount_type'), |
| 18 | + discount_value: request.get<number>('discount_value'), |
| 19 | + min_order_amount: request.get<number | undefined>('min_order_amount'), |
| 20 | + max_discount_amount: request.get<number | undefined>('max_discount_amount'), |
| 21 | + free_product_id: request.get('free_product_id'), |
| 22 | + is_active: request.get<boolean>('is_active'), |
| 23 | + usage_limit: request.get<number | undefined>('usage_limit'), |
| 24 | + usage_count: request.get<number>('usage_count'), |
| 25 | + start_date: request.get<string>('start_date'), |
| 26 | + end_date: request.get<string>('end_date'), |
| 27 | + applicable_products: request.get<string[] | undefined>('applicable_products') |
| 28 | + ? JSON.stringify(request.get<string[]>('applicable_products')) |
| 29 | + : JSON.stringify([]), |
| 30 | + applicable_categories: request.get<string[] | undefined>('applicable_categories') |
| 31 | + ? JSON.stringify(request.get<string[]>('applicable_categories')) |
| 32 | + : JSON.stringify([]), |
| 33 | + } |
| 34 | + |
| 35 | + try { |
| 36 | + // Insert the coupon record |
| 37 | + const createdCoupon = await db |
| 38 | + .insertInto('coupons') |
| 39 | + .values(couponData) |
| 40 | + .executeTakeFirst() |
| 41 | + |
| 42 | + // If insert was successful, retrieve the newly created coupon |
| 43 | + if (createdCoupon.insertId) { |
| 44 | + const coupon = await db |
| 45 | + .selectFrom('coupons') |
| 46 | + .where('id', '=', Number(createdCoupon.insertId)) |
| 47 | + .selectAll() |
| 48 | + .executeTakeFirst() |
| 49 | + |
| 50 | + return coupon |
| 51 | + } |
| 52 | + |
| 53 | + return undefined |
| 54 | + } |
| 55 | + catch (error) { |
| 56 | + if (error instanceof Error) { |
| 57 | + if (error.message.includes('Duplicate entry') && error.message.includes('code')) { |
| 58 | + throw new Error('A coupon with this code already exists') |
| 59 | + } |
| 60 | + |
| 61 | + throw new Error(`Failed to create coupon: ${error.message}`) |
| 62 | + } |
| 63 | + |
| 64 | + throw error |
| 65 | + } |
| 66 | +} |
0 commit comments