Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 340
BlockStudentReasonService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 10
3660.00
0.00% covered (danger)
0.00%
0 / 340
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 saveBlockStudentReason
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 34
 validateSaveBlockStudentReason
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 10
 insertBlockStudentReason
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 14
 updateBlockStudentReason
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 22
 deleteBlockStudentReason
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 23
 getBlockStudentReasons
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 39
 getBlockReasonsByRegistration
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 27
 getBlockStudentReport
0.00% covered (danger)
0.00%
0 / 1
156.00
0.00% covered (danger)
0.00%
0 / 89
 getBlockedStudentDetails
0.00% covered (danger)
0.00%
0 / 1
110.00
0.00% covered (danger)
0.00%
0 / 79
<?php
namespace com\linways\ec\core\service;
use com\linways\base\util\MakeSingletonTrait;
use com\linways\base\util\SecurityUtils;
use com\linways\ec\core\constant\StatusConstants;
use com\linways\ec\core\exception\ExamControllerException;
use com\linways\ec\core\dto\BlockStudentReason;
use com\linways\ec\core\logging\Events;
use com\linways\ec\core\logging\entities\Staff;
use com\linways\core\ams\professional\logging\AMSLogger;
use com\linways\core\ams\professional\service\StaffService;
use com\linways\base\util\TwigRenderer;
use com\linways\core\ams\professional\util\PdfUtil;
use com\linways\ec\core\request\SearchExamRegistrationRequest;
use com\linways\ec\core\service\ExamRegistrationService;
class BlockStudentReasonService extends BaseService
{
    use MakeSingletonTrait;
    private function __construct()
    {
        $this->logger = AMSLogger::getLogger('exam-controller-log');
    }
    /**
     * Save Block Student Reason
     * @param BlockStudentReason $blockStudentReason
     * @return $id
     */
    public function saveBlockStudentReason(BlockStudentReason $blockStudentReason){
        $blockStudentReason = $this->realEscapeObject($blockStudentReason);
        $blockStudentReason->createdBy = $GLOBALS['userId'];
        $blockStudentReason->updatedBy = $GLOBALS['userId'];
        $staffId = $GLOBALS['userId'];
        try {
            $this->validateSaveBlockStudentReason($blockStudentReason);
            if (!empty($blockStudentReason->id)) {
                $blockStudentReason->id = $this->updateBlockStudentReason($blockStudentReason);
            } else {
                $blockStudentReason->id = $this->insertBlockStudentReason($blockStudentReason);
            }
            AMSLogger::log_info($this->logger,Events::EC_SAVE_STUDENT_REASON, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $blockStudentReason,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_SAVE_STUDENT_REASON, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $blockStudentReason,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            if ($e->getCode() !== ExamControllerException::INVALID_PARAMETERS && $e->getCode() !== ExamControllerException::EMPTY_PARAMETERS && $e->getCode() !== "DUPLICATE_ENTRY") {
                throw new ExamControllerException($e->getCode(), "Failed to save block reason Type! Please try again");
            } else if ($e->getCode() === ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException(ExamControllerException::DUPLICATE_ENTRY, "Cannot create block reason.This block reason already created");
            } else {
                throw new ExamControllerException($e->getCode(), $e->getMessage());
            }
        }
        return $blockStudentReason->id;
    }
    /**
     * Validate Block Student Reason Request Before Saving
     * @param BlockStudentReason $blockStudentReason
     * @return NULL
     */
    private function validateSaveBlockStudentReason(BlockStudentReason $blockStudentReason){
        if (empty($blockStudentReason->name)){
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS, " Block reason name is  empty!");
        }
        else if (empty($blockStudentReason->type)){
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS, " Block reason type is  empty!");
        }
        else if (empty($blockStudentReason->blockPrivilegeUser->staffs)){
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS, " Block privilage staff missing!");
        }
            
    }
    /**
     * Insert Block Student Reason 
     * @param FeeBlockStudentReasonType $blockStudentReason
     * @return  $id
     */
    private function insertBlockStudentReason(BlockStudentReason $blockStudentReason){
        $properties = !empty($blockStudentReason->properties) ? "'" . json_encode($blockStudentReason->properties) . "'" : "'{}'";
        $contactPersonId = !empty($blockStudentReason->contactPersonId) ? "'" .$blockStudentReason->contactPersonId . "'" : "NULL";
        $blockPrivilegeUser = !empty($blockStudentReason->blockPrivilegeUser) ? "'" . json_encode($blockStudentReason->blockPrivilegeUser) . "'" : "'{}'";
        $query = "INSERT INTO ec_block_student_reason
                  (name,type,contact_person_id,block_privilege_user,properties,created_by,updated_by)
                  VALUES
                  ('$blockStudentReason->name','$blockStudentReason->type',$contactPersonId,$blockPrivilegeUser,$properties,'$blockStudentReason->createdBy','$blockStudentReason->updatedBy')";
        try {
            $blockStudentReason->id = $this->executeQuery($query,true)->id;
            return $blockStudentReason->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Update Block Student Reason 
     * @param BlockStudentReason $blockStudentReason
     * @return $blockStudentReason->id
     */
    private function updateBlockStudentReason(BlockStudentReason $blockStudentReason)
    {
        $properties = !empty($blockStudentReason->properties) ? "'" . json_encode($blockStudentReason->properties) . "'" : "'{}'";
        $contactPersonId = !empty($blockStudentReason->contactPersonId) ? "'" .$blockStudentReason->contactPersonId . "'" : "NULL";
        $blockPrivilegeUser = !empty($blockStudentReason->blockPrivilegeUser) ? "'" . json_encode($blockStudentReason->blockPrivilegeUser) . "'" : "'{}'";
        $query = "UPDATE
                    ec_block_student_reason
                SET
                    name = '$blockStudentReason->name',
                    type = '$blockStudentReason->type',
                    contact_person_id =  $contactPersonId,
                    block_privilege_user = $blockPrivilegeUser,
                    properties =  $properties,
                    updated_by = '$blockStudentReason->updatedBy'
                WHERE
                    id = '$blockStudentReason->id'";
        try {
            $this->executeQuery($query);
            return $blockStudentReason->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * Delete Block Student Reason 
     * @param String $id
     * @return NULL
     */
    public function deleteBlockStudentReason($id){
        $id = $this->realEscapeString($id);
        $staffId = $GLOBALS['userId'];
        $blockStudentReason = new \stdClass();
        $blockStudentReason->id = $id;
        $currentBlockStudentReasonDetails = reset($this->getBlockStudentReasons($blockStudentReason));
        if(empty($currentBlockStudentReasonDetails)){
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"Can't delete ! Block reason missing.");
        }
        $query = "DELETE FROM
                    ec_block_student_reason
                WHERE
                    id = '$id'";
        try {
            $this->executeQuery($query);
             // LOGGING
            AMSLogger::log_info($this->logger,Events::EC_DELETE_STUDENT_REASON, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $currentBlockStudentReasonDetails,
                "status" => StatusConstants::SUCCESS
            ]);
        }catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::HAVE_RELATION,"Error deleting Block reason! Please try again");
        }
    }
    /**
     * get Block Student Reason 
     * @param $searchRequest
     * @return $blockStudentReasons
     */
    public function getBlockStudentReasons($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $whereQuery = null;
            $whereQuery = "";
            if (!empty($searchRequest->id)) {
                $blockStudentReasonIdString = is_array($searchRequest->id) ? "'" . implode("','", $searchRequest->id) . "'" : "'" . $searchRequest->id . "'";
                $whereQuery .= " AND ebsr.id IN ( $blockStudentReasonIdString )";
            }
            if (!empty($searchRequest->type)) {
                $blockStudentReasonTypeString = is_array($searchRequest->type) ? "'" . implode("','", $searchRequest->type) . "'" : "'" . $searchRequest->type . "'";
                $whereQuery .= " AND ebsr.type IN ( $blockStudentReasonTypeString )";
            }
            $query = "SELECT
                            DISTINCT 
                            ebsr.id as id,
                            ebsr.name as name,
                            ebsr.type as type,
                            ebsr.contact_person_id as contactPersonId,
                            ebsr.block_privilege_user as blockPrivilegeUser,
                            ebsr.properties
                        FROM
                            ec_block_student_reason ebsr
                        WHERE
                            1 = 1 ";
            $blockStudentReasons =  $this->executeQueryForList($query . $whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        foreach($blockStudentReasons as $blockStudentReason){
            $blockStudentReason->properties = json_decode($blockStudentReason->properties);
            $blockStudentReason->blockPrivilegeUser = json_decode($blockStudentReason->blockPrivilegeUser);
            $blockStudentReason->contactPerson = $blockStudentReason->contactPersonId ? StaffService::getInstance()->getStaffByIds([$blockStudentReason->contactPersonId]) : [];
            $blockStudentReason->staffs = StaffService::getInstance()->getStaffByIds($blockStudentReason->blockPrivilegeUser->staffs);
            $blockStudentReason->blockPrivilegeStaffIds = $blockStudentReason->blockPrivilegeUser->staffs;
            $blockStudentReason->isSemesterWise = $blockStudentReason->type =='SEMESTER_WISE' ? 1 : 0;
            $blockStudentReason->description = $blockStudentReason->properties->description ?? '';
        }
        return $blockStudentReasons;
    }
     /**
     * get Block  Reason By exam Registration
     * @param $searchRequest
     * @return $blockStudentReasons
     */
    public function getBlockReasonsByRegistration($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $whereQuery = null;
            $whereQuery = "";
           
            if (!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','", $searchRequest->examRegistrationId) . "'" : "'" . $searchRequest->examRegistrationId . "'";
                $whereQuery .= " AND esbrm.exam_registration_id IN ( $examRegistrationIdString )";
            }
            $query = "SELECT
                            DISTINCT 
                            ebsr.id as id,
                            ebsr.name as name,
                            ebsr.type as type,
                            ebsr.contact_person_id as contactPersonId,
                            ebsr.block_privilege_user as blockPrivilegeUser,
                            ebsr.properties
                        FROM
                            ec_block_student_reason ebsr
                        INNER JOIN ec_student_block_reason_mapping esbrm ON esbrm.ec_block_student_reason_id = ebsr.id
                        WHERE
                            1 = 1 ";
            $blockStudentReasons =  $this->executeQueryForList($query . $whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return $blockStudentReasons;
    }
    /**
     * Get Block Student Report
     * @param $searchRequest 
     * @return $programResult 
     */
    public function getBlockStudentReport($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        $request = new \stdClass;
        $request->examRegistrationId = $searchRequest->examRegistrationId;
        if($searchRequest->reportType == 'STUDENT_WISE'){
            $request->blockReasonId = $searchRequest->blockReasonId;
        }
        $resultData = new \stdClass;
        $requestForExamRegistration = new SearchExamRegistrationRequest;
        $requestForExamRegistration->id = $searchRequest->examRegistrationId;
        $resultData->examRegistration = reset(ExamRegistrationService::getInstance()->searchExamRegistration($requestForExamRegistration));
        $students =  $this->getBlockedStudentDetails($request);
        $batchWiseStudentData = [];
        if(empty($students)){
            throw new ExamControllerException(ExamControllerException::NO_REPORTS_DETAILS_FOUND,"No details found.");
        }
        if($searchRequest->reportType == 'STUDENT_WISE'){
            $templateName = "block-student-report-student-wise-template-1";
            $blockStudentReason = new \stdClass();
            $blockStudentReason->id = $searchRequest->blockReasonId;
            $resultData->blockReason = reset($this->getBlockStudentReasons($blockStudentReason));
            $resultData->blockReason->contactPersonNames = array_column( $resultData->blockReason->contactPerson, "name");
            $resultData->blockReason->contactPersonName =  implode(",", $resultData->blockReason->contactPersonNames) ;
            foreach($students as $student){
                if($resultData->blockReason->type == 'SUBJECT_WISE'){
                    $student->subjectNames = array_column( $student->subjects, "nameCode");
                    $student->subjectName = implode(",", $student->subjectNames);
                }
                else{
                    $student->subjectName ="ALL";
                }
                $batchWiseStudentData[$student->groupId]->id = $student->groupId;
                $batchWiseStudentData[$student->groupId]->name = $student->groupName;
                $batchWiseStudentData[$student->groupId]->students[] = $student;
            }
        }
        elseif($searchRequest->reportType == 'BATCH_WISE'){
            $templateName = "block-student-report-batch-wise-template-1";
            $blockStudentReason = new \stdClass();
            $resultData->blockReasons = $this->getBlockStudentReasons($blockStudentReason);
            $resultData->colspan = count($resultData->blockReasons) + 3;
            $templateName = "block-student-report-batch-wise-template-1";
            foreach($students as $student){
                if(!empty($student->blockReasons)){
                    $batchWiseStudentData[$student->groupId]->id = $student->groupId;
                    $batchWiseStudentData[$student->groupId]->name = $student->groupName;
                    $batchWiseStudentData[$student->groupId]->students[] = $student;
                }
            }
        }
        elseif($searchRequest->reportType == 'COURSE_WISE'){
            $blockStudentReason = new \stdClass();
            $resultData->blockReasons = $this->getBlockStudentReasons($blockStudentReason);
            $templateName = "block-student-report-subject-wise-template-1";
            $resultData->colspan = count($resultData->blockReasons) + 4;
            foreach($students as $student){
                if(!empty($student->subjects)){
                    $batchWiseStudentData[$student->groupId]->id = $student->groupId;
                    $batchWiseStudentData[$student->groupId]->name = $student->groupName;
                    $batchWiseStudentData[$student->groupId]->students[] = $student;
                }
                
            }
        }
        $resultData->students = $batchWiseStudentData;
        $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/blockStudentReports/$templateName.twig"), [ 'resultData'=>$resultData]);
        $prtContent = NULL;
            $prtContent .= '<html><head>';
            $prtContent .= "<style>
                </style>";
            $prtContent .= '</head><title>Block Student Report</title><body>';
            $prtContent .= $responseHtml;
            $prtContent .= '</body></html>';
            $totalWidth = 210 ;
            $totalHeight = 297;
            $options = array(
                'page-width'     => $totalWidth."mm",
                'page-height'    => $totalHeight."mm",
                'dpi'            => 96,
                'margin-top' => "10mm",
                'margin-left' => "10mm",
                'margin-right' => "10mm",
                'margin-bottom' => "10mm",
                'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
            );
        $programResult = new \stdClass;
        $programResult->dispalyHtmlData = $responseHtml;
        $programResult->printData = PdfUtil::renderPdf($prtContent, $options);
        return  $programResult;
    }
    /**
     * get Block  Reason Details
     * @param $searchRequest
     * @return $studentSubjectDetails
     */
    public function getBlockedStudentDetails($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $whereQuery = null;
            $orderBy = " ORDER BY CAST(spa.properties->>'$.registerNumber' AS CHAR) ASC ";
            $studentSubjectDetails = [];
            if (!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','", $searchRequest->examRegistrationId) . "'" : "'" . $searchRequest->examRegistrationId . "'";
                $whereQuery .= " AND esbrm.exam_registration_id IN ( $examRegistrationIdString )";
            }
            if (!empty($searchRequest->blockReasonId)) {
                $blockReasonIdString = is_array($searchRequest->blockReasonId) ? "'" . implode("','", $searchRequest->blockReasonId) . "'" : "'" . $searchRequest->blockReasonId . "'";
                $whereQuery .= " AND esbrm.ec_block_student_reason_id IN ( $blockReasonIdString )";
            }
            $query = "SELECT
                            DISTINCT 
                            sa.studentID AS studentId,
                            sa.studentName,
                            spa.properties->>'$.registerNumber' as regNo,
                            spa.properties->>'$.rollNumber' as rollNo,
                            g.id AS groupId,
                            g.name AS groupName,
                            s.id AS subjectId,
                            s.code AS subjectCode,
                            s.name AS subjectName,
                            ebsr.id as blockReasonId,
                            ebsr.name as blockReasonName,
                            ebsr.type as blockReasonType,
                            ebsr.contact_person_id as contactPersonId,
                            staff.staffName as contactPersonName
                        FROM
                            ec_student_block_reason_mapping esbrm 
                        INNER JOIN ec_block_student_reason ebsr ON ebsr.id = esbrm.ec_block_student_reason_id
                        INNER JOIN ec_exam_registration_batch eerb ON eerb.ec_exam_registration_id = esbrm.exam_registration_id
                        INNER JOIN `groups` g ON g.id = eerb.groups_id 
                        INNER JOIN program p ON p.id = g.properties ->> '$.programId'
                        INNER JOIN student_program_account spa ON spa.student_id  = esbrm.student_id  AND spa.current_program_id = p.id 
                        INNER JOIN ec_exam_registration_subject eers ON eers.ec_exam_registration_batch_id = eerb.id 
                        INNER JOIN ec_student_assessment_registration esar ON esar.am_assessment_id = eers.am_assessment_id AND esar.student_id = esbrm.student_id 
                        INNER JOIN studentaccount sa ON  sa.studentID = esbrm.student_id
                        LEFT JOIN staffaccounts staff ON staff.staffID = ebsr.contact_person_id
                        LEFT JOIN cm_academic_paper_subjects aps ON aps.id = esbrm.cm_academic_paper_subjects_id
                        LEFT JOIN  v4_ams_subject s ON aps.ams_subject_id = s.id
                        WHERE
                            1 = 1 ";
            $studentDetails =  $this->executeQueryForList($query . $whereQuery.$orderBy);
            foreach($studentDetails as $student){
                $studentSubjectDetails[$student->studentId]->id = $student->studentId;
                $studentSubjectDetails[$student->studentId]->studentId = $student->studentId;
                $studentSubjectDetails[$student->studentId]->name = $student->studentName;
                $studentSubjectDetails[$student->studentId]->regNo = $student->regNo;
                $studentSubjectDetails[$student->studentId]->rollNo = $student->rollNo;
                $studentSubjectDetails[$student->studentId]->groupId = $student->groupId;
                $studentSubjectDetails[$student->studentId]->groupName = $student->groupName;
                if($student->blockReasonType == 'SEMESTER_WISE'){
                    $studentSubjectDetails[$student->studentId]->blockReasons[$student->blockReasonId]->id = $student->blockReasonId;
                    $studentSubjectDetails[$student->studentId]->blockReasons[$student->blockReasonId]->name = $student->blockReasonName;
                    $studentSubjectDetails[$student->studentId]->blockReasons[$student->blockReasonId]->type = $student->blockReasonType;
                    $studentSubjectDetails[$student->studentId]->blockReasons[$student->blockReasonId]->contactPersonId = $student->contactPersonId;
                    $studentSubjectDetails[$student->studentId]->blockReasons[$student->blockReasonId]->contactPersonName = $student->contactPersonName;
                }
                if($student->subjectId){
                    $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->id = $student->subjectId;
                    $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->code = $student->subjectCode;
                    $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->name = $student->subjectName;
                    $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->nameCode = $student->subjectName." ( ". $student->subjectCode.") ";
                    if($student->blockReasonType == 'SUBJECT_WISE'){
                        $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->blockReasons[$student->blockReasonId]->id = $student->blockReasonId;
                        $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->blockReasons[$student->blockReasonId]->name = $student->blockReasonName;
                        $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->blockReasons[$student->blockReasonId]->type = $student->blockReasonType;
                        $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->blockReasons[$student->blockReasonId]->contactPersonId = $student->contactPersonId;
                        $studentSubjectDetails[$student->studentId]->subjects[$student->subjectId]->blockReasons[$student->blockReasonId]->contactPersonName = $student->contactPersonName;
                    }
                }
            }
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return $studentSubjectDetails;
    }
    
}