Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @file
- * Stargater Reclamos module file.
- */
- use Drupal\node\Entity\Node;
- use Drupal\Core\Access\AccessResult;
- use Drupal\Core\Session\AccountInterface;
- use Drupal\node\NodeInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Datetime\DrupalDateTime;
- use Drupal\changed_fields\NodeSubject;
- use Drupal\stargate_reclamos\ObservarCambioNode;
- const RECLAMO_NO_FACTURABLE = 'No facturable';
- const RECLAMO_BLOQUEADO_FACTURACION = 'Bloqueado para facturación';
- const RECLAMO_FACTURADO = 'Facturado';
- const RECLAMO_NUEVO = 'Nuevo';
- const RECLAMO_EN_PROGRESO = 'En progreso';
- const RECLAMO_TERMINADO = 'Terminado';
- const ID_ESTADO_NO_FACTURABLE = '1';
- const ID_ESTADO_BLOQUEADO_PARA_FACTURACION = '2';
- const ID_ESTADO_TERMINADO = 'finished';
- /**
- * Implements hook_theme().
- */
- function stargate_reclamos_theme($existing, $type, $theme, $path) {
- return [
- 'node__reclamo' => [
- 'template' => 'node--reclamo',
- 'base hook' => 'node',
- ],
- 'stargate_risk_report' => [
- 'template' => 'stargate_risk_report',
- 'variables' => ['report' => [], 'content' => [], 'node' => []],
- ],
- ];
- }
- function stargate_reclamos_preprocess_node(&$vars) {
- //Add vars
- $node = $vars['node'];
- // Risk reort
- $risk_report = json_decode($node->field_risk_report->value);
- // Legal report
- $legal_report = ['Juicios' => []];
- if ($node->field_has_trial_history->value) {
- libxml_use_internal_errors(TRUE);
- $xml = simplexml_load_string(trim($node->field_trial_history->value));
- if ($xml === FALSE) {
- $message = "Falló el parseo del XML de Juicios para el nodo [" . $node->ID() . "]\n";
- foreach(libxml_get_errors() as $error) {
- $message .= "\n" . $error->message;
- }
- \Drupal::logger('stargate_reclamos')->error($message);
- }
- $legal_report = json_decode(json_encode($xml));
- if (!is_array($legal_report->Juicio)) {
- $legal_report->Juicio = array($legal_report->Juicio);
- }
- }
- // Clean up
- $index = 0;;
- foreach($legal_report->Juicio as $trial) {
- foreach(array_keys((array) $trial) as $key) {
- if (is_object($trial->{$key})) {
- if (count((array) $trial->{$key}) == 0) {
- $legal_report->Juicio[$index]->{$key} = '';
- }
- }
- }
- $index++;
- }
- // Accident report
- $accident_report = ['#theme' => 'markup', '#markup' => $node->field_has_srt->value ? $node->field_srt->value : ''];
- // Render risk report
- $report_render_array = [
- '#theme' => 'stargate_risk_report',
- '#report' => [
- 'risk' => $risk_report,
- 'legal' => $legal_report,
- 'accident' => $accident_report
- ],
- '#content' => $vars['content'],
- '#node' => $vars['node']
- ];
- $vars['risk_report'] = Drupal::service('renderer')->render($report_render_array);
- // decide which homepage the user must go back to
- $vars['frontpage_url'] = _stargate_reclamos_get_frontpage_url();
- }
- /**
- * Implements hook_cron().
- */
- function stargate_reclamos_cron() {
- $interval = \Drupal::state()->get('stargate_reclamos_cron_interval') ? : 30; // 30 seg
- $next_execution = \Drupal::state()->get('stargate_reclamos.next_execution');
- $next_execution = !empty($next_execution) ? $next_execution : 0;
- if (REQUEST_TIME >= $next_execution) {
- $nodes = _stargate_reclamos_get_nodes();
- \Drupal::logger('stargate_reclamos')->notice('Procesando reclamos ...');
- foreach ($nodes as $key => $id) {
- _stargate_reclamos_populate_fields($id);
- }
- \Drupal::state()->set('stargate_reclamos.next_execution', REQUEST_TIME + $interval);
- }
- else {
- \Drupal::logger('stargate_reclamos')->notice('Salteando reclamos.');
- }
- // Process: Block for billing.
- _stargate_reclamos_block_for_billing_cron_process();
- }
- function _stargate_reclamos_get_nodes() {
- $range = \Drupal::state()->get('stargate_reclamos_query_range') ? : 50;
- $query = \Drupal::entityQuery('node');
- $query->condition('status', 1);
- $query->condition('type', 'reclamo');
- $query->condition('field_state', 'new');
- $group = $query->orConditionGroup()
- ->condition('field_has_trial_history', FALSE)
- ->condition('field_has_risk_report', FALSE);
- $query->condition($group);
- $query->range(0, $range);
- $entity_ids = $query->execute();
- return $entity_ids;
- }
- function _stargate_reclamos_populate_fields($id) {
- $node = Node::load($id);
- $cuil = $node->get('field_cuil')->value;
- $message = "Haciendo llamadas a los WS para cuil: $cuil (nid: $id)";
- \Drupal::logger('stargate_reclamos')->notice($message);
- if (empty($cuil)) {
- $message = "El reclamo con nid: $id no tiene seteado CUIL!";
- \Drupal::logger('stargate_reclamos')->warning($message);
- return;
- }
- $success = TRUE;
- //trial_history
- $user = \Drupal::state()->get('reclamo_ws_user') ?: 'abiuso@experta.com.ar';
- $pass = \Drupal::state()->get('reclamo_ws_pass') ?: 'ga12345678';
- $default_url = 'http://186.182.220.51/ws/wsjuicios.asmx/ObtenerJuiciosPorEmpleado?usuario=%s&constraseña=%s&cuil=%s';
- $url = \Drupal::state()->get('reclamo_ws_url') ?: $default_url;
- //@TODO: how solve encoding : Windows-1252
- $request_url = sprintf($url, $user, $pass, $cuil);
- $request_url = str_replace('ñ', '%F1', $request_url);
- $param = ['Accept' => 'application/xml'];
- $output = _stargate_reclamos_call_ws('GET', $request_url, $param);
- if ($output != '') {
- // https://stackoverflow.com/questions/8830599/php-convert-xml-to-json
- $xml = simplexml_load_string($output);
- $json = json_encode($xml);
- $node->set('field_trial_history', $output);
- $node->set('field_has_trial_history', TRUE);
- }
- else {
- \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Juicios!');
- $success = FALSE;
- }
- //risk_report
- $default_url_ws_risk = 'http://api.fidelitas.com.ar/v1/ic/json';
- $url = \Drupal::state()->get('reclamo_risk_ws_url') ?: $default_url_ws_risk;
- $apikey = \Drupal::state()->get('reclamo_apikey') ?: '928BFC592F76DB92';
- $param = [
- 'form_params' => [
- 'apikey' => $apikey,
- 'cuit' => $cuil,
- ]
- ];
- $output = _stargate_reclamos_call_ws('POST', $url, $param);
- if ($output != '') {
- $node->set('field_risk_report', $output);
- $node->set('field_has_risk_report', TRUE);
- }
- else {
- \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Riesgos!');
- $success = FALSE;
- }
- if ($success) {
- $node->set('field_state', 'progress');
- }
- $node->save();
- }
- function _stargate_reclamos_call_ws($method, $url, $param) {
- $output = '';
- $client = \Drupal::httpClient();
- try {
- $response = $client->request($method, $url, $param);
- $code = $response->getStatusCode();
- if ($code == 200) { //OK
- $output = $response->getBody();
- }
- }
- catch (GuzzleHttp\Exception\ClientException $e) {
- \Drupal::logger('stargate_reclamos')->error($e->getMessage());
- }
- return $output;
- }
- /**
- * implements hook_node_presave(\Drupal\Core\Entity\EntityInterface $node)
- */
- function stargate_reclamos_node_presave(\Drupal\Core\Entity\EntityInterface $node) {
- if ( isset($node->field_srt->value) && !empty($node->field_srt->value) ) {
- $node->field_has_srt = true;
- } else {
- $node->field_has_srt = false;
- }
- if ( isset($node->field_social_network_analysis->value) && !empty($node->field_social_network_analysis->value) ) {
- $node->field_has_social_network = true;
- } else {
- $node->field_has_social_network = false;
- }
- // Antes de guardar o actualizar un nodo reclamo, Setear fechas.
- if ($node->bundle() == 'reclamo') {
- _actualizar_fechas_reclamo($node);
- }
- }
- function _stargate_reclamos_get_frontpage_url() {
- $rol = _get_current_rol();
- $url = '/reclamos';
- if ($rol == 'contador') {
- $url = '/admin/content/facturacion';
- }
- elseif ($rol == 'administrator' or $rol == 'analista') {
- $url = '/admin/content/reclamos';
- }
- return $url;
- }
- /**
- * Implements hook_node_access().
- */
- function stargate_reclamos_node_access(NodeInterface $node, $op, AccountInterface $account) {
- $rol = _get_current_rol();
- $estado_facturacion = $node->get('field_estado_facturacion')->getString();
- switch ($op) {
- case 'update':
- if ($node->bundle() == 'reclamo') {
- if ($rol =='contador' || $rol == 'usuario_art' ||
- ($rol == 'analista' && $estado_facturacion != ID_ESTADO_NO_FACTURABLE)) {
- // Permisos denegados para editar nodos reclamo
- return AccessResult::forbidden()->cachePerPermissions();
- }
- else {
- return AccessResult::allowed();
- }
- }
- default:
- // No opinion.
- return AccessResult::neutral();
- }
- }
- /**
- * Get current rol.
- */
- function _get_current_rol() {
- $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
- $roles = $user->getRoles(TRUE);
- return $roles[0];
- }
- // Setear fechas reclamo
- function _actualizar_fechas_reclamo($node) {
- $fecha_hoy = \Drupal::time()->getCurrentTime();
- $fecha_hoy = date('Y-m-d\TH:i:s', $fecha_hoy);
- // Obtener solo los estados que cambiaron
- $fields_changed = _get_estados_cambiados($node);
- // Saber el/los estados que fueron cambiados
- $hay_cambio_estado = array_key_exists('field_state', $fields_changed);
- $hay_cambio_estado_facturacion = array_key_exists('field_estado_facturacion', $fields_changed);
- // Si cambió algun estado
- if (!empty($fields_changed)) {
- $message_estado = "";
- $message_estado_facturacion = "";
- // Si hay cambio de estado
- if ($hay_cambio_estado) {
- $cambio_estado = $fields_changed['field_state']['new_value'][0]['value'];
- $ya_terminado = $node->field_fecha_estado_activo->value;
- $reclamo_estado_name = _estado_reclamo($cambio_estado);
- if ($cambio_estado == ID_ESTADO_TERMINADO && !$ya_terminado) {
- // Actualizar a estado Terminado, establecer fecha y marcar como Terminado
- $node->set('field_date_finished', $fecha_hoy);
- $node->set('field_fecha_estado_activo', TRUE);
- }
- $message_estado = "Nuevo estado a: ". $reclamo_estado_name. '. ';
- }
- // Si hay cambio de estado de facturacion
- if ($hay_cambio_estado_facturacion) {
- $cambio_estado_facturacion = $fields_changed['field_estado_facturacion']['new_value'][0]['value'];
- $ya_facturado = $node->field_fecha_facturado_activo->value;
- $reclamo_facturado_name = _estado_facturacion($cambio_estado_facturacion);
- if ($cambio_estado_facturacion == ID_ESTADO_FACTURADO && !$ya_facturado) {
- // Actualizar a estado Facturado, establecer fecha y marcar como Facturado
- $node->set('field_date_billed', $fecha_hoy);
- $node->set('field_fecha_facturado_activo', TRUE);
- }
- $message_estado_facturacion = "Nuevo estado de facturacion a: ". $reclamo_facturado_name.'. ';
- }
- _establecer_revision_estados($node, $message_estado, $message_estado_facturacion);
- $message_log = "Cambio en nodo reclamo de id: " . $node->id().'. '.$message_estado.$message_estado_facturacion;
- _stargate_reclamos_log('notice', $message_log);
- }
- }
- // Obtener solo los estados que cambiaron al guardar un reclamo
- function _get_estados_cambiados($node) {
- $nodeSubject = new NodeSubject($node, 'default_field_comparator');
- $nodeSubject->attach(new ObservarCambioNode());
- $nodeSubject->notify();
- return $nodeSubject->getChangedFields();
- }
- // Obtener nombre real del estado del reclamo
- function _estado_reclamo($cambio_estado) {
- $estado_reclamo = [
- 'new' => RECLAMO_NUEVO,
- 'progress' => RECLAMO_EN_PROGRESO,
- 'finished' => RECLAMO_TERMINADO,
- ];
- return $estado_reclamo[$cambio_estado];
- }
- // Obtener nombre real del estado de facturacion
- function _estado_facturacion($reclamo_facturado) {
- $estado_facturacion = [
- '1' => RECLAMO_NO_FACTURABLE,
- '2' => RECLAMO_BLOQUEADO_FACTURACION,
- '3' => RECLAMO_FACTURADO,
- ];
- return $estado_facturacion[$reclamo_facturado];
- }
- // Crear revision al cambiar de estados
- function _establecer_revision_estados($node, $message_estado, $message_estado_facturacion) {
- $current_user = \Drupal::currentUser();
- $node->setNewRevision(TRUE);
- $node->revision_log = "Nueva revisión para el nodo de id: " . $node->id().'. ' .$message_estado.$message_estado_facturacion;
- $node->setRevisionCreationTime(REQUEST_TIME);
- $node->setRevisionUserId($current_user->id());
- }
- /**
- * Implements hook_form_alter().
- */
- function stargate_reclamos_form_alter(&$form, FormStateInterface $form_state, $form_id) {
- switch ($form_id) {
- case 'node_reclamo_edit_form':
- $rol = _get_current_rol();
- $node = $form_state->getFormObject()->getEntity();
- if ($rol != 'administrator') {
- // Bloquear fechas para estados, en nodo reclamo.
- $form['field_date_finished']['#disabled'] = TRUE;
- $form['field_date_billed']['#disabled'] = TRUE;
- }
- }
- }
- /**
- * Cron for process "Block for billing".
- */
- function _stargate_reclamos_block_for_billing_cron_process() {
- $current_time = \Drupal::time()->getRequestTime();
- $should_run = _stargate_reclamos_should_run_block_for_billing($current_time);
- if ($should_run) {
- \Drupal::state()->set('stargate_reclamos.last_execution', $current_time);
- _stargate_reclamos_log('notice', 'Verificación de reclamos bloqueables para facturación iniciado.');
- _stargate_reclamos_block_for_billing_process();
- _stargate_reclamos_log('notice', 'Verificación de reclamos bloqueables para facturación finalizado.');
- }
- }
- /**
- * Returns TRUE if the "Block for Billing" process have to run.
- */
- function _stargate_reclamos_should_run_block_for_billing($time) {
- $scheduled_time = '23:59';
- // Get the last execution of cron for this process.
- $cron_last_exec = \Drupal::state()->get('stargate_reclamos.last_execution');
- $last_exec_timestamp = $cron_last_exec ? $cron_last_exec : 0;
- $last_exec_date = \DateTime::createFromFormat('U', $last_exec_timestamp);
- // Create a new Date that has the date equal to the last run of cron,
- // and the time equal to the expected hour on which the cron have to run.
- $scheduled_date = \DateTime::createFromFormat('U', $last_exec_timestamp);
- $scheduled_date->setTime(...explode(':', $scheduled_time));
- // This process have to run once per day, then if the process already ran, return false.
- if ($scheduled_date->getTimestamp() < $last_exec_date->getTimestamp()) {
- return FALSE;
- }
- // In another case, return True or False depending on whether the scheduled date passed or not.
- return ($scheduled_date->getTimestamp() <= $time);
- }
- /**
- * Process: set nodes of type Reclamo as blocked for billing.
- */
- function _stargate_reclamos_block_for_billing_process() {
- // Get all nodes of type Reclamo.
- $query = \Drupal::entityQuery('node');
- $query->condition('type', 'reclamo');
- $nids = $query->execute();
- $reclamos = entity_load_multiple('node', $nids);
- foreach ($reclamos as $reclamo) {
- if (stargate_reclamos_lockable_for_billing($reclamo)) {
- $reclamo->set('field_estado_facturacion', ID_ESTADO_BLOQUEADO_PARA_FACTURACION);
- $reclamo->save();
- _stargate_reclamos_log('notice', 'Reclamo ' . $reclamo->id() . ' bloqueado para facturación.');
- }
- }
- }
- /**
- * Returns TRUE if the node can be lockable for billing.
- */
- function stargate_reclamos_lockable_for_billing($reclamo) {
- if ($reclamo) {
- // Check State.
- $state = $reclamo->get('field_state')->getString();
- $finished = ($state == ID_ESTADO_TERMINADO);
- // Check the finished date.
- $current_time = \Drupal::time()->getRequestTime();
- $field_finished_date = $reclamo->get('field_date_finished')->getString();
- $finished_date = new DrupalDateTime($field_finished_date);
- $passed_date = ($finished_date->format('U') <= $current_time);
- // Check for billing state.
- $billing_state = $reclamo->get('field_estado_facturacion')->getString();
- $not_billable = ($billing_state == ID_ESTADO_NO_FACTURABLE);
- return ($finished && $passed_date && $not_billable);
- }
- return FALSE;
- }
- function _stargate_reclamos_log($level, $message) {
- switch ($level) {
- case 'error':
- \Drupal::logger('stargate_reclamos')->error($message);
- break;
- case 'notice':
- \Drupal::logger('stargate_reclamos')->notice($message);
- break;
- case 'debug':
- \Drupal::logger('stargate_reclamos')->debug($message);
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement