source: sipp/0.3-stable-modules/proyectos_reformulacion/proyectos_reformulacion.module @ f4301be

0.3-stable
Last change on this file since f4301be was f4301be, checked in by José Gregorio Puentes <jpuentes@…>, 9 años ago

se agregaron los campos codigo, objetivos y justificacion a la vista de consultas

  • Propiedad mode establecida a 100755
File size: 143.8 KB
Línea 
1<?php
2  /**
3  * Sistema Integral de Planificación y Presupuesto (SIPP)
4  * @file proyectos_reformulacion.module
5  * Drupal part Module to Sistema Integral de Planificación y Presupuesto (SIPP)
6  * Copyright 2013 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  * @author Cenditel Merida - Msc. Juan Vizcarrondo
23  * @date 2013-04-11 // (a&#241;o-mes-dia)
24  * @version 0.1 // (0.1)
25  *
26  */
27
28/*
29 * Implementation of hook_ente_procesos_alter()
30 */
31function proyectos_reformulacion_ente_procesos_alter(&$procesos, $type) {
32  if ($type != 'status') {
33    $procesos['proyectos_operativos_reformular'] = array(
34      'title' => t('Modificaciones los proyectos Operativos'),
35      'description' => t('Permite modificaciones los proyectos Operativos'),
36      'message' => 'Se podrá registrar y/o modificar las modificaciones de los proyectos Operativos desde %fecha hasta la fecha %fecha1',
37      'message_expire' => 'Registrar y/o modificar las modificaciones de los proyectos Operativos no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
38      'weight' => 4,
39      'proceso' => 'proyectos_operativos',
40    );
41  }
42}
43
44/*
45 * Implementation of acciones_centralizadas_status_planificacion_acciones_centralizadas()
46 */
47function proyectos_reformulacion_status_planificacion_proyectos_operativos($ente_planificador, $tipo = 2) {
48  $datos_proyectos_reformulacion_status = array();
49  //si existe al menos una reformulacion en estado aprobado la reformulacion se puede considerar terminado
50  $reformular = FALSE;
51  $year = variable_get('proyectos_operativos_anho_creacion', 0);
52  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);;
53  $result = db_query('SELECT COUNT(id_ref) AS cantidad FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS po ON po.nid = re.nid WHERE re.nid = %d AND estado <> %d AND po.year = %d', $ente_planificador, $estado_naprobado, $year);
54  $reformular = db_fetch_object($result);
55  $datos_proyectos_reformulacion_status['proyectos_operativos_reformular']['value'] = $reformular  ? 1 : 0;
56  $datos_proyectos_reformulacion_status['proyectos_operativos_reformular']['title'] = t('Moificaciones para el año @year', array('@year' => $year));
57  $datos_proyectos_reformulacion_status['proyectos_operativos_reformular']['link'] = 'proyectos_operativos';
58  $datos_acciones_centralizadas_status['proyectos_operativos_reformular']['mylink'] = 'proyectos_operativos';
59  $datos_proyectos_reformulacion_status['proyectos_operativos_reformular']['weight'] = -9;
60  return $datos_proyectos_reformulacion_status;
61}
62
63/*
64 * Implementation of hook_nodeapi()
65 */
66function proyectos_reformulacion_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
67  switch ($op) {
68    case 'view':
69      if ($node->type == 'proyectos_operativos') {
70        $format_number = array(
71          'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
72          'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
73          'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
74        );
75        //se obtiene la reformulacion
76        $variaciones = _proyectos_reformula_all_partidas_load($node);
77        $varia = isset($variaciones['total']) ? $variaciones['total'] : 0;
78        //se obtiene el monto anual del proyecto
79        $min = $node->field_proyecto_monto_anual[0]['value'] + $varia;
80        $node->content['proyectos_operativos_monto_anual_reformulado'] = array(
81          '#value' => '<div class="field"><div class="field-label">' . t('Monto Total del Proyecto para el año en curso') . ':</div>' . number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>',
82          '#weight' => 100,
83        );
84        //se obtiene el monto total del proyecto
85        $min = $node->field_proyecto_total[0]['value'] + $varia;
86        $node->content['proyectos_operativos_monto_total_reformulado'] = array(
87          '#value' => '<div class="field"><div class="field-label">' . t('Monto Total del Proyecto') . ':</div>' . number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>',
88          '#weight' => 100,
89        );
90        $unidad_medida = isset($variaciones['unidad']) ? $variaciones['unidad'] : $node->field_proyecto_unidadm[0]['tid'];
91        if ($unidad_medida) {
92          $unidad_medida_term = taxonomy_get_term($unidad_medida);
93          $unidad_nombre = t('No seleccionado');
94          // If this term's vocabulary supports localization.
95          if ($unidad_medida_term && module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($unidad_medida_term->vid) == I18N_TAXONOMY_LOCALIZE) {
96            $unidad_medida_term->name = tt("taxonomy:term:$unidad_medida_term->tid:name", $unidad_medida_term->name);
97          }
98           
99          if ($unidad_medida_term) {
100            $unidad_nombre = $unidad_medida_term->name;
101          }
102        }
103        $node->content['proyectos_operativos_unidad_medida_reformulado'] = array(
104          '#value' => '<div class="field"><div class="field-label">' . t('Unidad de Medida') . ':</div>' . $unidad_nombre . '</div>',
105          '#weight' => 100,
106        );
107        //meta fisica del proyecto
108        $output = '<fieldset><legend>' . t('Meta Física del proyecto') . '</legend>';
109        $ftypes = array(
110          'value' => t('January'),
111          'value_1' => t('February'),
112          'value_2' => t('March'),
113          'value_3' => t('April'),
114          'value_4' => t('May'),
115          'value_5' => t('June'),
116          'value_6' => t('July'),
117          'value_7' => t('August'),
118          'value_8' => t('September'),
119          'value_9' => t('Octuber'),
120          'value_10' => t('November'),
121          'value_11' => t('December'),
122        );
123        $header = array();
124        $rows = array();
125        $row = array();
126        $total = 0;
127        $total1 = 0;
128        foreach($ftypes as $id_field => $texto) {
129          $header[] = array('data' => $texto);
130          $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
131          $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
132          $valor = isset($reformula['field_proyecto_meta_fisica'][0][$id_field])? $reformula['field_proyecto_meta_fisica'][0][$id_field] : 0;
133          $total += $min;
134          $total1 += $valor;
135          $row[] = array('data' => $min, );
136        }
137        $row[] = array('data' => $total, );
138        $rows[] = $row;
139        $header[] = array('data' => t('TOTAL'));
140        $output .= theme('table', $header, $rows);
141        $output .= '</fieldset>';
142        $node->content['proyectos_operativos_meta_fisica_reformulado'] = array(
143          '#value' => $output,
144          '#weight' => 100,
145        );
146      }
147      elseif ($node->type == 'accion_especifica') {
148        $term_id = isset($node->variaciones) && isset($node->variaciones['field_accion_esp_metaf_'. $node->nid][0]['unidad']) ? $node->variaciones['field_accion_esp_metaf_'. $node->nid][0]['unidad'] : $node->field_accion_esp_unidadm[0]['value'];
149        $term = taxonomy_get_term($term_id);
150        //se agrega la unidad de medida reformulada
151        $node->content['proyectos_operativos_unidad_medida_reformulado'] = array(
152          '#value' => '<div class="field"><div class="field-label">' . t('Unidad de Medida') . ':</div>' . $term->name . '</div>',
153          '#weight' => 100,
154        );
155        $format_number = array(
156          'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
157          'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
158          'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
159        );
160
161
162
163
164        $ftypes = array(
165          'value' => t('January'),
166          'value_1' => t('February'),
167          'value_2' => t('March'),
168          'value_3' => t('April'),
169          'value_4' => t('May'),
170          'value_5' => t('June'),
171          'value_6' => t('July'),
172          'value_7' => t('August'),
173          'value_8' => t('September'),
174          'value_9' => t('Octuber'),
175          'value_10' => t('November'),
176          'value_11' => t('December'),
177          );
178          $proyecto = node_load($node->field_accion_esp_proyecto[0]['nid']);
179          $variaciones = _proyectos_reformula_all_partidas_load($proyecto);
180          $output = '<fieldset><legend>' . t('Meta Física de las Acción Específica') . '</legend>';
181          $header = array();
182          $rows = array();
183          $row = array();
184          foreach($ftypes as $id_field => $texto) {
185            $header[] = array('data' => $texto);
186            $varia = isset($variaciones['field_accion_esp_metaf_' . $node->nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $node->nid][0][$id_field] : 0;
187            $min = $node->field_accion_esp_metaf[0][$id_field] + $varia;
188            $total += $min;
189            $row[] = array('data' => number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
190          }
191          $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
192          $header[] = array('data' => t('TOTAL'));
193          $rows[] = $row;
194          $output .= theme('table', $header, $rows);
195          $output .= '</fieldset>';
196        $node->content['accion_especifica_meta_fisica_reformulado'] = array(
197          '#value' => $output,
198          '#weight' => 100,
199        );
200        $field = content_fields('field_accion_esp_programacion', 'accion_especifica');
201        $tree = taxonomy_get_tree($field['vid']);
202        $vtid = $field['vtid'];
203        $partidas = array();
204        if ($tree) {
205          foreach ($tree as $term) {
206            if (isset($vtid[$term->tid])) {
207              if ($term && module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
208                $term->name = tt("taxonomy:term:$term->tid:name", $unidad_medida_term->name);
209              }
210
211              $partidas[$term->tid] = $term->name;
212            }
213          }
214        }
215        $partidas_nodo = array();
216        foreach ($node->field_accion_esp_programacion as $partida) {
217          if(!empty($partida['tid'])) {
218            $partidas_nodo[$partida['tid']] = $partida;
219          }
220        }
221        $output = '';
222        $output .= '<fieldset><legend>' . t('Distribución por partidas Presupuestarias') . '</legend>';
223        $header = array();
224        $header[] = array('data' => t('Partidas'));
225        foreach($ftypes as $id_field => $texto) {
226          $header[] = array('data' => $texto);
227        }
228        $header[] = array('data' => t('TOTAL'));
229        $rows = array();
230        $rowsF = array();
231        $totales = array();
232        $totalT = 0;
233        $plant = array();
234        $sumaplan = 0;
235        $sumaplanm = array();
236
237        foreach($partidas as $tid => $grupo) {
238          $total = 0;
239          $total1 = 0;
240          $row = array();
241          $row[] = array('data' => $grupo);
242          foreach($ftypes as $id_field => $texto) {
243            $varia = isset($variaciones['field_accion_esp_programacion_' . $node->nid][$tid][$id_field]) ? $variaciones['field_accion_esp_programacion_' . $node->nid][$tid][$id_field] : 0;
244            $min = $partidas_nodo[$tid][$id_field] + $varia;
245            if (!isset($plant[$tid])) {
246              $plant[$tid] = 0;
247            }
248            $totalT += $min;
249            $plant[$tid] += $min;
250            $total += $min;
251            $sumaplan += $min;
252            if (!isset($sumaplanm[$id_field])) {
253              $sumaplanm[$id_field] = 0;
254            }
255            $sumaplanm[$id_field] += $min;
256            $row[] = array('data' => number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
257          }
258          $row[] = array('data' => number_format($plant[$tid], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
259          if ($plant[$tid] > 0) {
260            $rows[] = $row;
261          }
262        }
263        $row = array();
264        $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right');
265        foreach($ftypes as $id_field => $texto) {
266          $row[] = array('data' => number_format($sumaplanm[$id_field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
267        }
268        $row[] = array('data' => number_format($totalT, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
269        $rows[] = $row;
270        $output .= theme('table', $header, $rows);
271        $output .= '</fieldset>';
272        $node->content['accion_especifica_partidas_reformulado'] = array(
273          '#value' => $output,
274          '#weight' => 101,
275        );
276        $output = '';
277
278        //financiamiento
279        $arreglo_financiamiento = array();
280        $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
281        for($i = 0; $i < $accion_especifica_number_fields; $i++) {
282          $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
283          $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
284        }
285/*
286
287        $arreglo = array();
288        $titles = array(
289          'ordinarios' => t('Recursos Ordinarios'),
290          'propios' => t('Recursos Propios'),
291          'transferencias' => t('Donaciones'),
292          'otros' => t('Otros'),
293        );
294        $titles_field = array(
295          'field_accion_esp_transferencias' => t('Recursos Ordinarios'),
296          'field_accion_esp_creditosa' => t('Recursos Propios'),
297          'transferencias' => t('Donaciones'),
298          'otros' => t('Otros'),
299        );
300        $arreglo['ordinarios'] = array(
301          'field_accion_esp_transferencias' => 'field_accion_esp_transferencias',
302          'field_accion_esp_creditosa' => 'field_accion_esp_creditosa',
303          'field_accion_esp_mcti' => 'field_accion_esp_mcti',
304        );
305        $arreglo['propios'] = array(
306          'field_accion_esp_venta_act' => 'field_accion_esp_venta_act',
307          'field_accion_esp_activos' => 'field_accion_esp_activos',
308          'field_accion_esp_flujocaja' => 'field_accion_esp_flujocaja',
309          'field_accion_esp_ventapro' => 'field_accion_esp_ventapro',
310        );
311        $arreglo['transferencias'] = array(
312          'field_accion_esp_donaciones' => 'field_accion_esp_donaciones',
313        );
314        $arreglo['otros'] = array(
315          'field_accion_esp_gobernacion' => 'field_accion_esp_gobernacion',
316          'field_accion_esp_misionc' => 'field_accion_esp_misionc',
317          'field_accion_esp_bid_fona' => 'field_accion_esp_bid_fona',
318          'field_accion_esp_fonacit' => 'field_accion_esp_fonacit',
319          'field_accion_esp_fonden' => 'field_accion_esp_fonden',
320          'field_accion_esp_locti' => 'field_accion_esp_locti',
321          'field_accion_esp_fondoidi' => 'field_accion_esp_fondoidi',
322          'field_accion_esp_capitalrie' => 'field_accion_esp_capitalrie',
323          'field_accion_esp_infocentro' => 'field_accion_esp_infocentro',
324          'field_accion_esp_fidetel' => 'field_accion_esp_fidetel',
325        );
326*/
327        $rows = array();
328        $row = array();
329        $row1 = array();
330        $sumalT = 0;
331        foreach($arreglo_financiamiento as $id_items => $titulo) {
332          $sumal = 0;
333          $output1 = '<fieldset><legend>' . $titulo . '</legend>';
334          foreach($arreglo_financiamiento_fields[$id_items] as $id1) {
335            if ($id1) {
336              $field = content_fields($id1, 'accion_especifica');
337              $varia = isset($variaciones[$id1 . '_' . $node->nid][0]['value']) ? $variaciones[$id1 . '_' . $node->nid][0]['value'] : 0;
338              $min = $node->{$id1}[0]['value'] + $varia;
339              if (!isset($sumafinm[$id_items])) {
340                $sumafinm[$id_items] = 0;
341              }
342              $sumafinm[$id_items] += $min;
343              $sumatotalf += $min;
344              $field = content_fields($id1, 'accion_especifica');
345              $sumal += $min;
346              $sumalT += $min;
347              $output1 .= '<div class="field"><div class="field-label">' . $field['widget']['label'] . ':</div>' . '<div class="field-label-planificado">' . number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . '</div>';
348            }
349          }
350          $output1 .= '</fieldset>';
351          $row[] = array('data' => $output1, );
352          $row1[] = array('data' => number_format($sumal, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
353        }
354        $rows[] = $row;
355        $rows[] = $row1;
356        $row = array();
357        $row[] = array('data' => '<b>' . t('TOTAL') . ':</b>', 'colspan' => 3, 'align' => 'right');
358        $row[] = array('data' => number_format($sumalT, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
359        $rows[] = $row;
360        $output .= '<fieldset><legend>' . t('Distribución por fuentes de Financiamiento') . '</legend>' . theme('table', array(), $rows) . '</fieldset>';
361        $node->content['accion_especifica_fuentesfinanc_reformulado'] = array(
362          '#value' => $output,
363          '#weight' => 102,
364        );
365      }
366    break;
367    case 'delete':
368      if ($node->type = 'proyectos_operativos') {
369        db_query('DELETE FROM {proyectos_reformula} WHERE nid = %d', $node->nid);
370        db_query('DELETE FROM {proyectos_reformular} WHERE nid = %d', $node->nid);
371        db_query('DELETE FROM {proyectos_reformular_state} WHERE nid = %d', $node->nid);
372        db_query('DELETE FROM {proyectos_reformula_fuente} WHERE nid = %d', $node->nid);
373      }
374    break;
375    case 'load':
376      if ($node->type == 'accion_especifica') {
377        $proyecto = node_load($node->field_accion_esp_proyecto[0]['nid']);
378        $variaciones = _proyectos_reformula_all_partidas_load($proyecto);
379        $node->proyecto_asignado = $proyecto;
380        $node->variaciones = $proyecto->variaciones;
381
382
383      }
384      elseif ($node->type == 'proyectos_operativos'){
385        $variaciones = _proyectos_reformula_all_partidas_load($node);
386        $node->variaciones = $variaciones;
387
388      }
389    break;
390  }
391}
392
393
394/*
395 * Implementation of hook_proyecto_obtiene_links_alter()
396 */
397function proyectos_reformulacion_proyecto_obtiene_links_alter(&$links, $proyecto, $acceso = FALSE) {
398  $node_accion = node_load($proyecto->nid);
399  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
400  if($node_accion->_workflow == $estado_aprobado){
401    $links[] = array(
402      'data' => l(t('Modificaciones'), 'proyectosop/' . $proyecto->nid . '/reformular'),
403      'class' => 'proyectos-operativos-reformulaciones',
404    );
405  }
406}
407
408/*
409 * hook_form_alter()
410 */
411function proyectos_reformulacion_form_alter(&$form, $form_state, $form_id) {
412  if ($form_id == 'proyectos_operativos_proyecto_genera_campos_form') {
413    if (!isset($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]) || !count($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid])) {
414    //REFORMULACION DEL PROYECTO
415      $arreglo['proyectos_reformulacion']['reformulacion'] = array(
416        'proyectos_operativos_monto_anual_reformulado' => t('Monto Total del Proyecto para el año en curso (Modificado)'),
417        'proyectos_operativos_monto_total_reformulado' => t('Monto Total del Proyecto (Modificado)'),
418        'proyectos_operativos_unidad_medida_reformulado' => t('Unidad de Medida (Modificado)'),
419        'proyectos_operativos_meta_fisica_reformulado' => t('Meta Física del proyecto (Modificado)'),
420      );
421      $form['proyectos_reformulacion'] = array(
422        '#type' => 'fieldset',
423        '#title' => t('Modificaciones del Proyecto'),
424        '#weight' => 1,
425      );
426      //Clasificación Sectorial
427      $form['proyectos_reformulacion']['reformulacion'] = array(
428        '#type' => 'checkboxes',
429        '#options' => $arreglo['proyectos_reformulacion']['reformulacion'],
430        '#default_value' => array(),
431        '#title' => t('Reformulación del Proyecto'),
432        '#multiple' => TRUE,
433      );
434      $form['#title_combos']['reformulacion']['title'] = t('Modificaciones del Proyecto');
435    }
436  }
437  $states = array();
438  if ($form_id == 'proyectos_operativos_admin_settings') {
439    if (module_exists('workflow')) {
440      $wid = workflow_get_workflow_for_type('proyectos_operativos');
441      if ($wid){
442        $states = workflow_get_states($wid);
443        $rids = user_roles();
444        $rids['-1'] = t('author');
445        if (count($states)) {
446          foreach ($states as $sid => $state) {
447            $form['workflow']['proyectos_operativos_state_r_' . $sid] = array(
448              '#type' => 'checkboxes',
449              '#options' => $rids,
450              '#default_value' => variable_get('proyectos_operativos_state_r_' . $sid, array()),
451              '#title' => t('Roles que pueden editar las realizar modificaciones de los Proyectos Operativos'),
452              '#multiple' => TRUE,
453              '#prefix' => '<table width="100%" style="border: 0;"><tbody style="border: 0;"><tr><th colspan="3">' . t('State: @state', array('@state' => $state)) . '</th></tr><tr><td>',
454              '#suffix' => "</td></tr></tbody></table>",
455            );
456          }
457        }
458      }
459    }
460  }
461  if (count($states)) {
462    $form['workflow']['proyectos_operativos_state_reformulacion'] = array(
463      '#title' => t('Seleccione el estado de inicio cuando se añada una modificación'),
464      '#type' => 'select',
465      '#default_value' => variable_get('proyectos_operativos_state_reformulacion', 0),
466      '#options' => $states,
467      '#weight' => -6,
468    );
469  }
470}
471
472
473/**
474 * Menu access control callback. Determine access to reformula tab.
475 */
476function _proyectos_reformulacion_reformula_node_tab_access($node = NULL) {
477  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
478  return ($node->type == 'proyectos_operativos' && $node->_workflow == $estado_aprobado);
479}
480
481/**
482 * Menu access control callback. Determine access to reformulacion tab.
483 */
484function _proyectos_reformulacion_reformula_node_add_tab_access($node = NULL) {
485  global $user;
486  $year = variable_get('proyectos_operativos_anho_creacion', 0);
487  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
488  if ($node->type != 'proyectos_operativos' || $node->anhoproyectos_operativos != $year) {
489    return FALSE;
490  }
491  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
492    return FALSE;
493  }
494  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
495  $current_time = time();
496  $tipo_plan = 'proyectos_operativos_reformular';
497  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
498  $fecha = FALSE;
499  $ente = usuario_tiene_ente($user->uid);
500  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
501    $fecha = TRUE;
502  }
503  if ($fecha) {
504    if ($ente->nid == $ente_planificador->nid) {
505      $fecha = TRUE;
506    }
507    elseif (!user_access('admin planificador')) {
508      return FALSE;
509    }
510  }
511  if (!$fecha) {
512    return FALSE;
513  }
514  $roles_allow = variable_get('proyectos_operativos_state_r_1', array());
515  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
516  $result = db_query("SELECT count(ar.id_ref) AS cantidad FROM {proyectos_operativos} AS ac INNER JOIN {proyectos_reformular} AS ar ON ar.nid = ac.nid WHERE (ar.estado <> %d AND ar.estado <> %d) AND ac.ente = %d AND ac.year = %d and ac.nid = %d", $estado_aprobado, $estado_naprobado, $node->field_proyecto_ente[0]['nid'], $year, $node->nid);
517  $proyecto = db_fetch_array($result);
518  $roles = array_keys($user->roles);
519  if (count($roles)) {
520    foreach($roles as $rol) {
521      if($roles_allow[$rol]) {
522        return TRUE && !$proyecto['cantidad'];
523      }
524    }
525  }
526  return ($proyecto && !$proyecto['cantidad'] && $user->uid == 1);
527}
528
529/**
530 * Menu access control callback. Determine access to editar reformulacion tab.
531 */
532function _proyectos_reformulacion_reformula_node_edit_tab_access($node = NULL, $reformulacion) {
533  global $user;
534  $year = variable_get('proyectos_operativos_anho_creacion', 0);
535  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
536  if ($node->type != 'proyectos_operativos' || $node->anhoproyectos_operativos != $year) {
537    return FALSE;
538  }
539  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
540    return FALSE;
541  }
542  if ($estado_aprobado && $reformulacion->estado == $estado_aprobado) {
543    return FALSE;
544  }
545  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
546  $current_time = time();
547  $tipo_plan = 'proyectos_operativos_reformular';
548  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
549  $fecha = FALSE;
550  $ente = usuario_tiene_ente($user->uid);
551  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
552    $fecha = TRUE;
553  }
554  if ($fecha) {
555    if ($ente->nid == $ente_planificador->nid) {
556      $fecha = TRUE;
557    }
558    elseif (!user_access('admin planificador')) {
559      return FALSE;
560    }
561  }
562  if (!$fecha) {
563    return FALSE;
564  }
565  $roles_allow = variable_get('proyectos_operativos_state_r_' . $reformulacion->estado, array());
566  if ($user->uid == 1 || ($user->uid == $reformulacion->uid && $roles_allow[-1])) {
567    return TRUE;
568  }
569  $roles = array_keys($user->roles);
570  if (count($roles)) {
571    foreach($roles as $rol) {
572      if($roles_allow[$rol]) {
573        return TRUE;
574      }
575    }
576  }
577  return FALSE;
578}
579
580
581/**
582 * Implementation of proyectos_reformulacion_menu_reformulacion_load().
583 * Menu loader callback. Load a mes.
584 */
585function proyectosop_menu_reformulacion_load($id_ref = 0, $node = 0) {
586  $reformula = FALSE;
587  $nodo = $node ? $node->nid : arg(1);
588  if ($id_ref && is_numeric($nodo)) {
589    $result = db_query("SELECT * FROM {proyectos_reformular} WHERE nid = %d AND id_ref = %d", $nodo, $id_ref);
590    $reformula = db_fetch_object($result);
591  }
592  return $reformula;
593}
594
595/**
596 * Implementation of accionesp_menu_r_load().
597 * Devuelve la accion especifica.
598 */
599function accionesp_menu_r_load($nid) {
600  $ae = FALSE;
601  if ($nid && arg(1) && is_numeric(arg(1))) {
602    $ae = node_load($nid);
603    if ($ae->type != 'accion_especifica' || $ae->field_accion_esp_proyecto[0]['nid'] != arg(1)) {
604      return FALSE;
605    }
606  }
607  return $ae;
608}
609
610/*
611 * Implementation of proyectos_reformulacion_wk_menu_load()
612 */
613function proyectos_reformulacion_wk_menu_load($state = 0) {
614  $states = _proyectos_operativos_reformulacion_obtiene_estados();
615  if (isset($states['states'][$state])) {
616    return $state;
617  }
618  return FALSE;
619}
620
621/**
622 * Menu access control callback. Determine access to wk tab.
623 */
624function _proyectos_reformulacion_reformula_wk_node_tab_access($node = NULL, $reformulacion, $state = 0) {
625  global $user;
626  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
627  $reformula = _proyectos_reformulacion_load($node, $id_ref);
628  $suma_r_ae = total_reformulado_ae($node, $reformula);
629  if ($suma_r_ae != $reformulacion_load->variacion) {
630    return FALSE;
631  }
632  $year = variable_get('proyectos_operativos_anho_creacion', 0);
633  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
634  if ($node->type != 'proyectos_operativos' || $node->anhoproyectos_operativos != $year) {
635    return FALSE;
636  }
637  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
638    return FALSE;
639  }
640  $ente = usuario_tiene_ente($user->uid);
641  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
642  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
643    return FALSE;
644  }
645  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
646  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
647  if ($reformulacion->estado == $estado_naprobado || $reformulacion->estado == $estado_aprobado) {
648    return FALSE;
649  }
650  $states = _proyectos_operativos_reformulacion_obtiene_estados();
651  $first_state = 0;
652  if ($states['wid']) {
653    $first_state = _workflow_creation_state($states['wid']);
654  }
655  $roles = array_keys($user->roles);
656  if ($user->uid == 1) {
657    // Superuser is special.
658    $roles_transition = 'ALL';
659  }
660  else {
661    $roles_transition = $roles;
662    if ($user->uid == $reformulacion->uid && $reformulacion->uid > 0) {
663      $roles_transition += array('author' => 'author');
664    }
665  }
666  $transitions = array();
667  if ($states['wid']) {
668    $transitions = workflow_allowable_transitions($reformulacion->estado, 'to', $roles_transition);
669  }
670  if ($first_state && $reformulacion->estado == $first_state) {
671    unset($transitions[$reformulacion->estado]);
672  }
673  if (isset($transitions[$state])) {
674    return TRUE;
675  }
676  return FALSE;
677}
678
679/*
680 * Implementation of proyectos_reformulacion_reformula_wk_tab_page_form()
681 */
682function proyectos_reformulacion_reformula_wk_tab_page_form($form_state, $node, $reformulacion_load = 0, $state = 0) {
683  $estados = _proyectos_operativos_reformulacion_obtiene_estados();
684  $form = array();
685  $form['#node'] = $node;
686  $form['#nuevo_estado'] = $state;
687  $form['#estados'] = $estados['states'];
688  $form['#reformulacion'] = $reformulacion_load;
689  $form['comentario'] = array(
690    '#title' => t('Comentario'),
691    '#type' => 'textarea',
692    '#default_value' => '',
693  );
694  $message = t('Esta seguro de cambiar la modificación al estado %nombre_estado?', array('%nombre_estado' => $estados['states'][$state]));
695  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
696  $return_path = 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/view';
697  return confirm_form($form, $message, $return_path, $caption, t('Cambiar'));
698  return $form;
699}
700
701/**
702 * Implementation of proyectos_reformulacion_reformula_wk_tab_page_form_submit().
703 * Process funcion delete confirm form.
704 */
705function proyectos_reformulacion_reformula_wk_tab_page_form_submit($form, &$form_state) {
706  global $user;
707  $nuevo_estado = $form['#datos_institucionales_funcion'];
708  db_query('UPDATE {proyectos_reformular} SET estado = %d, estado_ant = %d WHERE nid = %d AND id_ref = %d', $form['#nuevo_estado'], $form['#reformulacion']->estado, $form['#node']->nid, $form['#reformulacion']->id_ref);
709  db_query("INSERT INTO {proyectos_reformular_state} (nid, estado, estado_ant, comentario, date, id_ref, uid) VALUES (%d, %d, %d, '%s', %d, %d, %d)", $form['#node']->nid, $form['#nuevo_estado'], $form['#reformulacion']->estado, check_plain($form_state['values']['comentario']), time(), $form['#reformulacion']->id_ref, $user->uid);
710  drupal_set_message(t('La modificación del proyecto fue cambiada al estado @nombre_estado', array('@nombre_estado' => $form['#estados'][$form['#nuevo_estado']])));
711  $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#reformulacion']->id_ref . '/view';
712}
713
714/*
715 * Implementation of hook_menu()
716 */
717function proyectos_reformulacion_menu() {
718  $items = array();
719  //consultar el estado de las reformulaciones sin aprobar
720  $items['proyectos_operativos/reformular'] = array(
721    'title' => t('Modificaciones'),
722    'page callback' => 'proyectos_reformulacion_search_ac_display_approved',
723    'access arguments' => array('ver planificador'),
724    'type' => MENU_LOCAL_TASK,
725  );
726  $items['proyectos_operativos/reformular/entramite'] = array(
727    'title' => t('Lista de Modificaciones sin Aprobar'),
728    'page callback' => 'proyectos_reformulacion_search_ac_display_not_approved',
729    'access arguments' => array('ver planificador'),
730    'type' => MENU_LOCAL_TASK,
731  );
732  $items['proyectos_operativos/reformular/default'] = array(
733    'title' => t('Lista de Modificaciones'),
734    'page callback' => 'proyectos_reformulacion_search_ac_display_approved',
735    'access arguments' => array('ver planificador'),
736    'type' => MENU_DEFAULT_LOCAL_TASK,
737  );
738  $items['proyectosop/%proyectosop/reformular'] = array(
739    'title' => 'Modificar',
740    'type' => MENU_LOCAL_TASK,
741    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
742    'access arguments' => array(1),
743    'page callback' => '_proyectos_reformulacion_reformula_list_page',
744    'page arguments' => array(1),
745    'weight' => 2,
746  );
747  $items['proyectosop/%proyectosop/reformular/list'] = array(
748    'title' => 'Modificaciones',
749    'type' => MENU_DEFAULT_LOCAL_TASK,
750    'weight' => -10
751  );
752  $items['proyectosop/%proyectosop/reformular/add'] = array(
753    'title' => 'Agregar Modificación',
754    'type' => MENU_LOCAL_TASK,
755    'access callback' => '_proyectos_reformulacion_reformula_node_add_tab_access',
756    'access arguments' => array(1),
757    'page callback' => 'drupal_get_form',
758    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_form', 1),
759    'weight' => 2,
760  );
761  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/view'] = array(
762    'title' => 'Ver modificación',
763    'type' => MENU_LOCAL_TASK,
764    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
765    'access arguments' => array(1),
766    'page callback' => '_proyectos_reformulacion_reformula_tab_page_ver',
767    'page arguments' => array(1, 3),
768    'weight' => 2,
769  );
770  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/edit'] = array(
771    'title' => 'Editar',
772    'type' => MENU_LOCAL_TASK,
773    'access callback' => '_proyectos_reformulacion_reformula_node_edit_tab_access',
774    'access arguments' => array(1, 3),
775    'page callback' => 'drupal_get_form',
776    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_form', 1, 3),
777    'weight' => 3,
778  );
779  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/ae/%accionesp_menu_r'] = array(
780    'title' => 'Acciones Especificas',
781    'type' => MENU_LOCAL_TASK,
782    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
783    'access arguments' => array(1),
784    'page callback' => '_proyectos_reformulacion_reformula_tab_page_ver_ae',
785    'page arguments' => array(1, 3, 5),
786    'weight' => 2,
787  );
788  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/ae/%accionesp_menu_r/edit'] = array(
789    'title' => 'Editar AEs',
790    'type' => MENU_LOCAL_TASK,
791    'access callback' => '_proyectos_reformulacion_reformula_node_edit_tab_access',
792    'access arguments' => array(1, 3),
793    'page callback' => 'drupal_get_form',
794    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_ae_form', 1, 3, 5),
795    'weight' => 3,
796  );
797  $items['proyectosop/%node/reformular/%proyectosop_menu_reformulacion/workflow/%proyectos_reformulacion_wk_menu'] = array(
798    'title' => 'Workflow',
799    'type' => MENU_LOCAL_TASK,
800    'access callback' => '_proyectos_reformulacion_reformula_wk_node_tab_access',
801    'access arguments' => array(1, 3, 5),
802    'page callback' => 'drupal_get_form',
803    'page arguments' => array('proyectos_reformulacion_reformula_wk_tab_page_form', 1, 3, 5),
804    'weight' => 3,
805  );
806  return $items;
807}
808
809/**
810 * Implementation of hook_theme().
811 */
812function proyectos_reformulacion_theme() {
813  return array(
814    'proyectos_reformulacion_reformula_tab_page_form' => array(
815      'arguments' => array('form' => NULL),
816    ),
817    'proyectos_reformulacion_reformula_tab_page_ae_form' => array(
818      'arguments' => array('form' => NULL),
819    ),
820  );
821}
822
823/*
824 * Implementation of proyectos_reformulacion_reformula_tab_page_form()
825 */
826function proyectos_reformulacion_reformula_tab_page_form($form_state, $node, $reformulacion_load = 0) {
827  $title = $reformulacion_load ? t('Editar Modificación') : t('Agregar Modificación al Proyecto');
828  drupal_set_title($title);
829  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
830  $breadcrumb = array();
831  $breadcrumb[] = l(t('Home'), '<front>');
832  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
833  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
834  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
835  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
836  $breadcrumb[] = $title;
837  // Set Breadcrumbs
838  drupal_set_breadcrumb($breadcrumb);
839  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
840  $reformula = _proyectos_reformulacion_load($node, $id_ref);
841  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
842  $field = content_fields('field_proyecto_unidadm', 'proyectos_operativos');
843  $unidad_ant = $node->field_proyecto_unidadm[0]['value'];
844  $text_unidad = t('N/A');
845  $tree = taxonomy_get_tree($field['vid']);
846  $options = array();
847  if ($tree) {
848    foreach ($tree as $term) {
849      if ($term->tid == $unidad_ant) {
850        $text_unidad = $term->name;
851      }
852      $choice = new stdClass();
853      $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
854      $options[] = $choice;
855    }
856  }
857  $field = content_fields('field_accion_esp_unidadm', 'accion_especifica');
858  $unidadesm = array();
859  $tree = taxonomy_get_tree($field['vid']);
860  if ($tree) {
861    foreach ($tree as $term) {
862      $unidadesm[$term->tid] = $term->name;
863    }
864  }
865  $form['field_proyecto_unidadm_ant'] = array(
866    '#title' => t('Unidad de Medida Actual'),
867    '#type' => 'textfield',
868    '#value' =>  $text_unidad,
869    '#attributes' => array('class' => 'campo-bloqueado '),
870  );
871  $valor_medida = $reformula['unidad'] ? $reformula['unidad'] : $node->field_proyecto_unidadm[0]['value'];
872  $form['field_proyecto_unidadm'] = array(
873    '#title' => t('Unidad de Medida Nueva'),
874    '#type' => 'select',
875    '#options' => $options,
876    '#default_value' => $valor_medida,
877  );
878  $ftypes = array(
879    'value' => t('January'),
880    'value_1' => t('February'),
881    'value_2' => t('March'),
882    'value_3' => t('April'),
883    'value_4' => t('May'),
884    'value_5' => t('June'),
885    'value_6' => t('July'),
886    'value_7' => t('August'),
887    'value_8' => t('September'),
888    'value_9' => t('Octuber'),
889    'value_10' => t('November'),
890    'value_11' => t('December'),
891  );
892  $grupos = array();
893  if ($node->field_proyecto_accion_esp[0]['nid']) {
894    foreach($node->field_proyecto_accion_esp as $ae) {
895      $grupos[$ae['nid']] = node_load($ae['nid']);
896      $array[$ae['nid']] = node_load($ae['nid']);
897    }
898  }
899  $varia = isset($variaciones['total']) ? $variaciones['total'] : 0;
900  $min = $node->field_proyecto_monto_anual[0]['value'] + $varia;
901  $form['#monto_reformulado'] = $min;
902  $valor = isset($reformulacion_load->variacion)? $reformulacion_load->variacion : 0;
903  $suma_variacion['primero'] = $min;
904  $total_accion = $min;
905  $idformuj = 'variacion';
906  $id_field = 'primero';
907  $fecha = array();
908  $fecha['dia'] = $reformula['fecha_onapre'] ? date('j', $reformula['fecha_onapre']) : date('j');
909  $fecha['mes'] = $reformula['fecha_onapre'] ? date('n', $reformula['fecha_onapre']) : date('m');
910  $fecha['year'] = $reformula['fecha_onapre'] ? date('Y', $reformula['fecha_onapre']) : date('Y');
911  $form['fecha_onapre'] = array(
912    '#type' => 'date',
913    '#title' => t('Fecha de Aprobación'),
914    '#default_value' => array('day' => $fecha['dia'], 'month' => $fecha['mes'], 'year' => $fecha['year']),
915    '#required' => TRUE,
916  );
917  $valor_justificacion = isset($reformula['justificacion'])? $reformula['justificacion'] : '';
918  $form['justificacion'] = array(
919    '#title' => t('Justificación'),
920    '#type' => 'textarea',
921    '#default_value' => $valor_justificacion,
922  );
923
924  $form['variacion'] = array(
925    '#type' => 'textfield',
926    '#title' => t('Variación Presupuestaria'),
927    '#default_value' => $valor,
928    '#size' => 30,
929    '#suffix' => '<div class="texto-variacion">' . t('Estimado Usuario: El monto a ingresar debe comenzar con el signo mas "+" o con el signo menos "-".') . '</div>',
930    '#attributes' => array('class' => $clase . ' field-variacion number', 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref2('" . 'field-variacion' . "', 'variacion', '" . $id_field . "');"),
931  );
932  $form['traspaso'] = array(
933    '#type' => 'checkbox',
934    '#title' => t('Traspaso'),
935    '#default_value' => (isset($reformula['tipo']) && $reformula['tipo'] == 1),
936  );
937
938
939  $form['variaciont'] = array(
940    '#type' => 'textfield',
941    '#title' => t('Monto Total de la Modificación'),
942    '#default_value' => $min + $valor,
943    '#size' => 30,
944    '#attributes' => array('class' => 'campo-bloqueado field-variacion-total number1'),
945  );
946  $form['#state_creation'] = -1;
947  //get first state
948  if (module_exists('workflow')) {
949    $estados = _proyectos_operativos_reformulacion_obtiene_estados();
950    $estado_inicial = variable_get('proyectos_operativos_state_reformulacion', 0);
951    if ($estados['wid']) {
952      if ($estado_inicial && $estados['states'][$estado_inicial]) {
953        $form['#state_creation'] = $estado_inicial;
954      }
955      else {
956        $form['#state_creation'] = _workflow_creation_state($estados['wid']);
957      }
958    }
959  }
960  $form['#node'] = $node;
961  $form['#ftypes'] = $ftypes;
962  $form['#grupos'] = $grupos;
963  $form['#unidadesm'] = $unidadesm;
964  $form['#variaciones'] = $variaciones;
965  $form['#reformula'] = $reformula;
966  $form['#id_ref'] = $id_ref;
967  $form['#total_accion'] = $total_accion;
968  $mes_inicio = 0;
969  $mes_fin = 12;
970  if (!variable_get('proyectos_operativos_reformulacion_meses', TRUE)) {
971    $f_aux = explode(' ', $node->field_proyecto_fecha_i[0]['value']);
972    $f_aux = explode('-', $f_aux[0]);
973    $mes_inicio = (int) $f_aux[1];
974    $f_aux = explode(' ', $node->field_proyecto_fecha_f[0]['value']);
975    $f_aux = explode('-', $f_aux[0]);
976    $mes_fin = (int) $f_aux[1];
977  }
978  $form['#mes'] = variable_get('accion_especifica_de_proyecto_seguimiento_anho_seguimiento', 0) == $node->anhoproyectos_operativos ? variable_get('accion_especifica_de_proyecto_seguimiento_mes_seguimiento', 0) - 1 : 0;
979  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
980  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
981  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
982  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
983  $format_number = array(
984    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
985    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
986    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
987  );
988  $form['#format_number'] = array('format_number' => $format_number);
989  drupal_add_js($form['#format_number'], 'setting');
990  $i = 1;
991  $sumafisica = 0;
992  $sumaT = 0;
993  $sumaTv = 0;
994  $sumaplanm = array();
995  foreach($ftypes as $id_field => $texto) {
996    $clase = '';
997    if ($form['#mes'] >= $i) {
998      $clase .= 'campo-bloqueado ';
999    }
1000    elseif($mes_inicio > $i) {
1001      $clase .= 'campo-bloqueado ';
1002    }
1003    elseif($mes_fin < $i) {
1004      $clase .= 'campo-bloqueado ';
1005    }
1006    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
1007    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
1008    $total_accion += $min;
1009    $valor = isset($reformula['field_proyecto_meta_fisica'][0][$id_field])? $reformula['field_proyecto_meta_fisica'][0][$id_field] : 0;
1010    $sumafisica += $valor;
1011    $sumaT += $min + $valor;
1012    $idformuj = str_replace('_', '-', 'field_proyecto_meta_fisica_' . $id_field);
1013    if (!isset($sumaplanm[$id_field])) {
1014      $sumaplanm[$id_field] = 0;
1015    }
1016    $sumaTv += $min;
1017    $sumaplanm[$id_field] = $min;
1018    $form['field_proyecto_meta_fisica_' . $id_field] = array(
1019      '#type' => 'textfield',
1020      '#default_value' => $valor,
1021      '#size' => 15,
1022      '#attributes' => array('class' => $clase . ' field-proyecto-meta-fisica-r subtotal-' . $id_field . ' number', 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref('" . 'field-proyecto-meta-fisica-r' . "');prsumaref2('" . 'subtotal-' . $id_field . "', 'sumaplan', '" . $id_field . "'); prsumaref('subtotales')"),
1023    );
1024    $form['field_proyecto_meta_fisica_to_' . $id_field] = array(
1025      '#type' => 'textfield',
1026      '#default_value' => $min + $valor,
1027      '#size' => 15,
1028      '#attributes' => array('class' => 'campo-bloqueado subtotales subtotal-' . $id_field . '-total number1'),
1029    );
1030    $i++;
1031  }
1032  $form['field_proyecto_meta_fisica_total'] = array(
1033    '#type' => 'textfield',
1034    '#default_value' => $sumafisica,
1035    '#size' => 15,
1036    '#attributes' => array('class' => 'campo-bloqueado field-proyecto-meta-fisica-r-total number1'),
1037  );
1038  $form['field_proyecto_meta_fisica_totalt'] = array(
1039    '#type' => 'textfield',
1040    '#default_value' => $sumaT,
1041    '#size' => 15,
1042    '#attributes' => array('class' => 'campo-bloqueado subtotales-total number1'),
1043  );
1044  $sumaacciones = 0;
1045  $sumaaccionm = array();
1046  $sumaaccionv = 0;
1047  foreach($grupos as $nid => $ae) {
1048    $i = 1;
1049    $sumaP = 0;
1050    $valor_unidad = $reformula['field_accion_esp_metaf_' . $nid][0]['unidad'] ? $reformula['field_accion_esp_metaf_' . $nid][0]['unidad'] : $ae->field_accion_esp_unidadm[0]['value'];
1051    $form[$nid . '_field_accion_esp_metaf_unidadm'] = array(
1052      '#title' => t('Unidad de Medida Nueva'),
1053      '#type' => 'select',
1054      '#options' => $options,
1055      '#default_value' => $valor_unidad,
1056    );
1057    foreach($ftypes as $id_field => $texto) {
1058      $clase = '';
1059      if ($form['#mes'] >= $i) {
1060        $clase = 'campo-bloqueado ';
1061      }
1062      elseif($mes_inicio > $i) {
1063        $clase .= 'campo-bloqueado ';
1064      }
1065      elseif($mes_fin < $i) {
1066        $clase .= 'campo-bloqueado ';
1067      }
1068      $idformuj = str_replace('_', '-', $nid . '_field_accion_esp_metaf_' . $id_field);
1069      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1070      $min = $ae->field_accion_esp_metaf[0][$id_field] + $varia;
1071      $total_accion += $min;
1072      $valor = isset($reformula['field_accion_esp_metaf_' . $nid][0][$id_field])? $reformula['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1073      $sumaacciones += $min + $valor;
1074      $sumaP += $valor;
1075      if (!isset($sumaaccionm[$id_field])) {
1076        $sumaaccionm[$id_field] = 0;
1077      }
1078      $sumaaccionv += $min;
1079      $sumaaccionm[$id_field] += $min;
1080      $form[$nid . '_field_accion_esp_metaf_' . $id_field] = array(
1081        '#type' => 'textfield',
1082        '#default_value' => $valor,
1083        '#size' => 15,
1084        '#attributes' => array('class' => $clase . ' ' . $nid . '-field-accion-esp-metaf subtotal1-' . $id_field . ' number', 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref('" . $nid . '-field-accion-esp-metaf' . "');prsumaref2('" . 'subtotal1-' . $id_field . "', 'sumaaccion', '" . $id_field . "'); prsumaref('subtotales1');sumatotalAE('" . $idformuj . "'," . $min . ");"),
1085      );
1086      $i++;
1087    }
1088    $form[$nid . '_field_accion_esp_metaf_t'] = array(
1089      '#type' => 'textfield',
1090      '#default_value' => $sumaP,
1091      '#size' => 15,
1092      '#attributes' => array('class' => 'campo-bloqueado ' . $nid . '-field-accion-esp-metaf-total number1'),
1093    );
1094  }
1095  foreach($ftypes as $id_field => $texto) {
1096    $form['field_accion_esp_metaft_' . $id_field] = array(
1097      '#type' => 'textfield',
1098      '#default_value' => $sumaaccionm[$id_field],
1099      '#size' => 15,
1100      '#attributes' => array('class' => 'campo-bloqueado subtotales1 subtotal1-' . $id_field . '-total number1'),
1101    );
1102  }
1103  $form['field_accion_esp_metaftt'] = array(
1104    '#type' => 'textfield',
1105    '#default_value' => $sumaacciones,
1106    '#size' => 15,
1107    '#attributes' => array('class' => 'campo-bloqueado subtotales1-total number1'),
1108  );
1109  $jse = array(
1110    'sumatotal' => $sumaTv,
1111    'sumaplan' => $sumaplanm,
1112    'sumaacciones' => $sumaaccionv,
1113    'sumaaccion' => $sumaaccionm,
1114    'variacion' => $suma_variacion,
1115  );
1116  $form['#jse'] = $jse;
1117  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
1118  $form['buttons'] = array(
1119    '#prefix' => '<div class="container-inline">',
1120    '#suffix' => '</div>',
1121  );
1122  $form['buttons']['registrar'] = array(
1123    '#type' => 'submit',
1124    '#default_value' => t('Guardar'),
1125    '#weight' => 100,
1126  );
1127  $form['buttons']['cancelar'] = array(
1128    '#type' => 'submit',
1129    '#default_value' => t('Cancelar'),
1130    '#weight' => 101,
1131  );
1132  return $form;
1133}
1134
1135/*
1136 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
1137 */
1138function proyectos_reformulacion_reformula_tab_page_form_validate($form, &$form_state) {
1139  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1140  if ($op == t('Cancelar')) {
1141    return;
1142  }
1143  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
1144  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
1145  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
1146  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
1147  drupal_add_js($form['#format_number'], 'setting');
1148  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
1149  $start = $form_state['values']['variacion'];
1150  $value = preg_replace('@[^-0-9]@', '', $start);
1151  if ($start != $value) {
1152    form_set_error('variacion', t('Solo números enteros son permitidos en la variación presupuestaria.'));
1153  }
1154  $ftypes = $form['#ftypes'];
1155  foreach($ftypes as $id_field => $texto) {
1156    $start = $form_state['values']['field_proyecto_meta_fisica_' . $id_field];
1157    $value = preg_replace('@[^-0-9]@', '', $start);
1158    if ($start != $value) {
1159      form_set_error('field_proyecto_meta_fisica_' . $id_field, t('Solo números enteros son permitidos en la meta física.'));
1160    }
1161
1162    if ($form_state['values']['field_proyecto_meta_fisica_' . $id_field] + $form['#jse']['sumaplan'][$id_field] < 0) {
1163      form_set_error('field_proyecto_meta_fisica_' . $id_field, t('El valor para modificar la meta física no puede ser menor que cero'));
1164    }
1165  }
1166  foreach($form['#grupos'] as $nid => $grupo) {
1167    foreach($ftypes as $id_field => $texto) {
1168      $start = $form_state['values'][$nid . '_field_accion_esp_metaf_' . $id_field];
1169      $value = preg_replace('@[^-0-9]@', '', $start);
1170      if ($start != $value) {
1171        form_set_error($nid . '_field_accion_esp_metaf_' . $id_field, t('Solo números enteros son permitidos en la meta física de las AEs.'));
1172      }
1173    }
1174  }
1175}
1176
1177/*
1178 * Implementation of proyectos_reformulacion_reformula_tab_page_form_submit()
1179 */
1180function proyectos_reformulacion_reformula_tab_page_form_submit($form, &$form_state) {
1181  global $user;
1182  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1183  if ($op == t('Cancelar')) {
1184    drupal_set_message(t('La modificación ha sido cancelada.'));
1185    if ($form['#id_ref']) {
1186      $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref'] . '/view';
1187    }
1188    else {
1189      $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular';
1190    }
1191    return;
1192  }
1193  $fecha_onapre = mktime(0, 0, 0, $form_state['values']['fecha_onapre']['month'], $form_state['values']['fecha_onapre']['day'], $form_state['values']['fecha_onapre']['year']);
1194  $ftypes = $form['#ftypes'];
1195  $id_ref = $form['#id_ref'];
1196  $campos = array();
1197  $justificacion = check_plain($form_state['values']['justificacion']);
1198  $campos[] = "field_name = 'field_proyecto_meta_fisica'";
1199  foreach($form['#grupos'] as $nid => $grupo) {
1200    $campos[] = "'field_accion_esp_metaf_" . $nid . "'";
1201  }
1202  db_query("DELETE FROM {proyectos_reformula} WHERE nid = %d AND id_ref = %d AND ae = 0", $form['#node']->nid, $id_ref);
1203  if(!$id_ref) {
1204    db_query("INSERT INTO {proyectos_reformular} (uid, nid, estado, date, estado_ant, monto, variacion, unidad, fecha_onapre, justificacion) VALUES (%d, %d, %d, %d, 0, %f, 0, %d, %d, '%s')", $user->uid, $form['#node']->nid, $form['#state_creation'], time(), $form['#total_accion'], $form['#node']->field_proyecto_unidadm[0]['value'], $fecha_onapre, $justificacion);
1205    $id_ref = db_last_insert_id('proyectos_reformular', 'id_ref');
1206  }
1207  $field = array();
1208  $field[] = $id_ref;
1209  $field[] = 'field_proyecto_meta_fisica';
1210  $field[] = 0;
1211  $field[] = $form['#node']->nid;
1212  foreach($ftypes as $id_field => $texto) {
1213    $field[] = $form_state['values']['field_proyecto_meta_fisica_' . $id_field];
1214  }
1215  db_query("INSERT INTO {proyectos_reformula} (id_ref, field_name, partida, nid, value, value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, ae) VALUES (%d, '%s', %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, 0)", $field);
1216  foreach($form['#grupos'] as $nid => $grupo) {
1217    $field = array();
1218    $field[] = $id_ref;
1219    $field[] = 'field_accion_esp_metaf_' . $nid;
1220    $field[] = 0;
1221    $field[] = $form['#node']->nid;
1222    foreach($ftypes as $id_field => $texto) {
1223      $field[] = $form_state['values'][$nid . '_field_accion_esp_metaf_' . $id_field];
1224    }
1225    $field[] = $form_state['values'][$nid . '_field_accion_esp_metaf_unidadm'];
1226    db_query("INSERT INTO {proyectos_reformula} (id_ref, field_name, partida, nid, value, value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, ae, unidad) VALUES (%d, '%s', %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, 0, %d)", $field);
1227  }
1228  drupal_set_message(t('La modificación fue actualizada'));
1229  $tipo = 1;
1230  if (!$form_state['values']['traspaso'] && $form_state['values']['variacion'] < 0){
1231    $tipo = 3;
1232  }
1233  elseif(!$form_state['values']['traspaso'] && $form_state['values']['variacion'] > 0) {
1234    $tipo = 2;
1235  }
1236  db_query("UPDATE {proyectos_reformular} SET variacion = %d, unidad = %d, fecha_onapre = %d, justificacion = '%s', tipo = %d WHERE nid = %d AND id_ref = %d", $form_state['values']['variacion'], $form_state['values']['field_proyecto_unidadm'], $fecha_onapre, $justificacion, $tipo, $form['#node']->nid, $id_ref);
1237  $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $id_ref . '/view';
1238}
1239
1240/*
1241 * Implementation of _proyectos_reformulacion_load()
1242 */
1243function _proyectos_reformulacion_load($node, $id_ref = 0) {
1244  $reformula_load = proyectosop_menu_reformulacion_load($id_ref, $node);
1245  $reformula = array();
1246  $inputs = array();
1247  $sql = "SELECT * FROM {proyectos_reformula} WHERE nid = %d";
1248  $sql1 = "SELECT * FROM {proyectos_reformula_fuente} WHERE nid = %d";
1249  $inputs[] = $node->nid;
1250  if ($reformula_load) {
1251    $reformula['total'] = $reformula_load->variacion;
1252    $reformula['unidad'] = $reformula_load->unidad;
1253    $reformula['fecha_onapre'] = $reformula_load->fecha_onapre;
1254    $reformula['justificacion'] = $reformula_load->justificacion;
1255    $reformula['estado'] = $reformula_load->estado;
1256    $reformula['tipo'] = $reformula_load->tipo;
1257    $sql .= ' AND id_ref = %d';
1258    $sql1 .= ' AND id_ref = %d';
1259    $inputs[] = $id_ref;
1260    $result = db_query($sql, $inputs);
1261    while($partida = db_fetch_array($result)) {
1262      $reformula[$partida['field_name']][$partida['partida']] = $partida;
1263    }
1264    $result = db_query($sql1, $inputs);
1265    while($partida = db_fetch_array($result)) {
1266      $reformula[$partida['field_name']][0] = $partida;
1267    }
1268  }
1269  return $reformula;
1270}
1271
1272/*
1273 * Implementation of _proyectos_reformula_all_load()
1274 */
1275function _proyectos_reformula_all_load($node, $id_ref = 0) {
1276  $reformulaciones = array();
1277  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1278  $result = db_query("SELECT * FROM {proyectos_reformular} WHERE nid = %d AND estado = %d ORDER BY id_ref DESC", $node->nid, $estado_aprobado);
1279  while($reformula = db_fetch_array($result)) {
1280    $reformulaciones[$reformula['id_ref']] = $reformula;
1281  }
1282  return $reformulaciones;
1283}
1284
1285/*
1286 * Implementation of _proyectos_reformulacion_reformula_all_partidas_load()
1287 */
1288function _proyectos_reformula_all_partidas_load($node, $id_ref = 0) {
1289  $variaciones = array();
1290  $ftypes = array(
1291    'value' => t('January'),
1292    'value_1' => t('February'),
1293    'value_2' => t('March'),
1294    'value_3' => t('April'),
1295    'value_4' => t('May'),
1296    'value_5' => t('June'),
1297    'value_6' => t('July'),
1298    'value_7' => t('August'),
1299    'value_8' => t('September'),
1300    'value_9' => t('Octuber'),
1301    'value_10' => t('November'),
1302    'value_11' => t('December'),
1303    'unidad' => t('Unidad'),
1304  );
1305  $load_reformulaciones = array();
1306  $reformulaciones = _proyectos_reformula_all_load($node, $id_ref);
1307  if ($id_ref) {
1308    foreach($reformulaciones as $id => $value) {
1309      if ($id < $id_ref) {
1310        $load_reformulaciones[$id] = $values;
1311      }
1312    }
1313  }
1314  else {
1315    $load_reformulaciones = $reformulaciones;
1316  }
1317  $current_id = 0;
1318  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1319  if(count($load_reformulaciones)) {
1320    foreach($load_reformulaciones as $id => $value) {
1321      $nueva_variacion = _proyectos_reformulacion_load($node, $id);
1322      if ($estado_aprobado == $nueva_variacion['estado'] && !$current_id) {
1323        $current_id = $id;
1324      }
1325      elseif($estado_aprobado == $nueva_variacion['estado'] && $current_id && $id > $current_id) {
1326        $current_id = $id;
1327      }
1328      if(count($nueva_variacion)) {
1329        foreach($nueva_variacion as $id_campo => $campo) {
1330          if ($id_campo != 'total' && $id_campo != 'unidad') {
1331            if(is_array($campo) && count($campo)) {
1332              foreach($campo as $id_partida => $partida) {
1333                if (!isset($variaciones[$id_campo][$id_partida]['partida'])) {
1334                  $variaciones[$id_campo][$id_partida]['partida'] = $partida['partida'];
1335                }
1336                foreach($ftypes as $idc => $valor) {
1337                  if (!isset($variaciones[$id_campo][$id_partida][$idc])) {
1338                    $variaciones[$id_campo][$id_partida][$idc] = 0;
1339                  }
1340                  if ($idc == 'unidad') {
1341                    if ($current_id == $id) {
1342                      $variaciones[$id_campo][$id_partida][$idc] = $partida[$idc];
1343                    }
1344                  }
1345                  else {
1346                    $variaciones[$id_campo][$id_partida][$idc] += $partida[$idc];
1347                  }
1348                }
1349              }
1350            }
1351          }
1352          else {
1353            if ($id_campo == 'total') {
1354              if (!isset($variaciones['total'])) {
1355                $variaciones['total'] = 0;
1356              }
1357              $variaciones['total'] += $campo;
1358            }
1359            else {
1360              $variaciones['unidad'] = $campo;
1361            }
1362          }
1363        }
1364      }
1365    }
1366  }
1367  return $variaciones;
1368}
1369
1370/*
1371 * Implementation of theme_proyectos_reformulacion_reformula_tab_page_form()
1372 */
1373function theme_proyectos_reformulacion_reformula_tab_page_form($form) {
1374  $node = $form['#node'];
1375  $variaciones = $form['#variaciones'];
1376  $reformula = $form['#reformula'];
1377  $planificado = t('planificado');
1378  $total_AE_text = t('Total AE');
1379  $variacion = t('variación');
1380  $reformula = _proyectos_reformulacion_load($node, $id_ref);
1381  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
1382  $output = '<p align="justify">Condiciones de las modificaciones de los proyectos:</p>
1383<ol>
1384<li>Los traspasos de créditos presupuestarios entre partidas cedentes o receptoras de un mismo o distintos proyecto o categoría equivalente a proyecto o acciones centralizadas, mayores al veinte por ciento (20%) serán autorizados por la Oficina Nacional de Presupuesto. Los traspasos de hasta el veinte por ciento (20%) y mayores al diez por ciento (10%), deberán ser autorizados por la máxima autoridad del órgano de adscripción; y los traspasos de hasta el diez por ciento (10%) los autorizará la máxima autoridad del ente descentralizado conforme a lo que establezca el manual de procedimientos del sistema de modificaciones presupuestarias del ente, y notificados al órgano de adscripción.</li>
1385<li>Las modificaciones que impliquen incremento superior al veinte por ciento (20%) en el total de los créditos originalmente aprobados en su presupuesto, que surjan como producto de una nueva fuente de financiamiento o por un incremento de los recursos inicialmente previstos serán autorizados por la Oficina Nacional de Presupuesto. Dichas modificaciones de hasta el veinte por ciento (20%) y mayores al diez por ciento (10%), deberán ser autorizados por la máxima autoridad del organismo de adscripción; y las modificaciones de hasta el diez por ciento (10%) la autorizará la máxima autoridad del ente descentralizado conforme a lo que establezca el manual de procedimientos del sistema de modificaciones presupuestarias del ente, y notificados al órgano de adscripción.</li>
1386<li>Las modificaciones que impliquen disminuciones de gastos corrientes, que surjan por efecto de disminución de ingresos corrientes o de capital, superiores al veinte por ciento (20%) en el total de los créditos originalmente aprobados en su presupuesto, serán autorizados por la Oficina Nacional de Presupuesto. Dichas modificaciones de hasta el veinte por ciento (20%) y mayores al diez por ciento (10%), deberán ser autorizados por la máxima autoridad del organismo de adscripción; y las modificaciones de hasta el diez por ciento (10%) los autorizará la máxima autoridad del ente descentralizado conforme a lo que establezca el manual de procedimientos del sistema de modificaciones presupuestarias del ente, y notificados al organismo de adscripción.</li>
1387<p align="justify">Cuando la suma de los traspasos que afecten a una misma partida, cedente o receptora, alcance o supere al veinte por ciento (20%) o al diez por ciento (10%) respectivamente, de los créditos originales, deberán ser aprobados conforme a lo previsto en el presente artículo.</p>';
1388  $output .= '<fieldset><legend>' . t('Monto Total del Proyecto') . '</legend>';
1389  $rows = array();
1390  $row = array();
1391  $row[] = array('data' => drupal_render($form['fecha_onapre']) . drupal_render($form['traspaso']));
1392  $row[] = array('data' => drupal_render($form['justificacion']));
1393  $rows[] = $row;
1394  $row = array();
1395  $row[] = array('data' => '<b>' . t('Monto Total del Proyecto para el año en curso: %monto', array('%monto' => number_format($form['#monto_reformulado'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))) . '</b>', 'colspan' => 2, 'align' => center);
1396  $rows[] = $row;
1397  $row = array();
1398  $row[] = array('data' => drupal_render($form['variacion']), );
1399  $row[] = array('data' => drupal_render($form['variaciont']), );
1400  $rows[] = $row;
1401  $output .= theme('table', array(), $rows) . '</fieldset>';
1402  $output .= '<fieldset><legend>' . t('Distribución de la Meta Física') . '</legend>';
1403  $output .= '<fieldset><legend>' . t('Meta Física del Proyecto') . '</legend>';
1404  $output .= drupal_render($form['field_proyecto_unidadm_ant']);
1405  $output .= drupal_render($form['field_proyecto_unidadm']);
1406  $header = array();
1407  $header[] = array('data' => t('Meta Física del Proyecto'));
1408  $rows = array();
1409  $row = array();
1410  $row1 = array();
1411  $row2 = array();
1412  $row[] = array('data' => $planificado, );
1413  $row1[] = array('data' => $variacion, );
1414  $row2[] = array('data' => '<b>' . t('TOTAL') . '</b>', );
1415  $min_planificado = 0;
1416  foreach($form['#ftypes'] as $id_field => $texto) {
1417    $header[] = array('data' => $texto);
1418    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
1419    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
1420    $min_planificado += $min;
1421    $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1422    $row1[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_' . $id_field]), );
1423    $row2[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_to_' . $id_field]), );
1424  }
1425  $row[] = array('data' => number_format($min_planificado, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1426  $row1[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_total']), );
1427  $row2[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_totalt']), );
1428  $rows[] = $row;
1429  $rows[] = $row1;
1430  $rows[] = $row2;
1431  $header[] = array('data' => t('TOTAL'));
1432  $output .= theme('table', $header, $rows);
1433  $output .= '<div class="texto-proyecto-metafisica">' . t('Estimado Usuario: El monto a ingresar debe comenzar con el signo mas "+" o con el signo menos "-".') . '</div>';
1434  $output .= '</fieldset>';
1435  $output .= '<fieldset><legend>' . t('Meta Física de las Acciones Específicas') . '</legend>';
1436  $header = array();
1437  $header[] = array('data' => t('Meta Física de las AEs'));
1438  $header[] = array('data' => t('Unidad de Medida'));
1439  $header[] = array('data' => t('% de la AEs'),);
1440  $header[] = array('data' => '-',);
1441  foreach($form['#ftypes'] as $id_field => $texto) {
1442    $header[] = array('data' => $texto);
1443  }
1444  $header[] = array('data' => t('TOTAL'));
1445  $rows = array();
1446  $rowsF = array();
1447  $i = 0;
1448    $rowF = array();
1449    $rowF[] = array('data' => '<b>' . t('Número') . '</b>', 'align' => center,);
1450    $rowF[] = array('data' => '<b>' . t('Nombre') . '</b>', 'align' => center,);
1451    $rowsF[] = $rowF;
1452  foreach($form['#grupos'] as $nid => $grupo) {
1453    $i++;
1454    $row = array();
1455    $rowF = array();
1456    $row1 = array();
1457    $row2 = array();
1458    $rowF[] = array('data' => t('AE %numero', array('%numero' => $i)));
1459    $rowF[] = array('data' => $grupo->titulo_asignado);
1460    $rowsF[] = $rowF;
1461    $row[] = array('data' => t('AE %numero', array('%numero' => $i)), 'rowspan' => 3);
1462    $row[] = array('data' => $form['#unidadesm'][$grupo->field_accion_esp_unidadm[0]['value']] . drupal_render($form[$nid . '_field_accion_esp_metaf_unidadm']), 'rowspan' => 3);
1463    $row[] = array('data' => $grupo->field_accion_esp_ponderacion[0]['value'], 'rowspan' => 3);
1464    $row[] = array('data' => $planificado, );
1465    $row1[] = array('data' => $variacion, );
1466    $row2[] = array('data' => $total_AE_text, );
1467    $min_planificado = 0;
1468    $total_AE = 0;
1469    $min_partida = 0;
1470    foreach($form['#ftypes'] as $id_field => $texto) {
1471      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1472      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1473      $min_partida += $min;
1474    }
1475    foreach($form['#ftypes'] as $id_field => $texto) {
1476      $idformuj = str_replace('_', '-', $nid . '_field_accion_esp_metaf_' . $id_field);
1477      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1478      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1479      $min_planificado += $min;
1480      $total_AE += $min + $form[$nid . '_field_accion_esp_metaf_' . $id_field]['#value'];
1481      $form[$nid . '_field_accion_esp_metaf_' . $id_field]['#attributes']['onchange'] .= "sumatotalAE('" . $nid . '-field-accion-esp-metaf-t' . "', " . $min_partida . ");";
1482      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1483      $row1[] = array('data' => drupal_render($form[$nid . '_field_accion_esp_metaf_' . $id_field]), );
1484      $row2[] = array('data' => '<div id ="' . $idformuj . '-texto">' . number_format($min + $form[$nid . '_field_accion_esp_metaf_' . $id_field]['#value'], 0, $format_number['dec_point'], $format_number['thousands_sep']) . '</div>', );
1485    }
1486    $row[] = array('data' => number_format($min_planificado, 0, ',', '.'), );
1487    $row1[] = array('data' => drupal_render($form[$nid . '_field_accion_esp_metaf_t']), );
1488    $row2[] = array('data' => '<div id ="' . $nid . '-field-accion-esp-metaf-t-texto' . '">' . number_format($total_AE, 0, $format_number['dec_point'], $format_number['thousands_sep']) . '</div>', );
1489    $rows[] = $row;
1490    $rows[] = $row1;
1491    $rows[] = $row2;
1492  }
1493  $row = array();
1494  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 4, 'align' => 'right');
1495  foreach($form['#ftypes'] as $id_field => $texto) {
1496    $row[] = array('data' => drupal_render($form['field_accion_esp_metaft_' . $id_field]), );
1497  }
1498  $row[] = array('data' => drupal_render($form['field_accion_esp_metaftt']), );
1499  $rows[] = $row;
1500  $output .= theme('table', $header, $rows);
1501  $output .= '<div class="texto-proyecto-metafisica">' . t('Estimado Usuario: El monto a ingresar debe comenzar con el signo mas "+" o con el signo menos "-".') . '</div>';
1502  $header = array();
1503  $header[] = array('data' => t('Detalles de las Acciones Específicas'), 'colspan' => 2, 'align' => center);
1504  $output .= theme('table', $header, $rowsF);
1505  $output .= '</fieldset>';
1506  $output .= '</fieldset>';
1507  $output .= '<div id="acciones-centralizadas-form-acciones">' . drupal_render($form) .'</div>';
1508  return $output;
1509}
1510
1511/**
1512 * Implementation of _proyectos_operativos_reformula_obtiene_estados().
1513 * Obtiene los estados del tipo de contenido proyecto.
1514 */
1515function _proyectos_operativos_reformulacion_obtiene_estados() {
1516  $estados = array();
1517  $wid = 0;
1518  if (module_exists('workflow')) {
1519    $wid = workflow_get_workflow_for_type('proyectos_operativos');
1520    if ($wid){
1521      $estados = workflow_get_states($wid);
1522    }
1523  }
1524  return array(
1525    'wid' => $wid,
1526    'states' => $estados,
1527  );
1528}
1529
1530/*
1531 * Implementation of _proyectos_reformulacion_reformula_list_page()
1532 */
1533function _proyectos_reformulacion_reformula_list_page($node) {
1534  drupal_set_title(t('Modificaciones del Proyecto'));
1535  $output = '';
1536  $output .= _proyectos_reformulacion_reformula_obtiene_list_page($node, TRUE);
1537  return $output;
1538}
1539
1540/*
1541 * Implementation of _proyectos_reformulacion_reformula_obtiene_list_page()
1542 */
1543function _proyectos_reformulacion_reformula_obtiene_list_page($node, $muestra = TRUE) {
1544  global $user;
1545  $format_number = array(
1546    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1547    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1548    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1549  );
1550  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1551  $breadcrumb = array();
1552  $breadcrumb[] = l(t('Home'), '<front>');
1553  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
1554  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
1555  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
1556  $breadcrumb[] = drupal_get_title();
1557  // Set Breadcrumbs
1558  drupal_set_breadcrumb($breadcrumb);
1559  $current_time = time();
1560  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
1561  $tipo_plan = 'proyectos_operativos_reformular';
1562  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
1563  $fecha = FALSE;
1564  $ente = usuario_tiene_ente($user->uid);
1565  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1566    $fecha = TRUE;
1567  }
1568  if (!$fecha) {
1569    if ($muestra) {
1570      muestra_mensaje($tipo_plan, $ente_planificador->tipo);
1571    }
1572  }
1573  else {
1574    if ($ente->nid == $ente_planificador->nid) {
1575      $fecha = TRUE;
1576      if ($muestra) {
1577        muestra_mensaje($tipo_plan, $ente_planificador->tipo, 0);
1578      }
1579    }
1580    elseif (!user_access('admin planificador')) {
1581      $fecha = FALSE;
1582    }
1583  }
1584  $tipos = array(
1585    1 => t('Traspaso'),
1586    2 => t('Incremento'),
1587    3 => t('Disminución'),
1588  );
1589  $enlaces_estados = TRUE;
1590  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
1591    $enlaces_estados = FALSE;
1592  }
1593  $states = _proyectos_operativos_reformulacion_obtiene_estados();
1594  $first_state = 0;
1595  if ($states['wid']) {
1596    $first_state = _workflow_creation_state($states['wid']);
1597  }
1598  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
1599  $result = db_query('SELECT re.*, u.name, u.uid FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid WHERE nid = %d AND estado <> %d ORDER BY id_ref DESC', $node->nid, $estado_naprobado);
1600  $header = array();
1601  $header[] = array('data' => t('Fecha'));
1602  $header[] = array('data' => t('Estado Actual'));
1603  $header[] = array('data' => t('Estado Anterior'));
1604  $header[] = array('data' => t('Fecha de Aprobación'));
1605  $header[] = array('data' => t('Monto (Bs)'));
1606  $header[] = array('data' => t('Variación (Bs)'));
1607  $header[] = array('data' => t('Tipo'));
1608  $header[] = array('data' => t('Total monto (Bs)'));
1609  $header[] = array('data' => t('Usuario'));
1610  $header[] = array('data' => t('Acción'));
1611  $rows = array();
1612  $i = 1;
1613  $roles = array_keys($user->roles);
1614  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1615  $editar = ($node->_workflow == $estado_aprobado);
1616  while($reformular = db_fetch_object($result)) {
1617    if ($user->uid == 1) {
1618      // Superuser is special.
1619      $roles_transition = 'ALL';
1620    }
1621    else {
1622      $roles_transition = $roles;
1623      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
1624        $roles_transition += array('author' => 'author');
1625      }
1626    }
1627    $transitions = array();
1628    if ($states['wid']) {
1629      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
1630    }
1631    unset($transitions[$reformular->estado]);
1632    $acciones = array();
1633    $row = array();
1634    $row[] = array('data' => format_date($reformular->date),);
1635    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
1636    $row[] = array('data' => $estado,);
1637    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
1638    $row[] = array('data' => $estado,);
1639    $row[] = array('data' => date( 'd/m/Y', $reformular->fecha_onapre),);
1640    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1641    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1642    $tipo = isset($tipos[$reformular->tipo]) ? $tipos[$reformular->tipo] : 'N/A';
1643    $row[] = array('data' => $tipo,);
1644    $total = $reformular->monto + $reformular->variacion;
1645    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1646    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid),);
1647    //display options
1648    if ($editar) {
1649      $acciones[] = l(t('Ver'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view');
1650    }
1651    if ($add_reformular) {
1652      $acciones[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add');
1653    }
1654    if ($editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
1655      $acciones[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit');
1656    }
1657    if ($enlaces_estados && count($transitions) && $reformular->estado != $estado_aprobado) {
1658      foreach($transitions as $id => $transition) {
1659        $acciones[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/workflow/' . $id);
1660      }
1661    }
1662    $row[] = array('data' =>  theme('item_list', $acciones),);
1663    $rows[] = $row;
1664    $i++;
1665  }
1666  if (!count($rows)) {
1667    $row[] = array('data' => 'No existen reformulaciones para este proyecto', 'colspan' => 10);
1668    $rows[] = $row;
1669  }
1670  $output = '';
1671  if ($node->field_acciones_ente[0]['nid']) {
1672    $output = '<fieldset><legend>' . t('Datos de la Acción Centralizada') . '</legend>';
1673    $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1674    $output .= '<div class="field"><div class="field-label">' . t('Ente') . ':</div>' . l($ente_planificador->title, 'proyectosop/' . $ente_planificador->nid) . '</div>';
1675    $output .= '<div class="field"><div class="field-label">' . t('Año') . ':</div>' . $node->anhoproyectos_operativos . '</div>';
1676    $output .= '<div class="field"><div class="field-label">' . t('Autor') . ':</div>' . l($node->name, 'user/' . $node->uid)  . '</div>';
1677    $output .= '<div class="field"><div class="field-label">' . t('Fecha de creación') . ':</div>' . format_date($node->created)  . '</div>';       
1678    $output .= '<div class="field"><div class="field-label">' . t('Fecha de la última actualización') . ':</div>' . format_date($node->changed)  . '</div>';         
1679    if (module_exists('workflow')) {
1680      $states = _proyectos_operativos_reformulacion_obtiene_estados();
1681      $first_state = _workflow_creation_state($states['wid']);
1682      $estado = $node->_workflow == $first_state ? t('Ingresado') : $states['states'][$node->_workflow];
1683      $output .= '<div class="field"><div class="field-label">' . t('Estado del proyecto') . ':</div>' . $estado . '</div>';
1684    }
1685    $output .= '</fieldset>';
1686  }
1687  $output .= '<fieldset><legend>' . t('Modificaciones del proyecto') . '</legend>';
1688  $output .= theme('table', $header, $rows) . '</fieldset>';
1689  return $output;
1690}
1691
1692/*
1693 * Implementation of total_reformulado_ae()
1694 * Obtiene el monto total de las partidas de las acciones especificas
1695 */
1696function total_reformulado_ae($node, $reformula, $exclude = array()) {
1697  $ae_l = array();
1698  $suma_r_ae = 0;
1699  $ftypes = array(
1700    'value' => t('January'),
1701    'value_1' => t('February'),
1702    'value_2' => t('March'),
1703    'value_3' => t('April'),
1704    'value_4' => t('May'),
1705    'value_5' => t('June'),
1706    'value_6' => t('July'),
1707    'value_7' => t('August'),
1708    'value_8' => t('September'),
1709    'value_9' => t('Octuber'),
1710    'value_10' => t('November'),
1711    'value_11' => t('December'),
1712  );
1713  if ($node->field_proyecto_accion_esp[0]['nid']) {
1714    foreach($node->field_proyecto_accion_esp as $ae) {
1715      $ae_l[$ae['nid']] = $ae['nid'];
1716      if (!isset($exclude[$ae['nid']])) {
1717
1718        if (array_key_exists('field_accion_esp_programacion_' . $ae['nid'], $reformula)) {
1719          foreach($reformula['field_accion_esp_programacion_' . $ae['nid']] as $montos_accion) {
1720            foreach ($ftypes as $clave => $valor) {
1721              $suma_r_ae += $montos_accion[$clave];
1722            }
1723          }
1724        }
1725      }
1726    }
1727  }
1728  return $suma_r_ae;
1729}
1730
1731/*
1732 * Implementation of _proyectos_reformulacion_reformula_tab_page_ver()
1733 */
1734function _proyectos_reformulacion_reformula_tab_page_ver($node, $reformulacion_load = 0, $show_variacion = TRUE, $muestra = TRUE) {
1735  drupal_set_title(t('Consultar Modificación'));
1736  global $user;
1737  $format_number = array(
1738    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1739    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1740    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1741  );
1742  $ftypes = array(
1743    'value' => t('January'),
1744    'value_1' => t('February'),
1745    'value_2' => t('March'),
1746    'value_3' => t('April'),
1747    'value_4' => t('May'),
1748    'value_5' => t('June'),
1749    'value_6' => t('July'),
1750    'value_7' => t('August'),
1751    'value_8' => t('September'),
1752    'value_9' => t('Octuber'),
1753    'value_10' => t('November'),
1754    'value_11' => t('December'),
1755  );
1756  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1757  $breadcrumb = array();
1758  $breadcrumb[] = l(t('Home'), '<front>');
1759  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
1760  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
1761  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
1762  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
1763  $breadcrumb[] = 'Ver Modificación';
1764  // Set Breadcrumbs
1765  drupal_set_breadcrumb($breadcrumb);
1766  $current_time = time();
1767  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
1768  $tipo_plan = 'proyectos_operativos_reformular';
1769  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
1770  $fecha = FALSE;
1771  $ente = usuario_tiene_ente($user->uid);
1772  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1773    $fecha = TRUE;
1774  }
1775  if (!$fecha) {
1776    if ($muestra) {
1777      muestra_mensaje($tipo_plan, $ente_planificador->tipo);
1778    }
1779  }
1780  else {
1781    if ($ente->nid == $ente_planificador->nid) {
1782      $fecha = TRUE;
1783      if ($muestra) {
1784        muestra_mensaje($tipo_plan, $ente_planificador->tipo, 0);
1785      }
1786    }
1787    elseif (!user_access('admin planificador')) {
1788      $fecha = FALSE;
1789    }
1790  }
1791  $enlaces_estados = TRUE;
1792  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
1793    $enlaces_estados = FALSE;
1794  }
1795  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1796  $editar = ($node->_workflow == $estado_aprobado);
1797  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
1798  $reformula = _proyectos_reformulacion_load($node, $id_ref);
1799  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
1800  //obtiene el total de las variaciones de las acciones especificas
1801  $ae_l = array();
1802  $suma_r_ae = total_reformulado_ae($node, $reformula);
1803  $field = content_fields('field_proyecto_unidadm', 'proyectos_operativos');
1804  $unidad_ant = $node->field_proyecto_unidadm[0]['value'];
1805  $text_unidad = t('N/A');
1806  $tree = taxonomy_get_tree($field['vid']);
1807  $planificado = t('planificado');
1808  $variacion = t('variación');
1809  $options = array();
1810  if ($tree) {
1811    foreach ($tree as $term) {
1812      if ($term->tid == $unidad_ant) {
1813        $text_unidad = $term->name;
1814      }
1815      $choice = new stdClass();
1816      $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
1817      $options[] = $choice;
1818    }
1819  }
1820  $field = content_fields('field_accion_esp_unidadm', 'accion_especifica');
1821  $unidadesm = array();
1822  $tree = taxonomy_get_tree($field['vid']);
1823  if ($tree) {
1824    foreach ($tree as $term) {
1825      $unidadesm[$term->tid] = $term->name;
1826    }
1827  }
1828  $grupos = array();
1829  if ($node->field_proyecto_accion_esp[0]['nid']) {
1830    foreach($node->field_proyecto_accion_esp as $ae) {
1831      $grupos[$ae['nid']] = node_load($ae['nid']);
1832    }
1833  }
1834  $varia = isset($variaciones['total']) ? $variaciones['total'] : 0;
1835  $min = $node->field_proyecto_monto_anual[0]['value'] + $varia;
1836  $valor = isset($reformula['total'])? $reformula['total'] : 0;
1837  $total_accion = $min;
1838  if (module_exists('workflow')) {
1839    $estados = _proyectos_operativos_reformulacion_obtiene_estados();
1840  }
1841  $mes = 2;
1842  $planificado = t('planificado');
1843  $variacion = t('variación');
1844  $subtotal = t('Total AE');
1845  $output = '';
1846  if ($suma_r_ae != $reformula['total']) {
1847    $output .= '<div id="mensaje_alerta"><label style ="color:red">' . t('El monto de la variación del proyecto (%monto_total_proyecto) es diferente al total de las variaciones de las Acciones Específicas (%monto_total_ae)', array('%monto_total_proyecto' => number_format($reformula['total'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '%monto_total_ae' => number_format($suma_r_ae, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))) . '</label></div>';
1848  }
1849  $output .= '<fieldset><legend>' . t('Resumen del Proyecto') . '</legend>';
1850  $output .= '<div class="field"><div class="field-label">' . t('Código Único del Proyecto') . ':</div>' . $node->field_proyecto_codigo[0]['value'] . '</div>';
1851  $output .= '<div class="field"><div class="field-label">' . t('Nombre del Proyecto') . ':</div>' . $node->titulo_asignado . '</div>';
1852  $output .= '<div class="field"><div class="field-label">' . t('Organismo') . ':</div>' . $ente_planificador->title . '</div>';
1853  $output .= '</fieldset>';
1854  $output .= '<fieldset><legend>' . t('Datos de la Reformulación') . '</legend>';
1855  $states = array();
1856  if (module_exists('workflow')) {
1857    $states = _proyectos_operativos_reformulacion_obtiene_estados();
1858    $header = array();
1859    $header[] = array('data' => t('Fecha'),);
1860    $header[] = array('data' => t('Estado'),);
1861    $header[] = array('data' => t('Estado anterior'),);
1862    $header[] = array('data' => t('Comentario'),);
1863    $header[] = array('data' => t('Usuario'),);
1864    $rows = array();
1865    $result = db_query('SELECT re.*, u.name, u.uid FROM {proyectos_reformular_state} re INNER JOIN {users} u ON u.uid = re.uid WHERE nid = %d AND id_ref = %d ORDER BY date DESC', $node->nid, $id_ref);
1866    while($history = db_fetch_object($result)) {
1867      $row = array();
1868      $row[] = array('data' => format_date($history->date),);
1869      $row[] = array('data' => $states['states'][$history->estado],);
1870      $row[] = array('data' => $states['states'][$history->estado_ant],);
1871      $row[] = array('data' => $history->comentario,);
1872      $row[] = array('data' => l($history->name, 'user/' . $history->uid),);
1873      $rows[] = $row;
1874    }
1875    if (count($rows)) {
1876      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . theme('table', $header, $rows) . '</div>';     
1877    }
1878    else {
1879      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . t('No existe historial para esta modificación') . '</div>';     
1880    }
1881  }
1882  $output .= '</fieldset>';
1883  $output .= '<fieldset><legend>' . t('Monto Total del Proyecto') . '</legend>';
1884  $rows = array();
1885  $row = array();
1886  $row[] = array('data' => t('<b>Fecha de Aprobación:</b> %fecha_onapre', array('%fecha_onapre' => date( 'd/m/Y', $reformula['fecha_onapre']))), 'align' => 'left');
1887  $row[] = array('data' => t('<b>Justificación:</b> %justificacion', array('%justificacion' => $reformula['justificacion'])), 'align' => 'left');
1888  $rows[] = $row;
1889  $row = array();
1890  $row[] = array('data' => '<b>' . t('Monto Total del Proyecto para el año en curso: %monto', array('%monto' => number_format($total_accion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))) . '</b>', 'colspan' => 2, 'align' => center);
1891  $rows[] = $row;
1892  $row = array();
1893  $signo = '';
1894  if ($reformulacion_load->variacion > 0) {
1895    $signo = '+';
1896  }
1897  $row[] = array('data' => t('Variación Presupuestaria: %variacion', array('%variacion' => $signo . number_format($reformulacion_load->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))), );
1898  $row[] = array('data' => t('Monto Total Modificación: %totalreformulacion', array('%totalreformulacion' => number_format($reformulacion_load->variacion + $total_accion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))), );
1899  $rows[] = $row;
1900  $output .= theme('table', array(), $rows) . '</fieldset>';
1901  $output .= '<fieldset><legend>' . t('Distribución de la Meta Física') . '</legend>';
1902  $output .= '<fieldset><legend>' . t('Meta Física del Proyecto') . '</legend>';
1903  $output .= '<div class="field"><div class="field-label">' . t('Unidad de Medida Anterior') . ':</div>' . $unidadesm[$node->field_proyecto_unidadm[0]['value']] . '</div>';
1904  $output .= '<div class="field"><div class="field-label">' . t('Unidad de Medida Nueva') . ':</div>' . $unidadesm[$reformulacion_load->unidad] . '</div>';
1905  $header = array();
1906  $header[] = array('data' => t('Meta Física del Proyecto'));
1907  $rows = array();
1908  $row = array();
1909  $row1 = array();
1910  $row2 = array();
1911  $row[] = array('data' => $planificado, );
1912  $row1[] = array('data' => $variacion, );
1913  $row2[] = array('data' => '<b>' . t('TOTAL') . '</b>', );
1914  $total = 0;
1915  $total1 = 0;
1916  foreach($ftypes as $id_field => $texto) {
1917    $header[] = array('data' => $texto);
1918    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
1919    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
1920    $valor = isset($reformula['field_proyecto_meta_fisica'][0][$id_field])? $reformula['field_proyecto_meta_fisica'][0][$id_field] : 0;
1921    $signo = '';
1922    if ($valor > 0) {
1923      $signo = '+';
1924    }
1925    $total += $min;
1926    $total1 += $valor;
1927    $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1928    $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1929    $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1930  }
1931  $row[] = array('data' => number_format($total, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1932  $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1933  $row2[] = array('data' => number_format($total + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1934  $rows[] = $row;
1935  $rows[] = $row1;
1936  $rows[] = $row2;
1937  $header[] = array('data' => t('TOTAL'));
1938  $output .= theme('table', $header, $rows);
1939  $output .= '</fieldset>';
1940  $output .= '<fieldset><legend>' . t('Meta Física de las Acciones Específicas') . '</legend>';
1941  $header = array();
1942  $header[] = array('data' => t('Meta Física de las AEs'));
1943  $header[] = array('data' => t('Unidad de Medida'));
1944  $header[] = array('data' => t('% de la AEs'),);
1945  $header[] = array('data' => '-',);
1946  foreach($ftypes as $id_field => $texto) {
1947    $header[] = array('data' => $texto);
1948  }
1949  $header[] = array('data' => t('TOTAL'));
1950  $rows = array();
1951  $rowsF = array();
1952  $i = 0;
1953    $rowF = array();
1954    $rowF[] = array('data' => '<b>' . t('Número') . '</b>', 'align' => center,);
1955    $rowF[] = array('data' => '<b>' . t('Nombre') . '</b>', 'align' => center,);
1956    $rowF[] = array('data' => '<b>' . t('Acción') . '</b>', 'align' => center,);
1957    $rowsF[] = $rowF;
1958  $totalA = array();
1959  $totalT;
1960  foreach($grupos as $nid => $grupo) {
1961    $i++;
1962    $row = array();
1963    $rowF = array();
1964    $row1 = array();
1965    $row2 = array();
1966    $rowF[] = array('data' => t('AE %numero', array('%numero' => $i)));
1967    $rowF[] = array('data' => $grupo->titulo_asignado);
1968    $links = array();
1969    $links[] = l(t('Ver modificación'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/ae/' . $grupo->nid);
1970    if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformulacion_load)) {
1971      $links[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/ae/' . $grupo->nid . '/edit');
1972    }
1973    $rowF[] = array('data' => theme('item_list', $links),);
1974    $rowsF[] = $rowF;
1975    $row[] = array('data' => t('AE %numero', array('%numero' => $i)), 'rowspan' => 3);
1976    $row[] = array('data' => t('<b>Unidad de Medida Anterior:</b> %umedida', array('%umedida' => $unidadesm[$grupo->field_accion_esp_unidadm[0]['value']])) . '<br/>'. t('<b>Unidad de Medida Nueva:</b> %umedida', array('%umedida' => $unidadesm[$reformula['field_accion_esp_metaf_' . $nid][0]['unidad']])), 'rowspan' => 3);
1977    $row[] = array('data' => $grupo->field_accion_esp_ponderacion[0]['value'], 'rowspan' => 3);
1978    $row[] = array('data' => $planificado, );
1979    $row1[] = array('data' => $variacion, );
1980    $row2[] = array('data' => $subtotal);
1981    $total = 0;
1982    $total1 = 0;
1983    foreach($ftypes as $id_field => $texto) {
1984      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1985      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1986      $valor = isset($reformula['field_accion_esp_metaf_' . $nid][0][$id_field])? $reformula['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1987      $signo = '';
1988      if ($valor > 0) {
1989        $signo = '+';
1990      }
1991      $total += $min;
1992      $total1 += $valor;
1993      if (!isset($totalA[$id_field])) {
1994        $totalA[$id_field] = 0;
1995      }
1996      $totalA[$id_field] += $min + $valor;
1997      $totalT += $min + $valor;
1998      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1999      $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2000      $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2001    }
2002    $row[] = array('data' => number_format($total, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2003    $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2004    $row2[] = array('data' => number_format($total + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2005    $rows[] = $row;
2006    $rows[] = $row1;
2007    $rows[] = $row2;
2008  }
2009  $row = array();
2010  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 4, 'align' => 'right');
2011  foreach($ftypes as $id_field => $texto) {
2012    $row[] = array('data' => number_format($totalA[$id_field], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2013  }
2014  $row[] = array('data' => number_format($totalT, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2015  $rows[] = $row;
2016  $output .= theme('table', $header, $rows);
2017  $header = array();
2018  $header[] = array('data' => t('Detalles de las Acciones Específicas'), 'colspan' => 3, 'align' => center);
2019  $output .= theme('table', $header, $rowsF);
2020  $output .= '</fieldset>';
2021  $output .= '</fieldset>';
2022  if ($show_variacion) {
2023    $links = array();
2024    if ($editar) {
2025      $links[] = l(t('Modificaciones'), 'proyectosop/' . $node->nid . '/reformular');
2026    }
2027    if ($add_reformular) {
2028      $links[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add');
2029    }
2030    if (isset($states['wid'])) {
2031      $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
2032      if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformulacion_load) && $editar && $fecha && $reformulacion_load->estado != $estado_naprobado &&  $reformulacion_load->estado != $estado_aprobado && $reformulacion_load->id_ref) {
2033        $links[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/edit');
2034      }
2035      $first_state = 0;
2036      if ($states['wid']) {
2037        $first_state = _workflow_creation_state($states['wid']);
2038      }
2039      if ($user->uid == 1) {
2040        // Superuser is special.
2041        $roles = 'ALL';
2042      }
2043      else {
2044        $roles = array_keys($user->roles);
2045        $roles_transition = $roles;
2046        if ($user->uid == $reformulacion_load->uid && $reformulacion_load->uid > 0) {
2047          $roles += array('author' => 'author');
2048        }
2049      }
2050      $transitions = array();
2051      if ($states['wid']) {
2052        $transitions = workflow_allowable_transitions($reformulacion_load->estado, 'to', $roles);
2053      }
2054      unset($transitions[$reformulacion_load->estado]);
2055      if ($suma_r_ae == $reformula['total'] && $enlaces_estados && count($transitions) && $estado_aprobado != $reformulacion_load->estado) {
2056        foreach($transitions as $id => $transition) {
2057          $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/workflow/' . $id);
2058        }
2059      }
2060    }
2061    $output .= '<div class="field"><div class="field-label">' . t('Acciones') . ':</div>' . implode(' | ', $links) . '</div>';
2062  }
2063  return $output;
2064}
2065
2066/*
2067 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form()
2068 * Formulario para reformular las acciones especificas
2069 */
2070function proyectos_reformulacion_reformula_tab_page_ae_form($form_state, $node, $reformulacion_load = 0, $ae = 0) {
2071  drupal_set_title(t('Modificar A.E.'));
2072  $form = array();
2073  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2074  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2075  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
2076  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
2077  $ftypes = array(
2078    'value' => t('January'),
2079    'value_1' => t('February'),
2080    'value_2' => t('March'),
2081    'value_3' => t('April'),
2082    'value_4' => t('May'),
2083    'value_5' => t('June'),
2084    'value_6' => t('July'),
2085    'value_7' => t('August'),
2086    'value_8' => t('September'),
2087    'value_9' => t('Octuber'),
2088    'value_10' => t('November'),
2089    'value_11' => t('December'),
2090  );
2091  $partidas_nodo = array();
2092  foreach ($ae->field_accion_esp_programacion as $partida) {
2093    if(!empty($partida['tid'])) {
2094      $partidas_nodo[$partida['tid']] = $partida;
2095    }
2096  }
2097  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2098  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2099  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2100  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2101  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2102  $field = content_fields('field_accion_esp_programacion', 'accion_especifica');
2103  $tree = taxonomy_get_tree($field['vid']);
2104  $vtid = $field['vtid'];
2105  $partidas = array();
2106  if ($tree) {
2107    foreach ($tree as $term) {
2108      if (isset($vtid[$term->tid])) {
2109        $partidas[$term->tid] = $term->name;
2110      }
2111    }
2112  }
2113  //$form['#mes'] = variable_get('accion_especifica_de_proyecto_seguimiento_mes_seguimiento', 0);
2114  $form['#mes'] = variable_get('accion_especifica_de_proyecto_seguimiento_anho_seguimiento', 0) == $node->anhoproyectos_operativos ? variable_get('accion_especifica_de_proyecto_seguimiento_mes_seguimiento', 0) - 1 : 0;
2115  $format_number = array(
2116    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2117    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2118    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2119  );
2120  $form['#format_number'] = array('format_number' => $format_number);
2121  drupal_add_js($form['#format_number'], 'setting');
2122  $totales = array();
2123  $totalT = 0;
2124  $plant = array();
2125  $sumaplan = 0;
2126  $sumaplanm = array();
2127  foreach($partidas as $tid => $term) {
2128    $total = 0;
2129    $total1 = 0;
2130    $i = 1;
2131    foreach($ftypes as $id_field => $texto) {
2132      $varia = isset($variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field]) ? $variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2133      $min = $partidas_nodo[$tid][$id_field] + $varia;
2134      $valor = isset($reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field])? $reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2135      $total1 += $valor;
2136      $totalT += $min + $valor;
2137      if (!isset($plant[$tid])) {
2138        $plant[$tid] = 0;
2139      }
2140      $plant[$tid] += $min;
2141      $sumaplan += $min;
2142      if (!isset($totales[$id_field])) {
2143        $totales[$id_field] = 0;
2144      }
2145      if (!isset($sumaplanm[$id_field])) {
2146        $sumaplanm[$id_field] = 0;
2147      }
2148      $sumaplanm[$id_field] += $min;
2149      $totales[$id_field] += $min + $valor;
2150      $idformu = $ae->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2151      $idformuj = str_replace('_', '-', $idformu);
2152      $clase = '';
2153      if ($form['#mes'] >= $i) {
2154        $clase = 'campo-bloqueado ';
2155      }
2156      $form[$idformu] = array(
2157        '#type' => 'textfield',
2158        '#default_value' => $valor,
2159        '#size' => 15,
2160        '#attributes' => array('class' => $clase . 'field-accion-esp-programacion-r-' . $tid . ' subtotal-' . $id_field . ' number', 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref('" . 'field-accion-esp-programacion-r-' . $tid . "');prsumaref2('" . 'subtotal-' . $id_field . "', 'sumaplan', '" . $id_field . "'); prsumaref('subtotales')", 'valor' => $min, 'indice' => $i - 1, 'taxonomia' => $tid, 'nodo' => $ae->nid),
2161      );
2162      $i++;
2163    }
2164    $form[$ae->nid . '_field_accion_esp_programacion_' . $tid . '_t'] = array(
2165      '#type' => 'textfield',
2166      '#default_value' => $total1,
2167      '#size' => 15,
2168      '#attributes' => array('class' => 'number1 campo-bloqueado field-accion-esp-programacion-r-' . $tid . '-total'),
2169    );
2170  }
2171  foreach($ftypes as $id_field => $texto) {
2172    $form[$ae->nid . '_field_accion_esp_programacion_t_' . $id_field] = array(
2173      '#type' => 'textfield',
2174      '#default_value' => $totales[$id_field],
2175      '#size' => 15,
2176      '#attributes' => array('class' => 'number1 campo-bloqueado subtotales subtotal-' . $id_field . '-total'),
2177    );
2178  }
2179  $form[$ae->nid . '_field_accion_esp_programacion_t'] = array(
2180    '#type' => 'textfield',
2181    '#default_value' => $totalT,
2182    '#size' => 15,
2183    '#attributes' => array('class' => 'number1 campo-bloqueado subtotales-total'),
2184  );
2185  //financiamiento
2186  $arreglo_financiamiento = array();
2187  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
2188  for($i = 0; $i < $accion_especifica_number_fields; $i++) {
2189    $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
2190    $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
2191  }
2192
2193  $form['#plant'] = $plant;
2194  $form['#partidas_nodo'] = $partidas_nodo;
2195  $form['#arreglo'] = $arreglo_financiamiento_fields;
2196  $form['#ftypes'] = $ftypes;
2197  $form['#partidas'] = $partidas;
2198  $form['#node'] = $node;
2199  $form['#variaciones'] = $variaciones;
2200  $form['#reformula'] = $reformula;
2201  $form['#id_ref'] = $id_ref;
2202  $form['#ae'] = $ae;
2203  $form['#reformula_load'] = $reformulacion_load;
2204  $suma_r_ae = total_reformulado_ae($node, $reformula, array($ae->nid => 1));
2205  $monto_asignar = $form['#reformula_load']->variacion - $suma_r_ae;
2206  $form['#monto_asignar'] = $monto_asignar;
2207  $total = 0;
2208  $sumafinm = array();
2209  $sumatotalf = 0;
2210  foreach($arreglo_financiamiento as $id_items => $titulo) {
2211    $form[$id_items] = array(
2212      '#type' => 'fieldset',
2213      '#title' => $titulo,
2214    );
2215    $total1 = 0;
2216    foreach($arreglo_financiamiento_fields[$id_items] as $id1) {
2217      if ($id1) {
2218        $id_items1 = str_replace('_', '-', $id_items);
2219        $varia = isset($variaciones[$id1 . '_' . $ae->nid][0]['value']) ? $variaciones[$id1 . '_' . $ae->nid][0]['value'] : 0;
2220        $min = $ae->{$id1}[0]['value'] + $varia;
2221        if (!isset($sumafinm[$id_items1])) {
2222          $sumafinm[$id_items1] = 0;
2223        }
2224        $valor = isset($reformula[$id1 . '_' . $ae->nid][0]['value'])? $reformula[$id1 . '_' . $ae->nid][0]['value'] : 0;
2225        $sumafinm[$id_items1] += $min;
2226        $sumatotalf += $min;
2227        $field = content_fields($id1, 'accion_especifica');
2228        $total1 += $valor;
2229        $total += $valor;
2230        $idformuj = str_replace('_', '-', $id1);
2231        $form[$id_items][$id1] = array(
2232          '#type' => 'textfield',
2233          '#default_value' => $valor,
2234          '#size' => 20,
2235          '#prefix' =>'<label><b>' . $field['widget']['label'] . ':</b></label><div class="field-label-planificado">' . t('Planificado') . ': ' . number_format($min, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div><div class="field-label-reformulado">' . t('Variación') . ':</div>',
2236          '#attributes' => array('class' => 'number subtotalff-' . $id_items1, 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref2('" . 'subtotalff-' . $id_items1 . "', 'financia', '" . $id_items1 . "'); prsumaref('subtotalesf')"),
2237        );
2238      }
2239    }
2240
2241    $form['totalf_' . $id_items] = array(
2242      '#type' => 'textfield',
2243      '#default_value' => $sumafinm[$id_items1],
2244      '#size' => 20,
2245      '#attributes' => array('class' => 'number1 campo-bloqueado subtotalesf subtotalff-' . $id_items1 . '-total'),
2246    );
2247  }
2248  $form['total_financiamiento'] = array(
2249    '#type' => 'textfield',
2250    '#default_value' => $sumatotalf,
2251    '#size' => 20,
2252    '#attributes' => array('class' => 'number1 campo-bloqueado subtotalesf-total'),
2253  );
2254  $jse = array(
2255    'sumatotal' => $sumaplan,
2256    'sumaplan' => $sumaplanm,
2257    'financia' => $sumafinm,
2258    'sumatotalf' => $sumatotalf,
2259  );
2260  $form['#jse'] = $jse;
2261  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
2262  $form['buttons'] = array(
2263    '#prefix' => '<div class="container-inline">',
2264    '#suffix' => '</div>',
2265  );
2266  $form['buttons']['registrar'] = array(
2267    '#type' => 'submit',
2268    '#default_value' => t('Guardar'),
2269    '#weight' => 100,
2270  );
2271  $form['buttons']['cancelar'] = array(
2272    '#type' => 'submit',
2273    '#default_value' => t('Cancelar'),
2274    '#weight' => 101,
2275  );
2276  return $form;
2277}
2278
2279/*
2280 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
2281 */
2282function proyectos_reformulacion_reformula_tab_page_ae_form_validate($form, &$form_state) {
2283  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2284  if ($op == t('Cancelar')) {
2285    return;
2286  }
2287  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2288  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2289  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
2290  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
2291  //drupal_add_js($form['#format_number'], 'setting');
2292  //drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
2293  //se obtienen la suma de la meta fisica
2294  $mf = $form['#jse']['sumatotal'];
2295  foreach($form['#partidas'] as $tid => $grupo) {
2296    foreach($form['#ftypes'] as $id_field => $texto) {
2297      $varia = isset($form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field]) ? $form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field] : 0;
2298      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2299      $start = $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2300      $value = preg_replace('@[^-0-9]@', '', $start);
2301      if ($start != $value) {
2302        form_set_error($form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field, t('Solo números enteros son permitidos en la modificación de la partida #nombre.', array('#nombre' => $form['#partidas'][$tid])));
2303      }
2304      if ($form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field] + $min < 0) {
2305        form_set_error($form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field, t('El valor para modificar la partida #nombre no puede ser menor que cero', array('#nombre' => $form['#partidas'][$tid])));
2306      }
2307      $mf += $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2308    }
2309  }
2310  $finan = $form['#jse']['sumatotalf'];
2311  //se obtiene la suma del financiamiento
2312  foreach($form['#arreglo'] as $id => $arreglo1) {
2313    foreach($arreglo1 as $id1) {
2314      $varia = isset($form['#variaciones'][$id1 . '_' . $form['#ae']->nid][0]['value']) ? $form['#variaciones'][$id1 . '_' . $form['#ae']->nid][0]['value'] : 0;
2315      $min = $form['#ae']->{$id1}[0]['value'] + $varia;
2316      $start = $form_state['values'][$id1];
2317      $value = preg_replace('@[^-0-9]@', '', $start);
2318      if ($start != $value) {
2319        form_set_error($id1, t('Solo números enteros son permitidos en la fuente de financiamiento #nombre.', array('#nombre' => $form[$id1]['#title'])));
2320      }
2321      if ($form_state['values'][$id1] + $min < 0) {
2322        form_set_error($id1, t('El valor para modificar la fuente de financiamiento #nombre no puede ser menor que cero', array('#nombre' => $form[$id1]['#title'])));
2323      }
2324      $finan += $form_state['values'][$id1];
2325    }
2326  }
2327  if ($mf != $finan) {
2328    form_set_error($form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field, t('La suma de la Programación Financiera (#valor) debe ser igual a las Fuentes de Financiamiento (#valor1)', array('#valor' => $mf, '#valor1' => $finan)));
2329  }
2330}
2331
2332/*
2333 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
2334 */
2335function proyectos_reformulacion_reformula_tab_page_ae_form_submit($form, &$form_state) {
2336  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2337  if ($op == t('Cancelar')) {
2338    drupal_set_message(t('La modificación ha sido cancelada.'));
2339    $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref']. '/ae/' . $form['#ae']->nid;
2340    return;
2341  }
2342  db_query("DELETE FROM {proyectos_reformula} WHERE nid = %d AND id_ref = %d AND ae = %d", $form['#node']->nid, $form['#id_ref'], $form['#ae']->nid);
2343  db_query("DELETE FROM {proyectos_reformula_fuente} WHERE nid = %d AND id_ref = %d AND ae = %d", $form['#node']->nid, $form['#id_ref'], $form['#ae']->nid);
2344  foreach($form['#partidas'] as $tid => $grupo) {
2345    $suma = 0;
2346    $field = array();
2347    $field[] = $form['#id_ref'];
2348    $field[] = 'field_accion_esp_programacion_' . $form['#ae']->nid;
2349    $field[] = $tid;
2350    $field[] = $form['#node']->nid;
2351    foreach($form['#ftypes'] as $id_field => $texto) {
2352      $suma += $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2353      $field[] = $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2354    }
2355    if ($suma) {
2356      $field[] = $form['#ae']->nid;
2357      db_query("INSERT INTO {proyectos_reformula} (id_ref, field_name, partida, nid, value, value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, ae) VALUES (%d, '%s', %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %d)", $field);
2358    }
2359  }
2360  foreach($form['#arreglo'] as $id => $arreglo1) {
2361    foreach($arreglo1 as $id1) {
2362      if ($form_state['values'][$id1]) {
2363        $field = array();
2364        $field[] = $form['#id_ref'];
2365        $field[] = $id1 . '_' . $form['#ae']->nid;
2366        $field[] = $form['#node']->nid;
2367        $field[] = $form['#ae']->nid;
2368        $field[] = $form_state['values'][$id1];
2369        db_query("INSERT INTO {proyectos_reformula_fuente} (id_ref, field_name, nid, ae, value) VALUES (%d, '%s', %d, %d, %f)", $field);
2370      }
2371    }
2372  }
2373  drupal_set_message(t('Se modifico la formulación de la acción específica @nombre', array('@nombre' => $form['#ae']->titulo_asignado)));
2374  $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref'] . '/ae/' . $form['#ae']->nid;
2375}
2376
2377/*
2378 * Implementation of theme_proyectos_reformulacion_reformula_tab_page_form()
2379 */
2380function theme_proyectos_reformulacion_reformula_tab_page_ae_form($form) {
2381  $planificado = t('planificado');
2382  $variacion = t('variación');
2383  $totalAEtexto = t('Total AE');
2384  $output = '';
2385  if ($form['#monto_asignar'] != 0) {
2386    $output .= '<div id="mensaje_alerta"><label style ="color:red">' . t('Usted puede asignar hasta %monto_total_ae para la variación de esta Acción Específica', array('%monto_total_ae' => number_format($form['#monto_asignar'], $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']))) . '</label></div>';
2387  }
2388  else {
2389    $output .= '<div id="mensaje_alerta"><label style ="color:red">' . t('Ya el monto del proyecto ha sido asignado a otras Acciones Específicas') . '</label></div>';
2390  }
2391  $output .= '<fieldset><legend>' . t('Resumen Financiero de las Acciones') . '</legend>';
2392  $header = array();
2393  $header[] = array('data' => t('Partidas'), 'colspan' => 2);
2394  foreach($form['#ftypes'] as $id_field => $texto) {
2395    $header[] = array('data' => $texto);
2396  }
2397  $header[] = array('data' => t('TOTAL'));
2398  $rows = array();
2399  $rowsF = array();
2400  $i = 0;
2401  foreach($form['#partidas'] as $tid => $grupo) {
2402    $i++;
2403    $row = array();
2404    $row1 = array();
2405    $row2 = array();
2406    $row[] = array('data' => $grupo, 'rowspan' => 3);
2407    $row[] = array('data' => $planificado, );
2408    $row1[] = array('data' => $variacion, );
2409    $row2[] = array('data' => $totalAEtexto, );
2410    $totales_partida = 0;
2411    foreach($form['#ftypes'] as $id_field => $texto) {
2412      $varia = isset($form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field]) ? $form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field] : 0;
2413      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2414      $totales_partida += $min;
2415    }
2416    foreach($form['#ftypes'] as $id_field => $texto) {
2417      $idformu = $form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2418      $idformuj = str_replace('_', '-', $idformu);
2419      $varia = isset($form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field]) ? $form['#variaciones']['field_accion_esp_programacion_' . $form['#ae']->nid][$tid][$id_field] : 0;
2420      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2421      $form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]['#attributes']['onchange'] .= ";sumatotalAE('" . $idformuj . "'," . $min . ")";
2422      $form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]['#attributes']['onchange'] .= ";sumatotalAE('" . $form['#ae']->nid . '-field-accion-esp-programacion-' . $tid . '-t' . "'," . $totales_partida . ");";
2423      $form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]['#attributes']['total_partida'] = $totales_partida;
2424      $row[] = array('data' => number_format($min, 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), );
2425      $row1[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]), );
2426      $row2[] = array('data' => '<div id ="' . $idformuj . '-texto">' . number_format($min, 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>', );
2427    }
2428    $row[] = array('data' => number_format($form['#plant'][$tid], 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), );
2429    $row1[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_t']), );
2430    $row2[] = array('data' => '<div id ="' . $form['#ae']->nid . '-field-accion-esp-programacion-' . $tid . '-t' . '-texto">' . number_format($form['#plant'][$tid], 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>', );
2431    $rows[] = $row;
2432    $rows[] = $row1;
2433    $rows[] = $row2;
2434  }
2435  $row = array();
2436  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 2, 'align' => 'right');
2437  foreach($form['#ftypes'] as $id_field => $texto) {
2438    $row[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_t_' . $id_field]), );
2439  }
2440  $row[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_t']), );
2441  $rows[] = $row;
2442  $output .= theme('table', $header, $rows);
2443  $output .= '</fieldset>';
2444  $rows = array();
2445  $row = array();
2446  $row1 = array();
2447  foreach($form['#arreglo'] as $id => $arreglo1) {
2448    $row[] = array('data' => drupal_render($form[$id]), );
2449    $row1[] = array('data' => drupal_render($form['totalf_' . $id]), );
2450  }
2451  $rows[] = $row;
2452  $rows[] = $row1;
2453  $row = array();
2454  $row[] = array('data' => '<b>' . t('TOTAL') . ':</b>', 'colspan' => 3, 'align' => 'right');
2455  $row[] = array('data' => drupal_render($form['total_financiamiento']), );
2456  $rows[] = $row;
2457  $output .= '<fieldset><legend>' . t('Distribución por fuentes de Financiamiento') . '</legend>' . theme('table', array(), $rows) . '</fieldset>';
2458  $output .= '<div id="proyectos-reformulacion-form-acciones">' . drupal_render($form) .'</div>';
2459  return $output;
2460}
2461
2462/*
2463 * Implementation of _proyectos_reformulacion_reformula_tab_page_ver_ae()
2464 */
2465function _proyectos_reformulacion_reformula_tab_page_ver_ae($node, $reformulacion_load = 0, $ae = 0) {
2466  drupal_set_title(t('Consultar Modificación de A.E.'));
2467  $planificado = t('planificado');
2468  $format_number = array(
2469    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2470    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2471    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2472  );
2473  $variacion = t('variación');
2474  $subtotal = t('Total AE');
2475  $ftypes = array(
2476    'value' => t('January'),
2477    'value_1' => t('February'),
2478    'value_2' => t('March'),
2479    'value_3' => t('April'),
2480    'value_4' => t('May'),
2481    'value_5' => t('June'),
2482    'value_6' => t('July'),
2483    'value_7' => t('August'),
2484    'value_8' => t('September'),
2485    'value_9' => t('Octuber'),
2486    'value_10' => t('November'),
2487    'value_11' => t('December'),
2488  );
2489  $partidas_nodo = array();
2490  foreach ($ae->field_accion_esp_programacion as $partida) {
2491    if(!empty($partida['tid'])) {
2492      $partidas_nodo[$partida['tid']] = $partida;
2493    }
2494  }
2495  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2496  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
2497  $breadcrumb = array();
2498  $breadcrumb[] = l(t('Home'), '<front>');
2499  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
2500  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
2501  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
2502  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
2503  $breadcrumb[] = l('Ver Modificación', 'proyectosop/' . $node->nid . '/reformular/' . $id_ref . '/view');
2504  $breadcrumb[] = t('Consultar Modificación de A.E.');
2505  // Set Breadcrumbs
2506  drupal_set_breadcrumb($breadcrumb);
2507  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2508  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2509  $field = content_fields('field_accion_esp_programacion', 'accion_especifica');
2510  $tree = taxonomy_get_tree($field['vid']);
2511  $vtid = $field['vtid'];
2512  $partidas = array();
2513  $suma_r_ae = total_reformulado_ae($node, $reformula);
2514  if ($tree) {
2515    foreach ($tree as $term) {
2516      if (isset($vtid[$term->tid])) {
2517        $partidas[$term->tid] = $term->name;
2518      }
2519    }
2520  }
2521  //financiamiento
2522  $arreglo_financiamiento = array();
2523  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
2524  for($i = 0; $i < $accion_especifica_number_fields; $i++) {
2525    $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
2526    $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
2527  }
2528
2529/*
2530  $arreglo = array();
2531  $titles = array(
2532    'ordinarios' => t('Recursos Ordinarios'),
2533    'propios' => t('Recursos Propios'),
2534    'transferencias' => t('Donaciones'),
2535    'otros' => t('Otros'),
2536  );
2537  $titles_field = array(
2538    'field_accion_esp_transferencias' => t('Recursos Ordinarios'),
2539    'field_accion_esp_creditosa' => t('Recursos Propios'),
2540    'transferencias' => t('Donaciones'),
2541    'otros' => t('Otros'),
2542  );
2543  $arreglo['ordinarios'] = array(
2544    'field_accion_esp_transferencias' => 'field_accion_esp_transferencias',
2545    'field_accion_esp_creditosa' => 'field_accion_esp_creditosa',
2546    'field_accion_esp_mcti' => 'field_accion_esp_mcti',
2547  );
2548  $arreglo['propios'] = array(
2549    'field_accion_esp_venta_act' => 'field_accion_esp_venta_act',
2550    'field_accion_esp_activos' => 'field_accion_esp_activos',
2551    'field_accion_esp_flujocaja' => 'field_accion_esp_flujocaja',
2552    'field_accion_esp_ventapro' => 'field_accion_esp_ventapro',
2553  );
2554  $arreglo['transferencias'] = array(
2555    'field_accion_esp_donaciones' => 'field_accion_esp_donaciones',
2556  );
2557  $arreglo['otros'] = array(
2558    'field_accion_esp_gobernacion' => 'field_accion_esp_gobernacion',
2559    'field_accion_esp_misionc' => 'field_accion_esp_misionc',
2560    'field_accion_esp_bid_fona' => 'field_accion_esp_bid_fona',
2561    'field_accion_esp_fonacit' => 'field_accion_esp_fonacit',
2562    'field_accion_esp_fonden' => 'field_accion_esp_fonden',
2563    'field_accion_esp_locti' => 'field_accion_esp_locti',
2564    'field_accion_esp_fondoidi' => 'field_accion_esp_fondoidi',
2565    'field_accion_esp_capitalrie' => 'field_accion_esp_capitalrie',
2566    'field_accion_esp_infocentro' => 'field_accion_esp_infocentro',
2567    'field_accion_esp_fidetel' => 'field_accion_esp_fidetel',
2568  );
2569*/
2570  $output = '';
2571  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
2572  if ($suma_r_ae != $reformula['total']) {
2573    $output .= '<div id="mensaje_alerta"><label style ="color:red">' . t('El monto de la variación del proyecto (%monto_total_proyecto) es diferente al total de las variaciones de las Acciones Específicas (%monto_total_ae)', array('%monto_total_proyecto' => number_format($reformula['total'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '%monto_total_ae' => number_format($suma_r_ae, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']))) . '</label></div>';
2574  }
2575  $output .= '<fieldset><legend>' . t('Resumen del Proyecto') . '</legend>';
2576  $output .= '<div class="field"><div class="field-label">' . t('Código Único del Proyecto') . ':</div>' . $node->field_proyecto_codigo[0]['value'] . '</div>';
2577  $output .= '<div class="field"><div class="field-label">' . t('Nombre del Proyecto') . ':</div>' . $node->titulo_asignado . '</div>';
2578  $output .= '<div class="field"><div class="field-label">' . t('Organismo') . ':</div>' . $ente_planificador->title . '</div>';
2579  $output .= '</fieldset>';
2580  $output .= '<fieldset><legend>' . t('Resumen Financiero de las Acciones') . '</legend>';
2581  $header = array();
2582  $header[] = array('data' => t('Partidas'), 'colspan' => 2);
2583  foreach($ftypes as $id_field => $texto) {
2584    $header[] = array('data' => $texto);
2585  }
2586  $header[] = array('data' => t('TOTAL'));
2587  $rows = array();
2588  $rowsF = array();
2589  $i = 0;
2590  $totales = array();
2591  $totalT = 0;
2592  $plant = array();
2593  $sumaplan = 0;
2594  $sumaplanm = array();
2595  foreach($partidas as $tid => $grupo) {
2596    $i++;
2597    $total = 0;
2598    $total1 = 0;
2599    $row = array();
2600    $row1 = array();
2601    $row2 = array();
2602    $row[] = array('data' => $grupo, 'rowspan' => 3);
2603    $row[] = array('data' => $planificado, );
2604    $row1[] = array('data' => $variacion, );
2605    $row2[] = array('data' => $subtotal, );
2606    foreach($ftypes as $id_field => $texto) {
2607      $varia = isset($variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field]) ? $variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2608      $min = $partidas_nodo[$tid][$id_field] + $varia;
2609      $valor = isset($reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field])? $reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2610      $signo = '';
2611      if ($valor > 0) {
2612        $signo = '+';
2613      }
2614      $total1 += $valor;
2615      $totalT += $min + $valor;
2616      if (!isset($plant[$tid])) {
2617        $plant[$tid] = 0;
2618      }
2619      $plant[$tid] += $min;
2620      $sumaplan += $min;
2621      if (!isset($totales[$id_field])) {
2622        $totales[$id_field] = 0;
2623      }
2624      if (!isset($sumaplanm[$id_field])) {
2625        $sumaplanm[$id_field] = 0;
2626      }
2627      $sumaplanm[$id_field] += $min;
2628      $totales[$id_field] += $min + $valor;
2629      $idformu = $ae->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2630      $idformuj = str_replace('_', '-', $idformu);
2631      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2632      $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2633      $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2634    }
2635    $row[] = array('data' => number_format($plant[$tid], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2636    $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2637    $row2[] = array('data' => number_format($plant[$tid] + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2638    $rows[] = $row;
2639    $rows[] = $row1;
2640    $rows[] = $row2;
2641  }
2642  $row = array();
2643  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 2, 'align' => 'right');
2644  foreach($ftypes as $id_field => $texto) {
2645    $row[] = array('data' => number_format($totales[$id_field], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2646  }
2647  $row[] = array('data' => number_format($totalT, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2648  $rows[] = $row;
2649  $output .= theme('table', $header, $rows);
2650  $output .= '</fieldset>';
2651  $rows = array();
2652  $row = array();
2653  $row1 = array();
2654  $sumalT = 0;
2655  foreach($arreglo_financiamiento as $id_items => $titulo) {
2656    $sumal = 0;
2657    $output1 = '';
2658    foreach($arreglo_financiamiento_fields[$id_items] as $id1) {
2659      if ($id1) {
2660        $field = content_fields($id1, 'accion_especifica');
2661        $varia = isset($variaciones[$id1 . '_' . $ae->nid][0]['value']) ? $variaciones[$id1 . '_' . $ae->nid][0]['value'] : 0;
2662        $min = $ae->{$id1}[0]['value'] + $varia;
2663        if (!isset($sumafinm[$id_items])) {
2664          $sumafinm[$id_items] = 0;
2665        }
2666        $sumafinm[$id_items] += $min;
2667        $sumatotalf += $min;
2668        $field = content_fields($id1, 'accion_especifica');
2669        $valor = isset($reformula[$id1 . '_' . $ae->nid][0]['value'])? $reformula[$id1 . '_' . $ae->nid][0]['value'] : 0;
2670        $total1 += $valor;
2671        $total += $valor;
2672        $sumal += $min + $valor;
2673        $sumalT += $min + $valor;
2674        $idformuj = str_replace('_', '-', $id1);
2675        $signo = '';
2676        if ($valor > 0) {
2677          $signo = '+';
2678        }
2679        $output1 .= '<div class="field"><div class="field-label">' . $field['widget']['label'] . ':</div>' . '<div class="field-label-planificado">' . t('Planificado') . ': ' . number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']) . '</div><div class="field-label-reformulado">' . t('Variación') . ': ' . $signo . number_format($valor, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . '</div>';
2680      }
2681    }
2682    $row[] = array('data' => $output1, );
2683    $row1[] = array('data' => number_format($sumal, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
2684  }
2685  $rows[] = $row;
2686  $rows[] = $row1;
2687  $row = array();
2688  $row[] = array('data' => '<b>' . t('TOTAL') . ':</b>', 'colspan' => 3, 'align' => 'right');
2689  $row[] = array('data' => number_format($sumalT, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
2690  $rows[] = $row;
2691  $output .= '<fieldset><legend>' . t('Distribución por fuentes de Financiamiento') . '</legend>' . theme('table', array(), $rows) . '</fieldset>';
2692  return $output;
2693}
2694
2695/**
2696 * Implementation of proyectos_reformulacion_search_ac_display_not_approved().
2697 * Muestra la lista de las reformulaciones disponibles que no han sido aprobados.
2698 */
2699function proyectos_reformulacion_search_ac_display_not_approved() {
2700  drupal_set_title(t("Consultar Modificaciones sin Aprobar"));
2701  global $user;
2702  $format_number = array(
2703    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2704    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2705    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2706  );
2707  $step = 10;
2708  $current_time = time();
2709  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
2710  $tipo_plan = 'proyectos_operativos_reformular';
2711  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
2712  $fecha = FALSE;
2713  $ente = usuario_tiene_ente($user->uid);
2714  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2715    $fecha = TRUE;
2716  }
2717  if (!$fecha) {
2718    if ($muestra) {
2719      muestra_mensaje($tipo_plan, $ente->tipo);
2720    }
2721  }
2722  else {
2723    if ($ente->nid) {
2724      $fecha = TRUE;
2725      if ($muestra) {
2726        muestra_mensaje($tipo_plan, $ente->tipo, 0);
2727      }
2728    }
2729    elseif (!user_access('admin planificador')) {
2730      $fecha = FALSE;
2731    }   
2732  }
2733  $enlaces_estados = TRUE;
2734  if ($ente->nid && !user_access('admin planificador')) {
2735    $enlaces_estados = FALSE;
2736  }
2737  $states = _proyectos_operativos_reformulacion_obtiene_estados();
2738  $first_state = 0;
2739  if ($states['wid']) {
2740    $first_state = _workflow_creation_state($states['wid']);
2741  }
2742  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
2743  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
2744  $sql = '';
2745  $sql_count = '';
2746  if (!user_access('admin planificador') && $user->entes) {
2747    $inputs[] = $estado_naprobado;
2748    $inputs[] = $estado_aprobado;
2749    $inputs[] = $user->entes;
2750    $sql .= 'SELECT re.*, u.name, u.uid FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND re.estado <> %d AND ac.ente = %d ORDER BY re.id_ref DESC';
2751    $sql_count .= 'SELECT count(re.nid) FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND re.estado <> %d AND ac.ente = %d';
2752  }
2753  elseif (user_access('admin planificador')) {
2754    $inputs[] = $estado_naprobado;
2755    $inputs[] = $estado_aprobado;
2756    $sql .= 'SELECT re.*, u.name, u.uid, ac.ente FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND re.estado <> %d ORDER BY re.id_ref DESC';
2757    $sql_count .= 'SELECT count(re.nid) FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND re.estado <> %d';
2758  }
2759  $header = array();
2760  $header[] = array('data' => t('Ente'));
2761  $header[] = array('data' => t('Proyecto'));
2762  $header[] = array('data' => t('Codigo Nueva Etapa'));
2763  $header[] = array('data' => t('Objetivos Específicos'));
2764  $header[] = array('data' => t('Justificación'));
2765  $header[] = array('data' => t('Fecha'));
2766  $header[] = array('data' => t('Estado Actual'));
2767  $header[] = array('data' => t('Fecha de Aprobación'));
2768  $header[] = array('data' => t('Monto (Bs)'));
2769  $header[] = array('data' => t('Variación (Bs)'));
2770  $header[] = array('data' => t('Total monto (Bs)'));
2771  $header[] = array('data' => t('Usuario'));
2772  $header[] = array('data' => t('Acción'));
2773  $rows = array();
2774  $i = 1;
2775  $roles = array_keys($user->roles);
2776  $result = pager_query($sql, $step, 0, $sql_count, $inputs);
2777  while($reformular = db_fetch_object($result)) {
2778    $node = node_load($reformular->nid);
2779    $editar = ($node->_workflow == $estado_aprobado);
2780    if ($user->uid == 1) {
2781      // Superuser is special.
2782      $roles_transition = 'ALL';
2783    }
2784    else {
2785      $roles_transition = $roles;
2786      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
2787        $roles_transition += array('author' => 'author');
2788      }
2789    }
2790    $transitions = array();
2791    if ($states['wid']) {
2792      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
2793    }
2794    $color = variable_get('proyectos_operativos_state_color_' . $reformular->estado, array());
2795    unset($transitions[$reformular->estado]);
2796    $acciones = array();
2797    $row = array();
2798    $items = array();
2799    //Ente de relacion con la reformulación
2800    $ente = node_load($node->field_proyecto_ente[0]);
2801    //lista de los objetivos generales
2802    foreach ($node->field_proyecto_oe as $item) {
2803      $text = substr($item["value"], 0 , 150);
2804      $items[] = $text . '...';
2805    }
2806    $row[] = array('data' => $ente->title, 'style' => 'background:' . $color,);
2807    $row[] = array('data' => $node->title, 'style' => 'background:' . $color,);
2808    $row[] = array('data' => $node->field_proyecto_codigo_n_etap[0]["value"], 'style' => 'background:' . $color, );
2809    $row[] = array('data' => theme('item_list', $items), 'style' => 'background:' . $color, );
2810    $row[] = array('data' => $node->field_proyecto_justificacion[0]["value"], 'style' => 'background:' . $color, );
2811    $row[] = array('data' => format_date($reformular->date), 'style' => 'background:' . $color,);
2812    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
2813    $row[] = array('data' => $estado, 'style' => 'background:' . $color,);
2814    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
2815    $row[] = array('data' => date( 'd/m/Y', $reformular->fecha_onapre), 'style' => 'background:' . $color,);
2816    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2817    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2818    $total = $reformular->monto + $reformular->variacion;
2819    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2820    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid, array('html' => true, 'query' => 'destination=proyectos_operativos/reformular')), 'style' => 'background:' . $color,);
2821    //display options
2822    if ($editar) {
2823      $acciones[] = l(t('Ver'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2824    }
2825    if ($add_reformular) {
2826      $acciones[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2827    }
2828    if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformular) && $editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2829      $acciones[] = l(t('Actualizar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2830    }
2831    if ($enlaces_estados && count($transitions) && $reformular->estado != $estado_aprobado) {
2832      foreach($transitions as $id => $transition) {
2833        $acciones[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/workflow/' . $id, array('html' => true, 'query' => 'destination=proyectos_operativos/proyectos/reformular'));
2834      }
2835      if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformular) && $editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2836        $links[] = l(t('Actualizar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2837      }
2838    }
2839    $row[] = array('data' =>  theme('item_list', $acciones), 'style' => 'background:' . $color,);
2840    $rows[] = $row;
2841    $i++;
2842  }
2843  if (!count($rows)) {
2844    $row[] = array('data' => 'No existen modificaciones en el sistema', 'colspan' => 9);
2845    $rows[] = $row;
2846  }
2847  $output = '';
2848  $table_attributes = array('style' => 'width:1400px; margin-left: -200px; margin-top: 30px;');
2849  $output .= theme('table', $header, $rows, $table_attributes);
2850  $output .= theme('pager', NULL);
2851  return $output;
2852}
2853
2854/**
2855 * Implementation of proyectos_reformulacion_search_ac_display_not_approved().
2856 * Muestra la lista de las reformulaciones disponibles que no han sido aprobados.
2857 */
2858function proyectos_reformulacion_search_ac_display_approved() {
2859  drupal_set_title(t("Consultar Lista de Modificaciones"));
2860  global $user;
2861  $format_number = array(
2862    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2863    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2864    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2865  );
2866  $step = 10;
2867  $current_time = time();
2868  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
2869  $tipo_plan = 'proyectos_operativos_reformular';
2870  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
2871  $fecha = FALSE;
2872  $ente = usuario_tiene_ente($user->uid);
2873  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2874    $fecha = TRUE;
2875  }
2876  if (!$fecha) {
2877    if ($muestra) {
2878      muestra_mensaje($tipo_plan, $ente->tipo);
2879    }
2880  }
2881  else {
2882    if ($ente->nid) {
2883      $fecha = TRUE;
2884      if ($muestra) {
2885        muestra_mensaje($tipo_plan, $ente->tipo, 0);
2886      }
2887    }
2888    elseif (!user_access('admin planificador')) {
2889      $fecha = FALSE;
2890    }   
2891  }
2892  $enlaces_estados = TRUE;
2893  if ($ente->nid && !user_access('admin planificador')) {
2894    $enlaces_estados = FALSE;
2895  }
2896  $states = _proyectos_operativos_reformulacion_obtiene_estados();
2897  $first_state = 0;
2898  if ($states['wid']) {
2899    $first_state = _workflow_creation_state($states['wid']);
2900  }
2901  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
2902  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
2903  $sql = '';
2904  $sql_count = '';
2905//print_r($user);
2906  if (!user_access('admin planificador') && $user->entes) {
2907    $inputs[] = $estado_naprobado;
2908    $inputs[] = $user->entes;
2909    $sql .= 'SELECT re.*, u.name, u.uid FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND ac.ente = %d ORDER BY re.id_ref DESC';
2910    $sql_count .= 'SELECT count(re.nid) FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d AND ac.ente = %d';
2911  }
2912  elseif (user_access('admin planificador')) {
2913    $inputs[] = $estado_naprobado;
2914    $sql .= 'SELECT re.*, u.name, u.uid, ac.ente FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d ORDER BY re.id_ref DESC';
2915    $sql_count .= 'SELECT count(re.nid) FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid INNER JOIN {proyectos_operativos} AS ac ON ac.nid = re.nid WHERE re.estado <> %d';
2916  }
2917  $header = array();
2918  $header[] = array('data' => t('Ente'));
2919  $header[] = array('data' => t('Proyecto'));
2920  $header[] = array('data' => t('Codigo Nueva Etapa'));
2921  $header[] = array('data' => t('Objetivos Específicos'));
2922  $header[] = array('data' => t('Justificación'));
2923  $header[] = array('data' => t('Fecha'));
2924  $header[] = array('data' => t('Estado Actual'));
2925  $header[] = array('data' => t('Fecha de Aprobación'));
2926  $header[] = array('data' => t('Monto (Bs)'));
2927  $header[] = array('data' => t('Variación (Bs)'));
2928  $header[] = array('data' => t('Total monto (Bs)'));
2929  $header[] = array('data' => t('Usuario'));
2930  $header[] = array('data' => t('Acción'));
2931  $rows = array();
2932  $i = 1;
2933  $roles = array_keys($user->roles);
2934  $result = pager_query($sql, $step, 0, $sql_count, $inputs);
2935  while($reformular = db_fetch_object($result)) {
2936    $node = node_load($reformular->nid);
2937
2938    $editar = ($node->_workflow == $estado_aprobado);
2939    if ($user->uid == 1) {
2940      // Superuser is special.
2941      $roles_transition = 'ALL';
2942    }
2943    else {
2944      $roles_transition = $roles;
2945      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
2946        $roles_transition += array('author' => 'author');
2947      }
2948    }
2949    $transitions = array();
2950    if ($states['wid']) {
2951      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
2952    }
2953    $color = variable_get('proyectos_operativos_state_color_' . $reformular->estado, array());
2954    unset($transitions[$reformular->estado]);
2955    $acciones = array();
2956    $row = array();
2957    //Ente de relacion con la reformulación
2958    $ente = node_load($node->field_proyecto_ente[0]);
2959    //lista de los objetivos generales
2960    foreach ($node->field_proyecto_oe as $item) {
2961      $text = substr($item["value"], 0 , 150);
2962      $items[] = $text . '...';
2963    }
2964    $row[] = array('data' => $ente->title, 'style' => 'background:' . $color,);
2965    $row[] = array('data' => $node->title, 'style' => 'background:' . $color,);
2966    $row[] = array('data' => $node->field_proyecto_codigo_n_etap[0]["value"], 'style' => 'background:' . $color, );
2967    $row[] = array('data' => theme('item_list', $items), 'style' => 'background:' . $color, );
2968    $row[] = array('data' => $node->field_proyecto_justificacion[0]["value"], 'style' => 'background:' . $color, );
2969    $row[] = array('data' => format_date($reformular->date), 'style' => 'background:' . $color,);
2970    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
2971    $row[] = array('data' => $estado, 'style' => 'background:' . $color,);
2972    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
2973    $row[] = array('data' => date( 'd/m/Y', $reformular->fecha_onapre), 'style' => 'background:' . $color,);
2974    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2975    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2976    $total = $reformular->monto + $reformular->variacion;
2977    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2978    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid, array('html' => true, 'query' => 'destination=proyectos_operativos/reformular')), 'style' => 'background:' . $color,);
2979    //display options
2980
2981    if ($editar) {
2982      $acciones[] = l(t('Ver'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2983    }
2984    if ($add_reformular) {
2985      $acciones[] = l(t('Agregar nueva reformulación'), 'proyectosop/' . $node->nid . '/reformular/add', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2986    }
2987    if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformular) && $editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2988      $acciones[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2989    }
2990    if ($enlaces_estados && count($transitions) && $reformular->estado != $estado_aprobado) {
2991      foreach($transitions as $id => $transition) {
2992        $acciones[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/workflow/' . $id, array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2993      }
2994      if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformular) && $editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2995        $links[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit', array('html' => true, 'query' => 'destination=proyectos_operativos/reformular'));
2996      }
2997    }
2998    $row[] = array('data' =>  theme('item_list', $acciones), 'style' => 'background:' . $color,);
2999    $rows[] = $row;
3000    $i++;
3001  }
3002  if (!count($rows)) {
3003    $row[] = array('data' => 'No existen reformulaciones sin Aprobar', 'colspan' => 9);
3004    $rows[] = $row;
3005  }
3006  $output = '';
3007  $table_attributes = array('style' => 'width:1400px; margin-left: -200px; margin-top: 30px;');
3008  $output .= theme('table', $header, $rows, $table_attributes);
3009  $output .= theme('pager', NULL);
3010  return $output;
3011}
3012
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.