Skip to content

Commit

Permalink
feat: english level option on form, update formSchema and fix form em…
Browse files Browse the repository at this point in the history
…pty field error
  • Loading branch information
Luisfp0 committed Oct 21, 2024
1 parent 10c7ab6 commit 8af2f62
Show file tree
Hide file tree
Showing 6 changed files with 177 additions and 103 deletions.
15 changes: 11 additions & 4 deletions apps/web/app/(roles)/formSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ export const formSchema = z
.url({ message: 'URL inválida.' }),
title: z.string({ required_error: 'O título da vaga é obrigatório.' }),
company: z.string({ required_error: 'Sem empresa -> Sem vaga 😶‍🌫️' }),
currency: z.enum(['USD', 'BRL'], { required_error: 'Moeda inválida.' }),
currency: z.enum(['USD', 'BRL', 'EUR'], {
required_error: 'Moeda inválida.',
}),
description: z.string({ required_error: 'Campo obrigatório.' }).nullable(),
language: z.string({ required_error: 'Idioma inválido.' }),
skillsId: z.array(z.string(), {
Expand All @@ -70,10 +72,15 @@ export const formSchema = z
.transform((val) => parseInt(val, 10)),
minSalary: z.number().default(10),
maxSalary: z.number().default(10000),
salaryFrequency: z.enum(['monthly', 'annual'], {
required_error: 'Por favor, selecione a frequência salarial',
}),
salaryFrequency: z.enum(['monthly', 'annual']).default('monthly'),
isSingleValue: z.boolean().default(false),
englishLevel: z.enum(
['Beginner', 'Intermediary', 'Advanced', 'Fluent'] as const,
{
required_error:
'Por favor, selecione o nível de inglês mínimo requerido.',
}
),
companyLogo: z
.any()
.optional()
Expand Down
2 changes: 2 additions & 0 deletions apps/web/app/(roles)/vaga/[id]/RolePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import React from 'react'

export const RolePage = ({ role }) => {
const isEnglish = role.language === 'English'
console.log({ language: role.language })
console.log(isEnglish)

return isEnglish ? <USRolePage role={role} /> : <PTBRRolePage role={role} />
}
Expand Down
60 changes: 32 additions & 28 deletions apps/web/app/(roles)/vagas/publique/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,41 @@ interface SendCompanyLogoParams {

const supabase = getSupabaseClient()

export const createRole = async (roleData: Role, email: string) => {
const { data, error } = await supabase
.from('Roles')
.insert(roleData)
.select()
.single()
export const createRole = async (
roleData: Role,
email: string,
userId: string
) => {
console.log({ roleData })
try {
const { data: newRole, error: roleError } = await supabase
.from('Roles')
.insert(roleData)
.select()
.single()

if (roleError) throw roleError

if (!roleData) throw new Error('Role data is null after insertion')

const { error: ownerError } = await supabase.from('RoleOwner').insert({
roleID: newRole.id,
subscriberID: userId,
})

if (error) throw error

if (data) {
try {
await sendJobCreatedEmail({
email,
id: data.id,
title: data.title,
})
} catch (emailError) {
console.error('Erro ao enviar e-mail:', emailError)
}
}
if (ownerError) throw ownerError

return data
}

export const createRoleOwner = async (roleID: string, subscriberID: string) => {
const { error } = await supabase.from('RoleOwner').insert({
roleID,
subscriberID,
})
await sendJobCreatedEmail({
email,
id: roleData.id,
title: roleData.title,
})

if (error) throw error
return newRole
} catch (error) {
console.error('Error in createRole:', error)
throw error
}
}

export const checkUserHasRoles = async (email: string) => {
Expand Down
43 changes: 29 additions & 14 deletions apps/web/app/(roles)/vagas/publique/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,15 @@ import { LoadingOverlay } from 'app/components/ui/loadingOverlay'
import {
CurrencySelect,
CustomFormField,
EnglishLevelSelect,
LanguageSelect,
TextInput,
} from 'app/components/CustomFormField'
import { SkillsField } from 'app/subscribers/profile/components/SkillsField'

import { useToast } from 'app/hooks/use-toast'
import login from 'app/utils/LoginPreferencesActions'
import {
checkUserHasRoles,
createRole,
createRoleOwner,
sendCompanyLogoToR2,
} from './action'
import { checkUserHasRoles, createRole, sendCompanyLogoToR2 } from './action'

import { FormSchema, formSchema } from 'app/(roles)/formSchema'
import { Database } from 'db'
Expand Down Expand Up @@ -137,6 +133,12 @@ export default function RolesCreate() {
const [hasRoles, setHasRoles] = useState(false)
const [userID, setUserID] = useState('')

const formValues = form.watch()

useEffect(() => {
console.log('Form changed:', formValues)
}, [formValues])

useEffect(() => {
const checkLoginAndRoles = async () => {
const email = localStorage.getItem('loginEmail')
Expand Down Expand Up @@ -180,7 +182,7 @@ export default function RolesCreate() {
}

const roleData: RolesInsert = {
language: formData.language === 'Português' ? 'Portuguese' : 'English',
language: formData.language === 'Portuguese' ? 'Portuguese' : 'English',
country: formData.country,
currency: formData.currency,
description: formData.description,
Expand All @@ -195,24 +197,29 @@ export default function RolesCreate() {
topicId: formData.topicId,
company_logo: company_logo_url,
minimumYears: formData.minimumYears,
englishLevel: formData.englishLevel,
}

const newRole = await createRole(roleData, email)
await createRoleOwner(newRole.id, userID)
console.log('should redirect')
router.push(`/vaga/${newRole.id}`)

form.reset()
const newRole = await createRole(roleData, email, userID)

toast.toast({
title: 'Vaga criada com sucesso!',
description: 'A vaga foi publicada e associada à sua conta.',
})

router.push(`/vaga/${newRole.id}`)
} catch (error) {
console.error('Erro ao criar vaga:', error)

let errorMessage =
'Ocorreu um erro ao criar a vaga. Por favor, tente novamente.'
if (error instanceof Error) {
errorMessage = error.message
}

toast.toast({
title: 'Erro ao criar a vaga',
description: 'Por favor, tente novamente mais tarde.',
description: errorMessage,
variant: 'destructive',
})
}
Expand All @@ -237,6 +244,14 @@ export default function RolesCreate() {
Input={props.Input || TextInput}
/>
))}
<CustomFormField
name="englishLevel"
label="Nível de inglês necessário"
placeholder="Initial, Intermediary..."
description="Insira o nível de inglês necessário"
Input={EnglishLevelSelect}
required
/>
<CustomFormField
name="currency"
label="Câmbio"
Expand Down
158 changes: 102 additions & 56 deletions apps/web/app/components/CustomFormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { format } from 'date-fns'
import { Database } from 'db/src/supabase/type'
import React, { InputHTMLAttributes, useEffect } from 'react'
import {
Controller,
ControllerRenderProps,
FieldValue,
Path,
Expand Down Expand Up @@ -116,13 +117,9 @@ export const TextInput = ({
)
}

export const LanguageSelect = ({
field,
isSubmitting,
placeholder,
name,
}: FormInputProps) => {
const { setValue } = useFormContext()
export const LanguageSelect = ({ placeholder, name }: FormInputProps) => {
const { control } = useFormContext()

const languages: {
value: Database['public']['Enums']['RoleLanguage']
label: string
Expand All @@ -137,36 +134,36 @@ export const LanguageSelect = ({
},
]
return (
<Select
onValueChange={(value) => {
setValue(name, value)
}}
disabled={isSubmitting}
{...(field as ControllerRenderProps)}
>
<SelectTrigger>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Linguagem</SelectLabel>
{languages.map(({ label, value }) => (
<SelectItem value={value} key={value}>
{label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<Controller
name={name}
control={control}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value}
defaultValue={field.value}
>
<SelectTrigger>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Linguagem</SelectLabel>
{languages.map(({ label, value }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
)}
/>
)
}
export const CurrencySelect = ({
field,
isSubmitting,
placeholder,
name,
}: FormInputProps) => {
const { setValue } = useFormContext()
export const CurrencySelect = ({ placeholder, name }: FormInputProps) => {
const { control } = useFormContext()

const languages: {
value: string
label: string
Expand All @@ -185,27 +182,76 @@ export const CurrencySelect = ({
},
]
return (
<Select
onValueChange={(value) => {
setValue(name, value)
}}
disabled={isSubmitting}
{...(field as ControllerRenderProps)}
>
<SelectTrigger>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Moeda</SelectLabel>
{languages.map(({ label, value }) => (
<SelectItem value={value} key={value}>
{label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<Controller
name={name}
control={control}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value}
defaultValue={field.value}
>
<SelectTrigger>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Câmbio</SelectLabel>
{languages.map(({ label, value }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
)}
/>
)
}

export const EnglishLevelSelect = ({
name,
placeholder,
}: {
name: string
placeholder: string
}) => {
const { control } = useFormContext()

const languages = [
{ value: 'Beginner', label: 'Iniciante' },
{ value: 'Intermediary', label: 'Intermediário' },
{ value: 'Advanced', label: 'Avançado' },
{ value: 'Fluent', label: 'Fluente' },
]

return (
<Controller
name={name}
control={control}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value}
defaultValue={field.value}
>
<SelectTrigger>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Nível de inglês</SelectLabel>
{languages.map(({ label, value }) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
)}
/>
)
}

Expand Down
Loading

0 comments on commit 8af2f62

Please sign in to comment.