Skip to content

Commit

Permalink
feat: Added api connection for employee form
Browse files Browse the repository at this point in the history
  • Loading branch information
khesir committed Aug 28, 2024
1 parent c1cb6f5 commit 846efd3
Show file tree
Hide file tree
Showing 11 changed files with 281 additions and 42 deletions.
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
"crypto": "1.0.1",
"dotenv": "^16.4.5",
"lucide-react": "0.428.0",
"next-themes": "^0.3.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "7.52.2",
"react-router-dom": "6.26.1",
"sonner": "^1.5.0",
"tailwind-merge": "2.5.2",
"tailwindcss-animate": "1.0.7",
"vite-tsconfig-paths": "5.0.1",
Expand Down
9 changes: 3 additions & 6 deletions src/api/axios.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import axios, { AxiosRequestConfig } from 'axios';

export interface ApiResponse<T> {
data: DataResponse<T>;
}
export interface DataResponse<T> {
timeStamp: string; // Date as a string
statusCode: number;
httpStatus: string;
message: string;
data: T[]; // Generic array of data
data: T | T[]; // Generic array of data
}


Expand All @@ -30,7 +27,7 @@ axios.defaults.headers.post['Content-Type'] = 'application/json';
export const request = async <T>(
method: AxiosRequestConfig['method'],
url: string,
data?: T
data?: unknown
): Promise<T> => {
const headers: Record<string, string> = {};

Expand All @@ -44,5 +41,5 @@ export const request = async <T>(
url: url,
headers: headers,
data: data,
});
}).then(response=> response.data);
};
31 changes: 31 additions & 0 deletions src/components/ui/sonner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use client"

import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"

type ToasterProps = React.ComponentProps<typeof Sonner>

const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()

return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}

export { Toaster }
15 changes: 13 additions & 2 deletions src/features/employee/api/activity-logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@ import { ActivityLogs } from "../types/types";
export async function getAllActivityLogs(){
try{
const response = await request<ApiResponse<ActivityLogs>>('GET', '/ems/activity-logs/')
console.log(response.data.data)
return response.data.data

return response.data
} catch (error){
console.log('Error sending data: ', error);
throw error
}
}

export async function createActivityLog(data: ActivityLogs){
try{
const response = await request<ApiResponse<ActivityLogs>>('POST', '/ems/activity-logs/', data)

console.log(response)
} catch (error){
console.log('Error sending data: ', error);
throw error
Expand Down
3 changes: 1 addition & 2 deletions src/features/employee/api/department.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { Department } from "../types/types";
export async function getAllDepartment(){
try{
const response = await request<ApiResponse<Department>>('GET', '/ems/department/')
console.log(response.data.data)
return response.data.data
return response.data
} catch (error){
console.log('Error sending data: ', error);
throw error
Expand Down
4 changes: 2 additions & 2 deletions src/features/employee/api/designation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import { ApiResponse, request} from "@/api/axios";
import { Designation } from "../types/types";

export async function getAllDesignation(){
export async function getAllDesignation(): Promise<Designation[] | Designation>{
try{
const response = await request<ApiResponse<Designation>>('GET', '/ems/designation/')

return response.data.data
return response.data
} catch (error){
console.log('Error sending data: ', error);
throw error
Expand Down
60 changes: 55 additions & 5 deletions src/features/employee/api/employee.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,64 @@

import { ApiResponse, request} from "@/api/axios";
import { Employee } from "../types/types";
import { Employee, EmployeeEmploymentInformation, EmployeeIdentificationFinancialInformation, EmployeePersonalInformation, EmployeeSalaryInformation } from "../types/types";


export async function getAllEmployee(){
try{
const response = await request<ApiResponse<Employee>>('GET', '/ems/employee/')

return response.data.data
return response.data
} catch (error){
console.log('Error sending data: ', error);
throw error
}
}
}


export async function CreateEmployeeIdentificationFinancialInformation(data: EmployeeIdentificationFinancialInformation){
try{
const response = await request('POST', '/ems/employee/idenficationFinancialInformation/', data)

console.log(response)
} catch(error){
console.log(error)
}
}

export async function CreateSalaryInformation(data: EmployeeSalaryInformation){
try{
const response = await request('POST', '/ems/employee/salaryInformation/', data)

console.log(response)
} catch(error){
console.log(error)
}
}

export async function CreateEmploymentInformation(data: EmployeeEmploymentInformation){
try{
const response = await request('POST', '/ems/employee/employmentInformation/', data)

console.log(response)
} catch(error){
console.log(error)
}
}

export async function CreateEmployeePersonalInformation(data: EmployeePersonalInformation){
try{
const response = await request('POST', '/ems/employee/personalInformation/', data)

console.log(response)
} catch(error){
console.log(error)
}
}
export async function AddEmployee(data : Employee){
try{
const response = await request<ApiResponse<Employee>>('POST', '/ems/employee/', data)

return response.data
} catch (error) {
console.log('Error sending data: ', error )
}
}

91 changes: 72 additions & 19 deletions src/features/employee/components/form/create-employee-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,26 @@ import { Input } from "@/components/ui/input";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { useCallback, useEffect, useState } from "react";
import { useToast } from "@/components/ui/use-toast";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

import { EmployeeStatus, EmployeeType, Gender, PayrollFrequency } from "../../constant/constant-data";
import { generateCustomUUID } from "@/lib/utils";
import { CreateEmployeeSchema } from "../../zod/schema";
import { Department, Designation } from "../../types/types";
import { ActivityLogs, Department, Designation, EmployeeEmploymentInformation, EmployeeIdentificationFinancialInformation, EmployeePersonalInformation, EmployeeSalaryInformation } from "../../types/types";
import { getAllDepartment } from "../../api/department";
import { getAllDesignation } from "../../api/designation"
import { AddEmployee, CreateEmployeeIdentificationFinancialInformation, CreateEmployeePersonalInformation, CreateEmploymentInformation, CreateSalaryInformation } from "../../api/employee";
import { toast } from "sonner";
import { createActivityLog } from "../../api/activity-logs";
import { useNavigate } from "react-router-dom";

export function CreateEmployeeForm(){
const [uuid, setUUID] = useState<string>()
const [isSubmitting, setIsSubmitting] = useState<boolean>(false)
const [isFetching, setIsFetching] = useState<boolean>(false)
const {toast} = useToast()
const [designations, setDesignations] = useState<Designation[]>()
const [departments, setDepartments] = useState<Department[]>()

const navigate = useNavigate()
const form = useForm<z.infer<typeof CreateEmployeeSchema>>({
resolver: zodResolver(CreateEmployeeSchema),
defaultValues: {
Expand Down Expand Up @@ -81,9 +83,7 @@ export function CreateEmployeeForm(){
setDepartments(departmentResponse);
}
} catch (error) {
toast({
variant: "destructive",
title: "Something went wrong",
toast("Something went wrong",{
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(error, null, 2)}</code>
Expand All @@ -93,7 +93,7 @@ export function CreateEmployeeForm(){
} finally {
setIsFetching(false);
}
}, [toast]);
}, []);

const fetchEmployeeID = useCallback(() => {
const data = generateCustomUUID();
Expand Down Expand Up @@ -127,19 +127,72 @@ export function CreateEmployeeForm(){
const handleSubmit = async (data: z.infer<typeof CreateEmployeeSchema>) => {
setIsSubmitting(true)
try{
toast({
variant:'default',
title:'Data sent to backend',
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(data, null, 2)}</code>
</pre>
),

const employee = {
uuid: data.employee_id,
firstname: data.firstname,
middlename: data.middlename,
lastname: data.lastname,
status: 'active'
}
console.log(data)
const {employee_id} : any = await AddEmployee(employee)
console.log(employee_id)
toast("Success",{
description: `Employee ${employee_id} Created. Now Creating employee information` ,
})
const personal_info : EmployeePersonalInformation= {
employee_id: Number(employee_id),
birthday: data.birthday,
gender: data.gender,
phone: data.phone,
email: data.email,
address_line: data.addressLine,
postal_code: data.postalCode,
emergency_contact_name: 'N/A',
emergency_contact_phone: 'N/A',
emergency_contact_relationship: 'N/A'
}
const employment_info : EmployeeEmploymentInformation = {
employee_id: Number(employee_id),
department_id: Number(data.department_id),
designation_id: Number(data.designation_id),
employee_type: data.employee_type,
employee_status: data.employee_status
}
const salary_info : EmployeeSalaryInformation = {
employee_id: Number(employee_id),
payroll_frequency: data.payroll_frequency,
base_salary: Number(data.base_salary)
}
const identification_financial_info : EmployeeIdentificationFinancialInformation = {
employee_id: Number(employee_id),
pag_ibig_id: data.pagibig_id,
sss_id: data.sssid,
philhealth_id: data.philhealth_id,
tin: data.tin_id,
bank_account_number: '123123'
}
await Promise.all([
await CreateEmployeePersonalInformation(personal_info),
await CreateEmploymentInformation(employment_info),
await CreateSalaryInformation(salary_info),
await CreateEmployeeIdentificationFinancialInformation(identification_financial_info),
])

toast("Success",{
description: 'Employee Data has been successfully created',
})


const activity_log: ActivityLogs = {
'employee_id': 1,
'action': `Create Employee ID: ${employee_id}`
}
await createActivityLog(activity_log)
navigate('/employee/users')
} catch (error){
toast({
variant: "destructive",
title: "Something went wrong",
toast("Error",{
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(error, null, 2)}</code>
Expand Down
Loading

0 comments on commit 846efd3

Please sign in to comment.