Skip to content

Commit

Permalink
feat: implemented create role in supabase and createRoleOwner
Browse files Browse the repository at this point in the history
  • Loading branch information
Luisfp0 committed Oct 10, 2024
1 parent 8a9e098 commit c6d083c
Show file tree
Hide file tree
Showing 3 changed files with 248 additions and 17 deletions.
146 changes: 146 additions & 0 deletions apps/web/app/(roles)/vagas/publique/action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
'use server'

import { getSupabaseClient } from 'db'
import { Filter } from 'app/components/SelectInput'

interface ItemExtracted {
option: {
value: string | number
label: string
}
inputType: string
}

const getFilter = (filters: Filter[], filterType: string) => {
return filters.filter(
(filter: ItemExtracted) => filter.inputType === filterType
)
}

const supabase = getSupabaseClient()

export const getFilterFromPreferences = async (email: string) => {
const { data } = await supabase
.from('Subscribers')
.select('skillsId')
.eq('email', email)

return data
}

export const fetchJobs = async (
filters: Filter[]
): Promise<{
data: any[]
isSuccess: boolean
message: string
count: number
}> => {
try {
const countryOptionsFormatted = getFilter(filters, 'country')
const skillsFormatted = getFilter(filters, 'skill')
const levelsFormated = getFilter(filters, 'level')
const orderFilter = filters.find((filter) => filter.inputType === 'order')

let query = supabase
.from('Roles')
.select('*', { count: 'exact' })
.eq('ready', true)

if (countryOptionsFormatted.length > 0) {
const countryValues = countryOptionsFormatted.map(
(country: ItemExtracted) => country.option.value as string
)
if (countryValues.includes('Global')) {
countryValues.push('International')
}
query = query.in('country', countryValues)
}

if (skillsFormatted.length > 0) {
const skillsId = skillsFormatted
.map((skill: ItemExtracted) => {
const value = skill.option.value
return typeof value === 'string' ? parseInt(value, 10) : value
})
.filter((id): id is number => !isNaN(id))

if (skillsId.length > 0) {
query = query.contains('skillsId', skillsId)
}
}

if (levelsFormated.length > 0) {
const filters = levelsFormated.map(
(level: ItemExtracted) => `description.ilike.%${level.option.value}%`
)
const combinedFilter = filters.join(',')
query = query.or(combinedFilter)
}

if (orderFilter) {
const orderOption = getFilter(filters, 'order')
query = query.order('createdAt', {
ascending: orderOption[0].option.value === 'ascending',
})
} else {
query = query.order('salary', { nullsFirst: false })
}

const { data, count, error } = await query

if (error) {
throw error
}

const sortedData = data?.sort((a, b) => {
const parseSalary = (salary: string) => {
if (!salary) return 0
const cleanedSalary = salary.replace(/[^0-9.-]+/g, '')
return parseFloat(cleanedSalary) || 0
}

const salaryA = parseSalary(a.salary)
const salaryB = parseSalary(b.salary)

if (salaryA === null || salaryA === undefined) return 1
if (salaryB === null || salaryB === undefined) return -1
return salaryB - salaryA
})

return {
data: sortedData || [],
isSuccess: true,
message: '',
count: count || 0,
}
} catch (error) {
console.error('Erro ao buscar dados do banco de dados:', error)
return {
data: [],
isSuccess: false,
message: error.message || 'Um erro ocorreu ao buscar os dados',
count: 0,
}
}
}

export const createRole = async (roleData: any) => {
const { data, error } = await supabase
.from('Roles')
.insert(roleData)
.select()
.single()

if (error) throw error
return data
}

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

if (error) throw error
}
69 changes: 52 additions & 17 deletions apps/web/app/(roles)/vagas/publique/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import { FormProvider, useForm } from 'react-hook-form'
import { RolePreviewModal } from './RolePreview'
import { RolePreviewSection } from './RolePreviewSection'
import { RoleTopic } from './RoleTopic'
import { Database } from 'db'
import login from 'app/utils/LoginPreferencesActions'
import { createRole, createRoleOwner } from './action'

type FormFields = {
name: keyof FormSchema
Expand All @@ -28,6 +31,8 @@ type FormFields = {
required?: true
}[]

type RolesInsert = Database['public']['Tables']['Roles']['Insert']

const salaryAndCurrencyField: FormFields = [
{
name: 'currency',
Expand Down Expand Up @@ -106,16 +111,43 @@ export default function RolesCreate() {
mode: 'onBlur',
})
const toast = useToast()
const onSubmit = async (data: FormSchema) => {
const headers = new Headers()
headers.set('Content-Type', 'application/json')

const response = await fetch('/api/vagas/publique', {
method: 'POST',
headers,
body: JSON.stringify(data),
})
if (response.ok) {
const onSubmit = async (formData: FormSchema) => {
const email = localStorage.getItem('loginEmail')
if (!email) {
toast.toast({
title: 'Erro de autenticação',
description: 'Você precisa estar logado para criar uma vaga.',
variant: 'destructive',
})
return
}

const userId = await login(email)

try {
const roleData: RolesInsert = {
language: formData.language === 'Português' ? 'Portuguese' : 'English',
country: formData.country,
currency: formData.currency,
description: formData.description,
salary: formData.salary?.toString(),
title: formData.title,
url: formData.url,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
company: formData.company,
skillsId: formData.skillsId || [],
ready: true,
topicId:
formData.currency === 'Real' || formData.currency === 'BRL' ? 1 : 2,
company_logo: null,
minimumYears: formData.minimumYears,
}

const newRole = await createRole(roleData)
await createRoleOwner(newRole.id, userId)

form.reset({
url: '',
company: '',
Expand All @@ -129,18 +161,21 @@ export default function RolesCreate() {
title: '',
topicsId: undefined,
})

toast.toast({
title: 'Vaga enviada com sucesso!',
description: 'Muito obrigado por enviar a vaga.',
title: 'Vaga criada com sucesso!',
description: 'A vaga foi publicada e associada à sua conta.',
})
} catch (error) {
console.error('Erro ao criar vaga:', error)
toast.toast({
title: 'Erro ao criar a vaga',
description: 'Por favor, tente novamente mais tarde.',
variant: 'destructive',
})
return
}
toast.toast({
title: 'Já temos essa vaga cadastrada! 😁',
description: 'Por favor, verifique o formulário novamente. 😊',
variant: 'destructive',
})
}

return (
<FormProvider {...form}>
{form.formState.isSubmitting && <LoadingOverlay className="flex" />}
Expand Down
50 changes: 50 additions & 0 deletions packages/db/src/supabase/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,56 @@ export type Json =
export type Database = {
public: {
Tables: {
RoleOwner: {
Row: {
createdAt: string | null
id: string
roleID: string
subscriberID: string
}
Insert: {
createdAt?: string | null
id?: string
roleID: string
subscriberID: string
}
Update: {
createdAt?: string | null
id?: string
roleID?: string
subscriberID?: string
}
Relationships: [
{
foreignKeyName: "roleowner_roleid_fkey"
columns: ["roleID"]
isOneToOne: false
referencedRelation: "Roles"
referencedColumns: ["id"]
},
{
foreignKeyName: "roleowner_roleid_fkey"
columns: ["roleID"]
isOneToOne: false
referencedRelation: "RolesSkillsView"
referencedColumns: ["id"]
},
{
foreignKeyName: "roleowner_subscriberid_fkey"
columns: ["subscriberID"]
isOneToOne: false
referencedRelation: "Subscribers"
referencedColumns: ["id"]
},
{
foreignKeyName: "roleowner_subscriberid_fkey"
columns: ["subscriberID"]
isOneToOne: false
referencedRelation: "SubscriberSkillsView"
referencedColumns: ["id"]
},
]
}
Roles: {
Row: {
company: string | null
Expand Down

0 comments on commit c6d083c

Please sign in to comment.