<?php
namespace App\Controller;
use App\Service\DlmsService;
use App\Service\NotificationService;
use Psr\Log\LoggerInterface;
use App\Service\CitrixService;
use App\Service\ContestService;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\ORM\EntityManagerInterface;
class CronController extends AbstractController
{
private $lockPath;
private EntityManagerInterface $entityManager;
public function __construct(KernelInterface $appKernel, EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->lockPath = $appKernel->getProjectDir() . '/var/lock/';
}
/**
* @Route("/user/task-schedule", name="user-task-schedule")
*/
public function runTaskSchedule(LoggerInterface $logger, CitrixService $citrixService, DlmsService $dlmsService, NotificationService $notificationService, ContestService $contestService)
{
/**
* This is called every minutes from outside.
*/
$expiredUser = NULL;
$expiredTeam = NULL;
$expiredCustomer = NULL;
$releaseCitrix = $this->releaseCitrix($logger, $citrixService);
$confirmUser = $this->sendConfirmationdNotificationForUser($dlmsService, $logger);
$activeBuymore = $this->sendBuymoreActiveNotification($notificationService, $logger);
$expireSoonBuymore = $this->sendBuymoreExpireSoonNotification($notificationService, $logger);
$deactivateExpiredBuymore = $this->deactivateExpiredBuymore($logger);
$deactivateExpiredTrial = $this->deactivateExpiredTrial($logger);
$remindCheckout = $this->senRemindCheckoutNotification($notificationService, $logger);
$citrixUsageResource = $this->checkCitrixUsageResourceNotification($notificationService, $citrixService, $logger);
$publishContestResult = $this->publishContestResult($contestService, $logger);
$isCheckExpiration = $this->getParameter('is.check.expiration');
if ($isCheckExpiration == 'true') {
$expiredUser = $this->sendExpiredNotificationForUser($dlmsService, $logger);
// $expiredTeam = $this->sendExpiredNotificationForTeam($dlmsService, $logger);
$expiredCustomer = $this->sendExpiredNotificationForCustomer($dlmsService, $logger);
}
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, [
'Access-Control-Allow-Origin' => '*'
]);
}
// ==================================================
// ==== common functions
// ==================================================
private function handleOverlappingRequest($taskName, $fileLockPath)
{
if (file_exists($fileLockPath)) {
try {
$taskSchedule = $this->getTaskSchedule($taskName);
$diffMinute = $this->getDiffMinute($taskSchedule['last_succeed_at']);
if ($diffMinute >= $taskSchedule['max_time_skip']) {
throw new \Exception("The previous request is processed too long in {$diffMinute} minutes.");
}
return $diffMinute;
} catch (\Exception $e) {
unlink($fileLockPath);
throw $e;
}
}
throw new \Exception("There is no lock file {$fileLockPath}.");
}
private function getTaskSchedule($taskName)
{
$conn = $this->entityManager->getConnection();
$sql = '
SELECT *
FROM task_schedule
WHERE task_name = :task_name
';
$stmt = $conn->prepare($sql);
$stmt->execute(['task_name' => $taskName]);
$task = $stmt->fetch();
if (empty($task)) {
throw new \Exception('There is no task: ' . $taskName);
}
return $task;
}
private function getDiffMinute($lastSucceedTime)
{
try {
$lastSucceedDateTime = new \DateTime($lastSucceedTime);
$diffDate = $lastSucceedDateTime->diff(new \DateTime());
$diffMinute = $diffDate->days * 24 * 60;
$diffMinute += $diffDate->h * 60;
$diffMinute += $diffDate->i;
return $diffMinute;
} catch (\Exception $e) {
throw new \Exception('There is an error on getDiffMinute: ' . $e->getMessage());
}
}
private function createLockFile($fileLockPath)
{
try {
if (!is_dir($this->lockPath)) {
mkdir($this->lockPath, 0777, true);
}
if (file_exists($fileLockPath)) {
throw new \Exception('Lock file is exist.');
} else {
$file = fopen($fileLockPath,"w");
fwrite($file, '');
fclose($file);
}
} catch (\Exception $e) {
throw new \Exception('There is an error on createLockFile: ' . $e->getMessage());
}
}
private function updateLastTimeSuccessForTask($taskName, $maxTimeSkip = 5)
{
$conn = $this->entityManager->getConnection();
$sql = "
INSERT INTO task_schedule (task_name, last_succeed_at, max_time_skip)
VALUES (:task_name, :last_succeed_at, :max_time_skip)
ON DUPLICATE KEY UPDATE
last_succeed_at = :last_succeed_at
";
$stmt = $conn->prepare($sql);
$stmt->execute([
'task_name' => $taskName,
'last_succeed_at' => date('Y-m-d H:i:s'),
'max_time_skip' => $maxTimeSkip
]);
}
private function getTrainerEmailOf($customerId, $getAll = false)
{
$trainerEmailArr = [];
$masterTrainer = $this->getMasterTrainerByCustomerId($customerId);
if (!empty($masterTrainer)) {
$trainerEmailArr[] = $masterTrainer['email'];
}
if ($getAll || !$this->isMultiSite($customerId)) {
$trainers = $this->getTrainerByCustomerId($customerId);
if (!empty($trainers)) {
$trainerEmail = array_column($trainers, 'email');
$trainerEmailArr = array_merge($trainerEmailArr, $trainerEmail);
}
}
return $trainerEmailArr;
}
private function getMasterTrainerByCustomerId($customerId)
{
$entityManager = $this->entityManager;
$conn = $entityManager->getConnection();
$sql = "
SELECT *
FROM users
WHERE
roles LIKE '%\"ROLE_MASTER_TRAINER\"%'
AND active = 1
AND verified = 1
AND customer_id = :customer_id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['customer_id' => $customerId]);
return $stmt->fetch();
}
private function isMultiSite($customerId)
{
$entityManager = $this->entityManager;
$conn = $entityManager->getConnection();
$sql = "
SELECT *
FROM sites
WHERE customer_id = :customer_id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['customer_id' => $customerId]);
$sites = $stmt->fetchAll();
if (count($sites) > 1) {
return true;
}
return false;
}
private function getTrainerByCustomerId($customerId)
{
$entityManager = $this->entityManager;
$conn = $entityManager->getConnection();
$sql = "
SELECT u.*
FROM users u
JOIN groups g ON g.id = u.group_id
JOIN sites s ON s.id = g.site_id
WHERE u.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%'
AND u.active = 1
AND u.verified = 1
AND s.customer_id = :customer_id
ORDER BY u.id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['customer_id' => $customerId]);
return $stmt->fetchAll();
}
private function getTrainerOfTeam($teamId)
{
$conn = $this->entityManager->getConnection();
$sql = "
SELECT us.*
FROM users us
JOIN trainer_team tt ON us.id = tt.trainer_id AND tt.team_id = :group_id
WHERE us.verified = 1
AND us.active = 1
AND us.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%'
ORDER BY us.id DESC
";
$stmt = $conn->prepare($sql);
$stmt->execute(['group_id' => $teamId]);
$trainers = $stmt->fetchAll();
if (empty($trainers)) {
throw new \Exception("There is no trainers on group id: {$teamId}.");
}
return $trainers;
}
private function getContactByCustomerId($customerId)
{
$conn = $this->entityManager->getConnection();
$sql = "
SELECT u.*
FROM users u
WHERE u.verified = 1
AND u.active = 1
AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
AND u.customer_id = :customer_id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['customer_id' => $customerId]);
$contact = $stmt->fetch();
return $contact;
}
// ==================================================
// ==== releaseCitrix
// ==================================================
private function releaseCitrix($logger, $citrixService)
{
$period = $this->getParameter('citrix.expire.period');
if (empty($period)) {
$period = 5;
}
$conn = $this->entityManager->getConnection();
$sql = '
SELECT *
FROM citrix
WHERE userid is not null
AND session_updated < :session_updated
';
$stmt = $conn->prepare($sql);
$stmt->execute(['session_updated' => date('Y-m-d H:i:s', strtotime('now -'.$period.' minute'))]);
$data = $stmt->fetchAll();
$output = [];
if (!empty($data)) {
foreach ($data as $item) {
$userid = $item['userid'];
$item['userid'] = 0; // clear assign
try {
$result = $citrixService->apiUpdateCitrix($item, $logger);
if ($result && $result->code == 201) {
$sql = '
UPDATE citrix
SET userid = null
WHERE login = :login
';
$stmt = $conn->prepare($sql);
$stmt->execute(['login' => $item['login']]);
$sql = '
SELECT id
FROM citrix_log
WHERE login = :login AND session_end is null
';
$stmt = $conn->prepare($sql);
$stmt->execute([
'login' => $item['login'],
]);
$logs = $stmt->fetchAll();
foreach ($logs as $log) {
$sql = '
UPDATE citrix_log
SET session_end = :session_end
WHERE id = :id
';
$stmt = $conn->prepare($sql);
$stmt->execute([
'id' => $log['id'],
'session_end' => date('Y-m-d H:i:s'),
]);
}
$output[] = $item['login'];
}
} catch (\Exception $e) {
$logger->error('apiUpdateCitrix ' . $e->getMessage());
}
}
}
$logger->error('userCitrixRelease ' . json_encode($output));
return $output;
}
// ==================================================
// ==== sendConfirmationdNotificationForUser
// ==================================================
private function sendConfirmationdNotificationForUser($dlmsService, $logger)
{
$logger->error("sendConfirmationdNotificationForUser at " . date('Y-m-d H:i:s'));
$taskName = 'confirmation_user_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$users = $this->getUserNeedConfirmation();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($users as $user) {
if (filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
if ($user['verified']) {
if ($user['enable_sso_microsoft']) {
$dlmsService->sendEmailSsoReactivate($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['language'], true);
} else {
$dlmsService->sendEmailReactivate($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['password'], $user['language'], true);
}
} elseif (strpos($user['roles'], '"ROLE_USER"') !== false) {
if ($user['company_type'] == 'Contest') {
$dlmsService->sendEmailComfirmationForContestUser($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['contest_name'], $user['language'], true);
} else {
$dlmsService->sendEmailComfirmationForUser($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['company'], $user['language'], true);
}
} else {
$dlmsService->sendEmailComfirmationForTrainer($user['email'], $user['first_name'] . ' ' . $user['last_name'], $user['id'], $user['company'], $user['language'], true);
}
}
$this->notifyOneUserConfirmationSuccess($user, $taskName);
}
$this->notifyUserConfirmationSuccess($users, $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('sendConfirmationdNotificationForUser success for user: ' . json_encode($users));
return true;
}
private function getUserNeedConfirmation()
{
$conn = $this->entityManager->getConnection();
$sql = 'SELECT u.*, s.customer_id, s.name as company, c.company_type, c.company as contest_name, c.enable_sso_microsoft
FROM users u
JOIN groups g ON g.id = u.group_id
JOIN sites s ON s.id = g.site_id
JOIN customers c ON c.id = s.customer_id
WHERE u.verify_queue = 1
AND u.active = 1
ORDER BY u.created_at ASC
LIMIT 4
';
// 4 emails / minute => 15s
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
if (empty($users)) {
throw new \Exception("There is no user need confirmation");
}
return $users;
}
private function notifyOneUserConfirmationSuccess($user, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE users
SET verify_queue = 0
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $user['id']]);
}
private function notifyUserConfirmationSuccess($users, $taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== sendBuymoreActiveNotification
// ==================================================
private function sendBuymoreActiveNotification($notificationService, $logger)
{
$logger->error("sendBuymoreActiveNotification at " . date('Y-m-d H:i:s'));
$taskName = 'buymore_active_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$purchases = $this->getBuymorePurchaseWillActive();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($purchases as $purchase) {
$trainerEmailArr = $this->getTrainerEmailOf($purchase['customer_id'], true);
$notificationService->sendEmailBuymoreActive($trainerEmailArr, $purchase, true);
$this->notifyOneBuymoreActiveSuccess($purchase, $taskName);
}
$this->notifyBuymoreActiveSuccess($purchases, $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('sendBuymoreActiveNotification success for user: ' . json_encode($purchases));
return true;
}
private function getBuymorePurchaseWillActive()
{
$buyMorePrimary = 99;
$conn = $this->entityManager->getConnection();
$sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
FROM purchases p
JOIN offers of ON p.offer_id = of.id
JOIN users u ON p.user_id = u.id
JOIN transactions as tr ON p.id = tr.purchase_id
WHERE of.is_primary = {$buyMorePrimary}
AND p.is_active = 1
AND tr.status = 'completed'
AND p.active_processed = 0
AND p.start_date <= :start_date
ORDER BY p.start_date
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute(['start_date' => date('Y-m-d H:i:s')]);
$purchases = $stmt->fetchAll();
if (empty($purchases)) {
throw new \Exception("There is no purchases will active");
}
return $purchases;
}
private function notifyOneBuymoreActiveSuccess($purchase, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE purchases
SET active_processed = 1
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $purchase['id']]);
}
private function notifyBuymoreActiveSuccess($purchases, $taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== sendBuymoreExpireSoonNotification
// ==================================================
private function sendBuymoreExpireSoonNotification($notificationService, $logger)
{
$logger->error("sendBuymoreExpireSoonNotification at " . date('Y-m-d H:i:s'));
$taskName = 'buymore_expiresoon_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$purchases = $this->getBuymorePurchaseExpireSoon();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($purchases as $purchase) {
$trainerEmailArr = $this->getTrainerEmailOf($purchase['customer_id'], true);
$notificationService->sendEmailBuymoreExpireSoon($trainerEmailArr, $purchase, true);
$this->notifyOneBuymoreExpireSoonSuccess($purchase, $taskName);
}
$this->notifyBuymoreExpireSoonSuccess($purchases, $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('sendBuymoreExpireSoonNotification success for user: ' . json_encode($purchases));
return true;
}
private function getBuymorePurchaseExpireSoon()
{
$buyMorePrimary = 99;
$conn = $this->entityManager->getConnection();
$sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
FROM purchases p
JOIN offers of ON p.offer_id = of.id
JOIN users u ON p.user_id = u.id
JOIN transactions as tr ON p.id = tr.purchase_id
WHERE of.is_primary = {$buyMorePrimary}
AND p.is_active = 1
AND tr.status = 'completed'
AND p.expire_soon_processed = 0
AND p.expired_date <= :expired_date
AND p.expired_date >= '" . date('Y-m-d') . "'
ORDER BY p.expired_date
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute(['expired_date' => date('Y-m-d H:i:s', strtotime('now +7 days'))]);
$purchases = $stmt->fetchAll();
if (empty($purchases)) {
throw new \Exception("There is no purchases will active");
}
return $purchases;
}
private function notifyOneBuymoreExpireSoonSuccess($purchase, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE purchases
SET expire_soon_processed = 1
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $purchase['id']]);
}
private function notifyBuymoreExpireSoonSuccess($purchases, $taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== deactivateExpiredBuymore
// ==================================================
private function deactivateExpiredBuymore($logger)
{
$logger->error("deactivateExpiredBuymore at " . date('Y-m-d H:i:s'));
$taskName = 'deactivate_expired_buymore';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$purchases = $this->getExpiredBuymorePurchase();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($purchases as $purchase) {
$this->deactivateUsersOfExpiredBuymorePurchase($purchase);
$this->updateBuyMoreQuotaForCustomer($purchase);
$this->notifyOneExpiredBuymorePurchaseSuccess($purchase, $taskName);
}
$this->notifyExpiredBuymorePurchaseSuccess($purchases, $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('deactivateExpiredBuymore success for user: ' . json_encode($purchases));
return true;
}
private function getExpiredBuymorePurchase()
{
$buyMorePrimary = 99;
$conn = $this->entityManager->getConnection();
$sql = "SELECT p.*, u.customer_id, u.language, CONCAT(u.first_name, ' ', u.last_name) as fullname
FROM purchases p
JOIN offers of ON p.offer_id = of.id
JOIN users u ON p.user_id = u.id
JOIN transactions as tr ON p.id = tr.purchase_id
WHERE of.is_primary = {$buyMorePrimary}
AND p.is_active = 1
AND tr.status = 'completed'
AND p.expire_processed = 0
AND p.expired_date < '" . date('Y-m-d') . "'
ORDER BY p.expired_date
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$purchases = $stmt->fetchAll();
if (empty($purchases)) {
throw new \Exception("There is no purchases will active");
}
return $purchases;
}
private function deactivateUsersOfExpiredBuymorePurchase($purchase)
{
$conn = $this->entityManager->getConnection();
$sql = "UPDATE users
SET active = 0
WHERE purchase_id = :purchase_id
AND roles LIKE '%\"ROLE_USER\"%'
";
$stmt = $conn->prepare($sql);
$stmt->execute(['purchase_id' => $purchase['id']]);
// don't need to send API to update "expired_date" of users to yesterday in DLMS
// because Purchase expired_date < today
// => users expired_date < today
}
private function updateBuyMoreQuotaForCustomer($purchase)
{
$conn = $this->entityManager->getConnection();
$sql = 'UPDATE `customers`
SET `num_users` = num_users - :num_users, `num_licenses` = num_licenses - :num_licenses
WHERE id = :id
';
$stmt = $conn->prepare($sql);
$stmt->execute([
'num_users' => $purchase['num_users'],
'num_licenses' => $purchase['num_licenses'],
'id' => $purchase['customer_id'],
]);
}
private function notifyOneExpiredBuymorePurchaseSuccess($purchase, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE purchases
SET expire_processed = 1
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $purchase['id']]);
}
private function notifyExpiredBuymorePurchaseSuccess($purchases, $taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== deactivateExpiredTrial
// ==================================================
private function deactivateExpiredTrial($logger)
{
$logger->error("deactivateExpiredTrial at " . date('Y-m-d H:i:s'));
$taskName = 'deactivate_expired_trial';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$users = $this->getExpiredTrialUsers();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($users as $user) {
$this->deactivateExpiredTrialUser($user);
}
$this->notifyExpiredTrialSuccess($taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('deactivateExpiredTrial success for user: ' . json_encode($users));
return true;
}
private function getExpiredTrialUsers()
{
$conn = $this->entityManager->getConnection();
$sql = "SELECT u.id
FROM settings s
JOIN groups g ON g.package_code = s.value
JOIN users u ON u.group_id = g.id
WHERE s.name IN ('trial_shots', 'trial_heatset', 'trial_flexo', 'trial_gravure')
AND u.roles LIKE '%\"ROLE_USER\"%'
AND u.active = 1
AND u.expired_date < :expired_date
";
$stmt = $conn->prepare($sql);
$stmt->execute(['expired_date' => date('Y-m-d')]);
$users = $stmt->fetchAll();
if (empty($users)) {
throw new \Exception("There is no expired trial user");
}
return $users;
}
private function deactivateExpiredTrialUser($user)
{
$conn = $this->entityManager->getConnection();
$sql = "UPDATE users
SET active = 0
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $user['id']]);
}
private function notifyExpiredTrialSuccess($taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== sendExpiredNotificationForUser
// ==================================================
private function sendExpiredNotificationForUser($dlmsService, $logger)
{
$logger->error("sendExpiredNotificationForUser at " . date('Y-m-d H:i:s'));
$taskName = 'expired_user_notification';
$dayBeforeExpiration = 5;
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$user = $this->getSoonExpiredUser($dayBeforeExpiration);
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
$user['username'] = $user['first_name'] . ' ' . $user['last_name'];
$user['expired_date'] = date('d-m-Y', strtotime($user['expired_date']));
$dlmsService->notifyUserExpiration($user);
$this->notifyUserExpirationSuccess($user['id'], $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('sendExpiredNotificationForUser success for user: ' . json_encode($user));
return true;
}
private function getSoonExpiredUser($dayBeforeExpiration)
{
$conn = $this->entityManager->getConnection();
$sql = "
SELECT u.*, s.name as company, DATEDIFF(u.expired_date, CURDATE()) as diff_days, g.name as team_name
FROM users u
JOIN groups g ON g.id = u.group_id
JOIN sites s ON s.id = g.site_id
JOIN customers c ON c.id = s.customer_id AND c.company_type != 'Contest'
WHERE u.expired_queue = 0
AND u.verified = 1
AND u.active = 1
AND u.customer_id is NULL
AND ( u.roles LIKE '%\"ROLE_USER\"%' OR u.roles LIKE '%\"ROLE_CLOUD_TRAINER\"%')
AND DATEDIFF(u.expired_date, CURDATE()) > 0
AND DATEDIFF(u.expired_date, CURDATE()) <= {$dayBeforeExpiration}
ORDER BY u.created_at ASC
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$user = $stmt->fetch();
if (empty($user)) {
throw new \Exception("There is no soon expired user in next {$dayBeforeExpiration} days.");
}
return $user;
}
private function notifyUserExpirationSuccess($userId, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE users SET expired_queue = 1
WHERE id = :id;
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $userId]);
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== sendExpiredNotificationForCustomer
// ==================================================
private function sendExpiredNotificationForCustomer($dlmsService, $logger)
{
$logger->error("sendExpiredNotificationForCustomer at " . date('Y-m-d H:i:s'));
$taskName = 'expired_customer_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$user = $this->getSoonExpiredCustomer();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
$trainerEmailArr = $this->getTrainerEmailOf($user['customer_id']);
$dlmsService->notifyCustomerExpiration($user, $trainerEmailArr);
$this->notifyCustomerExpirationSuccess($user['id'], $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('sendExpiredNotificationForCustomer success for user: ' . json_encode($user));
return true;
}
private function getSoonExpiredCustomer()
{
$conn = $this->entityManager->getConnection();
// $sql = "
// 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
// FROM users u
// JOIN customers c ON c.id = u.customer_id AND c.company_type != 'Contest'
// WHERE u.expired_queue = 0
// AND u.verified = 1
// AND u.active = 1
// AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
// AND DATEDIFF(c.end_date, CURDATE()) > 0
// AND DATEDIFF(c.end_date, CURDATE()) <= (DATEDIFF(c.end_date, c.start_date) /4)
// ORDER BY u.created_at ASC
// LIMIT 1
// ";
$sql = "
SELECT u.*, c.company, c.end_date, c.language as company_language, DATEDIFF(c.end_date, CURDATE()) as diff_days
FROM users u
JOIN customers c ON c.id = u.customer_id AND c.company_type != 'Contest'
WHERE u.expired_queue = 0
AND u.verified = 1
AND u.active = 1
AND u.roles LIKE '%\"ROLE_CUSTOMER\"%'
AND DATEDIFF(c.end_date, CURDATE()) > 0
AND DATEDIFF(c.end_date, CURDATE()) <= 30
ORDER BY u.created_at ASC
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$user = $stmt->fetch();
if (empty($user)) {
throw new \Exception("There is no soon expired customer.");
}
return $user;
}
private function notifyCustomerExpirationSuccess($userId, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE users SET expired_queue = 1
WHERE id = :id;
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $userId]);
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== sendExpiredNotificationForTeam
// ==================================================
private function sendExpiredNotificationForTeam($dlmsService, $logger)
{
$logger->error("sendExpiredNotificationForTeam at " . date('Y-m-d H:i:s'));
$taskName = 'expired_team_notification';
$dayBeforeExpiration = 10;
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$team = $this->getSoonExpiredTeam($dayBeforeExpiration);
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
$trainers = $this->getTrainerOfTeam($team['id']);
$emailArr = array_column($trainers, 'email');
$contact = $this->getContactByCustomerId($team['customer_id']);
if (!empty($contact)) {
array_push($emailArr, $contact['email']);
}
if (!empty($emailArr)) {
$dlmsService->notifyTeamExpiration($team, $emailArr);
}
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
$this->notifyTeamExpirationSuccess($team['id'], $taskName);
unlink($fileLockPath);
$logger->error('sendExpiredNotificationForTeam success for team: ' . json_encode($team));
return true;
}
private function getSoonExpiredTeam($dayBeforeExpiration)
{
$conn = $this->entityManager->getConnection();
$sql = "
SELECT g.*, s.name as company, s.customer_id, DATEDIFF(g.expired_date, CURDATE()) as diff_days
FROM groups g
JOIN sites s ON s.id = g.site_id
JOIN customers c ON c.id = s.customer_id AND c.company_type != 'Contest'
WHERE g.expired_queue = 0
AND DATEDIFF(g.expired_date, CURDATE()) > 0
AND DATEDIFF(g.expired_date, CURDATE()) <= {$dayBeforeExpiration}
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$team = $stmt->fetch();
if (empty($team)) {
throw new \Exception("There is no soon expired team in next {$dayBeforeExpiration} days.");
}
return $team;
}
private function notifyTeamExpirationSuccess($teamId, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE groups SET expired_queue = 1
WHERE id = :id;
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $teamId]);
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== senRemindCheckoutNotification
// ==================================================
private function senRemindCheckoutNotification($notificationService, $logger)
{
$logger->error("senRemindCheckoutNotification at " . date('Y-m-d H:i:s'));
$taskName = 'remind_checkout_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$purchases = $this->getQuotationRemindCheckout();
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
foreach ($purchases as $purchase) {
$notificationService->sendEmailRemindCheckout($purchase, true);
$this->notifyOneRemindCheckoutSuccess($purchase, $taskName);
}
$this->notifyRemindCheckoutSuccess($purchases, $taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('senRemindCheckoutNotification success for user: ' . json_encode($purchases));
return true;
}
private function getQuotationRemindCheckout()
{
$buyMorePrimary = 99;
$conn = $this->entityManager->getConnection();
$sql = "SELECT p.*, u.customer_id, u.language, u.email, CONCAT(u.first_name, ' ', u.last_name) as fullname, tr.status
FROM purchases p
JOIN offers of ON p.offer_id = of.id
JOIN users u ON p.user_id = u.id
LEFT JOIN transactions as tr ON p.id = tr.purchase_id
WHERE (of.is_primary is NULL OR of.is_primary != {$buyMorePrimary})
AND p.is_active = 1
AND tr.status is NULL
AND p.remind_checkout_processed = 0
AND p.created_at <= :end_date
AND p.created_at >= :start_date
ORDER BY p.created_at
LIMIT 1
";
$stmt = $conn->prepare($sql);
$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'))]);
$purchases = $stmt->fetchAll();
if (empty($purchases)) {
throw new \Exception("There is no purchases to remind checkout");
}
return $purchases;
}
private function notifyOneRemindCheckoutSuccess($purchase, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "
UPDATE purchases
SET remind_checkout_processed = 1
WHERE id = :id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $purchase['id']]);
}
private function notifyRemindCheckoutSuccess($purchases, $taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== checkCitrixUsageResourceNotification
// ==================================================
private function checkCitrixUsageResourceNotification($notificationService, $citrixService, $logger)
{
$logger->error("checkCitrixUsageResourceNotification at " . date('Y-m-d H:i:s'));
$taskName = 'citrix_usage_resource_notification';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$alert = $this->getCitrixUsageResourceAlert($taskName, $citrixService);
$this->checkCitrixUsageResourceAlertEmail($alert);
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
$notificationService->sendEmailCitrixUsageResource($alert, true);
$this->notifyOneCitrixUsageResourceSuccess($alert, $taskName);
$this->notifyCitrixUsageResourceSuccess($taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('checkCitrixUsageResourceNotification success: ' . $alert);
return true;
}
private function checkCitrixUsageResourceAlertEmail($alert)
{
$id2name = [
1 => 'disable_email_threshold_lv1',
2 => 'disable_email_threshold_lv2',
3 => 'disable_email_threshold_lv3',
4 => 'disable_email_threshold_lv4',
0 => 'disable_email_threshold_normal',
];
if (!isset($id2name[$alert])) {
throw new \Exception("Wrong alert code");
}
$key = $id2name[$alert];
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $key]);
$data = $stmt->fetch();
if (!empty($data) && $data['value'] == 'y') {
throw new \Exception("This alert was disabled in Settings");
} else {
return true;
}
}
private function getCitrixUsageResourceAlertPeriod($alert)
{
$id2name = [
1 => 'period_email_threshold_lv1',
2 => 'period_email_threshold_lv2',
3 => 'period_email_threshold_lv3',
4 => 'period_email_threshold_lv4',
0 => 'period_email_threshold_normal',
];
if (!isset($id2name[$alert])) {
return 60;
}
$key = $id2name[$alert];
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $key]);
$data = $stmt->fetch();
if (!empty($data)) {
return $data['value'];
} else {
return 60;
}
}
private function getCitrixUsageResourceAlert($taskName, $citrixService)
{
$tmp = $citrixService->getCitrixUsageLevel();
$alert = $tmp['level'];
/**
* if last_alert = null:
* if alert > 0: notify alert
* else: nothing
* else:
* if last_alert >= period:
* if alert > 0: notify alert
* else:
* if last_alert > 0: notify normal
* else: nothing
* else:
* if alert > last_alert: notify alert
* else: nothing
* --------------------------------------------
* period: depends on each level
*/
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $taskName]);
$data = $stmt->fetch();
if (empty($data)) {
if ($alert == 0) {
throw new \Exception("There is no alert to Citrix usage resource");
}
} else {
$json = json_decode($data['value'], true);
$period = $this->getCitrixUsageResourceAlertPeriod($json['level']);
if (strtotime($json['created_at']) <= strtotime('now -'.$period.' minutes')) { // out of period
if ($alert == 0 && $json['level'] == 0) {
throw new \Exception("There is no alert to Citrix usage resource");
}
} else { // in period
if ($alert <= $json['level']) {
throw new \Exception("There is no alert to Citrix usage resource");
}
}
}
return $alert;
}
private function notifyOneCitrixUsageResourceSuccess($alert, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $taskName]);
$data = $stmt->fetch();
if (empty($data)) {
$sql = "INSERT INTO settings (`name`, `value`)
VALUES (:name, :value)
";
} else {
$sql = "UPDATE settings
SET value = :value
WHERE name = :name
";
}
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $taskName, 'value' => json_encode([
'level' => $alert,
'created_at' => date('Y-m-d H:i:s'),
])
]);
}
private function notifyCitrixUsageResourceSuccess($taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
// ==================================================
// ==== publishContestResult
// ==================================================
private function publishContestResult($contestService, $logger)
{
$logger->error("publishContestResult at " . date('Y-m-d H:i:s'));
$taskName = 'publish_contest_result';
$fileLockPath = $this->lockPath . $taskName . '.lock';
try {
$diffMinute = $this->handleOverlappingRequest($taskName, $fileLockPath);
$logger->error("The previous request has been proccessed for {$diffMinute} minutes.");
return NULL;
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
try {
$contest = $this->getAutoPublishContest($taskName);
$this->createLockFile($fileLockPath);
} catch (\Exception $e) {
$logger->error($e->getMessage());
return NULL;
}
try {
$this->actionPublishResult($contest, $contestService);
$this->notifyOnePublishContestResultSuccess($contest, $taskName);
$this->notifyPublishContestResultSuccess($taskName);
} catch (\Exception $e) {
$logger->error($e->getMessage());
}
unlink($fileLockPath);
$logger->error('publishContestResult success for contest: ' . json_encode($contest));
return true;
}
private function getAutoPublishContest($taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $taskName]);
$data = $stmt->fetch();
if (empty($data)) {
$lastRun = [];
} else {
$lastRun = json_decode($data['value'], true);
}
$sql = "SELECT c.*
FROM customers c
WHERE c.company_type = 'Contest'
AND c.contest_publish_auto = 1
AND c.end_date >= '" . date('Y-m-d H:i:s') . "'
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$contests = $stmt->fetchAll();
foreach ($contests as $contest) {
if ( !isset($lastRun[$contest['id']]) || strtotime($lastRun[$contest['id']]) < strtotime('now -1 hour') ) {
return $contest;
}
}
throw new \Exception("There is no contest");
}
private function actionPublishResult($contest, $contestService)
{
$conn = $this->entityManager->getConnection();
$sql = "SELECT r.*
FROM contest_rounds r
WHERE r.customer_id = :customer_id
AND r.result_included = 1
ORDER BY r.id
";
$stmt = $conn->prepare($sql);
$stmt->execute(['customer_id' => $contest['id']]);
$contestRounds = $stmt->fetchAll();
foreach ($contestRounds as $round) {
$contestService->collectDlmsPoints($round);
$contestService->publishContestResult($round);
}
}
private function notifyOnePublishContestResultSuccess($contest, $taskName)
{
$conn = $this->entityManager->getConnection();
$sql = "SELECT *
FROM settings
WHERE name = :name
";
$stmt = $conn->prepare($sql);
$stmt->execute(['name' => $taskName]);
$data = $stmt->fetch();
if (empty($data)) {
$sql = "INSERT INTO settings (`name`, `value`)
VALUES (:name, :value)
";
$value[$contest['id']] = date('Y-m-d H:i:s');
} else {
$sql = "UPDATE settings
SET value = :value
WHERE name = :name
";
$value = json_decode($data['value'], true);
$value[$contest['id']] = date('Y-m-d H:i:s');
}
$stmt = $conn->prepare($sql);
$stmt->execute([ 'name' => $taskName, 'value' => json_encode($value) ]);
}
private function notifyPublishContestResultSuccess($taskName)
{
$this->updateLastTimeSuccessForTask($taskName);
}
}