source: sipes/0.3-modules/ente_planificador_importar/ente_planificador_importar.module @ c71dab6

version-3.0
Last change on this file since c71dab6 was c71dab6, checked in by Sipes Apn <root@…>, 7 años ago

se corrigio lo relacionado al cambio de estado

  • Propiedad mode establecida a 100644
File size: 28.7 KB
Línea 
1<?php
2
3  /**
4  * Modulo para importar entes y terminos
5  * Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana
6  * @file ente_planificador_importar.module
7  * Drupal part Module to code ente planificador module
8  * Copyright 2011 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  * @author Cenditel Merida - Msc. Juan Vizcarrondo
25  * @date 2016-07-07 // (a&#241;o-mes-dia)
26  * @date 2017-03-22 // (a&#241;o-mes-dia)
27  * @version 0.2 // (0.1)
28  *
29  */
30
31/*
32 * Implementation of hook_perm
33 */
34function ente_planificador_importar_perm() {
35  return array(
36    'access import entes planificadores',
37    'import entes planificadores',
38    'import term',
39    'update proyecto state',
40  );
41}
42
43/*
44 * Implementation of hook_menu()
45 */
46function ente_planificador_importar_menu() {
47  $items = array();
48  $items['ente_planificador_importar'] = array(
49    'title' => 'Importar Entes Planificadores',
50    'page callback' => '_ente_planificador_importar_listar',
51    'access arguments' => array('access import entes planificadores'),
52    'type' => MENU_NORMAL_ITEM,
53  );
54  $items['ente_planificador_importar/entes'] = array(
55    'title' => 'Importar Entes Planificadores',
56    'page callback' => 'drupal_get_form',
57    'page arguments' => array('ente_planificador_importar_form'),
58    'access arguments' => array('import entes planificadores'),
59    'type' => MENU_CALLBACK,
60  );
61  $items['ente_planificador_importar/terminos'] = array(
62    'title' => 'Importar Terminos',
63    'page callback' => 'drupal_get_form',
64    'page arguments' => array('ente_planificador_importar_terminos_form'),
65    'access arguments' => array('import term'),
66    'type' => MENU_CALLBACK,
67  );
68  $items['ente_planificador_importar/estadoproyecto'] = array(
69    'title' => 'Modificar estado de poyectos',
70    'page callback' => 'drupal_get_form',
71    'page arguments' => array('ente_planificador_importar_aprobar_proyectos_form'),
72    'access arguments' => array('update proyecto state'),
73    'type' => MENU_CALLBACK,
74  );
75
76  return $items;
77}
78
79/*
80 * Implementation of _ente_planificador_importar_listar()
81 * Muestra las opciones de importacion disponibles
82 */
83function _ente_planificador_importar_listar() {
84  $links = array();
85  drupal_alter('ente_planificador_importar_links', $links);
86  return theme('item_list', $links);
87}
88
89/*
90 * Implementation of hook_ente_planificador_importar_links_alter()
91 */
92function ente_planificador_ente_planificador_importar_links_alter(&$links) {
93  if (user_access('import entes planificadores')) {
94    $links['entes'] = array(
95      'data' => l(t('Importar Entes Planificadores'), 'ente_planificador_importar/entes'),
96      'class' => 'ente-planificador-importar-entes',
97    );
98  }
99  if (user_access('import term')) {
100    $links['term'] = array(
101      'data' => l(t('Importar terminos'), 'ente_planificador_importar/terminos'),
102      'class' => 'ente-planificador-importar-term',
103    );
104  }
105  if (user_access('update proyecto state')) {
106    $links['estadoproyecto'] = array(
107      'data' => l(t('Actualizar estado de proyectos'), 'ente_planificador_importar/estadoproyecto'),
108      'class' => 'ente-planificador-importar-estado-proyecto',
109    );
110  }
111}
112
113
114/**
115 * Implementation of ente_planificador_importar_terminos_form().
116 * Form to load cvs file in term import
117 */
118function ente_planificador_importar_terminos_form() {
119  $form = array();
120  // If this #attribute is not present, upload will fail on submit
121  $form['#attributes']['enctype'] = 'multipart/form-data';
122  $form['file_import_entes'] = array(
123    '#title' => t('Terminos a importar'),
124    '#type'  => 'file',
125    '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
126  );
127  $vocabularies = taxonomy_get_vocabularies();
128  $vocabulary_options = array();
129  foreach($vocabularies as $vocabulary) {
130    $vocabulary_options[$vocabulary->vid] = $vocabulary->name;
131  }
132  $form['vid'] = array(
133    '#type' => 'select',
134    '#title' => t('Taxonomy'),
135    '#default_value' => !empty($field['vid']) ? $field['vid'] : '',
136    '#options' => $vocabulary_options,
137  );
138  $options = array();
139  for($i = 0;$i < 11; $i++) {
140    if (!$i) {
141      $options[$i] = t('N/A');
142    }
143    else {
144      $options[$i] = t('Fila') . ' ' . $i;
145    }
146  }
147  $form['nombre'] = array(
148    '#type' => 'select',
149    '#title' => t('Nombre'),
150    '#options' => $options,
151    '#description' => t("La fila donde se encuentra el nombre del termino."),
152    '#required' => TRUE,
153  );
154  $ids = array(
155    'code' => t('Código'),
156  );
157  foreach ($ids as $id =>$text) {
158    $form[$id] = array(
159      '#type' => 'select',
160      '#title' => $text,
161      '#options' => $options,
162    );
163  }
164  $form['encabezado'] = array(
165    '#title' => 'Primera columna como encabezado',
166    '#type' => 'checkbox',
167    '#return_value' => '1',
168  );
169  $form['submit'] = array(
170    '#type' => 'submit',
171    '#value' => 'Submit',
172  );
173  return $form;
174}
175
176/**
177 * Implementation of ente_planificador_importar_terminos_form_submit().
178 * Submit cvs file in term import
179 */
180function ente_planificador_importar_terminos_form_submit($form, &$form_state) {
181  global $user;
182  $validators = array('file_validate_extensions' => array('csv'));
183  // Check for a new uploaded file.
184  $file = file_save_upload('file_import_entes', $validators);
185  if (isset($file)) {
186    // File upload was attempted.
187    if ($file) {
188      // Put the temporary file in form_values so we can save it on submit.
189      $csv = $file->filepath;
190      $file = fopen($csv, 'r');
191      $time = time();
192      $i = 1;
193      $datas = array();
194      $batch = array(
195        'title' => t('Importing terminos ...', array('@format' => $format)),
196        'operations' => array(),
197        'init_message' => t('Commencing'),
198        'progress_message' => t('Processed @current out of @total.'),
199        'error_message' => t('An error occurred during processing'),
200        'finished' => '_batch_ente_planificador_importar_term_finished',
201      );
202      while (($data = fgetcsv($file)) !== FALSE) {
203        $term = array(
204          'vid' => $form_state['values']['vid'], // Voacabulary ID
205          'name' => check_plain($data[$form_state['values']['nombre'] - 1]), // Term Name
206          'fields' => array(
207            'unidad_codigo1' =>  array(
208              'value' => check_plain($data[$form_state['values']['code'] - 1]),
209            ),
210          ),
211        );
212        if (!($form_state['values']['encabezado'] && $i == 1)) {
213          $batch['operations'][] = array('_batch_ente_planificador_importar_term', array($term));
214        }
215        $i++;
216      }
217      batch_set($batch);
218      batch_process('ente_planificador_importar/terminos');
219    }
220    else {
221
222      // File upload failed.
223      form_set_error('file_import_entes', t('The term file could not be uploaded.'));
224    }
225  }
226}
227
228/**
229 * Implementation of _ente_planificador_importar_terminos_execute().
230 * Batch 'execute' callback
231 */
232function _ente_planificador_importar_terminos_execute($execute_id){
233  if ($execute_id && isset($_SESSION['ente_planificador_importar_terminos'][$execute_id]) && is_array($_SESSION['ente_planificador_importar_terminos'][$execute_id])) {
234    $batch = array(
235      'title' => t('Importing terminos ...', array('@format' => $format)),
236      'operations' => array(),
237      'init_message' => t('Commencing'),
238      'progress_message' => t('Processed @current out of @total.'),
239      'error_message' => t('An error occurred during processing'),
240      'finished' => '_batch_ente_planificador_importar_term_finished',
241    );
242    $datas = $_SESSION['ente_planificador_importar_terminos'][$execute_id];
243
244    unset($_SESSION['ente_planificador_importar_terminos'][$execute_id]);
245    $cantidad = count($datas);
246    $i = 1;
247    foreach($datas as $data) {
248      $batch['operations'][] = array('_batch_ente_planificador_importar_term', array($data));
249      $i++;
250    }
251    batch_set($batch);
252    batch_process('ente_planificador_importar/terminos');
253  }
254  else {
255    drupal_set_message(t('Ocurrio un error al intentar importar los entes planificadores'));
256    drupal_goto('ente_planificador_importar/terminos');
257  }
258}
259
260/**
261 * Implementation of _batch_ente_planificador_importar_term_finished().
262 * Batch 'finished' callback
263 */
264function _batch_ente_planificador_importar_term_finished($success, $results, $operations) {
265  if ($success) {
266    // Here we do something meaningful with the results.
267    $message = t('!count_webform terminos processed', array('!count_webform' => count($results)));
268  }
269  else {
270    // An error occurred.
271    // $operations contains the operations that remained unprocessed.
272    $error_operation = reset($operations);
273    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
274  }
275  drupal_set_message($message);
276}
277
278/**
279 * Implementation of _batch_ente_planificador_importar_term().
280 * display term saved (used in _ente_planificador_importar_terminos_execute)
281 * Batch run callback 
282 */
283function _batch_ente_planificador_importar_term($term, &$context) {
284  taxonomy_save_term($term);
285  $context['message'] = t('Now processing ente: %submission', array('%submission' => $term->name));
286  $context['results'][] = 'term importado: ' . $term->name . '</pre>';
287/*
288  if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
289    $context['finished'] = 1;
290  } else {
291    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
292  }
293*/
294}
295
296/**
297 * Implementation of ente_planificador_importar_form().
298 * Form to load cvs file in entes import
299 */
300function ente_planificador_importar_form() {
301  $form = array();
302  // If this #attribute is not present, upload will fail on submit
303  $form['#attributes']['enctype'] = 'multipart/form-data';
304  $form['file_import_entes'] = array(
305    '#title' => t('Entes a importar'),
306    '#type'  => 'file',
307    '#description' => t('Archivo cvs con el contenido de los entes planificadores a importar'),
308  );
309  $options = array();
310  for($i = 0;$i < 30; $i++) {
311    if (!$i) {
312      $options[$i] = t('N/A');
313    }
314    else {
315      $options[$i] = t('Fila') . ' ' . $i;
316    }
317  }
318  $form['titulo'] = array(
319    '#type' => 'select',
320    '#title' => t('Titulo'),
321    '#options' => $options,
322    '#description' => t("La fila donde se encuentra el nombre del ente."),
323    '#required' => TRUE,
324  );
325  $form['level'] = array(
326    '#type' => 'select',
327    '#title' => t('Nivel'),
328    '#options' => $options,
329    '#description' => t("La fila donde se encuentra el nivel de jerarquia del ente."),
330    '#required' => TRUE,
331  );
332  $form['father'] = array(
333    '#type' => 'select',
334    '#title' => t('Ente padre'),
335    '#options' => $options,
336    '#description' => t("La fila donde se encuentra el ente padre del ente."),
337    '#required' => TRUE,
338  );
339  $form['sector'] = array(
340    '#type' => 'select',
341    '#title' => t('Sector'),
342    '#options' => $options,
343    '#description' => t("La fila donde se encuentra el sector del ente."),
344  );
345  $form['acronimo'] = array(
346    '#type' => 'select',
347    '#title' => t('Acrónimo'),
348    '#options' => $options,
349    '#description' => t("La fila donde se encuentra el acrónimo del ente."),
350  );
351  $node_type = content_types('ente_planificador');
352  $fields = $node_type['fields'];
353  $campos = array();
354  if (count($fields)) {
355    $form['campos'] = array(
356      '#type' => 'fieldset',
357      '#title' => t('campos'),
358    );
359    foreach($fields as $field_id => $field) {
360      $campos[$field_id] =  $field;
361      $form['campos'][$field_id] = array(
362        '#type' => 'select',
363        '#title' => $field['widget']['label'],
364        '#options' => $options,
365        '#description' => t("La fila donde se encuentra el campo del ente."),
366      );
367    }
368  }
369  $form['encabezado'] = array(
370    '#title' => 'Primera columna como encabezado',
371    '#type' => 'checkbox',
372    '#return_value' => '1',
373  );
374  $form['#ente_fields'] = $campos;
375  $form['submit'] = array(
376    '#type' => 'submit',
377    '#value' => 'Submit',
378  );
379  return $form;
380}
381
382/**
383 * Implementation of ente_planificador_importar_form_submit().
384 * Submit cvs file in entes import
385 */
386function ente_planificador_importar_form_submit($form, &$form_state) {
387  global $user;
388  $validators = array('file_validate_extensions' => array('csv'));
389  // Check for a new uploaded file.
390  $file = file_save_upload('file_import_entes', $validators);
391  if (isset($file)) {
392    // File upload was attempted.
393    if ($file) {
394      // Put the temporary file in form_values so we can save it on submit.
395      $csv = $file->filepath;
396      $file = fopen($csv, 'r');
397      $time = time();
398      $i = 1;
399      $batch = array(
400        'title' => t('Importing entes planificadores ...', array('@format' => $format)),
401        'operations' => array(),
402        'init_message' => t('Commencing'),
403        'progress_message' => t('Processed @current out of @total.'),
404        'error_message' => t('An error occurred during processing'),
405        'finished' => '_batch_ente_planificador_importar_finished',
406      );
407      while (($data = fgetcsv($file)) !== FALSE) {
408        $ente = new stdClass();
409        if ($form_state['values']['encabezado'])
410        $ente->type = 'ente_planificador';
411        $ente->title = check_plain($data[$form_state['values']['titulo'] - 1]);
412        $ente->father = $data[$form_state['values']['father'] - 1];
413        if ($data[$form_state['values']['sector']] -1) {
414          $ente->sector_social = $data[$form_state['values']['sector'] - 1];
415        }
416        if ($data[$form_state['values']['acronimo']] -1) {
417          $ente->import_acronimo = check_plain($data[$form_state['values']['acronimo'] - 1]);
418        }
419        //se agregan los campos
420        if (count($form['#ente_fields'])) {
421          foreach($form['#ente_fields'] as $field_id => $field) {
422            if ($data[$form_state['values'][$field_id]]) {
423              $tipo = 'value';
424              if ($field['type'] == 'nodereference') {
425                $tipo = 'nid';
426              }
427              if ($field['type'] == 'userreference') {
428                $tipo = 'uid';
429              }
430              if ($field['type'] == 'email') {
431                $tipo = 'email';
432              }
433              if ($field['type'] == 'link') {
434                $tipo = 'link';
435              }
436              if ($field['type'] == 'content_taxonomy') {
437                $tipo = 'content_taxonomy';
438              }
439              $ente->{$field_id}[0][$tipo] = check_plain($data[$form_state['values'][$field_id] - 1]);
440            }
441          }
442        }
443        $ente->status = 1;
444        $ente->tipo = $data[$form_state['values']['level']];
445        $ente->promote = 0;
446        $ente->promote = 0;
447        $ente->sticky = 0;
448        $ente->uid = $user->uid;
449        $ente->revision = 1;
450        $texto = t('Agregado el ente @nombre_ente', array('@nombre_ente' => $ente->title));
451        $ente->log = $texto;
452        if (!($form_state['values']['encabezado'] && $i == 1)) {
453          $batch['operations'][] = array('_batch_ente_planificador_importar', array($ente));
454          $datas[] = $ente;
455        }
456        $i++;
457      }
458      batch_set($batch);
459      batch_process('ente_planificador_importar/entes');
460    }
461    else {
462
463      // File upload failed.
464      form_set_error('file_import_entes', t('The entes file could not be uploaded.'));
465    }
466  }
467}
468
469/**
470 * Implementation of _ente_planificador_importar_execute().
471 * Batch 'execute' callback
472 */
473function _ente_planificador_importar_execute($execute_id){
474  if ($execute_id && isset($_SESSION['ente_planificador_importar'][$execute_id]) && is_array($_SESSION['ente_planificador_importar'][$execute_id])) {
475    $batch = array(
476      'title' => t('Importing entes planificadores ...', array('@format' => $format)),
477      'operations' => array(),
478      'init_message' => t('Commencing'),
479      'progress_message' => t('Processed @current out of @total.'),
480      'error_message' => t('An error occurred during processing'),
481      'finished' => '_batch_ente_planificador_importar_finished',
482    );
483    $datas = $_SESSION['ente_planificador_importar'][$execute_id];
484
485    unset($_SESSION['ente_planificador_importar'][$execute_id]);
486    $cantidad = count($datas);
487    $i = 1;
488    foreach($datas as $data) {
489      $batch['operations'][] = array('_batch_ente_planificador_importar', array($data));
490    }
491    batch_set($batch);
492    batch_process('ente_planificador_importar');
493  }
494  else {
495    drupal_set_message(t('Ocurrio un error al intentar importar los entes planificadores'));
496    drupal_goto('ente_planificador_importar');
497  }
498}
499
500/**
501 * Implementation of _ente_planificador_importar_usuarios().
502 * Obtiene la cantidad de usuarios por tipo de ente
503 */
504function _ente_planificador_importar_usuarios($tipo = 0) {
505  $cant_usuarios = array();
506  $cant_usuarios[1] = array(
507    'for' => 0,
508    'enl' => 5,
509    'sup' => 5,
510  );
511  $cant_usuarios[2] = array(
512    'for' => 0,
513    'enl' => 3,
514    'sup' => 3,
515  );
516  $cant_usuarios[3] = array(
517    'for' => 10,
518    'enl' => 2,
519    'sup' => 1,
520  );
521  $cant_usuarios[4] = array(
522    'for' => 3,
523    'enl' => 0,
524    'sup' => 1,
525  );
526  return $cant_usuarios[$tipo];
527}
528
529/**
530 * Implementation of _batch_ente_planificador_importar().
531 * Save entes (used in _ente_planificador_importar_execute)
532 * Batch run callback 
533 */
534function _batch_ente_planificador_importar($ente, &$context) {
535  $father = $ente->father;
536  //Se consulta la jerarquia del ente padre
537  $desc = _ente_planificador_hierarchical_get_descbyacronimo($ente->father);
538  $count = count($desc);
539  if ($count) {
540    foreach($desc as $idfathers) {
541      if ($idfathers['father']) {
542        $parent = taxonomy_get_parents($ente->sector_social);
543        $ente->sector = $ente->sector_social;
544        $ente->ambito = key($parent);
545        $ente->ente_planificador_hierarchical[$idfathers['level']] = $idfathers['father'];
546        $ente->{'ente_planificador_hierarchical_father_' . $idfathers['level']} = $idfathers['father'];
547      }
548      else {
549        $ente->ente_planificador_hierarchical[$idfathers['level']] = $idfathers['nid'];
550        $ente->{'ente_planificador_hierarchical_father_' . $idfathers['level']} = $idfathers['nid'];
551      }
552    }
553    $ente->{'ente_planificador_hierarchical_father_' . ($count + 1)} = 0;
554  }
555  $level = count($ente->ente_planificador_hierarchical[$idfathers['level']]);
556  if ($level) {
557    $level++;
558    //Se ajusta el nivel
559    if ($ente->tipo != $level) {
560      $ente->tipo = $level;
561    }
562    $acronimo = isset($ente->import_acronimo)? $ente->import_acronimo : 0;
563    $ente->sector = isset($ente->sector_social)? $ente->sector_social : 0;
564    node_save($ente);
565    $falla = $ente->nid ? '' : 'FALLA';
566    //insert sector
567
568    $context['results'][] = 'ente importado: <pre>' . print_r($ente, 1) . $falla . '</pre>';
569    if ($ente && $ente->nid) {
570      //Se ingresa el acronimo si existe
571      if ($acronimo) {
572        db_query("UPDATE {ente_planificador_hierarchical} SET acronimo = '%s' WHERE nid = %d", $acronimo, $ente->nid);
573      }
574      else {
575        $acronimo = 'ente_' . $acronimo;
576      }
577      //se crean los usuarios segun el tipo
578      $roles_type = _ente_planificador_hierarchical_get_roles_type($ente->tipo);
579      $cant_usuarios = _ente_planificador_importar_usuarios($ente->tipo);
580      foreach ($roles_type as $rol => $text) {
581        $array = array();
582        $array['roles'] = array();
583        $array['roles'][DRUPAL_AUTHENTICATED_RID] = DRUPAL_AUTHENTICATED_RID;
584        $rol_tipo = variable_get('ente_planificador_hierarchical_rol_' . $rol . '_' . $ente->tipo, 2);
585        //existe el rol para el usuario
586        if ($rol_tipo && $cant_usuarios[$rol]) {
587          for ($i = 0; $i < $cant_usuarios[$rol]; $i++) {
588            $array['roles'][$rol_tipo] = $rol_tipo;
589            $array['name'] = $acronimo . '_' . $rol . '_' . ($i + 1);
590            $array['pass'] = $acronimo . '_' . $rol . '_' . ($i + 1);
591            $array['mail'] = $rol . '_' . ($i + 1) . '@' . 'ente_' . $acronimo . '.com';
592            $array['status'] = 1;
593            $array['entes'] = $ente->nid;
594            user_save(NULL, $array);
595          }
596        }
597      }
598    }
599  }
600  $context['message'] = t('Now processing ente: %submission', array('%submission' => $ente->title));
601}
602
603/**
604 * Implementation of _batch_ente_planificador_importar_finished().
605 * Batch 'finished' callback
606 */
607function _batch_ente_planificador_importar_finished($success, $results, $operations) {
608  if ($success) {
609    // Here we do something meaningful with the results.
610    $message = t('!count_webform entes processed', array('!count_webform' => print_r($results, TRUE)));
611  }
612  else {
613    // An error occurred.
614    // $operations contains the operations that remained unprocessed.
615    $error_operation = reset($operations);
616    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
617  }
618  drupal_set_message($message);
619}
620
621/**
622 * Implementation of _ente_planificador_hierarchical_get_descbyacronimo().
623 * Obtiene los padres de un ente por el acronimo o nombre
624 */
625function _ente_planificador_hierarchical_get_descbyacronimo($acronimo = '') {
626  $fathers = array();
627  //get fathers
628  if ($acronimo) {
629    //Se verifica que el arconimo exista
630    $query = db_query("SELECT * FROM {ente_planificador_hierarchical} WHERE acronimo = '%s'", $acronimo);
631    $father_acronimo = db_fetch_object($query);
632    if (!$father_acronimo || !$father_acronimo->acronimo) {
633      $query = db_query("SELECT h.* FROM {node} AS n INNER JOIN {ente_planificador_hierarchical} AS h ON h.nid = n.nid WHERE n.title = '%s'", $acronimo);
634      $father_acronimo = db_fetch_object($query);
635    }
636    if ($father_acronimo && $father_acronimo->nid) {
637      $query = db_query('SELECT * FROM {ente_planificador_hierarchical} WHERE nid = %d', $father_acronimo->nid);
638      while ($father = db_fetch_object($query)) {
639        $fathers[] = array(
640          'title' => $father->title,
641          'nid' =>  $father->nid,
642          'father' =>  $father->father,
643          'level' =>  $father->level,
644          'title' => $father->acronimo,
645        );
646      }
647    }
648  }
649  return $fathers;
650}
651
652
653/**
654 * Implementation of ente_planificador_importar_aprobar_proyectos_form().
655 * Form to load cvs file and setting in proyectos estate update
656 */
657function ente_planificador_importar_aprobar_proyectos_form() {
658  $form = array();
659  // If this #attribute is not present, upload will fail on submit
660  $form['#attributes']['enctype'] = 'multipart/form-data';
661  $form['file_import_proyectos'] = array(
662    '#title' => t('Proyectos a aprobar'),
663    '#type'  => 'file',
664    '#description' => t('Archivo cvs con el contenido de los proyectos a aprobar'),
665  );
666  $options = array();
667  for($i = 0;$i < 11; $i++) {
668    if (!$i) {
669      $options[$i] = t('N/A');
670    }
671    else {
672      $options[$i] = t('Fila') . ' ' . $i;
673    }
674  }
675  $form['sipes'] = array(
676    '#type' => 'select',
677    '#title' => t('Código SIPES del proyecto'),
678    '#options' => $options,
679    '#description' => t("La fila donde se encuentra el código SIPES del proyecto."),
680    '#required' => TRUE,
681  );
682  $estados = _proyectos_operativos_reformula_obtiene_estados();
683  $form['workflow'] = array(
684    '#type' => 'select',
685    '#title' => t('Nuevo estado del proyecto'),
686    '#options' => $estados['states'],
687    '#description' => t("Seleccione el nuevo estado que se colocara a los proyectos contenidos en el archivo de importación."),
688    '#required' => TRUE,
689  );
690  $form['encabezado'] = array(
691    '#title' => 'Primera columna como encabezado',
692    '#type' => 'checkbox',
693    '#return_value' => '1',
694  );
695  $form['submit'] = array(
696    '#type' => 'submit',
697    '#value' => 'Submit',
698  );
699  return $form;
700}
701
702
703/**
704 * Implementation of ente_planificador_importar_aprobar_proyectos_form_submit().
705 * Submit cvs file in proyectos estate update
706 */
707function ente_planificador_importar_aprobar_proyectos_form_submit($form, &$form_state) {
708  global $user;
709  $validators = array('file_validate_extensions' => array('csv'));
710  // Check for a new uploaded file.
711  $file = file_save_upload('file_import_proyectos', $validators);
712  if (isset($file)) {
713    // File upload was attempted.
714    if ($file) {
715      // Put the temporary file in form_values so we can save it on submit.
716      $csv = $file->filepath;
717      $file = fopen($csv, 'r');
718      $time = time();
719      $i = 1;
720      $datas = array();
721      $batch = array(
722        'title' => t('Importing proyectos ...', array('@format' => $format)),
723        'operations' => array(),
724        'init_message' => t('Commencing'),
725        'progress_message' => t('Processed @current out of @total.'),
726        'error_message' => t('An error occurred during processing'),
727        'finished' => '_batch_proyecto_operativo_cambiar_estado_importar_finished',
728      );
729      while (($data = fgetcsv($file)) !== FALSE) {
730        $sipes = check_plain($data[$form_state['values']['sipes'] - 1]);
731        if ($sipes != '') {
732          $proyecto = array(
733            'sipes' => $sipes, // codigo sipes
734            'workflow' => $form_state['values']['workflow'], // workflow
735            'workflows' => $form['workflow']['#options'], // workflow options
736          );
737          if (!($form_state['values']['encabezado'] && $i == 1)) {
738            $batch['operations'][] = array('_batch_proyecto_operativo_cambiar_estado_importar', array($proyecto));
739          }
740          $i++;
741        }
742      }
743      batch_set($batch);
744      batch_process('ente_planificador_importar/estadoproyecto');
745    }
746    else {
747
748      // File upload failed.
749      form_set_error('file_import_proyectos', t('The proyectos file could not be uploaded.'));
750    }
751  }
752}
753
754
755/**
756 * Implementation of _batch_proyecto_operativo_cambiar_estado_importar().
757 * Update state proyectos (used in ente_planificador_importar_aprobar_proyectos_form_submit)
758 * Batch run callback 
759 */
760function _batch_proyecto_operativo_cambiar_estado_importar($proyecto, &$context) {
761  $context['message'] = t('Now processing proyecto: %submission', array('%submission' => check_plain($proyecto['sipes'])));
762  $query = db_query("SELECT nid FROM {node} WHERE title = '%s'", $proyecto['sipes']);
763  $proyecto_nid = db_fetch_object($query);
764  if ($proyecto_nid && $proyecto_nid->nid) {
765    $node = node_load($proyecto_nid->nid);
766    if ($node->nid) {
767      if ($node->_workflow != $proyecto['workflow']) {
768        $context['results'][] = t('Actualizado el proyecto @proyecto desde el estado @ant al @prox ', array('@proyecto' => $proyecto['sipes'], '@ant' => $proyecto['workflows'][$node->_workflow], '@prox' => $proyecto['workflows'][$proyecto['workflow']]));
769        //$node->_workflow = $proyecto['workflow'];
770        $node->revision = 1;
771        $texto = t('Se cambio el proyecto @nombre del estado @estado al @estado_next', array('@nombre' => $node->title, '@estado' => $proyecto['workflows'][$node->_workflow], '@estado_next' => $proyecto['workflows'][$proyecto['workflow']]));
772        $node->log = $texto;
773        workflow_execute_transition($node, $proyecto['workflow'], $texto, TRUE);
774        //$node->_workflow = $proyecto['workflow'];
775        node_save($node);
776      }
777      else {
778        $context['results'][] = t('El proyecto @proyecto ya se encuentra en el estado @prox ', array('@proyecto' => $proyecto['sipes'], '@prox' => $proyecto['workflows'][$proyecto['workflow']]));
779      }
780    }
781    else {
782      $context['results'][] = t('No se encontro el proyecto @proyecto', array('@proyecto' => $proyecto['sipes']));
783    }
784  }
785  else {
786    $context['results'][] = t('No se encontro el proyecto @proyecto', array('@proyecto' => $proyecto['sipes']));
787  }
788}
789
790/**
791 * Implementation of _batch_ente_planificador_importar_finished().
792 * Batch 'finished' callback
793 */
794function _batch_proyecto_operativo_cambiar_estado_importar_finished($success, $results, $operations) {
795  if ($success) {
796    // Here we do something meaningful with the results.
797    $message = t('!count_webform entes processed', array('!count_webform' => '<pre>' . print_r($results, TRUE) . '</pre>'));
798  }
799  else {
800    // An error occurred.
801    // $operations contains the operations that remained unprocessed.
802    $error_operation = reset($operations);
803    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
804  }
805  drupal_set_message($message);
806}
807
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.