Merge branch 'master' of https://gitea.nswteam.net/joseph/ManagementSystem into Sprint-4/MS-36-FE-Technical

This commit is contained in:
dbdbd9 2024-09-21 10:19:12 +07:00
commit 4d520a664d
6 changed files with 269 additions and 149 deletions

View File

@ -30,12 +30,17 @@ class EvaluationController extends Controller
]);
$userEmail = User::findOrFail($request->input('userID'))->email;
$projects = $this->jiraService->getAllProjects();
$startDate = $request->input('fromDate');
$endDate = $request->input('toDate');
$projectsData = self::getProjectReviewByParams($startDate, $endDate, $userEmail);
// Trả về kết quả
return AbstractController::ResultSuccess($projectsData);
}
public function getProjectReviewByParams($startDate, $endDate, $userEmail)
{
$projects = $this->jiraService->getAllProjects();
$userCriterias = UserCriteria::with([
'sprint' => function ($query) use ($startDate, $endDate) {
if ($startDate && $endDate) {
@ -58,8 +63,6 @@ class EvaluationController extends Controller
}
})
->get();
// dd($userCriterias);
// Xử lý dữ liệu thành cấu trúc mong muốn
$projectsData = $userCriterias->groupBy('sprint.project_id')->map(function ($userCriteriasByProject, $projectId) use ($projects) {
$result = self::getProjectById($projects, $projectId);
return [
@ -82,11 +85,11 @@ class EvaluationController extends Controller
})->values()
];
})->values();
// Trả về kết quả
return AbstractController::ResultSuccess($projectsData);
return $projectsData;
}
public function getProjectById($projects, $inputId)
{
$filteredProjects = array_filter($projects, function ($project) use ($inputId) {
@ -145,49 +148,10 @@ class EvaluationController extends Controller
// Query User
$user = User::findOrFail($request->input('userID'));
$userEmail = $user->email;
// Query User Criteria
$query = UserCriteria::where('user_email', $userEmail);
if ($request->filled('fromDate')) {
$fromDate = Carbon::parse($request->input('fromDate'));
$query->where('created_at', '>=', $fromDate);
}
if ($request->filled('toDate')) {
$toDate = Carbon::parse($request->input('toDate'));
$query->where('created_at', '<=', $toDate);
}
$userCriterias = $query->with(['sprint', 'criteria'])->get();
// Structure projects data
$projects = $this->jiraService->getAllProjects();
$projectsData = $userCriterias->groupBy('sprint.project_id')->map(function ($userCriteriasByProject, $projectId) use ($projects) {
$result = self::getProjectById($projects, $projectId);
return [
'name' => $result['name'],
'sprints' => $userCriteriasByProject->groupBy('sprint.id')->map(function ($userCriteriasBySprint) {
$sprint = $userCriteriasBySprint->first()->sprint;
return [
'name' => $sprint->name,
'criterias' => $userCriteriasBySprint->map(function ($userCriteria) {
$criteria = $userCriteria->criteria;
return [
'criteria' => $criteria->name,
'note' => $userCriteria->note ?? '',
'createdBy' => $userCriteria->created_by ?? '',
'point' => $userCriteria->point ?? '',
];
})
];
})->values()
];
})->values();
$startDate = $request->input('fromDate');
$endDate = $request->input('toDate');
$projectsData = self::getProjectReviewByParams($startDate, $endDate, $userEmail);
$technicalData = TechnicalController::getDataTechnicalsByUserId($request->input('userID'));
// Generate Word document
$phpWord = new PhpWord();
$phpWord->setDefaultFontName('Times New Roman');
@ -221,6 +185,7 @@ class EvaluationController extends Controller
'spaceAfter' => 400,
]);
//ProjectsData
foreach ($projectsData as $project) {
$section->addText("Project: {$project['name']}", ['bold' => true, 'size' => 14, 'color' => '000080']);
@ -234,17 +199,17 @@ class EvaluationController extends Controller
]);
$table->addRow();
$table->addCell(2000)->addText('Criteria', ['bold' => true]);
$table->addCell(2000)->addText('Note', ['bold' => true]);
$table->addCell(2000)->addText('Created By', ['bold' => true]);
$table->addCell(2000)->addText('Points', ['bold' => true]);
$table->addCell(2500)->addText('Criteria', ['bold' => true]);
$table->addCell(2500)->addText('Note', ['bold' => true]);
$table->addCell(2500)->addText('Created By', ['bold' => true]);
$table->addCell(2500)->addText('Point', ['bold' => true]);
foreach ($sprint['criterias'] as $criteria) {
$table->addRow();
$table->addCell(2000)->addText($criteria['criteria']);
$table->addCell(2000)->addText($criteria['note']);
$table->addCell(2000)->addText($criteria['createdBy']);
$table->addCell(2000)->addText($criteria['point']);
$table->addCell(2500)->addText($criteria['criteria']);
$table->addCell(2500)->addText($criteria['note']);
$table->addCell(2500)->addText($criteria['createdBy']);
$table->addCell(2500)->addText($criteria['point']);
}
$section->addText(' ', [], [
@ -256,6 +221,36 @@ class EvaluationController extends Controller
'spaceAfter' => 600,
]);
}
if ($technicalData)
$section->addPageBreak();
//Technical
$section->addText("Technicals", ['bold' => true, 'size' => 14, 'color' => '000080'], [
'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER
]);
$table = $section->addTable([
'borderColor' => '000000',
'borderSize' => 6,
'cellMargin' => 80,
]);
$table->addRow();
$table->addCell(2500)->addText('Level', ['bold' => true]);
$table->addCell(2500)->addText('Name', ['bold' => true]);
$table->addCell(2500)->addText('Point', ['bold' => true]);
$table->addCell(2500)->addText('Last Update', ['bold' => true]);
foreach ($technicalData as $technical) {
$updated_at = $technical['updated_at'] ? Carbon::parse($technical['updated_at'])->format('d/m/Y H:i:s') : null;
$table->addRow();
$table->addCell(2500)->addText($technical['level']);
$table->addCell(2500)->addText($technical['name']);
$table->addCell(2500)->addText($technical['point']);
$table->addCell(2500)->addText($updated_at);
}
$section->addText(' ', [], [
'spaceAfter' => 600,
]);
$tempFile = tempnam(sys_get_temp_dir(), 'word');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

View File

@ -83,13 +83,86 @@ class TechnicalController extends Controller
}
public function getTechnicalsByUserId($userId)
{
$technicalData = self::getDataTechnicalsByUserId($userId);
return AbstractController::ResultSuccess($technicalData);
// // Lấy tất cả các technical
// $allTechnicals = Technical::all();
// if ($technicals->isEmpty() && $allTechnicals->isEmpty()) {
// return AbstractController::ResultError("No technicals found.");
// }
// // Chuẩn bị dữ liệu để trả về
// $technicalData = $allTechnicals->map(function ($technical) use ($technicals) {
// // Tìm kiếm kỹ thuật từ bảng technical_users
// $technicalUser = $technicals->firstWhere('technical_id', $technical->id);
// return [
// 'id' => $technical->id,
// 'name' => $technical->name,
// 'level' => $technical->level,
// 'point' => $technicalUser ? $technicalUser->point : 0, // Nếu không tồn tại, điểm mặc định là 0
// 'updated_at' => $technicalUser ? $technicalUser->updated_at : null // Nếu không tồn tại, updated_at là null
// ];
// });
// $sortedTechnicalData = $technicalData->sortByDesc('point')->values(); // values() để giữ lại chỉ số
// return AbstractController::ResultSuccess($sortedTechnicalData);
}
public static function getDataTechnicalsByUserId($userId)
{
$technicals = TechnicalUser::with('technical')
->where('user_id', $userId)
->where('point', '>', 0)
->orderBy('point', 'desc')
->get();
if ($technicals->isEmpty()) {
return AbstractController::ResultError("No technicals found for this user.");
}
// Chuẩn bị dữ liệu để trả về
$technicalData = $technicals->map(function ($technicalUser) {
return [
'id' => $technicalUser->technical->id,
'name' => $technicalUser->technical->name,
'level' => $technicalUser->technical->level,
'point' => $technicalUser->point,
'updated_at' => $technicalUser->updated_at
];
});
return $technicalData;
}
public function getTechnicalsOfUser()
{
$userInfo = auth('admins')->user();
$userId = $userInfo->id;
$technicals = TechnicalUser::with('technical')
->where('user_id', $userId)
->get();
// if ($technicals->isEmpty()) {
// return AbstractController::ResultError("No technicals found for this user.");
// }
// // Chuẩn bị dữ liệu để trả về
// $technicalData = $technicals->map(function ($technicalUser) {
// return [
// 'id' => $technicalUser->technical->id,
// 'name' => $technicalUser->technical->name,
// 'level' => $technicalUser->technical->level,
// 'point' => $technicalUser->point,
// 'updated_at' => $technicalUser->updated_at
// ];
// });
// return AbstractController::ResultSuccess($technicalData);
// Lấy tất cả các technical
$allTechnicals = Technical::all();
if ($technicals->isEmpty() && $allTechnicals->isEmpty()) {
@ -115,32 +188,6 @@ class TechnicalController extends Controller
return AbstractController::ResultSuccess($sortedTechnicalData);
}
public function getTechnicalsOfUser()
{
$userInfo = auth('admins')->user();
$userId = $userInfo->id;
$technicals = TechnicalUser::with('technical')
->where('user_id', $userId)
->get();
if ($technicals->isEmpty()) {
return AbstractController::ResultError("No technicals found for this user.");
}
// Chuẩn bị dữ liệu để trả về
$technicalData = $technicals->map(function ($technicalUser) {
return [
'id' => $technicalUser->technical->id,
'name' => $technicalUser->technical->name,
'level' => $technicalUser->technical->level,
'point' => $technicalUser->point,
'updated_at' => $technicalUser->updated_at
];
});
return AbstractController::ResultSuccess($technicalData);
}
public function getListUserByTechnicalId($technicalId)
{
$users = TechnicalUser::with('user')

View File

@ -45,6 +45,7 @@ import { useCallback, useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import PasswordRequirementInput from '../PasswordRequirementInput/PasswordRequirementInput'
import classes from './NavbarSimpleColored.module.css'
import { checkPermissions } from '@/utils/checkRoles'
const data = [
// { link: '/dashboard', label: 'Dashboard', icon: IconHome },
@ -52,67 +53,84 @@ const data = [
link: '/timekeeping',
label: 'Timekeeping',
icon: IconCalendar,
group: 'normal',
permissions: 'admin,hr,staff,tester',
group: 'staff',
},
{
link: '/tracking',
label: 'Check in/out',
icon: IconScan,
group: 'admin',
permissions: 'hr,admin',
group: 'other',
},
{
link: '/worklogs',
label: 'Worklogs',
icon: IconReport,
group: 'normal',
permissions: 'admin,hr,staff,tester',
group: 'staff',
},
{
link: '/leave-management',
label: 'Leave Management',
icon: IconCalendarClock,
group: 'normal',
permissions: 'admin,hr,staff,tester',
group: 'staff',
},
{
link: '/tickets',
label: 'Tickets',
icon: IconTicket,
permissions: 'admin,hr,staff,tester',
group: 'staff',
},
{ link: '/tickets', label: 'Tickets', icon: IconTicket, group: 'normal' },
{
link: '/tickets-management',
label: 'Tickets Management',
icon: IconDevices,
group: 'admin',
permissions: 'hr,admin',
group: 'other',
},
{
link: '/users',
label: 'Users Management',
icon: IconUsersGroup,
permissions: 'admin',
group: 'admin',
},
{
link: '/sprint-review',
label: 'Sprint Review',
icon: IconListCheck,
permissions: 'admin',
group: 'admin',
},
{
link: '/test-report',
label: 'Test Report',
icon: IconZoomExclamation,
group: 'admin',
permissions: 'admin,tester',
group: 'test',
},
{
link: '/allocation',
label: 'Personnel allocation',
icon: IconBinaryTree2,
group: 'normal',
permissions: 'admin,hr,staff,tester',
group: 'staff',
},
{
link: '/profile',
label: 'Profile',
icon: IconZoomExclamation,
permissions: 'hidden',
group: 'hidden',
},
{
link: '/staff-avaluation',
label: 'Staff evaluation',
icon: IconChartDots2,
permissions: 'admin',
group: 'admin',
},
{
@ -212,22 +230,17 @@ const Navbar = ({
// })
const group = [
{ name: 'normal', label: 'Normal' },
{ name: 'admin', label: 'Admin' },
{ name: 'staff', label: 'General', permissions: 'admin,hr,staff,tester' },
{ name: 'admin', label: 'Admin', permissions: 'admin' },
{ name: 'other', label: 'Other', permissions: 'admin,hr' },
{ name: 'test', label: 'Test', permissions: 'admin,tester' },
]
const links = group.map((g) => {
return (
<div key={g.name}>
<Divider
display={
g.name === 'normal'
? 'block'
: user?.user?.permission.includes(g.name) ||
user?.user?.permission.includes('hr')
? 'block'
: 'none'
}
display={checkPermissions(g.permissions) ? 'block' : 'none'}
my="xs"
label={
<span style={{ color: 'white', fontWeight: 700 }}>{g.label}</span>
@ -236,12 +249,7 @@ const Navbar = ({
/>
{data
.filter((i) => {
return (
i.group === g.name &&
(user?.user?.permission.includes('admin') ||
user?.user?.permission.includes('hr') ||
g.name !== 'admin')
)
return i.group === g.name && checkPermissions(i.permissions)
})
.map((item) => (
<a
@ -249,7 +257,6 @@ const Navbar = ({
data-active={item.label === active || undefined}
key={item.link}
onClick={() => {
// setHeader(item.label);
setActive(active)
if (active !== item.label) {
navigate(item.link)

View File

@ -2,15 +2,14 @@ import {
evaluation,
getAllTechByUserId,
getAllUser,
sprintReview
sprintReview,
} from '@/api/Admin'
import DataTableAll from '@/components/DataTable/DataTable'
import ProjectInvolvement from '@/components/ProjectInvolvement/ProjectInvolvement'
import { get } from '@/rtk/helpers/apiService'
import { get, getDownloadFile } from '@/rtk/helpers/apiService'
import { Box, Button, Loader, Select, Text, Title } from '@mantine/core'
import { DateInput } from '@mantine/dates'
import { notifications } from '@mantine/notifications'
import axios from 'axios'
import moment from 'moment'
import { useEffect, useState } from 'react'
import classes from './StaffEvaluation.module.css'
@ -53,8 +52,6 @@ const StaffEvaluation = () => {
toDate: null,
})
console.log(filter, 'filter')
const getListUser = async () => {
try {
const params = {}
@ -72,35 +69,53 @@ const StaffEvaluation = () => {
return []
}
const downloadFile = async () => {
await axios({
url: evaluation,
method: 'GET',
responseType: 'blob',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvYXBpL3YxL2FkbWluL2xvZ2luIiwiaWF0IjoxNzI2ODE3ODU3LCJleHAiOjE3MjY5MDQyNTcsIm5iZiI6MTcyNjgxNzg1NywianRpIjoid0kzeXM5SGZiV21wS3pONSIsInN1YiI6IjE2IiwicHJ2IjoiZDJmZjI5MzM5YThhM2U4MmMzNTgyYTVhOGU3MzlkZjE3ODliYjEyZiJ9.oEHW0cIlQkawYQMVZnz5TZ5twzY18301eLmXjC55LfY`,
},
params: {
...filter,
userID: 3,
},
})
.then((response) => {
const fileURL = window.URL.createObjectURL(new Blob([response.data]))
function getFormattedDateTime(): string {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0') // Tháng bắt đầu từ 0
const day = String(now.getDate()).padStart(2, '0')
const hours = String(now.getHours()).padStart(2, '0')
const minutes = String(now.getMinutes()).padStart(2, '0')
const seconds = String(now.getSeconds()).padStart(2, '0')
return `${year}${month}${day}${hours}${minutes}${seconds}`
}
const downloadFile = async (filterSearch: Filter) => {
try {
const params = {
userID: filterSearch.userID ?? '',
fromDate: filterSearch.fromDate
? moment(filterSearch.fromDate).format('YYYY-MM-DD')
: null,
toDate: filterSearch.toDate
? moment(filterSearch.toDate).format('YYYY-MM-DD')
: null,
}
const res = await getDownloadFile(evaluation, params)
if (res.status) {
const fileURL = window.URL.createObjectURL(new Blob([res.data]))
const fileLink = document.createElement('a')
const fileName = `EXPORT_SPRINT_REVIEW_AND_TECHNICAL_EVALUATION_${getFormattedDateTime()}.docx`
fileLink.href = fileURL
fileLink.setAttribute('download', 'RENAME_WORD_FILE.docx') // -------------> RENAME_WORD_FILE
fileLink.setAttribute('download', fileName)
document.body.appendChild(fileLink)
fileLink.click()
fileLink.remove()
}
} catch (error: any) {
notifications.show({
title: 'Error',
message: error.message ?? error,
color: 'red',
})
.catch((error) => {
console.error('Error downloading the file:', error)
})
}
return []
}
useEffect(() => {
@ -224,16 +239,17 @@ const StaffEvaluation = () => {
size: '25%',
header: 'Last update',
render: (row: any) => {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
}}
>
{moment(row?.updated_at).format('DD/MM/YYYY HH:mm:ss')}
</div>
)
if (row?.updated_at)
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
}}
>
{moment(row?.updated_at).format('DD/MM/YYYY HH:mm:ss')}
</div>
)
},
},
]
@ -302,7 +318,8 @@ const StaffEvaluation = () => {
>
<Button
// m={5}
onClick={() => downloadFile()}
style={{ display: filter.userID != '' ? 'flex' : 'none' }}
onClick={() => downloadFile(filter)}
>
Export
</Button>

View File

@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import axios from 'axios'
import { getFormDataHeader, getHeaderInfo } from '@/rtk/helpers/tokenCreator'
import { removeTokens } from '@/rtk/localStorage'
import { notifications } from '@mantine/notifications'
import axios from 'axios'
const handleResponse = (response: any) => {
if (response.status === 401) {
removeTokens()
@ -14,6 +14,17 @@ const handleResponse = (response: any) => {
return response
}
const handleResponseDownloadFile = (response: any) => {
if (response.status === 401) {
removeTokens()
window.location.href = '/login'
}
if (response.status === 200) {
return response
}
return response
}
/**
*
* @param url
@ -69,6 +80,30 @@ export const get = async (url: any, params: any = {}) => {
}
}
export const getDownloadFile = async (url: any, params: any = {}) => {
const header = await getHeaderInfo()
try {
const resp = await axios.get(url, {
...header,
params,
responseType: 'blob',
})
return handleResponseDownloadFile(resp)
} catch (err: any) {
console.log(err)
if (err.response.status === 422) {
const errorMess = err.response.data.message
notifications.show({
title: 'Error',
message: errorMess,
color: 'red',
})
}
throw handleResponseDownloadFile(err.response)
}
}
export const put = async (url: any, body: any) => {
const header = await getHeaderInfo()

View File

@ -0,0 +1,19 @@
import { useAppSelector } from "@/rtk/hooks"
export const checkPermissions = (requirement:string) => {
try {
const requirePermissions = requirement.split(',')
const user = useAppSelector((state) => state.authentication.user)
const userPermissoions = user?.user?.permission.split(',')
for(let i=0; i <= userPermissoions.length; i++){
if(requirePermissions.includes(userPermissoions[i])){
return true
}
}
return false
} catch (error) {
console.log(error)
return false
}
}