Advertisement
Guest User

stargate.module

a guest
Dec 28th, 2017
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.16 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.  
  14. use Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList;
  15.  
  16. const RECLAMO_NO_FACTURABLE = 'No facturable';
  17. const RECLAMO_BLOQUEADO_FACTURACION = 'Bloqueado para facturación';
  18. const RECLAMO_FACTURADO = 'Facturado';
  19.  
  20. /**
  21.  * Implements hook_theme().
  22.  */
  23. function stargate_reclamos_theme($existing, $type, $theme, $path) {
  24.   return [
  25.     'node__reclamo' => [
  26.       'template' => 'node--reclamo',
  27.       'base hook' => 'node',
  28.     ],
  29.     'stargate_risk_report' => [
  30.       'template' => 'stargate_risk_report',
  31.       'variables' => ['report' => [], 'content' => [], 'node' => []],
  32.     ],
  33.   ];
  34. }
  35.  
  36. function stargate_reclamos_preprocess_node(&$vars) {
  37.   //Add vars
  38.   $node = $vars['node'];
  39.  
  40.   // Risk reort
  41.   $risk_report  = json_decode($node->field_risk_report->value);
  42.  
  43.   // Legal report
  44.   $legal_report = ['Juicios' => []];
  45.   if ($node->field_has_trial_history->value) {
  46.       libxml_use_internal_errors(TRUE);
  47.       $xml = simplexml_load_string(trim($node->field_trial_history->value));
  48.       if ($xml === FALSE) {
  49.         $message = "Falló el parseo del XML de Juicios para el nodo [" . $node->ID() . "]\n";
  50.         foreach(libxml_get_errors() as $error) {
  51.           $message .= "\n" . $error->message;
  52.         }
  53.         \Drupal::logger('stargate_reclamos')->error($message);
  54.       }
  55.  
  56.       $legal_report = json_decode(json_encode($xml));
  57.  
  58.       if (!is_array($legal_report->Juicio)) {
  59.         $legal_report->Juicio = array($legal_report->Juicio);
  60.       }
  61.   }
  62.  
  63.   // Clean up
  64.   $index = 0;;
  65.   foreach($legal_report->Juicio as $trial) {
  66.     foreach(array_keys((array) $trial) as $key) {
  67.       if (is_object($trial->{$key})) {
  68.         if (count((array) $trial->{$key}) == 0) {
  69.           $legal_report->Juicio[$index]->{$key} = '';
  70.         }
  71.       }
  72.     }
  73.     $index++;
  74.   }
  75.  
  76.   // Accident report
  77.   $accident_report = ['#theme' => 'markup', '#markup' => $node->field_has_srt->value ? $node->field_srt->value : ''];
  78.  
  79.   // Render risk report
  80.   $report_render_array = [
  81.     '#theme' => 'stargate_risk_report',
  82.     '#report' => [
  83.       'risk'  => $risk_report,
  84.       'legal' => $legal_report,
  85.       'accident' => $accident_report
  86.     ],
  87.     '#content' => $vars['content'],
  88.     '#node' => $vars['node']
  89.   ];
  90.  
  91.   $vars['risk_report'] = Drupal::service('renderer')->render($report_render_array);
  92.  
  93.   // decide which homepage the user must go back to
  94.   $vars['frontpage_url'] = _stargate_reclamos_get_frontpage_url();
  95. }
  96.  
  97.  
  98. /**
  99.  * Implements hook_cron().
  100.  */
  101. function stargate_reclamos_cron() {
  102.   $interval = \Drupal::state()->get('stargate_reclamos_cron_interval') ? : 30; // 30 seg
  103.  
  104.   $next_execution = \Drupal::state()->get('stargate_reclamos.next_execution');
  105.   $next_execution = !empty($next_execution) ? $next_execution : 0;
  106.   if (REQUEST_TIME >= $next_execution) {
  107.     $nodes = _stargate_reclamos_get_nodes();
  108.     \Drupal::logger('stargate_reclamos')->notice('Procesando reclamos ...');
  109.     foreach ($nodes as $key => $id) {
  110.       _stargate_reclamos_populate_fields($id);
  111.     }
  112.     \Drupal::state()->set('stargate_reclamos.next_execution', REQUEST_TIME + $interval);
  113.   }
  114.   else {
  115.     \Drupal::logger('stargate_reclamos')->notice('Salteando reclamos.');
  116.   }
  117.  
  118.  
  119.  
  120. /*
  121.   $query = \Drupal::entityQuery('node');
  122.   $query->condition('status', 1);
  123.   $query->condition('type', 'reclamo');
  124.   $nids = $query->execute();
  125.   $nodes = entity_load_multiple('node', array_keys($nids));
  126.  
  127.  
  128.   foreach ($nodes as $reclamo) {
  129.     $reclamo->set('field_estado_facturacion', '2');
  130.   }*/
  131.  
  132.   $ids = \Drupal::entityQuery('node')->condition('type','reclamo')->execute();
  133.   $reclamos = Node::loadMultiple($ids);
  134.  
  135.   foreach ($reclamos as $reclamo) {
  136.      $reclamo->set('field_estado_facturacion', '2');
  137.   }
  138.  
  139. }
  140.  
  141. function _stargate_reclamos_get_nodes() {
  142.   $range = \Drupal::state()->get('stargate_reclamos_query_range') ? : 50;
  143.   $query = \Drupal::entityQuery('node');
  144.   $query->condition('status', 1);
  145.   $query->condition('type', 'reclamo');
  146.   $query->condition('field_state', 'new');
  147.   $group = $query->orConditionGroup()
  148.     ->condition('field_has_trial_history', FALSE)
  149.     ->condition('field_has_risk_report', FALSE);
  150.   $query->condition($group);
  151.   $query->range(0, $range);
  152.   $entity_ids = $query->execute();
  153.   return $entity_ids;
  154. }
  155.  
  156. function _stargate_reclamos_populate_fields($id) {
  157.  
  158.   $node = Node::load($id);
  159.   $cuil = $node->get('field_cuil')->value;
  160.  
  161.   $message = "Haciendo llamadas a los WS para cuil: $cuil (nid: $id)";
  162.   \Drupal::logger('stargate_reclamos')->notice($message);
  163.  
  164.   if (empty($cuil)) {
  165.     $message = "El reclamo con nid: $id no tiene seteado CUIL!";
  166.     \Drupal::logger('stargate_reclamos')->warning($message);
  167.     return;
  168.   }
  169.  
  170.   $success = TRUE;
  171.  
  172.   //trial_history
  173.   $user = \Drupal::state()->get('reclamo_ws_user') ?: 'abiuso@experta.com.ar';
  174.   $pass = \Drupal::state()->get('reclamo_ws_pass') ?: 'ga12345678';
  175.  
  176.   $default_url = 'http://186.182.220.51/ws/wsjuicios.asmx/ObtenerJuiciosPorEmpleado?usuario=%s&constraseña=%s&cuil=%s';
  177.   $url = \Drupal::state()->get('reclamo_ws_url') ?: $default_url;
  178.   //@TODO: how solve encoding : Windows-1252
  179.   $request_url = sprintf($url, $user, $pass, $cuil);
  180.   $request_url = str_replace('ñ', '%F1', $request_url);
  181.   $param = ['Accept' => 'application/xml'];
  182.   $output = _stargate_reclamos_call_ws('GET', $request_url, $param);
  183.   if ($output != '') {
  184.     // https://stackoverflow.com/questions/8830599/php-convert-xml-to-json
  185.     $xml = simplexml_load_string($output);
  186.     $json = json_encode($xml);
  187.  
  188.     $node->set('field_trial_history', $output);
  189.     $node->set('field_has_trial_history', TRUE);
  190.   }
  191.   else {
  192.     \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Juicios!');
  193.     $success = FALSE;
  194.   }
  195.  
  196.   //risk_report
  197.   $default_url_ws_risk = 'http://api.fidelitas.com.ar/v1/ic/json';
  198.   $url = \Drupal::state()->get('reclamo_risk_ws_url') ?: $default_url_ws_risk;
  199.   $apikey = \Drupal::state()->get('reclamo_apikey') ?: '928BFC592F76DB92';
  200.   $param = [
  201.     'form_params' => [
  202.         'apikey' => $apikey,
  203.         'cuit' => $cuil,
  204.       ]
  205.   ];
  206.   $output = _stargate_reclamos_call_ws('POST', $url, $param);
  207.   if ($output != '') {
  208.     $node->set('field_risk_report', $output);
  209.     $node->set('field_has_risk_report', TRUE);
  210.   }
  211.   else {
  212.     \Drupal::logger('stargate_reclamos')->error('Fallo llamada a WS de Riesgos!');
  213.     $success = FALSE;
  214.   }
  215.  
  216.   if ($success) {
  217.     $node->set('field_state', 'progress');
  218.   }
  219.  
  220.   $node->save();
  221.  
  222. }
  223.  
  224. function _stargate_reclamos_call_ws($method, $url, $param) {
  225.   $output = '';
  226.   $client = \Drupal::httpClient();
  227.   try {
  228.     $response = $client->request($method, $url, $param);
  229.     $code = $response->getStatusCode();
  230.     if ($code == 200) { //OK
  231.       $output = $response->getBody();
  232.     }
  233.   }
  234.   catch (GuzzleHttp\Exception\ClientException $e) {
  235.     \Drupal::logger('stargate_reclamos')->error($e->getMessage());
  236.   }
  237.   return $output;
  238. }
  239.  
  240.  
  241. /**
  242.  *  implements hook_node_presave(\Drupal\Core\Entity\EntityInterface $node)
  243.  */
  244. function stargate_reclamos_node_presave(\Drupal\Core\Entity\EntityInterface $node) {
  245.  
  246.   if ( isset($node->field_srt->value) && !empty($node->field_srt->value) ) {
  247.     $node->field_has_srt = true;
  248.   } else {
  249.     $node->field_has_srt = false;
  250.   }
  251.  
  252.   if ( isset($node->field_social_network_analysis->value) && !empty($node->field_social_network_analysis->value) ) {
  253.     $node->field_has_social_network = true;
  254.   } else {
  255.     $node->field_has_social_network = false;
  256.   }
  257.  
  258.   // Antes de guardar o actualizar un nodo reclamo, bloquear fechas.
  259.   if ($node->bundle() == 'reclamo') {
  260.     _actualizar_fechas_reclamo($node);
  261.   }
  262. }
  263.  
  264.  
  265. function _stargate_reclamos_get_frontpage_url() {
  266.   $rol = _get_current_rol();
  267.  
  268.     $url = '/reclamos';
  269.  
  270.     if ($rol == 'contador') {
  271.       $url = '/admin/content/facturacion';
  272.     }
  273.     elseif ($rol == 'administrator' or $rol == 'analista') {
  274.       $url = '/admin/content/reclamos';
  275.     }
  276.  
  277.   return $url;
  278. }
  279.  
  280.  
  281. /**
  282.  * Implements hook_node_access().
  283.  */
  284. function stargate_reclamos_node_access(NodeInterface $node, $op, AccountInterface $account) {
  285.   $c_type = $node->bundle();
  286.   $rol = _get_current_rol();
  287.   $f_value = $node->field_estado_facturacion->value;
  288.  
  289.   switch ($op) {
  290.     case 'update':
  291.       if ($c_type == 'reclamo') {
  292.         !($f_value == '2' || $f_value == '3') ? $node->set('field_estado_facturacion', '1') : $f_value = $f_value;
  293.         if ($rol =='contador' || $rol == 'usuario_art' || ($rol == 'analista'
  294.           && $f_value != '1')) {
  295.           // Permisos denegados para editar nodos reclamo
  296.           return AccessResult::forbidden()->cachePerPermissions();
  297.         }
  298.         else {
  299.           return AccessResult::allowed();
  300.         }
  301.       }
  302.     default:
  303.       // No opinion.
  304.       return AccessResult::neutral();
  305.   }
  306. }
  307.  
  308.  
  309. /**
  310.  * Get current rol.
  311.  */
  312. function _get_current_rol() {
  313.   $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  314.   $roles = $user->getRoles(TRUE);
  315.   return $roles[0];
  316. }
  317.  
  318. // Obtener nombre del estado de facturacion
  319. function _estado_facturacion($reclamo_facturado) {
  320.   $estado_facturacion = [
  321.     '1' => RECLAMO_NO_FACTURABLE,
  322.     '2' => RECLAMO_BLOQUEADO_FACTURACION,
  323.     '3' => RECLAMO_FACTURADO,
  324.   ];
  325.   return $estado_facturacion[$reclamo_facturado];
  326. }
  327.  
  328. // Setear fechas reclamo
  329. function _actualizar_fechas_reclamo($node) {
  330.  // Estado del Reclamo
  331.  $reclamo_terminado = $node->field_state->value;
  332.  $fecha_terminado = $node->field_date_finished->value;
  333.  
  334.  // Estado de Facturacion
  335.  $reclamo_facturado = $node->field_estado_facturacion->value;
  336.  $fecha_facturado = $node->field_date_billed->value;
  337.  $reclamo_facturado_name = _estado_facturacion($reclamo_facturado);
  338.  
  339.  
  340.  $current_user = \Drupal::currentUser();
  341.  
  342.  //************* Setear Fecha Estado Reclamo
  343.  
  344.  // Si hay una fecha definida sin estar marcado como Terminado el reclamo
  345.  if (isset($fecha_terminado) && $reclamo_terminado != 'finished') {
  346.       // Si el campo fecha esta bloqueado
  347.       // Significa que esta en estado Terminado, y se quiere volver a reiniciar/cambiar.
  348.       if (!$node->field_fecha_estado_activo->value) {
  349.         // Si el campo fecha esta desactivado/bloqueado
  350.         // Significa que anteriormente se puso a estado Terminado
  351.         // y se quiere volver a cambiar de estado.
  352.         $node->field_fecha_estado_activo = TRUE; // Volver a poner activo.
  353.         $node->set('field_date_finished', NULL); // Reiniciar la fecha a ninguna.
  354.  
  355.         \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado a " . $reclamo_terminado . " en el nodo de id " . $node->id(). '. Reseteo del campo fecha TERMINADO');
  356.       }
  357.       // Si el reclamo esta marcado como Terminado y tiene fecha
  358.   } elseif ($reclamo_terminado == 'finished' && isset($fecha_terminado)){
  359.       // Bool para indicar desabilitar/bloquear el campo fecha
  360.       $node->field_fecha_estado_activo = FALSE;
  361.  
  362.       \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado a " . $reclamo_terminado . " en el nodo de id " . $node->id(). '. Bloqueo del campo fecha TERMINADO');
  363.   } else {
  364.     \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado a " . $reclamo_terminado . " en el nodo de id " . $node->id());
  365.   }
  366.  
  367.  //************* Setear Fecha Estado Facturacion
  368.  
  369.   // Si hay una fecha definida sin estar marcado como Facturado el reclamo
  370.  if (isset($fecha_facturado) && $reclamo_facturado != '3') {
  371.       // Si el campo fecha esta bloqueado
  372.       // Significa que esta en estado Facturado, y se quiere volver a reiniciar/cambiar.
  373.       if (!$node->field_fecha_facturado_activo->value) {
  374.         // Si el campo fecha esta desactivado/bloqueado
  375.         // Significa que anteriormente se puso a estado Facturado
  376.         // y se quiere volver a cambiar de estado.
  377.         $node->field_fecha_facturado_activo = TRUE; // Volver a poner activo.
  378.         $node->set('field_date_billed', NULL); // Reiniciar la fecha a ninguna.
  379.  
  380.         \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado de facturacion a " . $reclamo_facturado_name . " en el nodo de id " . $node->id(). '. Reseteo del campo fecha FACTURADO');
  381.       }
  382.       // Si el reclamo esta marcado como Facturado y tiene fecha
  383.   } elseif ($reclamo_facturado == '3' && isset($fecha_facturado)){
  384.       // Bool para indicar desabilitar/bloquear el campo fecha
  385.       $node->field_fecha_facturado_activo = FALSE;
  386.  
  387.       \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado de facturacion a " . $reclamo_facturado_name . " en el nodo de id " . $node->id(). '. Bloqueo del campo fecha FACTURADO');
  388.   } else {
  389.     \Drupal::logger('Stargate Reclamo')->notice("Cambio de estado de facturacion a " . $reclamo_facturado_name . " en el nodo de id " . $node->id());
  390.   }
  391.  
  392.   $node->setNewRevision(TRUE);
  393.   $node->revision_log = 'Nueva revisión para el nodo ' . $node->id() . '. Nuevo estado a: ' . $reclamo_terminado. ' y '.$reclamo_facturado_name;
  394.   $node->setRevisionCreationTime(REQUEST_TIME);
  395.   $node->setRevisionUserId($current_user->id());
  396. }
  397.  
  398.  
  399. /**
  400.  * Implements hook_form_alter().
  401.  */
  402. function stargate_reclamos_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  403.   switch ($form_id) {
  404.     case 'node_reclamo_edit_form':
  405.  
  406.       $rol = _get_current_rol();
  407.  
  408.       $form['#validate'][] = 'stargate_reclamos_node_form_validate';
  409.  
  410.       $node = $form_state->getFormObject()->getEntity();
  411.       // Si es FALSE significa que el reclamo esta en estado Terminado.
  412.       if (!$node->field_fecha_estado_activo->value && $rol != 'administrator') {
  413.         // Bloquer campo fecha
  414.         $form['field_date_finished']['#disabled'] = TRUE;
  415.       }
  416.       // Si es FALSE significa que el reclamo esta en estado Facturado.
  417.       if (!$node->field_fecha_facturado_activo->value && $rol != 'administrator') {
  418.         // Bloquer campo fecha
  419.         $form['field_date_billed']['#disabled'] = TRUE;
  420.         break;
  421.       }
  422.   }
  423. }
  424.  
  425. // Validar campos fechas de estados, antes de guardar un reclamo
  426. function stargate_reclamos_node_form_validate($form, &$form_state) {
  427.   // Obtener datos de campos
  428.   $node = $form_state->getFormObject()->getEntity();
  429.   $values = $form_state->getValues();
  430.  
  431.   // Estado del Reclamo
  432.   $reclamo_terminado = $values['field_state'][0]['value'];
  433.   $fecha_terminado = $values['field_date_finished'][0]['value'];
  434.  
  435.   // Estado de Facturacion
  436.   $reclamo_facturado = $values['field_estado_facturacion'][0]['value'];
  437.   $fecha_facturado = $values['field_date_billed'][0]['value'];
  438.  
  439.  
  440.   //************* Validar Estado Reclamo
  441.  
  442.   // Si el reclamo se marca como Terminado, pero no tiene fecha definida
  443.   if ($reclamo_terminado == 'finished' && !isset($fecha_terminado)) {
  444.     $form_state->setErrorByName('field_date_finished', t('Si el reclamo pasa a estado Terminado, debe definir la fecha.'));
  445.  
  446.     // Si hay una fecha definida sin estar marcado como Terminado el reclamo
  447.   } elseif (isset($fecha_terminado) && $reclamo_terminado != 'finished') {
  448.  
  449.       // Si el campo fecha esta habilitado/activo
  450.       // Significa que no se ha pasado a estado Terminado aun
  451.       if ($node->field_fecha_estado_activo->value) {
  452.         $form_state->setErrorByName('field_date_finished', t('Si el reclamo no esta en estado Terminado, no se puede definir fecha.'));
  453.       }
  454.     }
  455.  
  456.   //************* Validar Estado Facturacion
  457.  
  458.      // Si el reclamo se marca como Facturado, pero no tiene fecha definida
  459.   if ($reclamo_facturado == '3' && !isset($fecha_facturado)) {
  460.     $form_state->setErrorByName('field_date_billed', t('Si el reclamo pasa a estado Facturado, debe definir la fecha.'));
  461.  
  462.     // Si hay una fecha definida sin estar marcado como Facturado el reclamo
  463.   } elseif (isset($fecha_facturado) && $reclamo_facturado != '3') {
  464.  
  465.       // Si el campo fecha esta habilitado/activo
  466.       // Significa que no se ha pasado a estado Facturado aun
  467.       if ($node->field_fecha_facturado_activo->value) {
  468.         $form_state->setErrorByName('field_date_billed', t('Si el reclamo no esta en estado Facturado, no se puede definir fecha.'));
  469.       }
  470.     }
  471. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement