add discount

This commit is contained in:
2025-12-24 01:40:07 -03:00
parent 1a59ad9e91
commit 2459bafc5d
16 changed files with 423 additions and 132 deletions

View File

@@ -0,0 +1,312 @@
import { Fragment } from 'react'
import { Trash2Icon, PlusIcon, CircleQuestionMarkIcon } from 'lucide-react'
import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form'
import { useParams } from 'react-router'
import { ErrorMessage } from '@hookform/error-message'
import { zodResolver } from '@hookform/resolvers/zod'
import { Form } from '@repo/ui/components/ui/form'
import {
InputGroup,
InputGroupAddon,
InputGroupInput
} from '@repo/ui/components/ui/input-group'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
HoverCard,
HoverCardContent,
HoverCardTrigger
} from '@repo/ui/components/ui/hover-card'
import {
MAX_ITEMS,
formSchema,
type Course,
type User
} from '../_.$orgid.enrollments.add/data'
import { ScheduledForInput } from '../_.$orgid.enrollments.add/scheduled-for'
import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { UserPicker } from '../_.$orgid.enrollments.add/user-picker'
const emptyRow = {
user: undefined,
course: undefined,
scheduled_for: undefined
}
type AssignedProps = {
onSubmit: (value: any) => void | Promise<void>
courses: Promise<{ hits: Course[] }>
}
export function Assigned({ courses, onSubmit }: AssignedProps) {
const { orgid } = useParams()
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: { enrollments: [emptyRow] }
})
const { formState, control, handleSubmit } = form
const { fields, remove, append } = useFieldArray({
control,
name: 'enrollments'
})
const items = useWatch({
control,
name: 'enrollments'
})
const subtotal = items.reduce(
(acc, { course }) => acc + (course?.unit_price || 0),
0
)
const onSearch = async (search: string) => {
const params = new URLSearchParams({ q: search })
const r = await fetch(`/${orgid}/users.json?${params.toString()}`)
const { hits } = (await r.json()) as { hits: User[] }
return hits
}
const onSubmit_ = async (data: any) => {
await onSubmit(data)
}
return (
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit_)} className="space-y-4">
<div className="grid w-full gap-1.5 lg:grid-cols-[3fr_3fr_2fr_2fr_auto]">
{/* Header */}
<>
<Cell>Colaborador</Cell>
<Cell>Curso</Cell>
<Cell className="flex items-center gap-1.5">
Matricular em
<HoverCard openDelay={0}>
<HoverCardTrigger asChild>
<button type="button">
<CircleQuestionMarkIcon className="size-4 text-muted-foreground" />
</button>
</HoverCardTrigger>
<HoverCardContent
align="end"
className="text-sm space-y-1.5 lg:w-76"
>
<p>
Escolha a data em que o colaborador será matriculado no
curso.
</p>
<p>
Você poderá acompanhar as matrículas em{' '}
<Kbd>Agendamentos</Kbd>
</p>
</HoverCardContent>
</HoverCard>
</Cell>
<Cell>Valor unit.</Cell>
<Cell>{/**/}</Cell>
</>
{/* Rows */}
{fields.map((field, index) => {
const { unit_price } = items?.[index]?.course || { unit_price: 0 }
return (
<Fragment key={field.id}>
{/* Separator only for mobile */}
{index >= 1 && <div className="h-2.5 lg:hidden"></div>}
{/* User */}
<Controller
control={control}
name={`enrollments.${index}.user`}
render={({
field: { name, value, onChange },
fieldState
}) => (
<div className="grid gap-1">
<UserPicker
value={value}
onChange={onChange}
onSearch={onSearch}
fieldState={fieldState}
/>
<ErrorMessage
errors={formState.errors}
name={name}
render={({ message }) => (
<p className="text-destructive text-sm">{message}</p>
)}
/>
</div>
)}
/>
{/* Course */}
<Controller
control={control}
name={`enrollments.${index}.course`}
render={({
field: { name, value, onChange },
fieldState
}) => (
<div className="grid gap-1">
<CoursePicker
value={value}
onChange={onChange}
options={courses}
error={fieldState.error}
readOnly
/>
<ErrorMessage
errors={formState.errors}
name={name}
render={({ message }) => (
<p className="text-destructive text-sm">{message}</p>
)}
/>
</div>
)}
/>
{/* Scheduled for */}
<Controller
control={control}
name={`enrollments.${index}.scheduled_for`}
render={({ field: { value, onChange } }) => (
<ScheduledForInput value={value} onChange={onChange} />
)}
/>
{/* Unit price */}
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Valor unit.
</InputGroupAddon>
<InputGroupInput
className="pointer-events-none"
tabIndex={-1}
readOnly
value={currency.format(unit_price)}
/>
</InputGroup>
{/* Action */}
<Button
tabIndex={-1}
variant="destructive"
className="cursor-pointer"
disabled={fields.length == 1}
onClick={() => remove(index)}
>
<Trash2Icon />
</Button>
</Fragment>
)
})}
{/* Add button */}
<div className="max-lg:mb-2.5">
<Button
type="button"
// @ts-ignore
onClick={() => append(emptyRow)}
className="cursor-pointer"
disabled={fields.length == MAX_ITEMS}
variant="outline"
size="sm"
>
<PlusIcon /> Adicionar
</Button>
</div>
{/* Subtotal */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
Subtotal
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Subtotal
</InputGroupAddon>
<InputGroupInput
name="subtotal"
value={currency.format(subtotal)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
{/* Discount */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
Cupom
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Cupom
</InputGroupAddon>
<InputGroupInput
name="discount"
value={currency.format(0)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
<InputGroupAddon align="inline-end">
<Button
variant="outline"
className="text-xs cursor-pointer h-6 px-2"
type="button"
>
Adicionar
</Button>
</InputGroupAddon>
</InputGroup>
</>
{/* Total */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
Total
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Total
</InputGroupAddon>
<InputGroupInput
name="total"
value={currency.format(subtotal)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
</div>
<Separator />
<Button
type="submit"
className="cursor-pointer"
disabled={formState.isSubmitting}
>
{formState.isSubmitting && <Spinner />}
Continuar
</Button>
</form>
</Form>
)
}
const currency = new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})

View File

@@ -0,0 +1,400 @@
import { Fragment } from 'react'
import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form'
import { ErrorMessage } from '@hookform/error-message'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput
} from '@repo/ui/components/ui/input-group'
import { Form } from '@repo/ui/components/ui/form'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { MAX_ITEMS, type Course } from '../_.$orgid.enrollments.add/data'
import { Discount } from './discount'
const emptyRow = {
course: undefined
}
type BulkProps = {
onSubmit: (value: any) => void | Promise<void>
courses: Promise<{ hits: Course[] }>
}
const item = z.object({
course: z
.object(
{
id: z.string(),
name: z.string(),
access_period: z.number(),
unit_price: z.number()
},
{ error: 'Escolha um curso' }
)
.required(),
quantity: z.number().min(1)
})
const formSchema = z.object({
items: z.array(item).min(1).max(MAX_ITEMS),
coupon: z
.object({
coupon: z.string(),
type: z.enum(['FIXED', 'PERCENT']),
amount: z.number().positive()
})
.optional()
})
type Schema = z.infer<typeof formSchema>
export function Bulk({ courses, onSubmit }: BulkProps) {
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: { items: [emptyRow] }
})
const {
formState,
control,
handleSubmit,
register,
setValue,
getValues,
setFocus
} = form
const { fields, remove, append } = useFieldArray({
control,
name: 'items'
})
const items = useWatch({
control,
name: 'items'
})
const coupon = useWatch({ control, name: 'coupon' })
const subtotal = items.reduce(
(acc, { course, quantity }) =>
acc +
(course?.unit_price || 0) *
(Number.isFinite(quantity) && quantity > 0 ? quantity : 1),
0
)
const discount = coupon
? applyDiscount(subtotal, coupon.amount, coupon.type)
: 0
const total = subtotal > 0 ? subtotal - discount : 0
const onSubmit_ = async (data: Schema) => {
await onSubmit(data)
}
return (
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit_)} className="space-y-4">
<div className="grid w-full gap-1.5 lg:grid-cols-[4fr_2fr_2fr_2fr_auto]">
{/* Header */}
<>
<Cell>Curso</Cell>
<Cell>Quantidade</Cell>
<Cell>Valor unit.</Cell>
<Cell>Total</Cell>
<Cell>{/**/}</Cell>
</>
{/* Rows */}
{fields.map((field, index) => {
const item = items?.[index] || { course: {}, quantity: 1 }
const { course, quantity } = item
return (
<Fragment key={field.id}>
{/* Separator only for mobile */}
{index >= 1 && <div className="h-2.5 lg:hidden"></div>}
{/* Course */}
<Controller
control={control}
name={`items.${index}.course`}
render={({
field: { name, value, onChange, ref },
fieldState
}) => (
<div className="grid gap-1">
<CoursePicker
ref={ref}
name={name}
autoFocus={index === 0}
value={value}
onChange={onChange}
options={courses}
error={fieldState.error}
readOnly
/>
<ErrorMessage
errors={formState.errors}
name={name}
render={({ message }) => (
<p className="text-destructive text-sm">{message}</p>
)}
/>
</div>
)}
/>
{/* Quantity */}
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Qtd.
</InputGroupAddon>
<InputGroupInput
type="number"
min={1}
defaultValue={1}
className="no-spinner"
{...register(`items.${index}.quantity`, {
valueAsNumber: true,
onBlur: (e) => {
const value = Number(e.target.value)
if (!value || value < 1) {
setValue(`items.${index}.quantity`, 1)
}
}
})}
/>
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
tabIndex={-1}
size="icon-xs"
className="border cursor-pointer"
onClick={() => {
const quantity =
getValues(`items.${index}.quantity`) || 1
setValue(
`items.${index}.quantity`,
Math.max(1, quantity - 1)
)
}}
>
<MinusIcon />
</InputGroupButton>
</InputGroupAddon>
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
tabIndex={-1}
size="icon-xs"
className="border cursor-pointer"
onClick={() => {
const quantity =
getValues(`items.${index}.quantity`) || 1
setValue(`items.${index}.quantity`, quantity + 1)
}}
>
<PlusIcon />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
{/* Unit price */}
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Valor unit.
</InputGroupAddon>
<InputGroupInput
tabIndex={-1}
className="pointer-events-none"
readOnly
value={currency.format(course?.unit_price || 0)}
/>
</InputGroup>
{/* Total */}
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Total
</InputGroupAddon>
<InputGroupInput
tabIndex={-1}
className="pointer-events-none"
readOnly
value={currency.format(
(course?.unit_price || 0) *
(Number.isFinite(quantity) && quantity > 0
? quantity
: 1)
)}
/>
</InputGroup>
{/* Action */}
<Button
tabIndex={-1}
variant="destructive"
className="cursor-pointer"
disabled={fields.length == 1}
onClick={() => remove(index)}
>
<Trash2Icon />
</Button>
</Fragment>
)
})}
{/* Add button */}
<div className="max-lg:mb-2.5">
<Button
type="button"
onClick={() => {
// @ts-ignore
append(emptyRow, { shouldFocus: false })
queueMicrotask(() => {
setFocus(`items.${fields.length}.course`)
})
}}
className="cursor-pointer"
variant="outline"
size="sm"
>
<PlusIcon /> Adicionar
</Button>
</div>
{/* Subtotal */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
Subtotal
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Subtotal
</InputGroupAddon>
<InputGroupInput
tabIndex={-1}
name="subtotal"
value={currency.format(subtotal)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
{/* Discount */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
{coupon ? <>Descontos</> : <>Cupom</>}
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
{coupon ? <>Descontos</> : <>Cupom</>}
</InputGroupAddon>
<InputGroupInput
name="discount"
value={currency.format(discount * -1)}
tabIndex={-1}
className="pointer-events-none text-muted-foreground"
readOnly
/>
<InputGroupAddon align="inline-end">
{coupon ? (
<InputGroupButton
size="icon-xs"
className="cursor-pointer"
variant="ghost"
onClick={() => {
setValue('coupon', undefined)
}}
>
<XIcon />
</InputGroupButton>
) : (
<Discount
disabled={subtotal === 0}
onChange={({ sk, discount_amount, discount_type }) => {
setValue('coupon', {
coupon: sk,
amount: discount_amount,
type: discount_type
})
}}
/>
)}
</InputGroupAddon>
</InputGroup>
</>
{/* Total */}
<>
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
Total
</div>
<InputGroup>
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
Total
</InputGroupAddon>
<InputGroupInput
name="total"
tabIndex={-1}
value={currency.format(total)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
</div>
<Separator />
<Button
type="submit"
className="cursor-pointer"
disabled={formState.isSubmitting}
>
{formState.isSubmitting && <Spinner />}
Continuar
</Button>
</form>
</Form>
)
}
const currency = new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})
function applyDiscount(
subtotal: number,
discountAmount: number,
discountType: 'FIXED' | 'PERCENT'
) {
if (subtotal <= 0) {
return 0
}
const amount =
discountType === 'PERCENT'
? (subtotal * discountAmount) / 100
: discountAmount
return Math.min(amount, subtotal)
}

View File

@@ -0,0 +1,135 @@
import type { InputHTMLAttributes } from 'react'
import { useRequest, useToggle } from 'ahooks'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@repo/ui/components/ui/button'
import { Input } from '@repo/ui/components/ui/input'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
Popover,
PopoverContent,
PopoverTrigger
} from '@repo/ui/components/ui/popover'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from '@repo/ui/components/ui/form'
export const formSchema = z.object({
coupon: z.string().min(3, { error: 'Digite um cupom válido' }).trim()
})
export type Schema = z.infer<typeof formSchema>
interface DiscountProps extends Omit<
InputHTMLAttributes<HTMLInputElement>,
'value' | 'onChange'
> {
onChange?: (value: any) => void
}
export function Discount({ onChange, ...props }: DiscountProps) {
const form = useForm({
resolver: zodResolver(formSchema)
})
const [open, { toggle, set }] = useToggle()
const { runAsync } = useRequest(
async (coupon) => {
return await fetch(`/~/api/coupons/${coupon}`, {
method: 'GET'
})
},
{ manual: true }
)
const { handleSubmit, control, formState, setError, reset } = form
const onSubmit = async (data: Schema) => {
const r = await runAsync(data.coupon)
if (!r.ok) {
return setError('coupon', { message: 'Cupom inválido' })
}
onChange?.(await r.json())
reset()
set(false)
}
return (
<Popover open={open} onOpenChange={toggle} modal={true}>
<PopoverTrigger asChild>
<Button
tabIndex={-1}
variant="outline"
className="text-xs cursor-pointer h-6 px-2"
type="button"
{...props}
>
Adicionar
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-82">
<Form {...form}>
<form
onSubmit={async (e) => {
e.stopPropagation()
e.preventDefault()
await handleSubmit(onSubmit)(e)
}}
>
<div className="space-y-2.5">
<h4 className="leading-none font-medium">Recebeu um cupom?</h4>
<p className="text-muted-foreground text-sm">
Aplique seu cupom e tenha acesso aos cursos com descontos
exclusivos.
</p>
<FormField
control={control}
name="coupon"
defaultValue=""
render={({ field }) => (
<FormItem className="grid grid-cols-[20%_auto] gap-1">
<FormLabel>Cupom</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage className="col-start-2 " />
</FormItem>
)}
/>
<div className="flex justify-end gap-2.5">
<Button
type="button"
variant="link"
tabIndex={-1}
className="cursor-pointer dark:text-white text-black"
onClick={() => set(false)}
>
Cancelar
</Button>
<Button
type="submit"
className="cursor-pointer"
disabled={formState.isSubmitting}
>
{formState.isSubmitting && <Spinner />}
Aplicar
</Button>
</div>
</div>
</form>
</Form>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,122 @@
import type { Route } from './+types/route'
import { Link } from 'react-router'
import { useToggle } from 'ahooks'
import {
Card,
CardContent,
CardHeader,
CardDescription,
CardTitle
} from '@repo/ui/components/ui/card'
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator
} from '@repo/ui/components/ui/breadcrumb'
import { Switch } from '@repo/ui/components/ui/switch'
import { createSearch } from '@repo/util/meili'
import { cloudflareContext } from '@repo/auth/context'
import { Label } from '@repo/ui/components/ui/label'
import { Assigned } from './assigned'
import { Bulk } from './bulk'
import type { Course } from '../_.$orgid.enrollments.add/data'
export function meta({}: Route.MetaArgs) {
return [{ title: 'Comprar matrículas' }]
}
export async function loader({ params, context, request }: Route.LoaderArgs) {
const cloudflare = context.get(cloudflareContext)
const courses = createSearch<Course>({
index: 'saladeaula_courses',
sort: ['created_at:desc'],
filter: 'unlisted NOT EXISTS',
hitsPerPage: 100,
env: cloudflare.env
})
return { courses }
}
export async function action({ request }: Route.ActionArgs) {
const body = (await request.json()) as object
console.log(body)
}
export default function Route({
loaderData: { courses }
}: Route.ComponentProps) {
const [state, { toggle }] = useToggle('bulk', 'assigned')
const onSubmit = async (data: any) => {
await new Promise((r) => setTimeout(r, 2000))
console.log(data)
}
const props = { courses, onSubmit }
return (
<div className="space-y-2.5">
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink asChild>
<Link to="../enrollments">Matrículas</Link>
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>Comprar matrículas</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<div className="lg:max-w-4xl mx-auto space-y-2.5">
<Card>
<CardHeader>
<CardTitle className="text-2xl">Comprar matrículas</CardTitle>
<CardDescription>
Siga os passos abaixo para comprar novas matrículas.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Label
className="flex flex-row items-center justify-between cursor-pointer
bg-accent/50 hover:bg-accent rounded-lg border p-4
dark:has-aria-checked:border-blue-900
dark:has-aria-checked:bg-blue-950"
>
<div className="grid gap-1.5 font-normal">
<p className="text-sm leading-none font-medium">
Adicionar colaboradores
</p>
<p className="text-muted-foreground text-sm">
Você pode adicionar agora os colaboradores que irão fazer o
curso ou deixar isso para depois.
</p>
</div>
<Switch
checked={state === 'assigned'}
onCheckedChange={toggle}
className="cursor-pointer"
/>
</Label>
{state == 'assigned' ? (
<Assigned {...props} />
) : (
<Bulk {...props} />
)}
</CardContent>
</Card>
</div>
</div>
)
}