70 lines
2.3 KiB
TypeScript
70 lines
2.3 KiB
TypeScript
import React from 'react'
|
|
import { createFileRoute } from '@tanstack/react-router'
|
|
import { AppContainer } from 'web-components'
|
|
import CouponForm from '../components/CouponForm'
|
|
import { trpc } from '@/lib/trpc-client'
|
|
import { ErrorToast } from '@/services/toaster'
|
|
|
|
export const Route = createFileRoute('/dashboard/coupons/new')({
|
|
component: CreateCoupon,
|
|
})
|
|
|
|
function CreateCoupon() {
|
|
const createCoupon = trpc.admin.coupon.create.useMutation()
|
|
const createReservedCoupon = trpc.admin.coupon.createReservedCoupon.useMutation()
|
|
const { refetch: refetchCoupons } = trpc.admin.coupon.getAll.useInfiniteQuery(
|
|
{ limit: 20, search: '' },
|
|
{
|
|
enabled: false,
|
|
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
|
}
|
|
)
|
|
const { refetch: refetchReservedCoupons } = trpc.admin.coupon.getReservedCoupons.useInfiniteQuery(
|
|
{ limit: 20, search: '' },
|
|
{
|
|
enabled: false,
|
|
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
|
}
|
|
)
|
|
|
|
const handleCreateCoupon = async (values: any) => {
|
|
const { isReservedCoupon, couponCodes, ...rest } = values
|
|
// Transform targetUsers array to targetUser for backend compatibility
|
|
const payload = {
|
|
...rest,
|
|
targetUser: rest.targetUsers?.[0] || undefined,
|
|
}
|
|
delete payload.targetUsers
|
|
|
|
// For flat discounts, send the discount value as maxValue too
|
|
if (payload.flatDiscount !== undefined) {
|
|
payload.maxValue = payload.flatDiscount
|
|
}
|
|
|
|
const codes = (couponCodes || []).map((c: string) => c.trim()).filter(Boolean)
|
|
if (codes.length === 0) {
|
|
ErrorToast('At least one coupon code is required')
|
|
return
|
|
}
|
|
|
|
const mutation = isReservedCoupon ? createReservedCoupon : createCoupon
|
|
try {
|
|
await mutation.mutateAsync({ ...payload, couponCodes: codes })
|
|
await refetchCoupons()
|
|
await refetchReservedCoupons()
|
|
window.alert(`Success: ${codes.length} coupon${codes.length > 1 ? 's' : ''} created successfully`)
|
|
window.history.back()
|
|
} catch (error: any) {
|
|
ErrorToast(error.message || 'Failed to create coupons')
|
|
}
|
|
}
|
|
|
|
return (
|
|
<AppContainer>
|
|
<CouponForm
|
|
onSubmit={handleCreateCoupon}
|
|
isLoading={createCoupon.isPending || createReservedCoupon.isPending}
|
|
/>
|
|
</AppContainer>
|
|
)
|
|
}
|