add discount
This commit is contained in:
@@ -15,7 +15,7 @@ from aws_lambda_powertools.utilities.typing import LambdaContext
|
|||||||
from api_gateway import JSONResponse
|
from api_gateway import JSONResponse
|
||||||
from json_encoder import JSONEncoder
|
from json_encoder import JSONEncoder
|
||||||
from middlewares.authentication_middleware import AuthenticationMiddleware
|
from middlewares.authentication_middleware import AuthenticationMiddleware
|
||||||
from routes import courses, enrollments, orders, orgs, users
|
from routes import coupons, courses, enrollments, orders, orgs, users
|
||||||
|
|
||||||
logger = Logger(__name__)
|
logger = Logger(__name__)
|
||||||
tracer = Tracer()
|
tracer = Tracer()
|
||||||
@@ -35,6 +35,7 @@ app = APIGatewayHttpResolver(
|
|||||||
)
|
)
|
||||||
app.use(middlewares=[AuthenticationMiddleware()])
|
app.use(middlewares=[AuthenticationMiddleware()])
|
||||||
app.enable_swagger(path='/swagger')
|
app.enable_swagger(path='/swagger')
|
||||||
|
app.include_router(coupons.router, prefix='/coupons')
|
||||||
app.include_router(courses.router, prefix='/courses')
|
app.include_router(courses.router, prefix='/courses')
|
||||||
app.include_router(enrollments.router, prefix='/enrollments')
|
app.include_router(enrollments.router, prefix='/enrollments')
|
||||||
app.include_router(enrollments.cancel, prefix='/enrollments')
|
app.include_router(enrollments.cancel, prefix='/enrollments')
|
||||||
|
|||||||
25
api.saladeaula.digital/app/routes/coupons/__init__.py
Normal file
25
api.saladeaula.digital/app/routes/coupons/__init__.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from aws_lambda_powertools.event_handler.api_gateway import Router
|
||||||
|
from aws_lambda_powertools.event_handler.exceptions import (
|
||||||
|
NotFoundError,
|
||||||
|
)
|
||||||
|
from aws_lambda_powertools.event_handler.openapi.params import Path
|
||||||
|
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
|
||||||
|
|
||||||
|
from boto3clients import dynamodb_client
|
||||||
|
from config import ORDER_TABLE
|
||||||
|
|
||||||
|
router = Router()
|
||||||
|
dyn = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)
|
||||||
|
|
||||||
|
|
||||||
|
class CouponNotFoundError(NotFoundError): ...
|
||||||
|
|
||||||
|
|
||||||
|
@router.get('/<coupon>')
|
||||||
|
def coupon(coupon: Annotated[str, Path(min_length=3)]):
|
||||||
|
return dyn.collection.get_item(
|
||||||
|
KeyPair('COUPON', coupon.upper()),
|
||||||
|
exc_cls=CouponNotFoundError,
|
||||||
|
)
|
||||||
@@ -17,6 +17,7 @@ SK = 'sk'
|
|||||||
def pytest_configure():
|
def pytest_configure():
|
||||||
os.environ['TZ'] = 'America/Sao_Paulo'
|
os.environ['TZ'] = 'America/Sao_Paulo'
|
||||||
os.environ['COURSE_TABLE'] = PYTEST_TABLE_NAME
|
os.environ['COURSE_TABLE'] = PYTEST_TABLE_NAME
|
||||||
|
os.environ['ORDER_TABLE'] = PYTEST_TABLE_NAME
|
||||||
os.environ['USER_TABLE'] = PYTEST_TABLE_NAME
|
os.environ['USER_TABLE'] = PYTEST_TABLE_NAME
|
||||||
os.environ['ENROLLMENT_TABLE'] = PYTEST_TABLE_NAME
|
os.environ['ENROLLMENT_TABLE'] = PYTEST_TABLE_NAME
|
||||||
os.environ['BUCKET_NAME'] = 'saladeaula.digital'
|
os.environ['BUCKET_NAME'] = 'saladeaula.digital'
|
||||||
|
|||||||
19
api.saladeaula.digital/tests/routes/test_coupons.py
Normal file
19
api.saladeaula.digital/tests/routes/test_coupons.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from http import HTTPMethod, HTTPStatus
|
||||||
|
|
||||||
|
from ..conftest import HttpApiProxy, LambdaContext
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_coupon(
|
||||||
|
app,
|
||||||
|
seeds,
|
||||||
|
http_api_proxy: HttpApiProxy,
|
||||||
|
lambda_context: LambdaContext,
|
||||||
|
):
|
||||||
|
r = app.lambda_handler(
|
||||||
|
http_api_proxy(
|
||||||
|
raw_path='/coupons/10off',
|
||||||
|
method=HTTPMethod.GET,
|
||||||
|
),
|
||||||
|
lambda_context,
|
||||||
|
)
|
||||||
|
assert r['statusCode'] == HTTPStatus.OK
|
||||||
@@ -39,3 +39,8 @@
|
|||||||
|
|
||||||
// Course scormset
|
// Course scormset
|
||||||
{"id": "c27d1b4f-575c-4b6b-82a1-9b91ff369e0b", "sk": "SCORMSET#76c75561-d972-43ef-9818-497d8fc6edbe", "packages": [{"version": "1.2", "scormdriver": "s3://saladeaula.digital/scorm/nr-33-espacos-confinados-conteudo-de-demonstracao-scorm12/scormdriver/indexAPI.html"}]}
|
{"id": "c27d1b4f-575c-4b6b-82a1-9b91ff369e0b", "sk": "SCORMSET#76c75561-d972-43ef-9818-497d8fc6edbe", "packages": [{"version": "1.2", "scormdriver": "s3://saladeaula.digital/scorm/nr-33-espacos-confinados-conteudo-de-demonstracao-scorm12/scormdriver/indexAPI.html"}]}
|
||||||
|
|
||||||
|
|
||||||
|
// Discounts
|
||||||
|
{"id": "COUPON", "sk": "PRIMEIRACOMPRA", "discount_amount": 15, "discount_type": "FIXED", "created_at": "2025-12-24T00:05:27-03:00"}
|
||||||
|
{"id": "COUPON", "sk": "10OFF", "discount_amount": 10, "discount_type": "PERCENT", "created_at": "2025-12-24T00:05:27-03:00"}
|
||||||
|
|||||||
@@ -3,6 +3,5 @@ import type { Route } from './+types/route'
|
|||||||
import { redirect } from 'react-router'
|
import { redirect } from 'react-router'
|
||||||
|
|
||||||
export async function loader({ params }: Route.LoaderArgs) {
|
export async function loader({ params }: Route.LoaderArgs) {
|
||||||
const { orgid } = params
|
throw redirect(`/${params.orgid}/main`)
|
||||||
throw redirect(`/${orgid}/main`)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -230,6 +230,7 @@ function List({ items, search }) {
|
|||||||
<TableHead>Valor unit.</TableHead>
|
<TableHead>Valor unit.</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
|
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{charges?.map(
|
{charges?.map(
|
||||||
(
|
(
|
||||||
@@ -306,6 +307,7 @@ function List({ items, search }) {
|
|||||||
<Currency>{subtotal}</Currency>
|
<Currency>{subtotal}</Currency>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
|
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell colSpan={4} className="text-right pointer-events-none">
|
<TableCell colSpan={4} className="text-right pointer-events-none">
|
||||||
Descontos
|
Descontos
|
||||||
@@ -314,6 +316,7 @@ function List({ items, search }) {
|
|||||||
<Currency>{discounts}</Currency>
|
<Currency>{discounts}</Currency>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
|
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell colSpan={4} className="text-right pointer-events-none">
|
<TableCell colSpan={4} className="text-right pointer-events-none">
|
||||||
Total
|
Total
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
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'
|
|
||||||
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 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>
|
|
||||||
<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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -62,12 +62,6 @@ export async function loader({ params, context, request }: Route.LoaderArgs) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatted = new Intl.DateTimeFormat('en-CA', {
|
|
||||||
year: 'numeric',
|
|
||||||
month: '2-digit',
|
|
||||||
day: '2-digit'
|
|
||||||
})
|
|
||||||
|
|
||||||
export default function Route({ loaderData: { data } }: Route.ComponentProps) {
|
export default function Route({ loaderData: { data } }: Route.ComponentProps) {
|
||||||
const { orgid } = useParams()
|
const { orgid } = useParams()
|
||||||
const [searchParams, setSearchParams] = useSearchParams()
|
const [searchParams, setSearchParams] = useSearchParams()
|
||||||
@@ -176,6 +170,12 @@ export default function Route({ loaderData: { data } }: Route.ComponentProps) {
|
|||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
onChange={(props) => {
|
onChange={(props) => {
|
||||||
|
const dt = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit'
|
||||||
|
})
|
||||||
|
|
||||||
setSearchParams((searchParams) => {
|
setSearchParams((searchParams) => {
|
||||||
if (!props) {
|
if (!props) {
|
||||||
searchParams.delete('from')
|
searchParams.delete('from')
|
||||||
@@ -187,12 +187,9 @@ export default function Route({ loaderData: { data } }: Route.ComponentProps) {
|
|||||||
|
|
||||||
searchParams.set(
|
searchParams.set(
|
||||||
'from',
|
'from',
|
||||||
`${rangeField}:${formatted.format(dateRange?.from)}`
|
`${rangeField}:${dt.format(dateRange?.from)}`
|
||||||
)
|
|
||||||
searchParams.set(
|
|
||||||
'to',
|
|
||||||
formatted.format(dateRange?.to)
|
|
||||||
)
|
)
|
||||||
|
searchParams.set('to', dt.format(dateRange?.to))
|
||||||
|
|
||||||
return searchParams
|
return searchParams
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -65,7 +65,6 @@ import {
|
|||||||
MAX_ITEMS,
|
MAX_ITEMS,
|
||||||
formSchema,
|
formSchema,
|
||||||
type Schema,
|
type Schema,
|
||||||
type Course,
|
|
||||||
type User,
|
type User,
|
||||||
type Enrolled
|
type Enrolled
|
||||||
} from './data'
|
} from './data'
|
||||||
@@ -405,7 +404,7 @@ function DuplicateRowMultipleTimes({
|
|||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
|
|
||||||
<PopoverContent align={isMobile ? 'start' : 'end'} className="w-82">
|
<PopoverContent align={isMobile ? 'center' : 'end'} className="w-82">
|
||||||
<form
|
<form
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import {
|
|||||||
} from '@repo/ui/components/ui/input-group'
|
} from '@repo/ui/components/ui/input-group'
|
||||||
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 { Kbd } from '@repo/ui/components/ui/kbd'
|
||||||
|
import { Spinner } from '@repo/ui/components/ui/spinner'
|
||||||
import {
|
import {
|
||||||
HoverCard,
|
HoverCard,
|
||||||
HoverCardContent,
|
HoverCardContent,
|
||||||
@@ -29,7 +31,6 @@ 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 { Kbd } from '@repo/ui/components/ui/kbd'
|
|
||||||
|
|
||||||
const emptyRow = {
|
const emptyRow = {
|
||||||
user: undefined,
|
user: undefined,
|
||||||
@@ -38,10 +39,11 @@ const emptyRow = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AssignedProps = {
|
type AssignedProps = {
|
||||||
|
onSubmit: (value: any) => void | Promise<void>
|
||||||
courses: Promise<{ hits: Course[] }>
|
courses: Promise<{ hits: Course[] }>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Assigned({ courses }: 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),
|
||||||
@@ -68,13 +70,13 @@ export function Assigned({ courses }: AssignedProps) {
|
|||||||
return hits
|
return hits
|
||||||
}
|
}
|
||||||
|
|
||||||
const onSubmit = async (data: any) => {
|
const onSubmit_ = async (data: any) => {
|
||||||
console.log(data)
|
await onSubmit(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
<form onSubmit={handleSubmit(onSubmit_)} className="space-y-4">
|
||||||
<div className="grid w-full gap-1.5 lg:grid-cols-[3fr_3fr_2fr_2fr_auto]">
|
<div className="grid w-full gap-1.5 lg:grid-cols-[3fr_3fr_2fr_2fr_auto]">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<>
|
<>
|
||||||
@@ -291,7 +293,12 @@ export function Assigned({ courses }: AssignedProps) {
|
|||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<Button type="submit" className="cursor-pointer">
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="cursor-pointer"
|
||||||
|
disabled={formState.isSubmitting}
|
||||||
|
>
|
||||||
|
{formState.isSubmitting && <Spinner />}
|
||||||
Continuar
|
Continuar
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Fragment } from 'react'
|
import { Fragment } from 'react'
|
||||||
import { MinusIcon, PlusIcon, Trash2Icon } 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 } 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'
|
||||||
@@ -11,20 +11,22 @@ import {
|
|||||||
InputGroupButton,
|
InputGroupButton,
|
||||||
InputGroupInput
|
InputGroupInput
|
||||||
} from '@repo/ui/components/ui/input-group'
|
} from '@repo/ui/components/ui/input-group'
|
||||||
import { Input } from '@repo/ui/components/ui/input'
|
|
||||||
import { Form } from '@repo/ui/components/ui/form'
|
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 { 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'
|
||||||
|
|
||||||
const emptyRow = {
|
const emptyRow = {
|
||||||
course: undefined
|
course: undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
type BulkProps = {
|
type BulkProps = {
|
||||||
|
onSubmit: (value: any) => void | Promise<void>
|
||||||
courses: Promise<{ hits: Course[] }>
|
courses: Promise<{ hits: Course[] }>
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,12 +46,19 @@ const item = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
items: z.array(item).min(1).max(MAX_ITEMS)
|
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>
|
type Schema = z.infer<typeof formSchema>
|
||||||
|
|
||||||
export function Bulk({ courses }: BulkProps) {
|
export function Bulk({ courses, onSubmit }: BulkProps) {
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: { items: [emptyRow] }
|
defaultValues: { items: [emptyRow] }
|
||||||
@@ -71,6 +80,7 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
control,
|
control,
|
||||||
name: 'items'
|
name: 'items'
|
||||||
})
|
})
|
||||||
|
const coupon = useWatch({ control, name: 'coupon' })
|
||||||
const subtotal = items.reduce(
|
const subtotal = items.reduce(
|
||||||
(acc, { course, quantity }) =>
|
(acc, { course, quantity }) =>
|
||||||
acc +
|
acc +
|
||||||
@@ -78,14 +88,18 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
(Number.isFinite(quantity) && quantity > 0 ? quantity : 1),
|
(Number.isFinite(quantity) && quantity > 0 ? quantity : 1),
|
||||||
0
|
0
|
||||||
)
|
)
|
||||||
|
const discount = coupon
|
||||||
|
? applyDiscount(subtotal, coupon.amount, coupon.type)
|
||||||
|
: 0
|
||||||
|
const total = subtotal > 0 ? subtotal - discount : 0
|
||||||
|
|
||||||
const onSubmit = async (data: Schema) => {
|
const onSubmit_ = async (data: Schema) => {
|
||||||
console.log(data)
|
await onSubmit(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
<form onSubmit={handleSubmit(onSubmit_)} className="space-y-4">
|
||||||
<div className="grid w-full gap-1.5 lg:grid-cols-[4fr_2fr_2fr_2fr_auto]">
|
<div className="grid w-full gap-1.5 lg:grid-cols-[4fr_2fr_2fr_2fr_auto]">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<>
|
<>
|
||||||
@@ -272,6 +286,7 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
Subtotal
|
Subtotal
|
||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
|
tabIndex={-1}
|
||||||
name="subtotal"
|
name="subtotal"
|
||||||
value={currency.format(subtotal)}
|
value={currency.format(subtotal)}
|
||||||
className="pointer-events-none text-muted-foreground"
|
className="pointer-events-none text-muted-foreground"
|
||||||
@@ -283,26 +298,46 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
{/* Discount */}
|
{/* Discount */}
|
||||||
<>
|
<>
|
||||||
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
|
<div className="col-start-3 flex items-center justify-end text-sm font-medium max-lg:hidden">
|
||||||
Cupom
|
{coupon ? <>Descontos</> : <>Cupom</>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<InputGroup>
|
<InputGroup>
|
||||||
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
|
<InputGroupAddon className="border-r pr-2.5 w-1/3 lg:hidden justify-end">
|
||||||
Cupom
|
{coupon ? <>Descontos</> : <>Cupom</>}
|
||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
|
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
name="discount"
|
name="discount"
|
||||||
value={currency.format(0)}
|
value={currency.format(discount * -1)}
|
||||||
|
tabIndex={-1}
|
||||||
className="pointer-events-none text-muted-foreground"
|
className="pointer-events-none text-muted-foreground"
|
||||||
readOnly
|
readOnly
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<InputGroupAddon align="inline-end">
|
<InputGroupAddon align="inline-end">
|
||||||
<Button
|
{coupon ? (
|
||||||
variant="outline"
|
<InputGroupButton
|
||||||
className="text-xs cursor-pointer h-6 px-2"
|
size="icon-xs"
|
||||||
type="button"
|
className="cursor-pointer"
|
||||||
>
|
variant="ghost"
|
||||||
Adicionar
|
onClick={() => {
|
||||||
</Button>
|
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>
|
</InputGroupAddon>
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</>
|
</>
|
||||||
@@ -318,7 +353,8 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
name="total"
|
name="total"
|
||||||
value={currency.format(subtotal)}
|
tabIndex={-1}
|
||||||
|
value={currency.format(total)}
|
||||||
className="pointer-events-none text-muted-foreground"
|
className="pointer-events-none text-muted-foreground"
|
||||||
readOnly
|
readOnly
|
||||||
/>
|
/>
|
||||||
@@ -328,7 +364,12 @@ export function Bulk({ courses }: BulkProps) {
|
|||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<Button type="submit" className="cursor-pointer">
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="cursor-pointer"
|
||||||
|
disabled={formState.isSubmitting}
|
||||||
|
>
|
||||||
|
{formState.isSubmitting && <Spinner />}
|
||||||
Continuar
|
Continuar
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
@@ -340,3 +381,20 @@ const currency = new Intl.NumberFormat('pt-BR', {
|
|||||||
style: 'currency',
|
style: 'currency',
|
||||||
currency: 'BRL'
|
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)
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -101,6 +101,7 @@ export default function Route({ loaderData }: Route.ComponentProps) {
|
|||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
<div className="container mx-auto relative max-w-7xl">
|
<div className="container mx-auto relative max-w-7xl">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
|
|
||||||
<Toaster
|
<Toaster
|
||||||
position="top-center"
|
position="top-center"
|
||||||
richColors={true}
|
richColors={true}
|
||||||
|
|||||||
@@ -7,16 +7,14 @@ import {
|
|||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuCheckboxItem,
|
DropdownMenuCheckboxItem,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger
|
DropdownMenuTrigger
|
||||||
} from '@repo/ui/components/ui/dropdown-menu'
|
} from '@repo/ui/components/ui/dropdown-menu'
|
||||||
import { cn } from '@repo/ui/lib/utils'
|
import { cn } from '@repo/ui/lib/utils'
|
||||||
import { useDataTable } from './data-table'
|
import { useDataTable } from './data-table'
|
||||||
|
|
||||||
export function DataTableViewOptions<TData>({
|
export function DataTableViewOptions({ className }: { className?: string }) {
|
||||||
className
|
|
||||||
}: {
|
|
||||||
className?: string
|
|
||||||
}) {
|
|
||||||
const { table } = useDataTable()
|
const { table } = useDataTable()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -26,7 +24,12 @@ export function DataTableViewOptions<TData>({
|
|||||||
<Columns2Icon /> Colunas
|
<Columns2Icon /> Colunas
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-44 *:cursor-pointer">
|
<DropdownMenuContent align="end" className="w-44">
|
||||||
|
<DropdownMenuLabel className="text-muted-foreground text-sm">
|
||||||
|
Exibir colunas
|
||||||
|
</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
|
||||||
{table
|
{table
|
||||||
.getAllColumns()
|
.getAllColumns()
|
||||||
.filter(
|
.filter(
|
||||||
@@ -43,6 +46,7 @@ export function DataTableViewOptions<TData>({
|
|||||||
checked={column.getIsVisible()}
|
checked={column.getIsVisible()}
|
||||||
onSelect={(e) => e.preventDefault()}
|
onSelect={(e) => e.preventDefault()}
|
||||||
onCheckedChange={(value) => column.toggleVisibility(!!value)}
|
onCheckedChange={(value) => column.toggleVisibility(!!value)}
|
||||||
|
className="cursor-pointer"
|
||||||
>
|
>
|
||||||
{title}
|
{title}
|
||||||
</DropdownMenuCheckboxItem>
|
</DropdownMenuCheckboxItem>
|
||||||
|
|||||||
Reference in New Issue
Block a user