add checkout

This commit is contained in:
2025-12-23 10:56:38 -03:00
parent a524666837
commit 6eff69f168
12 changed files with 840 additions and 356 deletions

View File

@@ -0,0 +1,176 @@
import { Fragment } from 'react'
import { Trash2Icon, PlusIcon } 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, 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 {
MAX_ITEMS,
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 = {
courses: Promise<{ hits: Course[] }>
}
export function Assigned({ courses }: AssignedProps) {
const { orgid } = useParams()
const form = useForm({
// resolver: zodResolver(formSchema),
defaultValues: { enrollments: [emptyRow] }
})
const { formState, control, handleSubmit, getValues, watch } = form
const { fields, insert, remove, append } = useFieldArray({
control,
name: 'enrollments'
})
const items = useWatch({
control,
name: 'enrollments'
})
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
}
return (
<Form {...form}>
<div className="grid w-full gap-1.5 lg:grid-cols-[repeat(4,1fr)_auto]">
{/* Header */}
<>
<Cell>Colaborador</Cell>
<Cell>Curso</Cell>
<Cell>Matricular em</Cell>
<Cell>Valor unit.</Cell>
<Cell>{/**/}</Cell>
</>
{/* Rows */}
{fields.map((field, index) => {
const course = items?.[index]?.course
return (
<Fragment key={field.id}>
<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>
)}
/>
<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}
/>
<ErrorMessage
errors={formState.errors}
name={name}
render={({ message }) => (
<p className="text-destructive text-sm">{message}</p>
)}
/>
</div>
)}
/>
<Controller
control={control}
name={`enrollments.${index}.scheduled_for`}
render={({ field: { value, onChange } }) => (
<ScheduledForInput value={value} onChange={onChange} />
)}
/>
<InputGroup>
{/*<InputGroupAddon>
<InputGroupText>R$</InputGroupText>
</InputGroupAddon>*/}
<InputGroupInput
className="pointer-events-none"
value={currency.format(course?.unit_price || 0)}
/>
</InputGroup>
<Button
tabIndex={-1}
variant="destructive"
className="cursor-pointer"
disabled={fields.length == 1}
onClick={() => remove(index)}
>
<Trash2Icon />
</Button>
</Fragment>
)
})}
</div>
<Button
type="button"
// @ts-ignore
onClick={() => append(emptyRow)}
className="cursor-pointer"
disabled={fields.length == MAX_ITEMS}
variant="outline"
size="sm"
>
<PlusIcon /> Adicionar
</Button>
<Separator />
<Button type="submit" className="cursor-pointer">
Continuar
</Button>
</Form>
)
}
const currency = new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})

View File

@@ -0,0 +1,162 @@
import { Fragment } from 'react'
import { PlusIcon, Trash2Icon } 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 { Form } from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import { Button } from '@repo/ui/components/ui/button'
import { InputGroup, InputGroupInput } from '@repo/ui/components/ui/input-group'
import { Separator } from '@repo/ui/components/ui/separator'
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'
const emptyRow = {
course: undefined,
quantity: undefined
}
type BulkProps = {
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()
})
const formSchema = z.object({
items: z.array(item).min(1).max(MAX_ITEMS)
})
type Schema = z.infer<typeof formSchema>
export function Bulk({ courses }: BulkProps) {
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: { items: [emptyRow] }
})
const { formState, control, handleSubmit } = form
const { fields, remove, append } = useFieldArray({
control,
name: 'items'
})
const items = useWatch({
control,
name: 'items'
})
const onSubmit = async (data: Schema) => {
console.log(data)
}
return (
<Form {...form}>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="grid w-full gap-1.5 lg:grid-cols-[repeat(3,1fr)_auto]">
{/* Header */}
<>
<Cell>Curso</Cell>
<Cell>Quantidade</Cell>
<Cell>Valor unit.</Cell>
<Cell>{/**/}</Cell>
</>
{/* Rows */}
{fields.map((field, index) => {
const course = items?.[index]?.course
return (
<Fragment key={field.id}>
<Controller
control={control}
name={`items.${index}.course`}
render={({
field: { name, value, onChange },
fieldState
}) => (
<div className="grid gap-1">
<CoursePicker
value={value}
onChange={onChange}
options={courses}
error={fieldState.error}
/>
<ErrorMessage
errors={formState.errors}
name={name}
render={({ message }) => (
<p className="text-destructive text-sm">{message}</p>
)}
/>
</div>
)}
/>
<Input type="number" defaultValue={1} />
<InputGroup>
{/*<InputGroupAddon>
<InputGroupText>R$</InputGroupText>
</InputGroupAddon>*/}
<InputGroupInput
className="pointer-events-none"
value={currency.format(course?.unit_price || 0)}
/>
</InputGroup>
<Button
tabIndex={-1}
variant="destructive"
className="cursor-pointer"
disabled={fields.length == 1}
onClick={() => remove(index)}
>
<Trash2Icon />
</Button>
</Fragment>
)
})}
</div>
<Button
type="button"
// @ts-ignore
onClick={() => append(emptyRow)}
className="cursor-pointer"
disabled={fields.length == MAX_ITEMS}
variant="outline"
size="sm"
>
<PlusIcon /> Adicionar
</Button>
<Separator />
<Button type="submit" className="cursor-pointer">
Continuar
</Button>
</form>
</Form>
)
}
const currency = new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})

View File

@@ -1,15 +1,83 @@
import { Card, CardContent } from '@repo/ui/components/ui/card'
import type { Route } from './+types/route'
import { useToggle } from 'ahooks'
import {
Card,
CardContent,
CardHeader,
CardDescription,
CardTitle
} from '@repo/ui/components/ui/card'
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'
export function meta({}: Route.MetaArgs) {
return [{ title: '' }]
}
export default function Route() {
export async function loader({ params, context, request }: Route.LoaderArgs) {
const cloudflare = context.get(cloudflareContext)
const courses = createSearch({
index: 'saladeaula_courses',
sort: ['created_at:desc'],
filter: 'unlisted NOT EXISTS',
hitsPerPage: 100,
env: cloudflare.env
})
return { courses }
}
export default function Route({
loaderData: { courses }
}: Route.ComponentProps) {
const [state, { toggle }] = useToggle('bulk', 'assigned')
return (
<div className="lg:max-w-4xl mx-auto space-y-2.5">
<Card>
<CardContent>,,,</CardContent>
<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
bg-accent/50 rounded-lg border p-4 cursor-pointer
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 para fazer isso depois.
</p>
</div>
<Switch
checked={state === 'assigned'}
onCheckedChange={toggle}
className="cursor-pointer"
/>
</Label>
{state == 'assigned' ? (
<Assigned courses={courses} />
) : (
<Bulk courses={courses} />
)}
</CardContent>
</Card>
</div>
)