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 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 270
NotificationUtilityService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 18
2550.00
0.00% covered (danger)
0.00%
0 / 270
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 __clone
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 1
 getInstance
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 5
 getReceiverListForAssignmentPublishedNotification
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 22
 getStudentIdsByBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentIdsBySubbatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getParentPhoneNumbersOfAbsentStudents
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 16
 getNotificationTypeIdFromNotificationTypeCode
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getTemplateNameFromNotificationTypeId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 replaceNotificationTemplatesWithParameters
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 24
 getMessageForNotification
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getSmsSenderList
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 20
 getStudentListForSendingSms
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStaffListForSendingSms
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 getNotificationType
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 updateNotifyParentOnStudentAttendanceSpecifiedTime
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 44
 getNotificationGlobalSettings
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 updateEmailNotificationStudentAbsenteesList
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 33
<?php
namespace com\linways\core\ams\professional\service\notification;
use com\linways\base\util\StringUtil;
use com\linways\base\util\SecurityUtils;
use com\linways\core\ams\professional\constant\UserType;
use com\linways\core\ams\professional\service\BaseService;
use com\linways\core\ams\professional\exception\ProfessionalException;
use com\linways\core\ams\professional\dto\notification\NotificationRecipient;
use com\linways\core\ams\professional\exception\notification\NotificationException;
use com\linways\core\ams\professional\constant\notification\NotificationTemplateConstant;
use com\linways\core\ams\professional\request\GetParentPhoneNumbersOfAbsentStudentsRequest;
use com\linways\core\ams\professional\request\notification\GetReceiverListForAssignmentPublishedNotificationRequest;
use com\linways\core\ams\professional\constant\SchedulerCodesConstant;
use com\linways\nucleus\core\service\SchedulerService;
use com\linways\core\ams\professional\request\notification\UpdateNotifyParentOnStudentAttendance;
class NotificationUtilityService extends BaseService
{
    // /Condition 1 - Presence of a static member variable
    private static $_instance = null;
    private $mapper = [];
    // /Condition 2 - Locked down the constructor
    private function __construct()
    {
//         $this->mapper = NotificationServiceMapper::getInstance ()->getMapper ();
    }
    // Prevent any oustide instantiation of this class
    // /Condition 3 - Prevent any object or instance of that class to be cloned
    private function __clone()
    {}
    // Prevent any copy of this object
    // /Condition 4 - Have a single globally accessible static method
    public static function getInstance()
    {
        if (! is_object(self::$_instance)) // or if( is_null(self::$_instance) ) or if( self::$_instance == null )
            self::$_instance = new self();
            return self::$_instance;
    }
    public function getReceiverListForAssignmentPublishedNotification(GetReceiverListForAssignmentPublishedNotificationRequest $request){
        $recipientList = [];
        $studentIds = [];
        if(!$request->batchId && !$request->subbatchId){
            throw new NotificationException(NotificationException::EMPTY_ARGUMENTS, $e->getMessage());
        }
        if($request->subbatchId){
            $studentIds = $this->getStudentIdsBySubbatchId($request->subbatchId);
        }else{
            $studentIds = $this->getStudentIdsByBatchId($request->batchId);
        }
        if(empty($studentIds)){
            return $studentIds;
        }
        foreach ($studentIds as $studentId) {
            $recipient = NULL;
            $recipient = new NotificationRecipient();
            $recipient->recipientId = $studentId->id;
            $recipient->recipientType = UserType::STUDENT;
            $recipientList[] = $recipient;
        }
        return $recipientList;
    }
    /**
     *
     * @param unknown $batchId
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     * @author gadheyan
     */
    private function getStudentIdsByBatchId($batchId){
        $sql = "";
        $studentIds = [];
        $sql = "SELECT studentID as id FROM studentaccount WHERE batchID = '$batchId'";
        try {
            $studentIds = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentIds;
    }
    /**
     *
     * @param integer $subbatchId
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     * @author gadheyan
     */
    private function getStudentIdsBySubbatchId($subbatchId){
        $sql = "";
        $studentIds = [];
        $sql = "SELECT studentID as id FROM subbatch_student WHERE subbatchID = '$subbatchId'";
        try {
            $studentIds = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentIds;
    }
/**
 * [getParentPhoneNumbersOfAbsentStudents description]
 * @param  GetParentPhoneNumbersOfAbsentStudentsRequest $request [description]
 * @return [type]                                                [description]
 */
    public function getParentPhoneNumbersOfAbsentStudents( GetParentPhoneNumbersOfAbsentStudentsRequest $request){
       if($request->attendanceDate != date("Y-m-d")){
          return null;
     }
        $response = [];
        if(!$request->subbatchId){
            $sql = "SELECT DISTINCT stu.parentPhone as parentPhoneNo, stu.studentID as studentId FROM attendance att INNER JOIN studentaccount stu ON att.studentID = stu.studentID AND att.attendanceDate = '$request->attendanceDate' AND att.hour = '$request->hour' AND att.batchID = '$request->batchId' AND att.isAbsent = 1";
        }else{
            $sql = "SELECT DISTINCT stu.parentPhone as parentPhoneNo, stu.studentID as studentId FROM attendance att INNER JOIN studentaccount stu ON att.studentID = stu.studentID AND att.attendanceDate = '$request->attendanceDate' AND att.hour = '$request->hour' AND att.batchID = '$request->batchId' AND att.isAbsent = 1 INNER JOIN subbatch_student sbt ON sbt.studentID = stu.studentID AND sbt.subbatchID = '$request->subbatchId'";
        }
        try {
            $response = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $response;
    }
    /**
     *
     * @param unknown $context
     * @param unknown $feature
     * @throws ProfessionalException
     * @return unknown
     * @author gadheyan
     */
    public function getNotificationTypeIdFromNotificationTypeCode($context, $feature){
        $context = $this->realEscapeString($context);
        $feature = $this->realEscapeString($feature);
        $sql = "SELECT id FROM notification_type WHERE context = '$context' AND feature = '$feature'";
        try {
            $id = $this->executeQueryForObject($sql)->id;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $id;
    }
    /**
     *
     * @param unknown $notificationTypeId
     * @throws ProfessionalException
     * @return unknown
     * @author gadheyan
     */
    public function getTemplateNameFromNotificationTypeId($notificationTypeId){
        $notificationTypeId = $this->realEscapeString($notificationTypeId);
        $sql = "SELECT template_name as templateName FROM notification_type WHERE id = '$notificationTypeId'";
        try {
            $templateName = $this->executeQueryForObject($sql)->templateName;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $templateName;
    }
    /**
     *
     * @param unknown $notificationList
     * @throws NotificationException
     * @return unknown
     * @author gadheyan
     */
    public function replaceNotificationTemplatesWithParameters($notificationList){
        // print_r($notificationList);die();
        $templateForNotification = null;
        foreach ($notificationList as $key => $notification) {
            $refClass = new \ReflectionClass('com\linways\core\ams\professional\constant\notification\NotificationTemplateConstant');
            $templateForNotification = $refClass->getConstant($notification->notificationType->templateName);
            try {
                $parameters = stripslashes($notification->recipient->templateParameters);
                $parameters = json_decode($parameters);
            } catch (\Exception $e) {
                continue;
            }
            if(!$templateForNotification || !$parameters){
                throw new NotificationException(NotificationException::JSON_DECODE_ERROR, "error decoding parameters and template");
            }
            try {
                $templateForNotification = json_decode(StringUtil::replace_tags($templateForNotification,(array)$parameters));
            } catch (\Exception $e) {
            }
            $notification->content = $templateForNotification;
            $notification->title = $templateForNotification->message_template->native->title;
            $notification->body = $templateForNotification->message_template->native->body;
            $notification->url = $templateForNotification->url_template;
        }
        return $notificationList;
    }
    /**
     * [getMessageForNotification - replace the template with template parameters and return the actual message]
     * @param  [type] $template           [description]
     * @param  [type] $templateParameters [description]
     * @return [type]                     [description]
     */
    public function getMessageForNotification($template, $templateParameters, $isHtmlContent = 0){
        $template = json_encode($template);
        $templateParameters = stripslashes($templateParameters);
        if($isHtmlContent){
            $templateParameters = SecurityUtils::prepareSafeHTML($templateParameters);
            $templateParameters = str_replace('\n','<br>',$templateParameters);
        }
        try {
            $templateParameters = json_decode($templateParameters);
        } catch (\xception $e) {
        }
        $template = StringUtil::replace_tags($template, (array)$templateParameters);
        $template = json_decode($template);
        return $template;
    }
    public function getSmsSenderList($notification){
        $smsSenderList = null;
        if(!$notification->recipientType){
            error_log("\nRecipientType for notification not given. Cannot send sms");
            return null;
        }
        switch ($notification->recipientType) {
            case UserType::STUDENT:
                $smsSenderList = $this->getStudentListForSendingSms($notification);
                break;
            case UserType::STAFF:
                $smsSenderList = $this->getStaffListForSendingSms($notification);
                break;
            case UserType::PARENT:
                // code...
                break;
            default:
                error_log("\nInvalid UserType. Cannot get sms sender list!");
                break;
        }
        return $smsSenderList;
    }
    public function getStudentListForSendingSms($notification){
        $sql = "";
        $smsSenderList = null;
        $sql = "SELECT nr.id, sa.studentID as recipientId, sa.studentPhone as phone FROM notification_recipient nr INNER JOIN studentaccount sa ON nr.recipient_id = sa.studentID AND nr.is_read  = 0 AND nr.notification_id = '".$notification->id."'";
       try {
            $smsSenderList = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $smsSenderList;
    }
    public function getStaffListForSendingSms($notification){
        $sql = "";
        $smsSenderList = null;
        $sql = "SELECT
                    nr.id, sa.staffID AS recipientId, sa.staffPhone AS phone
                FROM
                    notification_recipient nr
                INNER JOIN
                    staffaccounts sa ON nr.recipient_id = sa.staffID AND sa.isResigned = 0 AND nr.is_read  = 0 AND nr.notification_id = '".$notification->id."'";
       try {
            $smsSenderList = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $smsSenderList;
    }
    /**
     * Method for getting notification type
     * @param string $context
     * @param string $feature
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function getNotificationType($context,$feature)
    {
        $notificationType = null;
        $context = $this->realEscapeString($context);
        $feature = $this->realEscapeString($feature);
        
        $sql = "select id, name, context, feature, template_name as templateName, custom_template as customTemplate, created_by as createdBy, created_date as createdDate, updated_by as updatedBy, updated_date as updatedDate from notification_type WHERE context = '$context' AND feature = '$feature'";
        
        try {
            $notificationType = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
            
        }
        return $notificationType;
    }
    /**
     * Method for updating notify parent on student attendance at specified time
     * @param UpdateNotifyParentOnStudentAttendance $updateNotifyParentOnStudentAttendance
     * @throws ProfessionalException
     */
    public function updateNotifyParentOnStudentAttendanceSpecifiedTime($updateNotifyParentOnStudentAttendance)
    {
        $sqlUpdateGlobalSettings = null;
        $sqlUpdateNotificationType = null;
        $smsEnabled = 0;
        $userId = $_SESSION['adminID'];
        $updateNotifyParentOnStudentAttendance = $this->realEscapeObject($updateNotifyParentOnStudentAttendance);
        
        try {
            //Update Global notification settings
            $smsEnabled = $updateNotifyParentOnStudentAttendance->enableSMSNotification;
            $customSettingsValue = new \stdClass();
            $customSettingsValue->previousDayAttendance = $updateNotifyParentOnStudentAttendance->previousDayAttendance;
            $customSettingsValue->includeOnlyAbsentHours = $updateNotifyParentOnStudentAttendance->includeOnlyAbsentHours;
            $customSettingsValue->time = $updateNotifyParentOnStudentAttendance->notifyTime;
            
            
            $sqlUpdateGlobalSettings = "UPDATE notification_settings_global set sms_enabled = $smsEnabled,custom_settings_value = '".json_encode($customSettingsValue)."',updated_by='$userId',updated_date=utc_timestamp() where id = $updateNotifyParentOnStudentAttendance->globalSettingsId";
            
            $this->executeQuery($sqlUpdateGlobalSettings);
            
            //Update notification type
            $sqlUpdateNotificationType = "UPDATE notification_type set 
custom_template = '$updateNotifyParentOnStudentAttendance->smsContent',
updated_by='$userId',
updated_date=utc_timestamp()
 where context = '$updateNotifyParentOnStudentAttendance->context' and feature = '$updateNotifyParentOnStudentAttendance->feature'";
            
            $this->executeQuery($sqlUpdateNotificationType);
            
            //Add or update Scheduler
            $scheduleCode = SchedulerCodesConstant::NOTIFY_PARENTS_ON_STUDENT_ATTENDANCE_SPECIFIED_TIME."_".$GLOBALS['COLLEGE_CODE'];
            //delete existing task 
            SchedulerService::getInstance()->deleteScheduledTaskByCode($scheduleCode);
            //add task if sms enabled
            if($smsEnabled)
            {
                
                $schedule         = new \stdClass();
                $schedule->params = [];
                $schedule->method = "com\\linways\\core\\ams\\professional\\service\\notification\\ScheduledNotifications::notifyParentOnStudentAttendanceOnSpecifiedTime";
                $schedule->params["command"] = 'EXECUTE SERVICE';
                $schedule->params["taskParams"] = [];
                $schedule->params["taskParams"]["className"] = "com\\\\linways\\\\core\\\\ams\\\\professional\\\\service\\\\notification\\\\ScheduledNotifications";
                $schedule->params["taskParams"]["methodName"] = "notifyParentOnStudentAttendanceOnSpecifiedTime";
                $schedule->params["taskParams"]["methodParams"] = [];
                $timeForSchedule = explode(':', $updateNotifyParentOnStudentAttendance->notifyTime);
                $hour = $timeForSchedule[0];
                $minute = $timeForSchedule[1];
                $schedule->frequency = "$minute $hour"." * * *";
                $schedule->code      = $scheduleCode;
                
                $schedule->id = SchedulerService::getInstance()->addTask($schedule);
                SchedulerService::getInstance()->updateNextExecution($schedule);
            }
           
            
        
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
    }
    /**
     * Method for getting notification settings
     * @param $context,$feature
     * @throws ProfessionalException
     * @return object|NULL
     */
    public function getNotificationGlobalSettings($context,$feature)
    {
        $context = $this->realEscapeString($context);
        $feature = $this->realEscapeString($feature);
        
        $sql = "SELECT nsg.id, nsg.name, nsg.notification_type_id, nsg.custom_settings_value,nsg.feature_enabled,nsg.email_enabled
                from notification_type nt
                inner join notification_settings_global nsg on nsg.notification_type_id = nt.id
                where nt.feature = 'EMAIL_NOTIFICATION_TO_FACULTYS_OF_ABSENTEES_STUDENT_REPORT'";
        
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
            
        }
    }
    /**
     * Method for update emailNotificationStudentAbsenteesList
     * @param $context,$feature
     * @throws ProfessionalException
     * @return object|NULL
     */
    public function updateEmailNotificationStudentAbsenteesList($request)
    {
        
        $sql = "UPDATE notification_settings_global SET
                custom_settings_value = '$request->customSettingsValue',
                feature_enabled = $request->isEnabled
                WHERE id = $request->globalSettingsId ";
        try {
            $this->executeQuery($sql);
            $notificationDetails = $this->getNotificationGlobalSettings($request->context,$request->feature);
            
            //Add or update Scheduler
            $scheduleCode = SchedulerCodesConstant::EMAIL_NOTIFICATION_TO_FACULTEES_ABSENTEES_STUDENT_LIST."_".$GLOBALS['COLLEGE_CODE'];
            //delete existing task 
            SchedulerService::getInstance()->deleteScheduledTaskByCode($scheduleCode);
            //add task if email enabled
            if($notificationDetails->email_enabled == '1')
            {
                
                $schedule         = new \stdClass();
                $schedule->params = [];
                $schedule->method = "com\\linways\\core\\ams\\professional\\service\\notification\\ScheduledNotifications::sendEmailNotificationToFaculteesAbsenteesStudentList";
                $schedule->params["command"] = 'EXECUTE SERVICE';
                $schedule->params["taskParams"] = [];
                $schedule->params["taskParams"]["className"] = "com\\\\linways\\\\core\\\\ams\\\\professional\\\\service\\\\notification\\\\ScheduledNotifications";
                $schedule->params["taskParams"]["methodName"] = "sendEmailNotificationToFaculteesAbsenteesStudentList";
                $schedule->params["taskParams"]["methodParams"] = [];
                $timeForSchedule = explode(':', $request->time);
                $hour = $timeForSchedule[0];
                $minute = str_replace("AM","",$timeForSchedule[1]);
+               $minute = str_replace("PM","",$minute);
                $schedule->frequency = "$minute $hour"." * * *";
                $schedule->code      = $scheduleCode;
                
                $schedule->id = SchedulerService::getInstance()->addTask($schedule);
                SchedulerService::getInstance()->updateNextExecution($schedule);
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
            
        }
    }
}