Advertisement
Guest User

Untitled

a guest
Jan 4th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.52 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * @file
  5.  * Stargater Reclamos module file.
  6. */
  7.  
  8. use Drupal\node\Entity\Node;
  9. use Drupal\Core\Access\AccessResult;
  10. use Drupal\Core\Session\AccountInterface;
  11. use Drupal\node\NodeInterface;
  12. use Drupal\Core\Form\FormStateInterface;
  13. use Drupal\Core\Datetime\DrupalDateTime;
  14. use Drupal\changed_fields\NodeSubject;
  15. use Drupal\stargate_reclamos\ObservarCambioNode;
  16.  
  17. const RECLAMO_NO_FACTURABLE = 'No facturable';
  18. const RECLAMO_BLOQUEADO_FACTURACION = 'Bloqueado para facturación';
  19. const RECLAMO_FACTURADO = 'Facturado';
  20.  
  21. const RECLAMO_NUEVO = 'Nuevo';
  22. const RECLAMO_EN_PROGRESO = 'En progreso';
  23. const RECLAMO_TERMINADO = 'Terminado';
  24.  
  25. const ID_ESTADO_NO_FACTURABLE = '1';
  26. const ID_ESTADO_BLOQUEADO_PARA_FACTURACION = '2';
  27.  
  28. const ID_ESTADO_TERMINADO = 'finished';
  29.  
  30. /**
  31.  * Implements hook_theme().
  32.  */
  33. function stargate_reclamos_theme($existing, $type, $theme, $path) {
  34.   return [
  35.     'node__reclamo' => [
  36.       'template' => 'node--reclamo',
  37.       'base hook' => 'node',
  38.     ],
  39.     'stargate_risk_report' => [
  40.       'template' => 'stargate_risk_report',
  41.       'variables' => ['report' => [], 'content' => [], 'node' => []],
  42.     ],
  43.   ];
  44. }
  45.  
  46. function stargate_reclamos_preprocess_node(&$vars) {
  47.   //Add vars
  48.   $node = $vars['node'];
  49.  
  50.   // Risk reort
  51.   $risk_report  = json_decode($node->field_risk_report->value);
  52.  
  53.   // Legal report
  54.   $legal_report = ['Juicios' => []];
  55.   if ($node->field_has_trial_history->value) {
  56.       libxml_use_internal_errors(TRUE);
  57.       $xml = simplexml_load_string(trim($node->field_trial_history->value));
  58.       if ($xml === FALSE) {
  59.         $message = "Falló el parseo del XML de Juicios para el nodo [" . $node->ID() . "]\n";
  60.         foreach(libxml_get_errors() as $error) {
  61.           $message .= "\n" . $error->message;
  62.         }
  63.         \Drupal::logger('stargate_reclamos')->error($message);
  64.       }
  65.  
  66.       $legal_report = json_decode(json_encode($xml));
  67.  
  68.       if (!is_array($legal_report->Juicio)) {
  69.         $legal_report->Juicio = array($legal_report->Juicio);
  70.       }
  71.   }
  72.  
  73.   // Clean up
  74.   $index = 0;;
  75.   foreach($legal_report->Juicio as $trial) {
  76.     foreach(array_keys((array) $trial) as $key) {
  77.       if (is_object($trial->{$key})) {
  78.         if (count((array) $trial->{$key}) == 0) {
  79.           $legal_report->Juicio[$index]->{$key} = '';
  80.         }
  81.       }
  82.     }
  83.     $index++;
  84.   }
  85.  
  86.   // Accident report
  87.   $accident_report = ['#theme' => 'markup', '#markup' => $node->field_has_srt->value ? $node->field_srt->value : ''];
  88.  
  89.   // Render risk report
  90.   $report_render_array = [
  91.     '#theme' => 'stargate_risk_report',
  92.     '#report' => [
  93.       'risk'  => $risk_report,
  94.       'legal' => $legal_report,
  95.       'accident' => $accident_report
  96.     ],
  97.     '#content' => $vars['content'],
  98.     '#node' => $vars['node']
  99.   ];
  100.  
  101.   $vars['risk_report'] = Drupal::service('renderer')->render($report_render_array);
  102.  
  103.   // decide which homepage the user must go back to
  104.   $vars['frontpage_url'] = _stargate_reclamos_get_frontpage_url();
  105. }
  106.  
  107.  
  108. /**
  109.  * Implements hook_cron().
  110.  */
  111. function stargate_reclamos_cron() {
  112.   $interval = \Drupal::state()->get('stargate_reclamos_cron_interval') ? : 30; // 30 seg
  113.  
  114.   $next_execution = \Drupal::state()->get('stargate_reclamos.next_execution');
  115.   $next_execution = !empty($next_execution) ? $next_execution : 0;
  116.   if (REQUEST_TIME >= $next_execution) {
  117.     $nodes = _stargate_reclamos_get_nodes();
  118.     \Drupal::logger('stargate_reclamos')->notice('Procesando reclamos ...');
  119.     foreach ($nodes as $key => $id) {
  120.       _stargate_reclamos_populate_fields($id);
  121.     }
  122.     \Drupal::state()->set('stargate_reclamos.next_execution', REQUEST_TIME + $interval);
  123.   }
  124.   else {
  125.     \Drupal::logger('stargate_reclamos')->notice('Salteando reclamos.');
  126.   }
  127.  
  128.   // Process: Block for billing.
  129.   _stargate_reclamos_block_for_billing_cron_process();
  130. }
  131.  
  132. function _stargate_reclamos_get_nodes() {
  133.   $range = \Drupal::state()->get('stargate_reclamos_query_range') ? : 50;
  134.   $query = \Drupal::entityQuery('node');
  135.   $query->condition('status', 1);
  136.   $query->condition('type', 'reclamo');
  137.   $query->condition('field_state', 'new');
  138.   $group = $query->orConditionGroup()
  139.     ->condition('field_has_trial_history', FALSE)
  140.     ->condition('field_has_risk_report', FALSE);
  141.   $query->condition($group);
  142.   $query->range(0, $range);
  143.   $entity_ids = $query->execute();
  144.   return $entity_ids;
  145. }
  146.  
  147. function _stargate_reclamos_populate_fields($id) {
  148.  
  149.   $node = Node::load($id);
  150.   $cuil = $node->get('field_cuil')->value;
  151.  
  152.   $message = "Haciendo llamadas a los WS para cuil: $cuil (nid: $id)";
  153.   \Drupal::logger('stargate_reclamos')->notice($message);
  154.  
  155.   if (empty($cuil)) {
  156.     $message = "El reclamo con nid: $id no tiene seteado CUIL!";
  157.     \Drupal::logger('stargate_reclamos')->warning($message);
  158.     return;
  159.   }
  160.  
  161.   $success = TRUE;
  162.  
  163.   //trial_history
  164.   $user = \Drupal::state()->get('reclamo_ws_user') ?: 'abiuso@experta.com.ar';
  165.   $pass = \Drupal::state()->get('reclamo_ws_pass') ?: 'ga12345678';
  166.  
  167.   $default_url = 'http://186.182.220.51/ws/wsjuicios.asmx/ObtenerJuiciosPorEmpleado?usuario=%s&constraseña=%s&cuil=%s';
  168.   $url = \Drupal::state()->get('reclamo_ws_url') ?: $default_url;
  169.   //@TODO: how solve encoding : Windows-1252
  170.   $request_url = sprintf($url, $user, $pass, $cuil);
  171.   $request_url = str_replace('ñ', '%F1', $request_url);
  172.   $param = ['Accept' => 'application/xml'];
  173.   $output = _stargate_reclamos_call_ws('GET', $request_url, $param);
  174.   if ($output != '') {
  175.     // https://stackoverflow.com/questions/8830599/php-convert-xml-to-json
  176.     $xml = simplexml_load_string($output);
  177.     $json = json_encode($xml);
  178.  
  179.     $node->set('field_trial_history', $output);
  180.     $node->set('field_has_trial_history', TRUE);
  181.   }
  182.   else {
  183.     \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Juicios!');
  184.     $success = FALSE;
  185.   }
  186.  
  187.   //risk_report
  188.   $default_url_ws_risk = 'http://api.fidelitas.com.ar/v1/ic/json';
  189.   $url = \Drupal::state()->get('reclamo_risk_ws_url') ?: $default_url_ws_risk;
  190.   $apikey = \Drupal::state()->get('reclamo_apikey') ?: '928BFC592F76DB92';
  191.   $param = [
  192.     'form_params' => [
  193.         'apikey' => $apikey,
  194.         'cuit' => $cuil,
  195.       ]
  196.   ];
  197.   $output = _stargate_reclamos_call_ws('POST', $url, $param);
  198.   if ($output != '') {
  199.     $node->set('field_risk_report', $output);
  200.     $node->set('field_has_risk_report', TRUE);
  201.   }
  202.   else {
  203.     \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Riesgos!');
  204.     $success = FALSE;
  205.   }
  206.  
  207.   if ($success) {
  208.     $node->set('field_state', 'progress');
  209.   }
  210.  
  211.   $node->save();
  212.  
  213. }
  214.  
  215. function _stargate_reclamos_call_ws($method, $url, $param) {
  216.   $output = '';
  217.   $client = \Drupal::httpClient();
  218.   try {
  219.     $response = $client->request($method, $url, $param);
  220.     $code = $response->getStatusCode();
  221.     if ($code == 200) { //OK
  222.       $output = $response->getBody();
  223.     }
  224.   }
  225.   catch (GuzzleHttp\Exception\ClientException $e) {
  226.     \Drupal::logger('stargate_reclamos')->error($e->getMessage());
  227.   }
  228.   return $output;
  229. }
  230.  
  231.  
  232. /**
  233.  *  implements hook_node_presave(\Drupal\Core\Entity\EntityInterface $node)
  234.  */
  235. function stargate_reclamos_node_presave(\Drupal\Core\Entity\EntityInterface $node) {
  236.  
  237.   if ( isset($node->field_srt->value) && !empty($node->field_srt->value) ) {
  238.     $node->field_has_srt = true;
  239.   } else {
  240.     $node->field_has_srt = false;
  241.   }
  242.  
  243.   if ( isset($node->field_social_network_analysis->value) && !empty($node->field_social_network_analysis->value) ) {
  244.     $node->field_has_social_network = true;
  245.   } else {
  246.     $node->field_has_social_network = false;
  247.   }
  248.  
  249.   // Antes de guardar o actualizar un nodo reclamo, Setear fechas.
  250.   if ($node->bundle() == 'reclamo') {
  251.     _actualizar_fechas_reclamo($node);
  252.   }
  253. }
  254.  
  255.  
  256. function _stargate_reclamos_get_frontpage_url() {
  257.   $rol = _get_current_rol();
  258.  
  259.     $url = '/reclamos';
  260.  
  261.     if ($rol == 'contador') {
  262.       $url = '/admin/content/facturacion';
  263.     }
  264.     elseif ($rol == 'administrator' or $rol == 'analista') {
  265.       $url = '/admin/content/reclamos';
  266.     }
  267.  
  268.   return $url;
  269. }
  270.  
  271.  
  272. /**
  273.  * Implements hook_node_access().
  274.  */
  275. function stargate_reclamos_node_access(NodeInterface $node, $op, AccountInterface $account) {
  276.   $rol = _get_current_rol();
  277.   $estado_facturacion = $node->get('field_estado_facturacion')->getString();
  278.  
  279.   switch ($op) {
  280.     case 'update':
  281.       if ($node->bundle() == 'reclamo') {
  282.         if ($rol =='contador' || $rol == 'usuario_art' ||
  283.            ($rol == 'analista' && $estado_facturacion != ID_ESTADO_NO_FACTURABLE)) {
  284.           // Permisos denegados para editar nodos reclamo
  285.           return AccessResult::forbidden()->cachePerPermissions();
  286.         }
  287.         else {
  288.           return AccessResult::allowed();
  289.         }
  290.       }
  291.     default:
  292.       // No opinion.
  293.       return AccessResult::neutral();
  294.   }
  295. }
  296.  
  297. /**
  298.  * Get current rol.
  299.  */
  300. function _get_current_rol() {
  301.   $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  302.   $roles = $user->getRoles(TRUE);
  303.   return $roles[0];
  304. }
  305.  
  306. // Setear fechas reclamo
  307. function _actualizar_fechas_reclamo($node) {
  308.   $fecha_hoy = \Drupal::time()->getCurrentTime();
  309.   $fecha_hoy = date('Y-m-d\TH:i:s', $fecha_hoy);
  310.  
  311.   // Obtener solo los estados que cambiaron
  312.   $fields_changed = _get_estados_cambiados($node);
  313.  
  314.   // Saber el/los estados que fueron cambiados
  315.   $hay_cambio_estado = array_key_exists('field_state', $fields_changed);
  316.   $hay_cambio_estado_facturacion = array_key_exists('field_estado_facturacion', $fields_changed);
  317.  
  318.   // Si cambió algun estado
  319.   if (!empty($fields_changed)) {
  320.     $message_estado = "";
  321.     $message_estado_facturacion = "";
  322.     // Si hay cambio de estado
  323.     if ($hay_cambio_estado) {
  324.       $cambio_estado = $fields_changed['field_state']['new_value'][0]['value'];
  325.       $ya_terminado = $node->field_fecha_estado_activo->value;
  326.       $reclamo_estado_name = _estado_reclamo($cambio_estado);
  327.       if ($cambio_estado == ID_ESTADO_TERMINADO && !$ya_terminado) {
  328.         // Actualizar a estado Terminado, establecer fecha y marcar como Terminado
  329.         $node->set('field_date_finished', $fecha_hoy);
  330.         $node->set('field_fecha_estado_activo', TRUE);
  331.       }
  332.       $message_estado = "Nuevo estado a: ". $reclamo_estado_name. '. ';
  333.     }
  334.     // Si hay cambio de estado de facturacion
  335.     if ($hay_cambio_estado_facturacion) {
  336.       $cambio_estado_facturacion = $fields_changed['field_estado_facturacion']['new_value'][0]['value'];
  337.       $ya_facturado = $node->field_fecha_facturado_activo->value;
  338.       $reclamo_facturado_name = _estado_facturacion($cambio_estado_facturacion);
  339.       if ($cambio_estado_facturacion == ID_ESTADO_FACTURADO && !$ya_facturado) {
  340.         // Actualizar a estado Facturado, establecer fecha y marcar como Facturado
  341.         $node->set('field_date_billed', $fecha_hoy);
  342.         $node->set('field_fecha_facturado_activo', TRUE);
  343.       }
  344.       $message_estado_facturacion = "Nuevo estado de facturacion a: ". $reclamo_facturado_name.'. ';
  345.     }
  346.  
  347.     _establecer_revision_estados($node, $message_estado, $message_estado_facturacion);
  348.     $message_log = "Cambio en nodo reclamo de id: " . $node->id().'. '.$message_estado.$message_estado_facturacion;
  349.  
  350.     _stargate_reclamos_log('notice', $message_log);
  351.   }
  352. }
  353.  
  354. // Obtener solo los estados que cambiaron al guardar un reclamo
  355. function _get_estados_cambiados($node) {
  356.   $nodeSubject = new NodeSubject($node, 'default_field_comparator');
  357.   $nodeSubject->attach(new ObservarCambioNode());
  358.   $nodeSubject->notify();
  359.   return $nodeSubject->getChangedFields();
  360. }
  361.  
  362. // Obtener nombre real del estado del reclamo
  363. function _estado_reclamo($cambio_estado) {
  364.   $estado_reclamo = [
  365.     'new'      => RECLAMO_NUEVO,
  366.     'progress' => RECLAMO_EN_PROGRESO,
  367.     'finished' => RECLAMO_TERMINADO,
  368.   ];
  369.   return $estado_reclamo[$cambio_estado];
  370. }
  371.  
  372. // Obtener nombre real del estado de facturacion
  373. function _estado_facturacion($reclamo_facturado) {
  374.   $estado_facturacion = [
  375.     '1' => RECLAMO_NO_FACTURABLE,
  376.     '2' => RECLAMO_BLOQUEADO_FACTURACION,
  377.     '3' => RECLAMO_FACTURADO,
  378.   ];
  379.   return $estado_facturacion[$reclamo_facturado];
  380.  }
  381.  
  382. // Crear revision al cambiar de estados
  383. function _establecer_revision_estados($node, $message_estado, $message_estado_facturacion) {
  384.   $current_user = \Drupal::currentUser();
  385.   $node->setNewRevision(TRUE);
  386.   $node->revision_log = "Nueva revisión para el nodo de id: " . $node->id().'. ' .$message_estado.$message_estado_facturacion;
  387.   $node->setRevisionCreationTime(REQUEST_TIME);
  388.   $node->setRevisionUserId($current_user->id());
  389. }
  390.  
  391. /**
  392.  * Implements hook_form_alter().
  393.  */
  394. function stargate_reclamos_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  395.   switch ($form_id) {
  396.     case 'node_reclamo_edit_form':
  397.       $rol = _get_current_rol();
  398.       $node = $form_state->getFormObject()->getEntity();
  399.       if ($rol != 'administrator') {
  400.         // Bloquear fechas para estados, en nodo reclamo.
  401.         $form['field_date_finished']['#disabled'] = TRUE;
  402.         $form['field_date_billed']['#disabled'] = TRUE;
  403.       }
  404.   }
  405. }
  406.  
  407. /**
  408.  * Cron for process "Block for billing".
  409.  */
  410. function _stargate_reclamos_block_for_billing_cron_process() {
  411.   $current_time = \Drupal::time()->getRequestTime();
  412.   $should_run = _stargate_reclamos_should_run_block_for_billing($current_time);
  413.   if ($should_run) {
  414.     \Drupal::state()->set('stargate_reclamos.last_execution', $current_time);
  415.     _stargate_reclamos_log('notice', 'Verificación de reclamos bloqueables para facturación iniciado.');
  416.     _stargate_reclamos_block_for_billing_process();
  417.     _stargate_reclamos_log('notice', 'Verificación de reclamos bloqueables para facturación finalizado.');
  418.   }
  419. }
  420.  
  421. /**
  422.  * Returns TRUE if the "Block for Billing" process have to run.
  423.  */
  424. function _stargate_reclamos_should_run_block_for_billing($time) {
  425.   $scheduled_time = '23:59';
  426.  
  427.   // Get the last execution of cron for this process.
  428.   $cron_last_exec = \Drupal::state()->get('stargate_reclamos.last_execution');
  429.   $last_exec_timestamp = $cron_last_exec ? $cron_last_exec : 0;
  430.   $last_exec_date = \DateTime::createFromFormat('U', $last_exec_timestamp);
  431.  
  432.   // Create a new Date that has the date equal to the last run of cron,
  433.   // and the time equal to the expected hour on which the cron have to run.
  434.   $scheduled_date = \DateTime::createFromFormat('U', $last_exec_timestamp);
  435.   $scheduled_date->setTime(...explode(':', $scheduled_time));
  436.  
  437.   // This process have to run once per day, then if the process already ran, return false.
  438.   if ($scheduled_date->getTimestamp() < $last_exec_date->getTimestamp()) {
  439.     return FALSE;
  440.   }
  441.  
  442.   // In another case, return True or False depending on whether the scheduled date passed or not.
  443.   return ($scheduled_date->getTimestamp() <= $time);
  444. }
  445.  
  446. /**
  447.  * Process: set nodes of type Reclamo as blocked for billing.
  448.  */
  449. function _stargate_reclamos_block_for_billing_process() {
  450.   // Get all nodes of type Reclamo.
  451.   $query = \Drupal::entityQuery('node');
  452.   $query->condition('type', 'reclamo');
  453.   $nids = $query->execute();
  454.  
  455.   $reclamos = entity_load_multiple('node', $nids);
  456.   foreach ($reclamos as $reclamo) {
  457.     if (stargate_reclamos_lockable_for_billing($reclamo)) {
  458.       $reclamo->set('field_estado_facturacion', ID_ESTADO_BLOQUEADO_PARA_FACTURACION);
  459.       $reclamo->save();
  460.       _stargate_reclamos_log('notice', 'Reclamo ' . $reclamo->id() . ' bloqueado para facturación.');
  461.     }
  462.   }
  463. }
  464.  
  465. /**
  466.  * Returns TRUE if the node can be lockable for billing.
  467.  */
  468. function stargate_reclamos_lockable_for_billing($reclamo) {
  469.   if ($reclamo) {
  470.     // Check State.
  471.     $state = $reclamo->get('field_state')->getString();
  472.     $finished = ($state == ID_ESTADO_TERMINADO);
  473.  
  474.     // Check the finished date.
  475.     $current_time = \Drupal::time()->getRequestTime();
  476.     $field_finished_date = $reclamo->get('field_date_finished')->getString();
  477.     $finished_date = new DrupalDateTime($field_finished_date);
  478.     $passed_date = ($finished_date->format('U') <= $current_time);
  479.  
  480.     // Check for billing state.
  481.     $billing_state = $reclamo->get('field_estado_facturacion')->getString();
  482.     $not_billable = ($billing_state == ID_ESTADO_NO_FACTURABLE);
  483.  
  484.     return ($finished && $passed_date && $not_billable);
  485.   }
  486.   return FALSE;
  487. }
  488.  
  489. function _stargate_reclamos_log($level, $message) {
  490.   switch ($level) {
  491.     case 'error':
  492.       \Drupal::logger('stargate_reclamos')->error($message);
  493.       break;
  494.     case 'notice':
  495.       \Drupal::logger('stargate_reclamos')->notice($message);
  496.       break;
  497.     case 'debug':
  498.       \Drupal::logger('stargate_reclamos')->debug($message);
  499.       break;
  500.   }
  501. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement