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 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 278
TranscriptApplicationService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 9
3540.00
0.00% covered (danger)
0.00%
0 / 278
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 saveTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 30
 validateSaveTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 3
 insertTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 14
 deleteTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 25
 getTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 44
 getStudentsForTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 17
 getAllStudentDetailsByTranscriptApplication
0.00% covered (danger)
0.00%
0 / 1
552.00
0.00% covered (danger)
0.00%
0 / 100
 downloadTranscriptApplicationTemplate
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 42
<?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\FeeType;
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\ec\core\service\CommonExamService;
use com\linways\base\util\TwigRenderer;
use com\linways\core\ams\professional\util\PdfUtil;
class TranscriptApplicationService extends BaseService
{
    use MakeSingletonTrait;
    private function __construct()
    {
        $this->logger = AMSLogger::getLogger('exam-controller-log');
    }
    /**
     * Save TranscriptApplication
     * @param  $transcriptApplication
     * @return $id
     */
    public function saveTranscriptApplication( $transcriptApplication){
        $transcriptApplication = $this->realEscapeObject($transcriptApplication);
        $transcriptApplication->createdBy = $GLOBALS['userId'];
        $transcriptApplication->updatedBy = $GLOBALS['userId'];
        $staffId = $GLOBALS['userId'];
        try {
            $this->validateSaveTranscriptApplication($transcriptApplication);
            $transcriptApplication->id = $this->insertTranscriptApplication($transcriptApplication);
            $this->logger->info(Events::EC_SAVE_STUDENT_TRANSCRIPT_APPLICATION, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $transcriptApplication,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            $this->logger->error(Events::EC_SAVE_STUDENT_TRANSCRIPT_APPLICATION, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $transcriptApplication,
                "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 transcript application! Please try again");
            } else if ($e->getCode() === ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException(ExamControllerException::DUPLICATE_ENTRY, "Cannot create transcript application.");
            } else {
                throw new ExamControllerException($e->getCode(), $e->getMessage());
            }
        }
        return $transcriptApplication->id;
    }
    /**
     * Validate Transcript Application Request Before Saving
     * @param  $transcriptApplication
     * @return NULL
     */
    private function validateSaveTranscriptApplication($transcriptApplication){
        if (empty($transcriptApplication->studentId) || empty($transcriptApplication->groupId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS, "empty parameter");
    }
    /**
     * insert Transcript Application
     * @param  $transcriptApplication
     * @return  $id
     */
    private function insertTranscriptApplication($transcriptApplication){
        $properties = !empty($transcriptApplication->properties) ? "'" . json_encode($transcriptApplication->properties) . "'" : "'{}'";
        $paymentDetails = !empty($transcriptApplication->paymentDetails) ? "'" . json_encode($transcriptApplication->paymentDetails) . "'" : "'{}'";
        $verificationDetails = !empty($transcriptApplication->verificationDetails) ? "'" . json_encode($transcriptApplication->verificationDetails) . "'" : "'{}'";
        $query = "INSERT INTO ec_student_applied_transcript_details
                  (student_id,groups_id,properties,payment_details,verification_details,created_by,updated_by)
                  VALUES
                  ('$transcriptApplication->studentId','$transcriptApplication->groupId',$properties,$paymentDetails,$verificationDetails,'$transcriptApplication->createdBy','$transcriptApplication->updatedBy')";
        try {
            $transcriptApplication->id = $this->executeQuery($query,true)->id;
            return $transcriptApplication->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * Delete Transcript Application
     * @param String $id
     * @return NULL
     */
    public function deleteTranscriptApplication($transcriptApplication){
        $transcriptApplication = $this->realEscapeObject($transcriptApplication);
        if (empty($transcriptApplication->studentId) || empty($transcriptApplication->groupId)){
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS, "Empty parameter.Can't delete ");
        }
        if (!empty($transcriptApplication->studentId)) {
            $whereQuery .= " AND student_id  = '$transcriptApplication->studentId";
        }
        if (!empty($transcriptApplication->groupId)) {
            $whereQuery .= " AND groups_id  = '$transcriptApplication->groupId";
        }
        
        $query = "DELETE FROM
                    ec_student_applied_transcript_details
                WHERE
                     1 = 1 ";
        try {
            $this->executeQuery($query.$whereQuery);
             // LOGGING
            $this->logger->info(Events::EC_DELETE_STUDENT_TRANSCRIPT_APPLICATION,[
                "staff" => new Staff(["id" => $staffId]),
                "request" => $transcriptApplication,
                "status" => StatusConstants::SUCCESS
            ]);
        }catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::HAVE_RELATION,"Error deleting mderation rule! Please try again");
        }
    }
     /**
     * get Transcript Application
     * @param $searchRequest
     * @return $feeTypes
     */
    public function getTranscriptApplication($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $whereQuery = null;
            $whereQuery = "";
            if (!empty($searchRequest->studentId)) {
                $studentIdString = is_array($searchRequest->studentId) ? "'" . implode("','", $searchRequest->studentId) . "'" : "'" . $searchRequest->studentId . "'";
                $whereQuery .= " AND esatd.student_id IN ( $studentIdString )";
            }
            if (!empty($searchRequest->id)) {
                $idString = is_array($searchRequest->id) ? "'" . implode("','", $searchRequest->id) . "'" : "'" . $searchRequest->id . "'";
                $whereQuery .= " AND esatd.id IN ( $idString )";
            }
            if (!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','", $searchRequest->groupId) . "'" : "'" . $searchRequest->groupId . "'";
                $whereQuery .= " AND esatd.groups_id IN ( $groupIdString )";
            }
            $query = "SELECT
                            DISTINCT 
                            esatd.id as id,
                            esatd.student_id as studentId,
                            esatd.groups_id as groupId,
                            esatd.properties as properties,
                            esatd.payment_details as paymentDetails,
                            esatd.verification_details as verificationDetails
                        FROM
                            ec_student_applied_transcript_details esatd
                        WHERE
                            1 = 1 ";
            $applications =  $this->executeQueryForList($query . $whereQuery);
            array_walk($applications,function($application){
                $application->properties =  json_decode($application->properties);
                $application->paymentDetails =  json_decode($application->paymentDetails);
                $application->verificationDetails =  json_decode($application->verificationDetails);
                $application->properties->address->permanentAddress->address = str_replace('\n', '  ', $application->properties->address->permanentAddress->address);
                $application->properties->address->permanentAddress->address = stripslashes($application->properties->address->permanentAddress->address);
                $transcriptApplication->documentAddr =  reset($applicationDetails)->properties->address->transmissionAddress;
                array_walk( $application->properties->address->transmissionAddress,function($documentAddr){
                    $documentAddr->address = str_replace('\n', '   ', $documentAddr->address);
                    $documentAddr->address  = stripslashes($documentAddr->address );
                });
            });
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return $applications;
    }
     /**
     * search All Student Details TA
     * @param $request
     * @return studentDetails
     */
    public function getStudentsForTranscriptApplication($request){
        try{
            $responseData = new \stdClass;
            if($request->registrationStatus == 'REGISTERED'){
                $request->paymentStatus = 'PAID';
            }
            else if($request->registrationStatus == 'APPLIED'){
                $request->paymentStatus = 'PENDING';
            }
            $studentDetails = $this->getAllStudentDetailsByTranscriptApplication($request);
            $studentDetails = (array)$studentDetails;
           
            $responseData->students = $studentDetails;
            return $responseData;
        }
        catch(\Exception $e) {
            throw new ExamControllerException ($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get All Student Details By ExamRegistration
     * @param $request
     * @return studentDetails
     */
    public function getAllStudentDetailsByTranscriptApplication($request){
        try{
            $request = $this->realEscapeObject($request);
            $whereQuery = "";
            $limitQuery = "";
            $joinQueary = "";
            $selectColumns = "";
            $sortBy = " ORDER BY spa.properties->>'$.registerNumber' ASC ";
           
            if(!empty($request->registrationStatus)){
                if($request->registrationStatus == 'REGISTERED' || $request->registrationStatus == 'APPLIED'){
                    $joinQueary .= " INNER JOIN ec_student_applied_transcript_details esatd ON
                        esatd.student_id = sa.studentID AND  esatd.groups_id = g.id ";
                    $selectColumns .= ", esatd.properties as transcriptProperties, esatd.payment_details as transcriptPaymentDetails,esatd.verification_details as transcriptVerificationDetails";
                    $whereQuery .= $request->registrationStatus == 'REGISTERED' ? " AND esatd.payment_details ->> '$.paymentStatus' = 'PAID'" : " AND esatd.payment_details ->> '$.paymentStatus' = 'PENDING'";
                }
                else{
                    $joinQueary .= " LEFT JOIN ec_student_applied_transcript_details esatd ON
                    esatd.student_id = sa.studentID AND  esatd.groups_id = g.id ";
                    $whereQuery .= " AND esatd.id IS NULL";
                }
            }
            if(!empty($request->registerNo)){
                $whereQuery .= " AND spa.properties->>'$.registerNumber' = '$request->registerNo'";
            }
            if(!empty($request->groupId)){
                $groupIdString = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
                $whereQuery .= " AND g.id IN ( $groupIdString )";
            }
          
            if(!empty($request->departmentId)){
                $departmentIdString = is_array($request->departmentId) ? "'" . implode("','",$request->departmentId) . "'" : "'".$request->departmentId."'";
                $whereQuery .= " AND g.properties ->> '$.departmentId' IN ( $departmentIdString )";
            }
            if(!empty($request->verificationStaff)){
                $verificationStaffString = is_array($request->verificationStaff) ? "'" . implode("','",$request->verificationStaff) . "'" : "'".$request->verificationStaff."'";
                $whereQuery .= " AND esatd.verification_details ->> '$.verificationStaff' IN ( $verificationStaffString )";
            }
            
            $query = "SELECT DISTINCT
                sa.studentID as studentId,
                sa.studentName as name,
                sa.studentEmail as email,
                sa.studentPhone as phone,
                spa.properties->>'$.registerNumber' AS registerNo,
                g.id AS groupId,
                g.name AS groupName,
                d.deptName as deptCode,
                d.departmentDesc as deptName
                $selectColumns
            FROM
                `groups` g 
            INNER JOIN group_members gm ON
                gm.groups_id = g.id
            INNER JOIN program p ON 
                p.id = g.properties->>'$.programId'
            INNER JOIN student_program_account spa ON 
               spa.id = gm.members->>'$.studentId' AND
               spa.current_program_id = p.id AND 
               spa.current_batch_id = g.id AND
               spa.properties->>'$.academicStatus' IN ('ACTIVE','COMPLETED')
            INNER JOIN studentaccount sa ON
                sa.studentID = spa.student_id
            INNER JOIN department d ON
                d.deptID = g.properties ->> '$.departmentId'
            $joinQueary 
            WHERE
                g.`type` = 'BATCH' ";
            $studentDetails = $this->executeQueryForList($query.$whereQuery.$sortBy.$limitQuery);
        }
        catch(\Exception $e) {
            throw new ExamControllerException ($e->getCode(),$e->getMessage());
        }
        array_walk($studentDetails,function($student){
            $student->isSelected = false;
            $student->verificationStaff = "";
            $student->verificationStatus = "";
            $student->transcriptProperties =   $student->transcriptProperties ? json_decode($student->transcriptProperties) : new \stdClass;;
            $student->transcriptPaymentDetails =   $student->transcriptPaymentDetails ? json_decode($student->transcriptPaymentDetails) : new \stdClass;;
            $student->transcriptVerificationDetails =   $student->transcriptVerificationDetails ? json_decode($student->transcriptVerificationDetails) : new \stdClass;;
            if($student->transcriptPaymentDetails){
                $student->dateOfPay = $student->transcriptPaymentDetails->dateOfPay ? date("d-m-Y", strtotime($student->transcriptPaymentDetails->dateOfPay)) : '';
                $student->amountPaid = $student->transcriptPaymentDetails->totalFee ?? '';
                $student->paymentMethod = '';
                if($student->transcriptPaymentDetails->paymentMethod == 'ONLINE_METHOD'){
                    $student->paymentMethod = 'Online Method';
                }
                elseif($student->transcriptPaymentDetails->paymentMethod == 'BACK_END_METHOD'){
                    $student->paymentMethod = 'College Registration ';
                }
                $student->paymentStatus = '';
                if($student->transcriptPaymentDetails->paymentStatus == 'PAID'){
                    $student->paymentStatus = 'Paid';
                }
                elseif($student->transcriptPaymentDetails->paymentStatus == 'PENDING'){
                    $student->paymentStatus = 'Pending';
                }
            }
            if($student->transcriptVerificationDetails){
                $student->verificationStaff = $student->transcriptVerificationDetails->verificationStaff;
                $student->verificationStatus = $student->transcriptVerificationDetails->verificationStatus;
            }
        });
        return $studentDetails;
    }
     /**
     * download Transcript Application Template
     * @param $request
     * @return studentDetails
     */
    public function downloadTranscriptApplicationTemplate($request){
        $request = $this->realEscapeObject($request);
        try{
            $requestForTA = new \stdClass;
            $requestForTA->studentId = $request->studentId;
            $requestForTA->groupId = $request->groupId;
            $applicationDetails = reset(TranscriptApplicationService::getInstance()->getTranscriptApplication($requestForTA));
            $transcriptApplication = new \stdClass();
            if($applicationDetails){
                $studentDetails = CommonExamService::getInstance()->getStudentDetailsByStudentId($request->studentId);
                $data = new \stdClass;
                $data->studentDetails = $studentDetails;
                $data->application = $applicationDetails;
                $data->currentDate = date('d-m-Y'); 
                $data->collegeData = CommonExamService::getInstance()->getCollegeDetails();
                $templateName = "transcriptApplicationTemplate";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/TranscriptApplication/$templateName.twig"), [ 'data'=>$data ]);
                $prtContent = NULL;
                $prtContent .= '<html><head>';
                $prtContent .= "";
                $prtContent .= '</head><title>Transcript Application</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")
                );
                $transcriptApplication->printData = PdfUtil::renderPdf($prtContent, $options);
            }
        }
        catch(\Exception $e) {
            throw new ExamControllerException ($e->getCode(),$e->getMessage());
        }
        return $transcriptApplication;
    }
    
    
}