src/Controller/CronController.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\DlmsService;
  4. use App\Service\NotificationService;
  5. use Psr\Log\LoggerInterface;
  6. use App\Service\CitrixService;
  7. use App\Service\ContestService;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpKernel\KernelInterface;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. class CronController extends AbstractController
  13. {
  14.     private $lockPath;
  15.     private EntityManagerInterface $entityManager;
  16.     public function __construct(KernelInterface $appKernel, EntityManagerInterface $entityManager)
  17.     {
  18.         $this->entityManager = $entityManager;
  19.         $this->lockPath = $appKernel->getProjectDir() . '/var/lock/';
  20.     }
  21.     /**
  22.      * @Route("/user/task-schedule", name="user-task-schedule")
  23.      */
  24.     public function runTaskSchedule(LoggerInterface $logger, CitrixService $citrixService, DlmsService $dlmsService, NotificationService $notificationService, ContestService $contestService)
  25.     {
  26.         /**
  27.          * This is called every minutes from outside.
  28.          */
  29.         $expiredUser = NULL;
  30.         $expiredTeam = NULL;
  31.         $expiredCustomer = NULL;
  32.         $releaseCitrix = $this->releaseCitrix($logger, $citrixService);
  33.         $confirmUser = $this->sendConfirmationdNotificationForUser($dlmsService, $logger);
  34.         $activeBuymore = $this->sendBuymoreActiveNotification($notificationService, $logger);
  35.         $expireSoonBuymore = $this->sendBuymoreExpireSoonNotification($notificationService, $logger);
  36.         $deactivateExpiredBuymore = $this->deactivateExpiredBuymore($logger);
  37.         $deactivateExpiredTrial = $this->deactivateExpiredTrial($logger);
  38.         $remindCheckout = $this->senRemindCheckoutNotification($notificationService, $logger);
  39.         $citrixUsageResource = $this->checkCitrixUsageResourceNotification($notificationService, $citrixService, $logger);
  40.         $publishContestResult = $this->publishContestResult($contestService, $logger);
  41.         
  42.         $isCheckExpiration = $this->getParameter('is.check.expiration');
  43.         if ($isCheckExpiration == 'true') {
  44.             $expiredUser = $this->sendExpiredNotificationForUser($dlmsService, $logger);
  45.             // $expiredTeam = $this->sendExpiredNotificationForTeam($dlmsService, $logger);
  46.             $expiredCustomer = $this->sendExpiredNotificationForCustomer($dlmsService, $logger);
  47.         }
  48.         return $this->json(['release_citrix' => count($releaseCitrix), 'confirm_user' => $confirmUser, 'active_buymore' => $activeBuymore, 'expiresoon_buymore' => $expireSoonBuymore, 'deactivate_expired_buymore' => $deactivateExpiredBuymore, 'deactivate_expired_trial' => $deactivateExpiredTrial, 'remind_checkout' => $remindCheckout, 'citrix_usage_resource' => $citrixUsageResource, 'publish_contest_result' => $publishContestResult, 'expired_user' => $expiredUser, 'expired_team' => $expiredTeam, 'expired_customer' => $expiredCustomer], 200, [
  49.             'Access-Control-Allow-Origin' => '*'
  50.         ]);
  51.     }
  52.     // ==================================================
  53.     // ==== common functions
  54.     // ==================================================
  55.     private function handleOverlappingRequest($taskName, $fileLockPath)
  56.     {
  57.         if (file_exists($fileLockPath)) {
  58.             try {
  59.                 $taskSchedule = $this->getTaskSchedule($taskName);
  60.                 $diffMinute = $this->getDiffMinute($taskSchedule['last_succeed_at']);
  61.                 if ($diffMinute >= $taskSchedule['max_time_skip']) {
  62.                     throw new \Exception("The previous request is processed too long in {$diffMinute} minutes.");
  63.                 }
  64.                 return $diffMinute;
  65.             } catch (\Exception $e) {
  66.                 unlink($fileLockPath);
  67.                 throw $e;
  68.             }
  69.         }
  70.         throw new \Exception("There is no lock file {$fileLockPath}.");
  71.     }
  72.     private function getTaskSchedule($taskName)
  73.     {
  74.         $conn = $this->entityManager->getConnection();
  75.         $sql = '
  76.             SELECT *
  77.             FROM task_schedule
  78.             WHERE task_name  = :task_name
  79.         ';
  80.         $stmt = $conn->prepare($sql);
  81.         $stmt->execute(['task_name' => $taskName]);
  82.         $task = $stmt->fetch();
  83.         if (empty($task)) {
  84.             throw new \Exception('There is no task: ' . $taskName);
  85.         }
  86.         return $task;
  87.     }
  88.     private function getDiffMinute($lastSucceedTime)
  89.     {
  90.         try {
  91.             $lastSucceedDateTime = new \DateTime($lastSucceedTime);
  92.             $diffDate = $lastSucceedDateTime->diff(new \DateTime());
  93.             $diffMinute = $diffDate->days * 24 * 60;
  94.             $diffMinute += $diffDate->h * 60;
  95.             $diffMinute += $diffDate->i;
  96.             return $diffMinute;
  97.         } catch (\Exception $e) {
  98.             throw new \Exception('There is an error on getDiffMinute: ' . $e->getMessage());
  99.         }
  100.     }
  101.     private function createLockFile($fileLockPath)
  102.     {
  103.         try {
  104.             if (!is_dir($this->lockPath)) {
  105.                 mkdir($this->lockPath, 0777, true);
  106.             }
  107.             if (file_exists($fileLockPath)) {
  108.                 throw new \Exception('Lock file is exist.');
  109.             } else {
  110.                 $file = fopen($fileLockPath,"w");
  111.                 fwrite($file, '');
  112.                 fclose($file);
  113.             }
  114.         } catch (\Exception $e) {
  115.             throw new \Exception('There is an error on createLockFile: ' . $e->getMessage());
  116.         }
  117.     }
  118.     private function updateLastTimeSuccessForTask($taskName, $maxTimeSkip = 5)
  119.     {
  120.         $conn = $this->entityManager->getConnection();
  121.         $sql = "
  122.             INSERT INTO task_schedule (task_name, last_succeed_at, max_time_skip)
  123.             VALUES (:task_name, :last_succeed_at, :max_time_skip)
  124.             ON DUPLICATE KEY UPDATE
  125.             last_succeed_at = :last_succeed_at
  126.         ";
  127.         $stmt = $conn->prepare($sql);
  128.         $stmt->execute([
  129.             'task_name' => $taskName,
  130.             'last_succeed_at' => date('Y-m-d H:i:s'),
  131.             'max_time_skip' => $maxTimeSkip
  132.         ]);
  133.     }
  134.     private function getTrainerEmailOf($customerId, $getAll = false)
  135.     {
  136.         $trainerEmailArr = [];
  137.         $masterTrainer = $this->getMasterTrainerByCustomerId($customerId);
  138.         if (!empty($masterTrainer)) {
  139.             $trainerEmailArr[] = $masterTrainer['email'];
  140.         }
  141.         if ($getAll || !$this->isMultiSite($customerId)) {
  142.             $trainers = $this->getTrainerByCustomerId($customerId);
  143.             if (!empty($trainers)) {
  144.                 $trainerEmail =  array_column($trainers, 'email');
  145.                 $trainerEmailArr = array_merge($trainerEmailArr, $trainerEmail);
  146.             }
  147.         }
  148.         return $trainerEmailArr;
  149.     }
  150.     private function getMasterTrainerByCustomerId($customerId)
  151.     {
  152.         $entityManager = $this->entityManager;
  153.         $conn = $entityManager->getConnection();
  154.         $sql = "
  155.             SELECT *
  156.             FROM users 
  157.             WHERE
  158.                 roles LIKE '%\"ROLE_MASTER_TRAINER\"%'
  159.                 AND active = 1
  160.                 AND verified = 1
  161.                 AND customer_id = :customer_id
  162.         ";
  163.         $stmt = $conn->prepare($sql);
  164.         $stmt->execute(['customer_id' => $customerId]);
  165.         return $stmt->fetch();
  166.     }
  167.     private function isMultiSite($customerId)
  168.     {
  169.         $entityManager = $this->entityManager;
  170.         $conn = $entityManager->getConnection();
  171.         $sql = "
  172.             SELECT *
  173.             FROM sites
  174.             WHERE customer_id = :customer_id
  175.         ";
  176.         $stmt = $conn->prepare($sql);
  177.         $stmt->execute(['customer_id' => $customerId]);
  178.         $sites = $stmt->fetchAll();
  179.         if (count($sites) > 1) {
  180.             return true;
  181.         }
  182.         return false;
  183.     }
  184.     private function getTrainerByCustomerId($customerId)
  185.     {
  186.         $entityManager = $this->entityManager;
  187.         $conn = $entityManager->getConnection();
  188.         $sql = "
  189.             SELECT u.*
  190.             FROM users u
  191.             JOIN groups g ON g.id = u.group_id
  192.             JOIN sites s ON s.id = g.site_id
  193.             WHERE u.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%'
  194.             AND u.active = 1
  195.             AND u.verified = 1
  196.             AND s.customer_id = :customer_id
  197.             ORDER BY u.id
  198.         ";
  199.         $stmt = $conn->prepare($sql);
  200.         $stmt->execute(['customer_id' => $customerId]);
  201.         return $stmt->fetchAll();
  202.     }
  203.     private function getTrainerOfTeam($teamId)
  204.     {
  205.         $conn = $this->entityManager->getConnection();
  206.         $sql = "
  207.             SELECT us.*
  208.             FROM users us
  209.             JOIN trainer_team tt ON us.id = tt.trainer_id AND tt.team_id = :group_id
  210.             WHERE us.verified = 1
  211.             AND us.active = 1
  212.             AND us.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%'
  213.             ORDER BY us.id DESC
  214.         ";
  215.         $stmt = $conn->prepare($sql);
  216.         $stmt->execute(['group_id' => $teamId]);
  217.         $trainers = $stmt->fetchAll();
  218.         if (empty($trainers)) {
  219.             throw new \Exception("There is no trainers on group id: {$teamId}.");
  220.         }
  221.         return $trainers;
  222.     }
  223.     private function getContactByCustomerId($customerId)
  224.     {
  225.         $conn = $this->entityManager->getConnection();
  226.         $sql = "
  227.             SELECT u.*
  228.             FROM users u
  229.             WHERE u.verified = 1
  230.             AND u.active = 1
  231.             AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
  232.             AND u.customer_id = :customer_id
  233.         ";
  234.         $stmt = $conn->prepare($sql);
  235.         $stmt->execute(['customer_id' => $customerId]);
  236.         $contact = $stmt->fetch();
  237.         return $contact;
  238.     }
  239.     // ==================================================
  240.     // ==== releaseCitrix
  241.     // ==================================================
  242.     private function releaseCitrix($logger, $citrixService)
  243.     {
  244.         $period = $this->getParameter('citrix.expire.period');
  245.         if (empty($period)) {
  246.             $period = 5;
  247.         }
  248.         $conn = $this->entityManager->getConnection();
  249.         $sql = '
  250.             SELECT *
  251.             FROM citrix
  252.             WHERE userid is not null
  253.             AND session_updated < :session_updated
  254.             ';
  255.         $stmt = $conn->prepare($sql);
  256.         $stmt->execute(['session_updated' => date('Y-m-d H:i:s', strtotime('now -'.$period.' minute'))]);
  257.         $data = $stmt->fetchAll();
  258.         $output = [];
  259.         if (!empty($data)) {
  260.             foreach ($data as $item) {
  261.                 $userid = $item['userid'];
  262.                 $item['userid'] = 0; // clear assign
  263.                 try {
  264.                     $result = $citrixService->apiUpdateCitrix($item, $logger);
  265.                     if ($result && $result->code == 201) {
  266.                         $sql = '
  267.                             UPDATE citrix
  268.                             SET userid = null
  269.                             WHERE login = :login
  270.                             ';
  271.                         $stmt = $conn->prepare($sql);
  272.                         $stmt->execute(['login' => $item['login']]);
  273.                         $sql = '
  274.                             SELECT id
  275.                             FROM citrix_log
  276.                             WHERE login = :login AND session_end is null
  277.                             ';
  278.                         $stmt = $conn->prepare($sql);
  279.                         $stmt->execute([
  280.                             'login' => $item['login'], 
  281.                         ]);
  282.                         $logs = $stmt->fetchAll();
  283.                         foreach ($logs as $log) {
  284.                             $sql = '
  285.                                 UPDATE citrix_log
  286.                                 SET session_end = :session_end
  287.                                 WHERE id = :id
  288.                             ';
  289.                             $stmt = $conn->prepare($sql);
  290.                             $stmt->execute([
  291.                                 'id' => $log['id'], 
  292.                                 'session_end' => date('Y-m-d H:i:s'),
  293.                             ]);  
  294.                         }
  295.                         $output[] = $item['login'];
  296.                     }
  297.                 } catch (\Exception $e) {
  298.                     $logger->error('apiUpdateCitrix ' . $e->getMessage());
  299.                 }
  300.             }
  301.         }
  302.         $logger->error('userCitrixRelease ' . json_encode($output));
  303.         return $output;
  304.     }
  305.     // ==================================================
  306.     // ==== sendConfirmationdNotificationForUser
  307.     // ==================================================
  308.     private function sendConfirmationdNotificationForUser($dlmsService, $logger)
  309.     {
  310.         $logger->error("sendConfirmationdNotificationForUser at " . date('Y-m-d H:i:s'));
  311.         $taskName = 'confirmation_user_notification';
  312.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  313.         try {
  314.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  315.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  316.             return NULL;
  317.         } catch (\Exception $e) {
  318.             $logger->error($e->getMessage());
  319.         }
  320.         try {
  321.             $users = $this->getUserNeedConfirmation();
  322.             $this->createLockFile($fileLockPath);
  323.         } catch (\Exception $e) {
  324.             $logger->error($e->getMessage());
  325.             return NULL;
  326.         }
  327.         try {
  328.             foreach ($users as $user) {
  329.                 if (filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
  330.                     if ($user['verified']) {
  331.                         if ($user['enable_sso_microsoft']) {
  332.                             $dlmsService->sendEmailSsoReactivate($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['language'], true);
  333.                         } else {
  334.                             $dlmsService->sendEmailReactivate($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['password'], $user['language'], true);
  335.                         }
  336.                     } elseif (strpos($user['roles'], '"ROLE_USER"') !== false) {
  337.                         if ($user['company_type'] == 'Contest') {
  338.                             $dlmsService->sendEmailComfirmationForContestUser($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['contest_name'], $user['language'], true);
  339.                         } else {
  340.                             $dlmsService->sendEmailComfirmationForUser($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['company'], $user['language'], true);
  341.                         }
  342.                     } else {
  343.                         $dlmsService->sendEmailComfirmationForTrainer($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['company'], $user['language'], true);
  344.                     }
  345.                 }
  346.                 $this->notifyOneUserConfirmationSuccess($user, $taskName);  
  347.             }
  348.             $this->notifyUserConfirmationSuccess($users, $taskName);  
  349.         } catch (\Exception $e) {
  350.             $logger->error($e->getMessage());
  351.         }
  352.         
  353.         unlink($fileLockPath);
  354.         $logger->error('sendConfirmationdNotificationForUser success for user: ' . json_encode($users));
  355.         return true;
  356.     }
  357.     private function getUserNeedConfirmation()
  358.     {
  359.         $conn = $this->entityManager->getConnection();
  360.         $sql = 'SELECT u.*, s.customer_id, s.name as company, c.company_type, c.company as contest_name, c.enable_sso_microsoft
  361.             FROM users u
  362.             JOIN groups g ON g.id = u.group_id
  363.             JOIN sites s ON s.id = g.site_id
  364.             JOIN customers c ON c.id = s.customer_id
  365.             WHERE u.verify_queue = 1
  366.             AND u.active = 1
  367.             ORDER BY u.created_at ASC
  368.             LIMIT 4
  369.         ';
  370.         // 4 emails / minute => 15s
  371.         $stmt = $conn->prepare($sql);
  372.         $stmt->execute();
  373.         $users = $stmt->fetchAll();
  374.         if (empty($users)) {
  375.             throw new \Exception("There is no user need confirmation");
  376.         }
  377.         return $users;
  378.     }
  379.     private function notifyOneUserConfirmationSuccess($user, $taskName)
  380.     {
  381.         $conn = $this->entityManager->getConnection();
  382.         $sql = "
  383.             UPDATE users
  384.             SET verify_queue = 0
  385.             WHERE id = :id
  386.         ";
  387.         $stmt = $conn->prepare($sql);
  388.         $stmt->execute(['id' => $user['id']]);
  389.     }
  390.     private function notifyUserConfirmationSuccess($users, $taskName)
  391.     {
  392.         $this->updateLastTimeSuccessForTask($taskName);
  393.     }
  394.     // ==================================================
  395.     // ==== sendBuymoreActiveNotification
  396.     // ==================================================
  397.     private function sendBuymoreActiveNotification($notificationService, $logger)
  398.     {
  399.         $logger->error("sendBuymoreActiveNotification at " . date('Y-m-d H:i:s'));
  400.         $taskName = 'buymore_active_notification';
  401.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  402.         try {
  403.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  404.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  405.             return NULL;
  406.         } catch (\Exception $e) {
  407.             $logger->error($e->getMessage());
  408.         }
  409.         try {
  410.             $purchases = $this->getBuymorePurchaseWillActive();
  411.             $this->createLockFile($fileLockPath);
  412.         } catch (\Exception $e) {
  413.             $logger->error($e->getMessage());
  414.             return NULL;
  415.         }
  416.         try {
  417.             foreach ($purchases as $purchase) {
  418.                 $trainerEmailArr = $this->getTrainerEmailOf($purchase['customer_id'], true);
  419.                 $notificationService->sendEmailBuymoreActive($trainerEmailArr, $purchase, true);
  420.                 $this->notifyOneBuymoreActiveSuccess($purchase, $taskName);  
  421.             }
  422.             $this->notifyBuymoreActiveSuccess($purchases, $taskName);  
  423.         } catch (\Exception $e) {
  424.             $logger->error($e->getMessage());
  425.         }
  426.         
  427.         unlink($fileLockPath);
  428.         $logger->error('sendBuymoreActiveNotification success for user: ' . json_encode($purchases));
  429.         return true;
  430.     }
  431.     private function getBuymorePurchaseWillActive()
  432.     {
  433.         $buyMorePrimary = 99;
  434.         $conn = $this->entityManager->getConnection();
  435.         $sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
  436.             FROM purchases p
  437.             JOIN offers of ON p.offer_id = of.id
  438.             JOIN users u ON p.user_id = u.id
  439.             JOIN transactions as tr ON p.id = tr.purchase_id
  440.             WHERE of.is_primary = {$buyMorePrimary}
  441.                 AND p.is_active = 1
  442.                 AND tr.status = 'completed'
  443.                 AND p.active_processed = 0
  444.                 AND p.start_date <= :start_date
  445.             ORDER BY p.start_date
  446.             LIMIT 1
  447.         ";
  448.         $stmt = $conn->prepare($sql);
  449.         $stmt->execute(['start_date' => date('Y-m-d H:i:s')]);
  450.         $purchases = $stmt->fetchAll();
  451.         if (empty($purchases)) {
  452.             throw new \Exception("There is no purchases will active");
  453.         }
  454.         return $purchases;
  455.     }
  456.     private function notifyOneBuymoreActiveSuccess($purchase, $taskName)
  457.     {
  458.         $conn = $this->entityManager->getConnection();
  459.         $sql = "
  460.             UPDATE purchases
  461.             SET active_processed = 1
  462.             WHERE id = :id
  463.         ";
  464.         $stmt = $conn->prepare($sql);
  465.         $stmt->execute(['id' => $purchase['id']]);
  466.     }
  467.     private function notifyBuymoreActiveSuccess($purchases, $taskName)
  468.     {
  469.         $this->updateLastTimeSuccessForTask($taskName);
  470.     }
  471.     // ==================================================
  472.     // ==== sendBuymoreExpireSoonNotification
  473.     // ==================================================
  474.     private function sendBuymoreExpireSoonNotification($notificationService, $logger)
  475.     {
  476.         $logger->error("sendBuymoreExpireSoonNotification at " . date('Y-m-d H:i:s'));
  477.         $taskName = 'buymore_expiresoon_notification';
  478.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  479.         try {
  480.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  481.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  482.             return NULL;
  483.         } catch (\Exception $e) {
  484.             $logger->error($e->getMessage());
  485.         }
  486.         try {
  487.             $purchases = $this->getBuymorePurchaseExpireSoon();
  488.             $this->createLockFile($fileLockPath);
  489.         } catch (\Exception $e) {
  490.             $logger->error($e->getMessage());
  491.             return NULL;
  492.         }
  493.         try {
  494.             foreach ($purchases as $purchase) {
  495.                 $trainerEmailArr = $this->getTrainerEmailOf($purchase['customer_id'], true);
  496.                 $notificationService->sendEmailBuymoreExpireSoon($trainerEmailArr, $purchase, true);
  497.                 $this->notifyOneBuymoreExpireSoonSuccess($purchase, $taskName);  
  498.             }
  499.             $this->notifyBuymoreExpireSoonSuccess($purchases, $taskName);  
  500.         } catch (\Exception $e) {
  501.             $logger->error($e->getMessage());
  502.         }
  503.         
  504.         unlink($fileLockPath);
  505.         $logger->error('sendBuymoreExpireSoonNotification success for user: ' . json_encode($purchases));
  506.         return true;
  507.     }
  508.     private function getBuymorePurchaseExpireSoon()
  509.     {
  510.         $buyMorePrimary = 99;
  511.         $conn = $this->entityManager->getConnection();
  512.         $sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
  513.             FROM purchases p
  514.             JOIN offers of ON p.offer_id = of.id
  515.             JOIN users u ON p.user_id = u.id
  516.             JOIN transactions as tr ON p.id = tr.purchase_id
  517.             WHERE of.is_primary = {$buyMorePrimary}
  518.                 AND p.is_active = 1
  519.                 AND tr.status = 'completed'
  520.                 AND p.expire_soon_processed = 0
  521.                 AND p.expired_date <= :expired_date
  522.                 AND p.expired_date >= '" . date('Y-m-d') . "'
  523.             ORDER BY p.expired_date
  524.             LIMIT 1
  525.         ";
  526.         $stmt = $conn->prepare($sql);
  527.         $stmt->execute(['expired_date' => date('Y-m-d H:i:s', strtotime('now +7 days'))]);
  528.         $purchases = $stmt->fetchAll();
  529.         if (empty($purchases)) {
  530.             throw new \Exception("There is no purchases will active");
  531.         }
  532.         return $purchases;
  533.     }
  534.     private function notifyOneBuymoreExpireSoonSuccess($purchase, $taskName)
  535.     {
  536.         $conn = $this->entityManager->getConnection();
  537.         $sql = "
  538.             UPDATE purchases
  539.             SET expire_soon_processed = 1
  540.             WHERE id = :id
  541.         ";
  542.         $stmt = $conn->prepare($sql);
  543.         $stmt->execute(['id' => $purchase['id']]);
  544.     }
  545.     private function notifyBuymoreExpireSoonSuccess($purchases, $taskName)
  546.     {
  547.         $this->updateLastTimeSuccessForTask($taskName);
  548.     }
  549.     // ==================================================
  550.     // ==== deactivateExpiredBuymore
  551.     // ==================================================
  552.     private function deactivateExpiredBuymore($logger)
  553.     {
  554.         $logger->error("deactivateExpiredBuymore at " . date('Y-m-d H:i:s'));
  555.         $taskName = 'deactivate_expired_buymore';
  556.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  557.         try {
  558.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  559.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  560.             return NULL;
  561.         } catch (\Exception $e) {
  562.             $logger->error($e->getMessage());
  563.         }
  564.         try {
  565.             $purchases = $this->getExpiredBuymorePurchase();
  566.             $this->createLockFile($fileLockPath);
  567.         } catch (\Exception $e) {
  568.             $logger->error($e->getMessage());
  569.             return NULL;
  570.         }
  571.         try {
  572.             foreach ($purchases as $purchase) {
  573.                 $this->deactivateUsersOfExpiredBuymorePurchase($purchase);  
  574.                 $this->updateBuyMoreQuotaForCustomer($purchase);  
  575.                 $this->notifyOneExpiredBuymorePurchaseSuccess($purchase, $taskName);  
  576.             }
  577.             $this->notifyExpiredBuymorePurchaseSuccess($purchases, $taskName);  
  578.         } catch (\Exception $e) {
  579.             $logger->error($e->getMessage());
  580.         }
  581.         
  582.         unlink($fileLockPath);
  583.         $logger->error('deactivateExpiredBuymore success for user: ' . json_encode($purchases));
  584.         return true;
  585.     }
  586.     private function getExpiredBuymorePurchase()
  587.     {
  588.         $buyMorePrimary = 99;
  589.         $conn = $this->entityManager->getConnection();
  590.         $sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
  591.             FROM purchases p
  592.             JOIN offers of ON p.offer_id = of.id
  593.             JOIN users u ON p.user_id = u.id
  594.             JOIN transactions as tr ON p.id = tr.purchase_id
  595.             WHERE of.is_primary = {$buyMorePrimary}
  596.                 AND p.is_active = 1
  597.                 AND tr.status = 'completed'
  598.                 AND p.expire_processed = 0
  599.                 AND p.expired_date < '" . date('Y-m-d') . "'
  600.             ORDER BY p.expired_date
  601.             LIMIT 1
  602.         ";
  603.         $stmt = $conn->prepare($sql);
  604.         $stmt->execute();
  605.         $purchases = $stmt->fetchAll();
  606.         if (empty($purchases)) {
  607.             throw new \Exception("There is no purchases will active");
  608.         }
  609.         return $purchases;
  610.     }
  611.     private function deactivateUsersOfExpiredBuymorePurchase($purchase)
  612.     {
  613.         $conn = $this->entityManager->getConnection();
  614.         $sql = "UPDATE users
  615.             SET active = 0
  616.             WHERE purchase_id = :purchase_id
  617.                 AND roles LIKE '%\"ROLE_USER\"%'
  618.         ";
  619.         $stmt = $conn->prepare($sql);
  620.         $stmt->execute(['purchase_id' => $purchase['id']]);
  621.         // don't need to send API to update "expired_date" of users to yesterday in DLMS
  622.         // because Purchase expired_date < today
  623.         // => users expired_date < today
  624.     }
  625.     private function updateBuyMoreQuotaForCustomer($purchase)
  626.     {
  627.         $conn = $this->entityManager->getConnection();
  628.         $sql = 'UPDATE `customers` 
  629.             SET `num_users` = num_users - :num_users, `num_licenses` = num_licenses - :num_licenses
  630.             WHERE id = :id
  631.         ';
  632.         $stmt = $conn->prepare($sql);
  633.         $stmt->execute([
  634.             'num_users' => $purchase['num_users'], 
  635.             'num_licenses' => $purchase['num_licenses'], 
  636.             'id' => $purchase['customer_id'], 
  637.         ]);
  638.     }
  639.     private function notifyOneExpiredBuymorePurchaseSuccess($purchase, $taskName)
  640.     {
  641.         $conn = $this->entityManager->getConnection();
  642.         $sql = "
  643.             UPDATE purchases
  644.             SET expire_processed = 1
  645.             WHERE id = :id
  646.         ";
  647.         $stmt = $conn->prepare($sql);
  648.         $stmt->execute(['id' => $purchase['id']]);
  649.     }
  650.     private function notifyExpiredBuymorePurchaseSuccess($purchases, $taskName)
  651.     {
  652.         $this->updateLastTimeSuccessForTask($taskName);
  653.     }
  654.     // ==================================================
  655.     // ==== deactivateExpiredTrial
  656.     // ==================================================
  657.     private function deactivateExpiredTrial($logger)
  658.     {
  659.         $logger->error("deactivateExpiredTrial at " . date('Y-m-d H:i:s'));
  660.         $taskName = 'deactivate_expired_trial';
  661.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  662.         try {
  663.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  664.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  665.             return NULL;
  666.         } catch (\Exception $e) {
  667.             $logger->error($e->getMessage());
  668.         }
  669.         try {
  670.             $users = $this->getExpiredTrialUsers();
  671.             $this->createLockFile($fileLockPath);
  672.         } catch (\Exception $e) {
  673.             $logger->error($e->getMessage());
  674.             return NULL;
  675.         }
  676.         try {
  677.             foreach ($users as $user) {
  678.                 $this->deactivateExpiredTrialUser($user);  
  679.             }
  680.             $this->notifyExpiredTrialSuccess($taskName);  
  681.         } catch (\Exception $e) {
  682.             $logger->error($e->getMessage());
  683.         }
  684.         
  685.         unlink($fileLockPath);
  686.         $logger->error('deactivateExpiredTrial success for user: ' . json_encode($users));
  687.         return true;
  688.     }
  689.     private function getExpiredTrialUsers()
  690.     {
  691.         $conn = $this->entityManager->getConnection();
  692.         $sql = "SELECT u.id
  693.             FROM settings s
  694.             JOIN groups g ON g.package_code = s.value
  695.             JOIN users u ON u.group_id = g.id
  696.             WHERE s.name IN ('trial_shots', 'trial_heatset', 'trial_flexo', 'trial_gravure')
  697.                 AND u.roles LIKE '%\"ROLE_USER\"%'
  698.                 AND u.active = 1
  699.                 AND u.expired_date < :expired_date
  700.         ";
  701.         $stmt = $conn->prepare($sql);
  702.         $stmt->execute(['expired_date' => date('Y-m-d')]);
  703.         $users = $stmt->fetchAll();
  704.         if (empty($users)) {
  705.             throw new \Exception("There is no expired trial user");
  706.         }
  707.         return $users;
  708.     }
  709.     private function deactivateExpiredTrialUser($user)
  710.     {
  711.         $conn = $this->entityManager->getConnection();
  712.         $sql = "UPDATE users
  713.             SET active = 0
  714.             WHERE id = :id
  715.         ";
  716.         $stmt = $conn->prepare($sql);
  717.         $stmt->execute(['id' => $user['id']]);
  718.     }
  719.     private function notifyExpiredTrialSuccess($taskName)
  720.     {
  721.         $this->updateLastTimeSuccessForTask($taskName);
  722.     }
  723.     // ==================================================
  724.     // ==== sendExpiredNotificationForUser
  725.     // ==================================================
  726.     private function sendExpiredNotificationForUser($dlmsService, $logger)
  727.     {
  728.         $logger->error("sendExpiredNotificationForUser at " . date('Y-m-d H:i:s'));
  729.         $taskName = 'expired_user_notification';
  730.         $dayBeforeExpiration = 5;
  731.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  732.         try {
  733.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  734.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  735.             return NULL;
  736.         } catch (\Exception $e) {
  737.             $logger->error($e->getMessage());
  738.         }
  739.         try {
  740.             $user = $this->getSoonExpiredUser($dayBeforeExpiration);
  741.             $this->createLockFile($fileLockPath);
  742.         } catch (\Exception $e) {
  743.             $logger->error($e->getMessage());
  744.             return NULL;
  745.         }
  746.         
  747.         try {
  748.             $user['username'] = $user['first_name'] . ' ' . $user['last_name'];
  749.             $user['expired_date'] = date('d-m-Y', strtotime($user['expired_date']));
  750.             $dlmsService->notifyUserExpiration($user);
  751.             $this->notifyUserExpirationSuccess($user['id'], $taskName);
  752.         } catch (\Exception $e) {
  753.             $logger->error($e->getMessage());
  754.         }
  755.         
  756.         unlink($fileLockPath);
  757.         $logger->error('sendExpiredNotificationForUser success for user: ' . json_encode($user));
  758.         return true;
  759.     }
  760.     private function getSoonExpiredUser($dayBeforeExpiration)
  761.     {
  762.         $conn = $this->entityManager->getConnection();
  763.         $sql = "
  764.             SELECT u.*, s.name as company, DATEDIFF(u.expired_date, CURDATE()) as diff_days, g.name as team_name
  765.             FROM users u
  766.             JOIN groups g ON g.id = u.group_id
  767.             JOIN sites s ON s.id = g.site_id
  768.             JOIN customers c ON c.id = s.customer_id AND c.company_type != 'Contest'
  769.             WHERE u.expired_queue = 0
  770.             AND u.verified = 1
  771.             AND u.active = 1
  772.             AND u.customer_id is NULL
  773.             AND ( u.roles LIKE '%\"ROLE_USER\"%' OR u.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%')
  774.             AND DATEDIFF(u.expired_date, CURDATE()) > 0
  775.             AND DATEDIFF(u.expired_date, CURDATE()) <= {$dayBeforeExpiration}
  776.             ORDER BY u.created_at ASC
  777.             LIMIT 1
  778.         ";
  779.         $stmt = $conn->prepare($sql);
  780.         $stmt->execute();
  781.         $user = $stmt->fetch();
  782.         if (empty($user)) {
  783.             throw new \Exception("There is no soon expired user in next {$dayBeforeExpiration} days.");
  784.         }
  785.         return $user;
  786.     }
  787.     private function notifyUserExpirationSuccess($userId, $taskName)
  788.     {
  789.         $conn = $this->entityManager->getConnection();
  790.         $sql = "
  791.             UPDATE users SET expired_queue = 1
  792.             WHERE id = :id;
  793.         ";
  794.         $stmt = $conn->prepare($sql);
  795.         $stmt->execute(['id' => $userId]);
  796.         $this->updateLastTimeSuccessForTask($taskName);
  797.     }
  798.     // ==================================================
  799.     // ==== sendExpiredNotificationForCustomer
  800.     // ==================================================
  801.     private function sendExpiredNotificationForCustomer($dlmsService, $logger)
  802.     {
  803.         $logger->error("sendExpiredNotificationForCustomer at " . date('Y-m-d H:i:s'));
  804.         $taskName = 'expired_customer_notification';
  805.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  806.         try {
  807.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  808.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  809.             return NULL;
  810.         } catch (\Exception $e) {
  811.             $logger->error($e->getMessage());
  812.         }
  813.         try {
  814.             $user = $this->getSoonExpiredCustomer();
  815.             $this->createLockFile($fileLockPath);
  816.         } catch (\Exception $e) {
  817.             $logger->error($e->getMessage());
  818.             return NULL;
  819.         }
  820.         try {
  821.             $trainerEmailArr = $this->getTrainerEmailOf($user['customer_id']);
  822.             $dlmsService->notifyCustomerExpiration($user, $trainerEmailArr);
  823.             $this->notifyCustomerExpirationSuccess($user['id'], $taskName);
  824.         } catch (\Exception $e) {
  825.             $logger->error($e->getMessage());
  826.         }
  827.         
  828.         unlink($fileLockPath);
  829.         $logger->error('sendExpiredNotificationForCustomer success for user: ' . json_encode($user));
  830.         return true;
  831.     }
  832.     private function getSoonExpiredCustomer()
  833.     {
  834.         $conn = $this->entityManager->getConnection();
  835.         // $sql = "
  836.         //     SELECT u.*, c.company, c.end_date, c.language as company_language, DATEDIFF(c.end_date, CURDATE()) as diff_days, (DATEDIFF(c.end_date, c.start_date) /4) as duration_4
  837.         //     FROM users u
  838.         //     JOIN customers c ON c.id = u.customer_id AND c.company_type != 'Contest'
  839.         //     WHERE u.expired_queue = 0
  840.         //     AND u.verified = 1
  841.         //     AND u.active = 1
  842.         //     AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
  843.         //     AND DATEDIFF(c.end_date, CURDATE()) > 0
  844.         //     AND DATEDIFF(c.end_date, CURDATE()) <= (DATEDIFF(c.end_date, c.start_date) /4)
  845.         //     ORDER BY u.created_at ASC
  846.         //     LIMIT 1
  847.         // ";
  848.         $sql = "
  849.             SELECT u.*, c.company, c.end_date, c.language as company_language, DATEDIFF(c.end_date, CURDATE()) as diff_days
  850.             FROM users u
  851.             JOIN customers c ON c.id = u.customer_id AND c.company_type != 'Contest'
  852.             WHERE u.expired_queue = 0
  853.             AND u.verified = 1
  854.             AND u.active = 1
  855.             AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
  856.             AND DATEDIFF(c.end_date, CURDATE()) > 0
  857.             AND DATEDIFF(c.end_date, CURDATE()) <= 30
  858.             ORDER BY u.created_at ASC
  859.             LIMIT 1
  860.         ";
  861.         $stmt = $conn->prepare($sql);
  862.         $stmt->execute();
  863.         $user = $stmt->fetch();
  864.         if (empty($user)) {
  865.             throw new \Exception("There is no soon expired customer.");
  866.         }
  867.         return $user;
  868.     }
  869.     private function notifyCustomerExpirationSuccess($userId, $taskName)
  870.     {
  871.         $conn = $this->entityManager->getConnection();
  872.         $sql = "
  873.             UPDATE users SET expired_queue = 1
  874.             WHERE id = :id;
  875.         ";
  876.         $stmt = $conn->prepare($sql);
  877.         $stmt->execute(['id' => $userId]);
  878.         $this->updateLastTimeSuccessForTask($taskName);
  879.     }
  880.     // ==================================================
  881.     // ==== sendExpiredNotificationForTeam
  882.     // ==================================================
  883.     private function sendExpiredNotificationForTeam($dlmsService, $logger)
  884.     {
  885.         $logger->error("sendExpiredNotificationForTeam at " . date('Y-m-d H:i:s'));
  886.         $taskName = 'expired_team_notification';
  887.         $dayBeforeExpiration = 10;
  888.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  889.         try {
  890.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  891.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  892.             return NULL;
  893.         } catch (\Exception $e) {
  894.             $logger->error($e->getMessage());
  895.         }
  896.         try {
  897.             $team = $this->getSoonExpiredTeam($dayBeforeExpiration);
  898.             $this->createLockFile($fileLockPath);
  899.         } catch (\Exception $e) {
  900.             $logger->error($e->getMessage());
  901.             return NULL;
  902.         }
  903.         try {
  904.             $trainers = $this->getTrainerOfTeam($team['id']);
  905.             $emailArr =  array_column($trainers, 'email');
  906.             $contact = $this->getContactByCustomerId($team['customer_id']);
  907.             if (!empty($contact)) {
  908.                 array_push($emailArr, $contact['email']);
  909.             }
  910.             if (!empty($emailArr)) {
  911.                 $dlmsService->notifyTeamExpiration($team, $emailArr);
  912.             }
  913.         } catch (\Exception $e) {
  914.             $logger->error($e->getMessage());
  915.         }
  916.         
  917.         $this->notifyTeamExpirationSuccess($team['id'], $taskName);
  918.         unlink($fileLockPath);
  919.         $logger->error('sendExpiredNotificationForTeam success for team: ' . json_encode($team));
  920.         return true;
  921.     }
  922.     private function getSoonExpiredTeam($dayBeforeExpiration)
  923.     {
  924.         $conn = $this->entityManager->getConnection();
  925.         $sql = "
  926.             SELECT g.*, s.name as company, s.customer_id, DATEDIFF(g.expired_date, CURDATE()) as diff_days
  927.             FROM groups g
  928.             JOIN sites s ON s.id = g.site_id
  929.             JOIN customers c ON c.id = s.customer_id AND c.company_type != 'Contest'
  930.             WHERE g.expired_queue = 0
  931.             AND DATEDIFF(g.expired_date, CURDATE()) > 0
  932.             AND DATEDIFF(g.expired_date, CURDATE()) <= {$dayBeforeExpiration}
  933.             LIMIT 1
  934.         ";
  935.         $stmt = $conn->prepare($sql);
  936.         $stmt->execute();
  937.         $team = $stmt->fetch();
  938.         if (empty($team)) {
  939.             throw new \Exception("There is no soon expired team in next {$dayBeforeExpiration} days.");
  940.         }
  941.         return $team;
  942.     }
  943.     private function notifyTeamExpirationSuccess($teamId, $taskName)
  944.     {
  945.         $conn = $this->entityManager->getConnection();
  946.         $sql = "
  947.             UPDATE groups SET expired_queue = 1
  948.             WHERE id = :id;
  949.         ";
  950.         $stmt = $conn->prepare($sql);
  951.         $stmt->execute(['id' => $teamId]);
  952.         $this->updateLastTimeSuccessForTask($taskName);
  953.     }
  954.     // ==================================================
  955.     // ==== senRemindCheckoutNotification
  956.     // ==================================================
  957.     private function senRemindCheckoutNotification($notificationService, $logger)
  958.     {
  959.         $logger->error("senRemindCheckoutNotification at " . date('Y-m-d H:i:s'));
  960.         $taskName = 'remind_checkout_notification';
  961.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  962.         try {
  963.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  964.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  965.             return NULL;
  966.         } catch (\Exception $e) {
  967.             $logger->error($e->getMessage());
  968.         }
  969.         try {
  970.             $purchases = $this->getQuotationRemindCheckout();
  971.             $this->createLockFile($fileLockPath);
  972.         } catch (\Exception $e) {
  973.             $logger->error($e->getMessage());
  974.             return NULL;
  975.         }
  976.         try {
  977.             foreach ($purchases as $purchase) {
  978.                 $notificationService->sendEmailRemindCheckout($purchase, true);
  979.                 $this->notifyOneRemindCheckoutSuccess($purchase, $taskName);  
  980.             }
  981.             $this->notifyRemindCheckoutSuccess($purchases, $taskName);  
  982.         } catch (\Exception $e) {
  983.             $logger->error($e->getMessage());
  984.         }
  985.         
  986.         unlink($fileLockPath);
  987.         $logger->error('senRemindCheckoutNotification success for user: ' . json_encode($purchases));
  988.         return true;
  989.     }
  990.     private function getQuotationRemindCheckout()
  991.     {
  992.         $buyMorePrimary = 99;
  993.         $conn = $this->entityManager->getConnection();
  994.         $sql = "SELECT p.*, u.customer_id, u.language, u.email, CONCAT(u.first_name, ' ', u.last_name) as fullname, tr.status
  995.             FROM purchases p
  996.             JOIN offers of ON p.offer_id = of.id
  997.             JOIN users u ON p.user_id = u.id
  998.             LEFT JOIN transactions as tr ON p.id = tr.purchase_id
  999.             WHERE (of.is_primary is NULL OR of.is_primary != {$buyMorePrimary})
  1000.                 AND p.is_active = 1
  1001.                 AND tr.status is NULL
  1002.                 AND p.remind_checkout_processed = 0
  1003.                 AND p.created_at <= :end_date
  1004.                 AND p.created_at >= :start_date
  1005.             ORDER BY p.created_at
  1006.             LIMIT 1
  1007.         ";
  1008.         $stmt = $conn->prepare($sql);
  1009.         $stmt->execute(['start_date' => date('Y-m-d H:i:s', strtotime('now -14 day')), 'end_date' => date('Y-m-d H:i:s', strtotime('now -7 day'))]);
  1010.         $purchases = $stmt->fetchAll();
  1011.         if (empty($purchases)) {
  1012.             throw new \Exception("There is no purchases to remind checkout");
  1013.         }
  1014.         return $purchases;
  1015.     }
  1016.     private function notifyOneRemindCheckoutSuccess($purchase, $taskName)
  1017.     {
  1018.         $conn = $this->entityManager->getConnection();
  1019.         $sql = "
  1020.             UPDATE purchases
  1021.             SET remind_checkout_processed = 1
  1022.             WHERE id = :id
  1023.         ";
  1024.         $stmt = $conn->prepare($sql);
  1025.         $stmt->execute(['id' => $purchase['id']]);
  1026.     }
  1027.     private function notifyRemindCheckoutSuccess($purchases, $taskName)
  1028.     {
  1029.         $this->updateLastTimeSuccessForTask($taskName);
  1030.     }
  1031.     // ==================================================
  1032.     // ==== checkCitrixUsageResourceNotification
  1033.     // ==================================================
  1034.     private function checkCitrixUsageResourceNotification($notificationService, $citrixService, $logger)
  1035.     {
  1036.         $logger->error("checkCitrixUsageResourceNotification at " . date('Y-m-d H:i:s'));
  1037.         $taskName = 'citrix_usage_resource_notification';
  1038.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  1039.         try {
  1040.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  1041.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  1042.             return NULL;
  1043.         } catch (\Exception $e) {
  1044.             $logger->error($e->getMessage());
  1045.         }
  1046.         try {
  1047.             $alert = $this->getCitrixUsageResourceAlert($taskName, $citrixService);
  1048.             $this->checkCitrixUsageResourceAlertEmail($alert);
  1049.             $this->createLockFile($fileLockPath);
  1050.         } catch (\Exception $e) {
  1051.             $logger->error($e->getMessage());
  1052.             return NULL;
  1053.         }
  1054.         try {
  1055.             $notificationService->sendEmailCitrixUsageResource($alert, true);
  1056.             $this->notifyOneCitrixUsageResourceSuccess($alert, $taskName);  
  1057.             $this->notifyCitrixUsageResourceSuccess($taskName);  
  1058.         } catch (\Exception $e) {
  1059.             $logger->error($e->getMessage());
  1060.         }
  1061.         
  1062.         unlink($fileLockPath);
  1063.         $logger->error('checkCitrixUsageResourceNotification success: ' . $alert);
  1064.         return true;
  1065.     }
  1066.     
  1067.     private function checkCitrixUsageResourceAlertEmail($alert)
  1068.     {
  1069.         $id2name = [
  1070.             1 => 'disable_email_threshold_lv1',
  1071.             2 => 'disable_email_threshold_lv2',
  1072.             3 => 'disable_email_threshold_lv3',
  1073.             4 => 'disable_email_threshold_lv4',
  1074.             0 => 'disable_email_threshold_normal',
  1075.         ];
  1076.         if (!isset($id2name[$alert])) {
  1077.             throw new \Exception("Wrong alert code");
  1078.         }
  1079.         $key = $id2name[$alert];
  1080.         $conn = $this->entityManager->getConnection();
  1081.         $sql = "SELECT *
  1082.             FROM settings
  1083.             WHERE name = :name
  1084.         ";
  1085.         $stmt = $conn->prepare($sql);
  1086.         $stmt->execute(['name' => $key]);
  1087.         $data = $stmt->fetch();
  1088.         if (!empty($data) && $data['value'] == 'y') {
  1089.             throw new \Exception("This alert was disabled in Settings");
  1090.         } else {
  1091.             return true;
  1092.         }
  1093.     }
  1094.     private function getCitrixUsageResourceAlertPeriod($alert)
  1095.     {
  1096.         $id2name = [
  1097.             1 => 'period_email_threshold_lv1',
  1098.             2 => 'period_email_threshold_lv2',
  1099.             3 => 'period_email_threshold_lv3',
  1100.             4 => 'period_email_threshold_lv4',
  1101.             0 => 'period_email_threshold_normal',
  1102.         ];
  1103.         if (!isset($id2name[$alert])) {
  1104.             return 60;
  1105.         }
  1106.         $key = $id2name[$alert];
  1107.         $conn = $this->entityManager->getConnection();
  1108.         $sql = "SELECT *
  1109.             FROM settings
  1110.             WHERE name = :name
  1111.         ";
  1112.         $stmt = $conn->prepare($sql);
  1113.         $stmt->execute(['name' => $key]);
  1114.         $data = $stmt->fetch();
  1115.         if (!empty($data)) {
  1116.             return $data['value'];
  1117.         } else {
  1118.             return 60;
  1119.         }
  1120.     }
  1121.     private function getCitrixUsageResourceAlert($taskName, $citrixService)
  1122.     {
  1123.         $tmp = $citrixService->getCitrixUsageLevel();
  1124.         $alert = $tmp['level'];
  1125.         /**
  1126.          * if last_alert = null:
  1127.          *     if alert > 0: notify alert
  1128.          *     else: nothing
  1129.          * else:
  1130.          *     if last_alert >= period:
  1131.          *         if alert > 0: notify alert
  1132.          *         else:
  1133.          *             if last_alert > 0: notify normal
  1134.          *             else: nothing
  1135.          *     else:
  1136.          *         if alert > last_alert: notify alert
  1137.          *         else: nothing
  1138.          * --------------------------------------------
  1139.          * period: depends on each level
  1140.          */
  1141.         $conn = $this->entityManager->getConnection();
  1142.         $sql = "SELECT *
  1143.             FROM settings
  1144.             WHERE name = :name
  1145.         ";
  1146.         $stmt = $conn->prepare($sql);
  1147.         $stmt->execute(['name' => $taskName]);
  1148.         $data = $stmt->fetch();
  1149.         if (empty($data)) {
  1150.             if ($alert == 0) {
  1151.                 throw new \Exception("There is no alert to Citrix usage resource");
  1152.             }
  1153.         } else {
  1154.             $json = json_decode($data['value'], true);
  1155.             $period = $this->getCitrixUsageResourceAlertPeriod($json['level']);
  1156.             if (strtotime($json['created_at']) <= strtotime('now -'.$period.' minutes')) { // out of period
  1157.                 if ($alert == 0 && $json['level'] == 0) {
  1158.                     throw new \Exception("There is no alert to Citrix usage resource");
  1159.                 }
  1160.             } else { // in period
  1161.                 if ($alert <= $json['level']) {
  1162.                     throw new \Exception("There is no alert to Citrix usage resource");
  1163.                 }
  1164.             }
  1165.         }
  1166.         return $alert;
  1167.     }
  1168.     private function notifyOneCitrixUsageResourceSuccess($alert, $taskName)
  1169.     {
  1170.         $conn = $this->entityManager->getConnection();
  1171.         $sql = "SELECT *
  1172.             FROM settings
  1173.             WHERE name = :name
  1174.         ";
  1175.         $stmt = $conn->prepare($sql);
  1176.         $stmt->execute(['name' => $taskName]);
  1177.         $data = $stmt->fetch();
  1178.         if (empty($data)) {
  1179.             $sql = "INSERT INTO settings (`name`, `value`)
  1180.                 VALUES (:name, :value)
  1181.             ";
  1182.         } else {
  1183.             $sql = "UPDATE settings
  1184.                 SET value = :value
  1185.                 WHERE name = :name
  1186.             ";
  1187.         }
  1188.         $stmt = $conn->prepare($sql);
  1189.         $stmt->execute(['name' => $taskName, 'value' => json_encode([
  1190.                 'level' => $alert,
  1191.                 'created_at' => date('Y-m-d H:i:s'),
  1192.             ])
  1193.         ]);
  1194.     }
  1195.     private function notifyCitrixUsageResourceSuccess($taskName)
  1196.     {
  1197.         $this->updateLastTimeSuccessForTask($taskName);
  1198.     }
  1199.     // ==================================================
  1200.     // ==== publishContestResult
  1201.     // ==================================================
  1202.     private function publishContestResult($contestService, $logger)
  1203.     {
  1204.         $logger->error("publishContestResult at " . date('Y-m-d H:i:s'));
  1205.         $taskName = 'publish_contest_result';
  1206.         $fileLockPath = $this->lockPath . $taskName . '.lock';
  1207.         try {
  1208.             $diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
  1209.             $logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
  1210.             return NULL;
  1211.         } catch (\Exception $e) {
  1212.             $logger->error($e->getMessage());
  1213.         }
  1214.         try {
  1215.             $contest = $this->getAutoPublishContest($taskName);
  1216.             $this->createLockFile($fileLockPath);
  1217.         } catch (\Exception $e) {
  1218.             $logger->error($e->getMessage());
  1219.             return NULL;
  1220.         }
  1221.         try {
  1222.             $this->actionPublishResult($contest, $contestService);  
  1223.             $this->notifyOnePublishContestResultSuccess($contest, $taskName);  
  1224.             $this->notifyPublishContestResultSuccess($taskName);  
  1225.         } catch (\Exception $e) {
  1226.             $logger->error($e->getMessage());
  1227.         }
  1228.         
  1229.         unlink($fileLockPath);
  1230.         $logger->error('publishContestResult success for contest: ' . json_encode($contest));
  1231.         return true;
  1232.     }
  1233.     private function getAutoPublishContest($taskName)
  1234.     {
  1235.         $conn = $this->entityManager->getConnection();
  1236.         $sql = "SELECT *
  1237.             FROM settings
  1238.             WHERE name = :name
  1239.         ";
  1240.         $stmt = $conn->prepare($sql);
  1241.         $stmt->execute(['name' => $taskName]);
  1242.         $data = $stmt->fetch();
  1243.         if (empty($data)) {
  1244.             $lastRun = [];
  1245.         } else {
  1246.             $lastRun = json_decode($data['value'], true);
  1247.         }
  1248.         $sql = "SELECT c.*
  1249.             FROM customers c
  1250.             WHERE c.company_type = 'Contest'
  1251.                 AND c.contest_publish_auto = 1
  1252.                 AND c.end_date >= '" . date('Y-m-d H:i:s') . "'
  1253.         ";
  1254.         $stmt = $conn->prepare($sql);
  1255.         $stmt->execute();
  1256.         $contests = $stmt->fetchAll();
  1257.         foreach ($contests as $contest) {
  1258.             if ( !isset($lastRun[$contest['id']]) || strtotime($lastRun[$contest['id']]) < strtotime('now -1 hour') ) {
  1259.                 return $contest;
  1260.             }
  1261.         }
  1262.         throw new \Exception("There is no contest");
  1263.     }
  1264.     private function actionPublishResult($contest, $contestService)
  1265.     {
  1266.         $conn = $this->entityManager->getConnection();
  1267.         $sql = "SELECT r.*
  1268.             FROM contest_rounds r
  1269.             WHERE r.customer_id = :customer_id
  1270.                 AND r.result_included = 1
  1271.             ORDER BY r.id
  1272.         ";
  1273.         $stmt = $conn->prepare($sql);
  1274.         $stmt->execute(['customer_id' => $contest['id']]);
  1275.         $contestRounds = $stmt->fetchAll();
  1276.         foreach ($contestRounds as $round) {
  1277.             $contestService->collectDlmsPoints($round);
  1278.             $contestService->publishContestResult($round);
  1279.         }
  1280.     }
  1281.     private function notifyOnePublishContestResultSuccess($contest, $taskName)
  1282.     {
  1283.         $conn = $this->entityManager->getConnection();
  1284.         $sql = "SELECT *
  1285.             FROM settings
  1286.             WHERE name = :name
  1287.         ";
  1288.         $stmt = $conn->prepare($sql);
  1289.         $stmt->execute(['name' => $taskName]);
  1290.         $data = $stmt->fetch();
  1291.         if (empty($data)) {
  1292.             $sql = "INSERT INTO settings (`name`, `value`)
  1293.                 VALUES (:name, :value)
  1294.             ";
  1295.             $value[$contest['id']] = date('Y-m-d H:i:s');
  1296.         } else {
  1297.             $sql = "UPDATE settings
  1298.                 SET value = :value
  1299.                 WHERE name = :name
  1300.             ";
  1301.             $value = json_decode($data['value'], true);
  1302.             $value[$contest['id']] = date('Y-m-d H:i:s');
  1303.         }
  1304.         $stmt = $conn->prepare($sql);
  1305.         $stmt->execute([ 'name' => $taskName, 'value' => json_encode($value) ]);
  1306.     }
  1307.     private function notifyPublishContestResultSuccess($taskName)
  1308.     {
  1309.         $this->updateLastTimeSuccessForTask($taskName);
  1310.     }
  1311. }