add discount

This commit is contained in:
2025-12-25 12:03:13 -03:00
parent 82ab691fbb
commit d0625546c8
4 changed files with 179 additions and 192 deletions

View File

@@ -4,6 +4,7 @@ import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form'
import { useParams } from 'react-router' import { useParams } from 'react-router'
import { ErrorMessage } from '@hookform/error-message' import { ErrorMessage } from '@hookform/error-message'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Form } from '@repo/ui/components/ui/form' import { Form } from '@repo/ui/components/ui/form'
import { import {
@@ -31,6 +32,9 @@ import { ScheduledForInput } from '../_.$orgid.enrollments.add/scheduled-for'
import { Cell } from '../_.$orgid.enrollments.add/route' import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker' import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { UserPicker } from '../_.$orgid.enrollments.add/user-picker' import { UserPicker } from '../_.$orgid.enrollments.add/user-picker'
import { Summary } from './bulk'
import { applyDiscount } from './discount'
import { currency } from './utils'
const emptyRow = { const emptyRow = {
user: undefined, user: undefined,
@@ -38,6 +42,18 @@ const emptyRow = {
scheduled_for: undefined scheduled_for: undefined
} }
const formSchema_ = formSchema.extend({
coupon: z
.object({
code: z.string(),
type: z.enum(['FIXED', 'PERCENT']),
amount: z.number().positive()
})
.optional()
})
type Schema = z.infer<typeof formSchema_>
type AssignedProps = { type AssignedProps = {
onSubmit: (value: any) => void | Promise<void> onSubmit: (value: any) => void | Promise<void>
courses: Promise<{ hits: Course[] }> courses: Promise<{ hits: Course[] }>
@@ -46,10 +62,10 @@ type AssignedProps = {
export function Assigned({ courses, onSubmit }: AssignedProps) { export function Assigned({ courses, onSubmit }: AssignedProps) {
const { orgid } = useParams() const { orgid } = useParams()
const form = useForm({ const form = useForm({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema_),
defaultValues: { enrollments: [emptyRow] } defaultValues: { enrollments: [emptyRow] }
}) })
const { formState, control, handleSubmit } = form const { formState, control, handleSubmit, setValue } = form
const { fields, remove, append } = useFieldArray({ const { fields, remove, append } = useFieldArray({
control, control,
name: 'enrollments' name: 'enrollments'
@@ -58,10 +74,15 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
control, control,
name: 'enrollments' name: 'enrollments'
}) })
const coupon = useWatch({ control, name: 'coupon' })
const subtotal = items.reduce( const subtotal = items.reduce(
(acc, { course }) => acc + (course?.unit_price || 0), (acc, { course }) => acc + (course?.unit_price || 0),
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 onSearch = async (search: string) => {
const params = new URLSearchParams({ q: search }) const params = new URLSearchParams({ q: search })
@@ -70,7 +91,7 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
return hits return hits
} }
const onSubmit_ = async (data: any) => { const onSubmit_ = async (data: Schema) => {
await onSubmit(data) await onSubmit(data)
} }
@@ -193,7 +214,7 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
className="pointer-events-none" className="pointer-events-none"
tabIndex={-1} tabIndex={-1}
readOnly readOnly
value={currency.format(unit_price)} value={currency(unit_price)}
/> />
</InputGroup> </InputGroup>
@@ -226,69 +247,7 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
</Button> </Button>
</div> </div>
{/* Subtotal */} <Summary {...{ total, subtotal, discount, coupon, setValue }} />
<>
<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> </div>
<Separator /> <Separator />
@@ -307,8 +266,3 @@ export function Assigned({ courses, onSubmit }: AssignedProps) {
</Form> </Form>
) )
} }
const currency = new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})

View File

@@ -1,6 +1,12 @@
import { Fragment } from 'react' import { Fragment } from 'react'
import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react' import { MinusIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form' import {
useForm,
useFieldArray,
Controller,
useWatch,
type UseFormSetValue
} from 'react-hook-form'
import { ErrorMessage } from '@hookform/error-message' import { ErrorMessage } from '@hookform/error-message'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod' import { z } from 'zod'
@@ -15,13 +21,14 @@ import { Form } from '@repo/ui/components/ui/form'
import { Button } from '@repo/ui/components/ui/button' import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator' import { Separator } from '@repo/ui/components/ui/separator'
import { Spinner } from '@repo/ui/components/ui/spinner' import { Spinner } from '@repo/ui/components/ui/spinner'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { Abbr } from '@repo/ui/components/abbr'
import { Cell } from '../_.$orgid.enrollments.add/route' import { Cell } from '../_.$orgid.enrollments.add/route'
import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker' import { CoursePicker } from '../_.$orgid.enrollments.add/course-picker'
import { MAX_ITEMS, type Course } from '../_.$orgid.enrollments.add/data' import { MAX_ITEMS, type Course } from '../_.$orgid.enrollments.add/data'
import { Discount } from './discount' import { Discount, applyDiscount } from './discount'
import { Kbd } from '@repo/ui/components/ui/kbd' import { currency } from './utils'
import { Abbr } from '@repo/ui/components/abbr'
const emptyRow = { const emptyRow = {
course: undefined course: undefined
@@ -93,7 +100,7 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
const discount = coupon const discount = coupon
? applyDiscount(subtotal, coupon.amount, coupon.type) * -1 ? applyDiscount(subtotal, coupon.amount, coupon.type) * -1
: 0 : 0
const total = subtotal > 0 ? subtotal - discount : 0 const total = subtotal > 0 ? subtotal + discount : 0
const onSubmit_ = async (data: Schema) => { const onSubmit_ = async (data: Schema) => {
await onSubmit(data) await onSubmit(data)
@@ -277,101 +284,7 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
</Button> </Button>
</div> </div>
{/* Subtotal */} <Summary {...{ total, subtotal, discount, coupon, setValue }} />
<>
<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(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 ? (
<span className="flex gap-1">
Descontos
<Kbd>
<Abbr maxLen={8}>{coupon.code}</Abbr>
</Kbd>
</span>
) : (
<>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(discount)}
tabIndex={-1}
className="pointer-events-none text-muted-foreground"
readOnly
/>
<InputGroupAddon align="inline-end">
{coupon ? (
<InputGroupButton
size="icon-xs"
className="cursor-pointer"
tabIndex={-1}
variant="ghost"
onClick={() => {
setValue('coupon', undefined)
}}
>
<XIcon />
</InputGroupButton>
) : (
<Discount
disabled={subtotal === 0}
onChange={({ sk, discount_amount, discount_type }) => {
setValue('coupon', {
code: 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(total)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
</div> </div>
<Separator /> <Separator />
@@ -391,25 +304,122 @@ export function Bulk({ courses, onSubmit }: BulkProps) {
) )
} }
function currency(value: number) { type SummaryProps = {
return new Intl.NumberFormat('pt-BR', { subtotal: number
style: 'currency', total: number
currency: 'BRL' discount: number
}).format(value) coupon?: {
} code: string
function applyDiscount( type: 'FIXED' | 'PERCENT'
subtotal: number, amount: number
discountAmount: number,
discountType: 'FIXED' | 'PERCENT'
) {
if (subtotal <= 0) {
return 0
} }
setValue: UseFormSetValue<Schema>
const amount = }
discountType === 'PERCENT'
? (subtotal * discountAmount) / 100 export function Summary({
: discountAmount subtotal,
total,
return Math.min(amount, subtotal) discount,
coupon,
setValue
}: SummaryProps) {
return (
<>
{/* 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(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 ? (
<span className="flex gap-1">
Descontos
<Kbd>
<Abbr maxLen={8}>{coupon.code}</Abbr>
</Kbd>
</span>
) : (
<>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(discount)}
tabIndex={-1}
className="pointer-events-none text-muted-foreground"
readOnly
/>
<InputGroupAddon align="inline-end">
{coupon ? (
<InputGroupButton
size="icon-xs"
className="cursor-pointer"
tabIndex={-1}
variant="ghost"
onClick={() => {
setValue('coupon', undefined)
}}
>
<XIcon />
</InputGroupButton>
) : (
<Discount
disabled={subtotal === 0}
onChange={({ sk, discount_amount, discount_type }) => {
setValue('coupon', {
code: 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(total)}
className="pointer-events-none text-muted-foreground"
readOnly
/>
</InputGroup>
</>
</>
)
} }

View File

@@ -134,3 +134,20 @@ export function Discount({ onChange, ...props }: DiscountProps) {
</Popover> </Popover>
) )
} }
export 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,6 @@
export function currency(value: number) {
return new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
}).format(value)
}