add steps

This commit is contained in:
2025-12-25 18:11:49 -03:00
parent d0625546c8
commit 0400dc4850
11 changed files with 366 additions and 56 deletions

View File

@@ -0,0 +1,80 @@
import { type ReactNode, createContext, useContext } from 'react'
import { type LucideIcon } from 'lucide-react'
import { cn } from '@repo/ui/lib/utils'
type StepContextValue = {
activeIndex: number
}
const StepContext = createContext<StepContextValue | null>(null)
function useStep() {
const ctx = useContext(StepContext)
if (!ctx) {
throw new Error('StepItem must be used inside <Step />')
}
return ctx
}
export function Step({
children,
className,
activeIndex
}: {
children: ReactNode
className?: string
activeIndex: number
}) {
return (
<StepContext.Provider value={{ activeIndex }}>
<ul
className={cn(
'flex max-lg:flex-col lg:items-center gap-1.5 lg:gap-4',
className
)}
>
{children}
</ul>
</StepContext.Provider>
)
}
export function StepSeparator() {
return (
<div className="max-lg:w-px max-lg:ml-[19px] h-3 lg:h-px lg:w-full bg-foreground/25" />
)
}
export function StepItem({
children,
icon: Icon,
index
}: {
children: ReactNode
icon: LucideIcon
index: number
}) {
const { activeIndex } = useStep()
const active = index === activeIndex
return (
<li
className={cn(
'flex items-center gap-2 flex-none text-muted-foreground',
active && 'dark:text-white'
)}
>
<div
className={cn(
'p-3 rounded-full',
active ? 'bg-primary text-white' : 'bg-accent'
)}
>
<Icon className="size-4" />
</div>
<div className="text-sm">{children}</div>
</li>
)
}

View File

@@ -0,0 +1,76 @@
import React, {
createContext,
useCallback,
useContext,
useMemo,
useState,
type ReactNode,
type ReactElement
} from 'react'
type WizardContextProps = (name: string) => void
const WizardContext = createContext<WizardContextProps | null>(null)
export function useWizard(): WizardContextProps {
const ctx = useContext(WizardContext)
if (!ctx) {
throw new Error('useWizard must be used within <Wizard />')
}
return ctx
}
type WizardProps = {
children: ReactNode
index?: number
onChange?: (index: number) => void
}
export function Wizard({
children,
index: initIndex = 0,
onChange
}: WizardProps) {
const [index, setIndex] = useState<number>(initIndex)
const components = useMemo(
() => React.Children.toArray(children) as ReactElement<WizardStepProps>[],
[children]
)
const steps = useMemo(
() => components.map((child) => child.props.name),
[components]
)
const child = components[index]
const onChange_ = useCallback<WizardContextProps>(
(name) => {
const nextIndex = steps.findIndex((n) => n === name)
if (nextIndex >= 0) {
setIndex(nextIndex)
onChange?.(nextIndex)
}
},
[steps]
)
return (
<WizardContext.Provider value={onChange_}>
{React.isValidElement(child) ? React.cloneElement(child) : child}
</WizardContext.Provider>
)
}
export type WizardStepProps = {
name: string
children: React.ReactNode
}
export function WizardStep({ children }: WizardStepProps) {
return <>{children}</>
}

View File

@@ -58,11 +58,13 @@ export async function loader({ params, context, request }: Route.LoaderArgs) {
})
return {
data: enrollments
enrollments
}
}
export default function Route({ loaderData: { data } }: Route.ComponentProps) {
export default function Route({
loaderData: { enrollments }
}: Route.ComponentProps) {
const { orgid } = useParams()
const [searchParams, setSearchParams] = useSearchParams()
const [selectedRows, setSelectedRows] = useState<Enrollment[]>([])
@@ -80,7 +82,7 @@ export default function Route({ loaderData: { data } }: Route.ComponentProps) {
</p>
</div>
<Await resolve={data}>
<Await resolve={enrollments}>
{({ hits, page = 1, hitsPerPage, totalHits }) => (
<DataTable
sort={[{ id: 'created_at', desc: true }]}
@@ -88,9 +90,9 @@ export default function Route({ loaderData: { data } }: Route.ComponentProps) {
data={hits as Enrollment[]}
columnPinning={{ left: ['select'], right: ['action'] }}
pageIndex={page - 1}
pageSize={hitsPerPage}
pageSize={Number(hitsPerPage)}
setSelectedRows={setSelectedRows}
rowCount={totalHits}
rowCount={Number(totalHits)}
columnVisibilityInit={{
created_at: true,
completed_at: false,

View File

@@ -35,6 +35,7 @@ import { UserPicker } from '../_.$orgid.enrollments.add/user-picker'
import { Summary } from './bulk'
import { applyDiscount } from './discount'
import { currency } from './utils'
import { useWizard } from '@/components/wizard'
const emptyRow = {
user: undefined,
@@ -42,7 +43,7 @@ const emptyRow = {
scheduled_for: undefined
}
const formSchema_ = formSchema.extend({
const formSchemaAssigned = formSchema.extend({
coupon: z
.object({
code: z.string(),
@@ -52,7 +53,7 @@ const formSchema_ = formSchema.extend({
.optional()
})
type Schema = z.infer<typeof formSchema_>
type Schema = z.infer<typeof formSchemaAssigned>
type AssignedProps = {
onSubmit: (value: any) => void | Promise<void>
@@ -60,9 +61,10 @@ type AssignedProps = {
}
export function Assigned({ courses, onSubmit }: AssignedProps) {
const wizard = useWizard()
const { orgid } = useParams()
const form = useForm({
resolver: zodResolver(formSchema_),
resolver: zodResolver(formSchemaAssigned),
defaultValues: { enrollments: [emptyRow] }
})
const { formState, control, handleSubmit, setValue } = form
@@ -79,10 +81,6 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
(acc, { course }) => acc + (course?.unit_price || 0),
0
)
const discount = coupon
? applyDiscount(subtotal, coupon.amount, coupon.type) * -1
: 0
const total = subtotal > 0 ? subtotal + discount : 0
const onSearch = async (search: string) => {
const params = new URLSearchParams({ q: search })
@@ -93,6 +91,7 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
const onSubmit_ = async (data: Schema) => {
await onSubmit(data)
wizard('payment')
}
return (
@@ -247,7 +246,8 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
</Button>
</div>
<Summary {...{ total, subtotal, discount, coupon, setValue }} />
{/* Summary */}
<Summary {...{ subtotal, coupon, setValue }} />
</div>
<Separator />

View File

@@ -29,6 +29,7 @@ import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { MAX_ITEMS, type Course } from '../_.$orgid.enrollments.add/data'
import { Discount, applyDiscount } from './discount'
import { currency } from './utils'
import { useWizard } from '@/components/wizard'
const emptyRow = {
course: undefined
@@ -68,6 +69,7 @@ const formSchema = z.object({
type Schema = z.infer<typeof formSchema>
export function Bulk({ courses, onSubmit }: BulkProps) {
const wizard = useWizard()
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: { items: [emptyRow] }
@@ -97,13 +99,10 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
(Number.isFinite(quantity) && quantity > 0 ? quantity : 1),
0
)
const discount = coupon
? applyDiscount(subtotal, coupon.amount, coupon.type) * -1
: 0
const total = subtotal > 0 ? subtotal + discount : 0
const onSubmit_ = async (data: Schema) => {
await onSubmit(data)
wizard('payment')
}
return (
@@ -284,7 +283,7 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
</Button>
</div>
<Summary {...{ total, subtotal, discount, coupon, setValue }} />
<Summary {...{ subtotal, coupon, setValue }} />
</div>
<Separator />
@@ -306,23 +305,20 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
type SummaryProps = {
subtotal: number
total: number
discount: number
coupon?: {
code: string
type: 'FIXED' | 'PERCENT'
amount: number
}
setValue: UseFormSetValue<Schema>
setValue: UseFormSetValue<any>
}
export function Summary({
subtotal,
total,
discount,
coupon,
setValue
}: SummaryProps) {
export function Summary({ subtotal, coupon, setValue }: SummaryProps) {
const discount = coupon
? applyDiscount(subtotal, coupon.amount, coupon.type) * -1
: 0
const total = subtotal > 0 ? subtotal + discount : 0
return (
<>
{/* Subtotal */}

View File

@@ -0,0 +1,42 @@
import { Button } from '@repo/ui/components/ui/button'
import { Label } from '@repo/ui/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@repo/ui/components/ui/radio-group'
import { Separator } from '@repo/ui/components/ui/separator'
export function Payment() {
return (
<>
<RadioGroup
defaultValue="comfortable"
className="lg:flex *:p-5 *:border *:rounded-xl *:flex-1 *:cursor-pointer
*:bg-accent/25 *:has-[button[data-state=checked]]:bg-accent"
>
<Label>
<RadioGroupItem value="default" id="r1" />
<span>Pix</span>
</Label>
<Label>
<RadioGroupItem value="comfortable" id="r2" />
<span>Boleto bancário</span>
</Label>
<Label>
<RadioGroupItem value="compact" id="r3" />
<span>Cartão de crédito</span>
</Label>
</RadioGroup>
<Separator />
<div className="flex justify-end">
<Button
type="submit"
className="cursor-pointer"
// disabled={formState.isSubmitting}
>
{/*{formState.isSubmitting && <Spinner />}*/}
Continuar
</Button>
</div>
</>
)
}

View File

@@ -2,6 +2,7 @@ import type { Route } from './+types/route'
import { Link } from 'react-router'
import { useToggle } from 'ahooks'
import { BookSearchIcon, CircleCheckBigIcon, WalletIcon } from 'lucide-react'
import {
Card,
@@ -23,9 +24,13 @@ import { createSearch } from '@repo/util/meili'
import { cloudflareContext } from '@repo/auth/context'
import { Label } from '@repo/ui/components/ui/label'
import { Wizard, WizardStep } from '@/components/wizard'
import { Step, StepItem, StepSeparator } from '@/components/step'
import type { Course } from '../_.$orgid.enrollments.add/data'
import { Assigned } from './assigned'
import { Bulk } from './bulk'
import type { Course } from '../_.$orgid.enrollments.add/data'
import { Payment } from './payment'
import { useState } from 'react'
export function meta({}: Route.MetaArgs) {
return [{ title: 'Comprar matrículas' }]
@@ -52,10 +57,11 @@ export async function action({ request }: Route.ActionArgs) {
export default function Route({
loaderData: { courses }
}: Route.ComponentProps) {
const [index, setIndex] = useState(0)
const [state, { toggle }] = useToggle('bulk', 'assigned')
const onSubmit = async (data: any) => {
await new Promise((r) => setTimeout(r, 2000))
// await new Promise((r) => setTimeout(r, 2000))
console.log(data)
}
@@ -87,33 +93,55 @@ export default function Route({
</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>
<Step className="mb-6" activeIndex={index}>
<StepItem index={0} icon={BookSearchIcon}>
Escolher cursos
</StepItem>
<StepSeparator />
<StepItem index={1} icon={WalletIcon}>
Pagamento
</StepItem>
<StepSeparator />
<StepItem index={2} icon={CircleCheckBigIcon}>
Revisão &amp; confirmação
</StepItem>
</Step>
{state == 'assigned' ? (
<Assigned {...props} />
) : (
<Bulk {...props} />
)}
<Wizard onChange={setIndex}>
<WizardStep name="courses">
<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} />
)}
</WizardStep>
<WizardStep name="payment">
<Payment />
</WizardStep>
</Wizard>
</CardContent>
</Card>
</div>