Show error messages in subscription - refs BT#9461

1.10.x
Angel Fernando Quiroz Campos 10 years ago
parent bd06ab8632
commit a71ad2ccc4
  1. 3
      plugin/advanced_subscription/lang/english.php
  2. 3
      plugin/advanced_subscription/lang/spanish.php
  3. 242
      plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php
  4. 16
      plugin/advanced_subscription/src/terms_and_conditions.php
  5. 10
      plugin/advanced_subscription/views/terms_and_conditions.tpl

@ -22,7 +22,7 @@ $strings['min_profile_percentage_help'] = "Percentage number( > 0.00 y < 100.00)
/* String for error message about requirements */
$strings['AdvancedSubscriptionNotConnected'] = "You are not connected to platform. Please login first";
$strings['AdvancedSubscriptionProfileIncomplete'] = "Your percentage completed profile require to exceed minimum percentage. Please complete percentage";
$strings['AdvancedSubscriptionProfileIncomplete'] = "You must fill the <strong>%d percent</strong> of your profile at least. For now you has filled the <strong>%d percent</strong>";
$strings['AdvancedSubscriptionIncompleteInduction'] = "You have not yet completed induction course. Please complete it first";
$strings['AdvancedSubscriptionCostXLimitReached'] = "We are sorry, you have already reached yearly limit %s TUV cost for courses ";
$strings['AdvancedSubscriptionTimeXLimitReached'] = "We are sorry, you have already reached yearly limit %s hours for courses";
@ -138,4 +138,3 @@ $strings['MailContentReminderMaxSuperior'] = 'We kindly remind you that we have
$strings['MailContentReminderMaxSuperiorSecond'] = 'This course have limited vacancies and has received a high subscription request rate, So we recommend all areas to accept at most <strong>%s</strong> candidates. We invite you to accept or reject the inscription request by clicking the corresponding button for each collaborator.';
$strings['YouMustAcceptTermsAndConditions'] = 'To subscribe to course <strong>%s</strong>, you must accept these terms and conditions.';
$strings['YouMustFillXPercentOfYourProfileAtLeast'] = "You must fill the <strong>%d percent</strong> of your profile at least. For now you has filled the <strong>%d percent</strong>";

@ -22,7 +22,7 @@ $strings['min_profile_percentage_help'] = 'Número porcentage ( > 0.00 y < 100.0
/* String for error message about requirements */
$strings['AdvancedSubscriptionNotConnected'] = "Usted no está conectado en la plataforma. Por favor ingrese su usuario / constraseña para poder inscribirse";
$strings['AdvancedSubscriptionProfileIncomplete'] = "Su perfil no es lo suficientemente completo para poder inscribirse al curso. Por favor complete su perfil";
$strings['AdvancedSubscriptionProfileIncomplete'] = "Debe llenar el <strong>%d porciento</strong> de tu perfil como mínimo. Por ahora has llenado el <strong>%d porciento</strong>";
$strings['AdvancedSubscriptionIncompleteInduction'] = "Usted aún no ha completado el curso de inducción. Por favor complete el curso inducción";
$strings['AdvancedSubscriptionCostXLimitReached'] = "Lo sentimos, usted ya ha alcanzado el límite anual de %s UIT para los cursos que ha seguido este año";
$strings['AdvancedSubscriptionTimeXLimitReached'] = "Lo sentimos, usted ya ha alcanzado el límite anual de %s horas para los cursos que ha seguido este año";
@ -138,4 +138,3 @@ $strings['MailContentReminderMaxSuperior'] = 'Le recordamos que hemos recibido l
$strings['MailContentReminderMaxSuperiorSecond'] = 'Este curso tiene una cantidad de cupos limitados y ha recibido una alta tasa de solicitudes de inscripción, por lo que recomendamos que cada área apruebe un máximo de <strong>%s</strong> candidatos. Le invitamos a aprobar o desaprobar las suscripciones, dando clic en el botón correspondiente a continuación para cada colaborador.';
$strings['YouMustAcceptTermsAndConditions'] = 'Para inscribirse al curso <strong>%s</strong>, debe aceptar estos términos y condiciones.';
$strings['YouMustFillXPercentOfYourProfileAtLeast'] = "Debes llenar el <strong>%d porciento</strong> de tu perfil como mínimo. Por ahora has llenado el <strong>%d porciento</strong>";

@ -10,6 +10,8 @@
class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
{
protected $strings;
private $errorMessages;
/**
* Constructor
*/
@ -29,6 +31,8 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
);
parent::__construct('1.0', 'Imanol Losada, Daniel Barreto', $parameters);
$this->errorMessages = array();
}
/**
@ -136,115 +140,175 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
Database::query("DELETE FROM $settingsTable WHERE subkey = 'advanced_subscription'");
}
/**
* Get the error messages list
* @return array The message list
*/
public function getErrorMessages()
{
return $this->errorMessages;
}
/**
* Return true if user is allowed to be added to queue for session subscription
* @param int $userId
* @param array $params MUST have keys:
* "is_connected" Indicate if the user is online on external web
* "profile_completed" Percentage of completed profile, given by WS
* @param boolean $collectErrors Optional. Default is false. Whether collect all errors or throw exeptions
* @throws Exception
* @return bool
*/
public function isAllowedToDoRequest($userId, $params = array())
public function isAllowedToDoRequest($userId, $params = array(), $collectErrors = false)
{
$isAllowed = null;
$plugin = self::create();
$wsUrl = $plugin->get('ws_url');
// Student always is connected
$isConnected = true;
if ($isConnected) {
$profileCompletedMin = (float) $plugin->get('min_profile_percentage');
if (is_string($wsUrl) && !empty($wsUrl)) {
$options = array(
'location' => $wsUrl,
'uri' => $wsUrl
);
$client = new SoapClient(null, $options);
$userInfo = UserManager::get_user_info_by_id($userId);
try {
$profileCompleted = $client->__soapCall('getProfileCompletionPercentage', $userInfo['extra']['drupal_user_id']);
} catch (\Exception $e) {
$profileCompleted = 0;
}
} elseif (isset($params['profile_completed'])) {
$profileCompleted = (float) $params['profile_completed'];
} else {
$profileCompleted = 0;
if (!$isConnected) {
$this->errorMessages[] = $this->get_lang('AdvancedSubscriptionNotConnected');
if (!$collectErrors) {
throw new \Exception($this->get_lang('AdvancedSubscriptionNotConnected'));
}
if ($profileCompleted >= $profileCompletedMin) {
$checkInduction = $plugin->get('check_induction');
// @TODO: check if user have completed at least one induction session
$completedInduction = true;
if (!$checkInduction || $completedInduction) {
$uitMax = $plugin->get('yearly_cost_unit_converter');
$uitMax *= $plugin->get('yearly_cost_limit');
$uitUser = 0;
$now = new DateTime(api_get_utc_datetime());
$newYearDate = $plugin->get('course_session_credit_year_start_date');
$newYearDate = !empty($newYearDate) ?
new \DateTime($newYearDate . $now->format('/Y')) :
$now;
$extra = new ExtraFieldValue('session');
$joinSessionTable = Database::get_main_table(TABLE_MAIN_SESSION_USER) . ' su INNER JOIN ' .
Database::get_main_table(TABLE_MAIN_SESSION) . ' s ON s.id = su.id_session';
$whereSessionParams = 'su.relation_type = ? AND s.date_start >= ? AND su.id_user = ?';
$whereSessionParamsValues = array(
0,
$newYearDate->format('Y-m-d'),
$userId
);
$whereSession = array(
'where' => array(
$whereSessionParams => $whereSessionParamsValues
)
);
$selectSession = 's.id AS id';
$sessions = Database::select(
$selectSession,
$joinSessionTable,
$whereSession
);
}
if (is_array($sessions) && count($sessions) > 0) {
foreach ($sessions as $session) {
$var = $extra->get_values_by_handler_and_field_variable($session['id'], 'cost');
$uitUser += $var['field_value'];
}
}
if ($uitMax >= $uitUser) {
$expendedTimeMax = $plugin->get('yearly_hours_limit');
$expendedTime = 0;
if (is_array($sessions) && count($sessions) > 0) {
foreach ($sessions as $session) {
$var = $extra->get_values_by_handler_and_field_variable($session['id'], 'teaching_hours');
$expendedTime += $var['field_value'];
}
}
if ($expendedTimeMax >= $expendedTime) {
$expendedNumMax = $plugin->get('courses_count_limit');
$expendedNum = count($sessions);
if ($expendedNumMax >= $expendedNum) {
$isAllowed = true;
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionCourseXLimitReached'));
}
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionTimeXLimitReached'));
}
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionCostXLimitReached'));
}
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionIncompleteInduction'));
}
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionProfileIncomplete'));
$profileCompletedMin = (float) $plugin->get('min_profile_percentage');
if (is_string($wsUrl) && !empty($wsUrl)) {
$options = array(
'location' => $wsUrl,
'uri' => $wsUrl
);
$client = new SoapClient(null, $options);
$userInfo = UserManager::get_user_info_by_id($userId);
try {
$profileCompleted = $client->__soapCall('getProfileCompletionPercentage', $userInfo['extra']['drupal_user_id']);
} catch (\Exception $e) {
$profileCompleted = 0;
}
} elseif (isset($params['profile_completed'])) {
$profileCompleted = (float) $params['profile_completed'];
} else {
throw new \Exception($this->get_lang('AdvancedSubscriptionNotConnected'));
$profileCompleted = 0;
}
if ($profileCompleted < $profileCompletedMin) {
$errorMessage = sprintf(
$this->get_lang('AdvancedSubscriptionProfileIncomplete'),
$profileCompletedMin,
$profileCompleted
);
$this->errorMessages[] = $errorMessage;
if (!$collectErrors) {
throw new \Exception($errorMessage);
}
}
$checkInduction = $plugin->get('check_induction');
// @TODO: check if user have completed at least one induction session
$completedInduction = true;
if ($checkInduction && !$completedInduction) {
$this->errorMessages[] = $this->get_lang('AdvancedSubscriptionIncompleteInduction');
if (!$collectErrors) {
throw new \Exception($this->get_lang('AdvancedSubscriptionIncompleteInduction'));
}
}
$uitMax = $plugin->get('yearly_cost_unit_converter');
$uitMax *= $plugin->get('yearly_cost_limit');
$uitUser = 0;
$now = new DateTime(api_get_utc_datetime());
$newYearDate = $plugin->get('course_session_credit_year_start_date');
$newYearDate = !empty($newYearDate) ?
new \DateTime($newYearDate . $now->format('/Y')) :
$now;
$extra = new ExtraFieldValue('session');
$joinSessionTable = Database::get_main_table(TABLE_MAIN_SESSION_USER) . ' su INNER JOIN ' .
Database::get_main_table(TABLE_MAIN_SESSION) . ' s ON s.id = su.id_session';
$whereSessionParams = 'su.relation_type = ? AND s.date_start >= ? AND su.id_user = ?';
$whereSessionParamsValues = array(
0,
$newYearDate->format('Y-m-d'),
$userId
);
$whereSession = array(
'where' => array(
$whereSessionParams => $whereSessionParamsValues
)
);
$selectSession = 's.id AS id';
$sessions = Database::select(
$selectSession,
$joinSessionTable,
$whereSession
);
if (is_array($sessions) && count($sessions) > 0) {
foreach ($sessions as $session) {
$var = $extra->get_values_by_handler_and_field_variable($session['id'], 'cost');
$uitUser += $var['field_value'];
}
}
if ($uitMax < $uitUser) {
$errorMessage = sprintf(
$this->get_lang('AdvancedSubscriptionCostXLimitReached'),
$uitMax
);
$this->errorMessages[] = $errorMessage;
if (!$collectErrors) {
throw new \Exception($errorMessage);
}
}
$expendedTimeMax = $plugin->get('yearly_hours_limit');
$expendedTime = 0;
if (is_array($sessions) && count($sessions) > 0) {
foreach ($sessions as $session) {
$var = $extra->get_values_by_handler_and_field_variable($session['id'], 'teaching_hours');
$expendedTime += $var['field_value'];
}
}
if ($expendedTimeMax < $expendedTime) {
$errorMessage = sprintf(
$this->get_lang('AdvancedSubscriptionTimeXLimitReached'),
$expendedTimeMax
);
$this->errorMessages[] = $errorMessage;
if (!$collectErrors) {
throw new \Exception($errorMessage);
}
}
$expendedNumMax = $plugin->get('courses_count_limit');
$expendedNum = count($sessions);
if ($expendedNumMax < $expendedNum) {
$errorMessage = sprintf(
$this->get_lang('AdvancedSubscriptionCourseXLimitReached'),
$expendedNumMax
);
$this->errorMessages[] = $errorMessage;
if (!$collectErrors) {
throw new \Exception($errorMessage);
}
}
return $isAllowed;
return empty($this->errorMessages);
}
/**

@ -24,7 +24,18 @@ $data['termsRejected'] = isset($_REQUEST['r']) ? intval($_REQUEST['r']) : 0;
// Init template
$tpl = new Template($plugin->get_lang('plugin_title'));
$requiredMinimun = $plugin->get('min_profile_percentage');
$isAllowToDoRequest = $plugin->isAllowedToDoRequest(
$data['studentUserId'],
array(
'is_connected' => $data['is_connected'],
'profile_completed' => $data['profile_completed']
),
true
);
if (!$isAllowToDoRequest) {
$tpl->assign('errorMessages', $plugin->getErrorMessages());
}
if (
!empty($data['sessionId']) &&
@ -76,7 +87,6 @@ $tpl->assign('student', $data['student']);
$tpl->assign('sessionId', $data['sessionId']);
$tpl->assign('termsContent', $termsContent);
$tpl->assign('termsFiles', $termFiles);
$tpl->assign('profileCompleted', $data['profile_completed']);
$tpl->assign('percentMinimun', $requiredMinimun);
$content = $tpl->fetch('/advanced_subscription/views/terms_and_conditions.tpl');
echo $content;

@ -25,11 +25,17 @@
{{ "YouMustAcceptTermsAndConditions" | get_plugin_lang("AdvancedSubscriptionPlugin") | format(session.name) }}
</div>
{% endif %}
{% if percentMinimun > profileCompleted %}
{% if errorMessages is defined %}
<div class="alert alert-warning legal-terms-popup">
{{ "YouMustFillXPercentOfYourProfileAtLeast" | get_plugin_lang("AdvancedSubscriptionPlugin") | format(percentMinimun, profileCompleted) }}
<ul>
{% for errorMessage in errorMessages %}
<li>{{ errorMessage }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="legal-terms legal-terms-popup">
{{ termsContent }}
</div>

Loading…
Cancel
Save