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

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

Se agregaron los nuevos cambios a los modulos

  • Propiedad mode establecida a 100755
File size: 132.1 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  $items['proyectos_operativos/proyectos/reformular'] = array(
720    'title' => t('Consultar Modificaciones sin Aprobar'),
721    'page callback' => 'proyectos_reformulacion_search_ac_display_not_approved',
722    'access arguments' => array('ver planificador'),
723    'type' => MENU_LOCAL_TASK,
724  );
725  $items['proyectosop/%proyectosop/reformular'] = array(
726    'title' => 'Modificar',
727    'type' => MENU_LOCAL_TASK,
728    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
729    'access arguments' => array(1),
730    'page callback' => '_proyectos_reformulacion_reformula_list_page',
731    'page arguments' => array(1),
732    'weight' => 2,
733  );
734  $items['proyectosop/%proyectosop/reformular/list'] = array(
735    'title' => 'Modificaciones',
736    'type' => MENU_DEFAULT_LOCAL_TASK,
737    'weight' => -10
738  );
739  $items['proyectosop/%proyectosop/reformular/add'] = array(
740    'title' => 'Agregar Modificación',
741    'type' => MENU_LOCAL_TASK,
742    'access callback' => '_proyectos_reformulacion_reformula_node_add_tab_access',
743    'access arguments' => array(1),
744    'page callback' => 'drupal_get_form',
745    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_form', 1),
746    'weight' => 2,
747  );
748  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/view'] = array(
749    'title' => 'Ver modificación',
750    'type' => MENU_LOCAL_TASK,
751    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
752    'access arguments' => array(1),
753    'page callback' => '_proyectos_reformulacion_reformula_tab_page_ver',
754    'page arguments' => array(1, 3),
755    'weight' => 2,
756  );
757  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/edit'] = array(
758    'title' => 'Editar',
759    'type' => MENU_LOCAL_TASK,
760    'access callback' => '_proyectos_reformulacion_reformula_node_edit_tab_access',
761    'access arguments' => array(1, 3),
762    'page callback' => 'drupal_get_form',
763    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_form', 1, 3),
764    'weight' => 3,
765  );
766  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/ae/%accionesp_menu_r'] = array(
767    'title' => 'Acciones Especificas',
768    'type' => MENU_LOCAL_TASK,
769    'access callback' => '_proyectos_reformulacion_reformula_node_tab_access',
770    'access arguments' => array(1),
771    'page callback' => '_proyectos_reformulacion_reformula_tab_page_ver_ae',
772    'page arguments' => array(1, 3, 5),
773    'weight' => 2,
774  );
775  $items['proyectosop/%proyectosop/reformular/%proyectosop_menu_reformulacion/ae/%accionesp_menu_r/edit'] = array(
776    'title' => 'Editar AEs',
777    'type' => MENU_LOCAL_TASK,
778    'access callback' => '_proyectos_reformulacion_reformula_node_edit_tab_access',
779    'access arguments' => array(1, 3),
780    'page callback' => 'drupal_get_form',
781    'page arguments' => array('proyectos_reformulacion_reformula_tab_page_ae_form', 1, 3, 5),
782    'weight' => 3,
783  );
784  $items['proyectosop/%node/reformular/%proyectosop_menu_reformulacion/workflow/%proyectos_reformulacion_wk_menu'] = array(
785    'title' => 'Workflow',
786    'type' => MENU_LOCAL_TASK,
787    'access callback' => '_proyectos_reformulacion_reformula_wk_node_tab_access',
788    'access arguments' => array(1, 3, 5),
789    'page callback' => 'drupal_get_form',
790    'page arguments' => array('proyectos_reformulacion_reformula_wk_tab_page_form', 1, 3, 5),
791    'weight' => 3,
792  );
793  return $items;
794}
795
796/**
797 * Implementation of hook_theme().
798 */
799function proyectos_reformulacion_theme() {
800  return array(
801    'proyectos_reformulacion_reformula_tab_page_form' => array(
802      'arguments' => array('form' => NULL),
803    ),
804    'proyectos_reformulacion_reformula_tab_page_ae_form' => array(
805      'arguments' => array('form' => NULL),
806    ),
807  );
808}
809
810/*
811 * Implementation of proyectos_reformulacion_reformula_tab_page_form()
812 */
813function proyectos_reformulacion_reformula_tab_page_form($form_state, $node, $reformulacion_load = 0) {
814  $title = $reformulacion_load ? t('Editar Modificación') : t('Agregar Modificación al Proyecto');
815  drupal_set_title($title);
816  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
817  $breadcrumb = array();
818  $breadcrumb[] = l(t('Home'), '<front>');
819  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
820  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
821  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
822  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
823  $breadcrumb[] = $title;
824  // Set Breadcrumbs
825  drupal_set_breadcrumb($breadcrumb);
826  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
827  $reformula = _proyectos_reformulacion_load($node, $id_ref);
828  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
829  $field = content_fields('field_proyecto_unidadm', 'proyectos_operativos');
830  $unidad_ant = $node->field_proyecto_unidadm[0]['value'];
831  $text_unidad = t('N/A');
832  $tree = taxonomy_get_tree($field['vid']);
833  $options = array();
834  if ($tree) {
835    foreach ($tree as $term) {
836      if ($term->tid == $unidad_ant) {
837        $text_unidad = $term->name;
838      }
839      $choice = new stdClass();
840      $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
841      $options[] = $choice;
842    }
843  }
844  $field = content_fields('field_accion_esp_unidadm', 'accion_especifica');
845  $unidadesm = array();
846  $tree = taxonomy_get_tree($field['vid']);
847  if ($tree) {
848    foreach ($tree as $term) {
849      $unidadesm[$term->tid] = $term->name;
850    }
851  }
852  $form['field_proyecto_unidadm_ant'] = array(
853    '#title' => t('Unidad de Medida Actual'),
854    '#type' => 'textfield',
855    '#value' =>  $text_unidad,
856    '#attributes' => array('class' => 'campo-bloqueado '),
857  );
858  $valor_medida = $reformula['unidad'] ? $reformula['unidad'] : $node->field_proyecto_unidadm[0]['value'];
859  $form['field_proyecto_unidadm'] = array(
860    '#title' => t('Unidad de Medida Nueva'),
861    '#type' => 'select',
862    '#options' => $options,
863    '#default_value' => $valor_medida,
864  );
865  $ftypes = array(
866    'value' => t('January'),
867    'value_1' => t('February'),
868    'value_2' => t('March'),
869    'value_3' => t('April'),
870    'value_4' => t('May'),
871    'value_5' => t('June'),
872    'value_6' => t('July'),
873    'value_7' => t('August'),
874    'value_8' => t('September'),
875    'value_9' => t('Octuber'),
876    'value_10' => t('November'),
877    'value_11' => t('December'),
878  );
879  $grupos = array();
880  if ($node->field_proyecto_accion_esp[0]['nid']) {
881    foreach($node->field_proyecto_accion_esp as $ae) {
882      $grupos[$ae['nid']] = node_load($ae['nid']);
883      $array[$ae['nid']] = node_load($ae['nid']);
884    }
885  }
886  $varia = isset($variaciones['total']) ? $variaciones['total'] : 0;
887  $min = $node->field_proyecto_monto_anual[0]['value'] + $varia;
888  $form['#monto_reformulado'] = $min;
889  $valor = isset($reformulacion_load->variacion)? $reformulacion_load->variacion : 0;
890  $suma_variacion['primero'] = $min;
891  $total_accion = $min;
892  $idformuj = 'variacion';
893  $id_field = 'primero';
894  $fecha = array();
895  $fecha['dia'] = $reformula['fecha_onapre'] ? date('j', $reformula['fecha_onapre']) : date('j');
896  $fecha['mes'] = $reformula['fecha_onapre'] ? date('n', $reformula['fecha_onapre']) : date('m');
897  $fecha['year'] = $reformula['fecha_onapre'] ? date('Y', $reformula['fecha_onapre']) : date('Y');
898  $form['fecha_onapre'] = array(
899    '#type' => 'date',
900    '#title' => t('Fecha de Aprobación'),
901    '#default_value' => array('day' => $fecha['dia'], 'month' => $fecha['mes'], 'year' => $fecha['year']),
902    '#required' => TRUE,
903  );
904  $valor_justificacion = isset($reformula['justificacion'])? $reformula['justificacion'] : '';
905  $form['justificacion'] = array(
906    '#title' => t('Justificación'),
907    '#type' => 'textarea',
908    '#default_value' => $valor_justificacion,
909  );
910
911  $form['variacion'] = array(
912    '#type' => 'textfield',
913    '#title' => t('Variación Presupuestaria'),
914    '#default_value' => $valor,
915    '#size' => 30,
916    '#suffix' => '<div class="texto-variacion">' . t('Estimado Usuario: El monto a ingresar debe comenzar con el signo mas "+" o con el signo menos "-".') . '</div>',
917    '#attributes' => array('class' => $clase . ' field-variacion number', 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref2('" . 'field-variacion' . "', 'variacion', '" . $id_field . "');"),
918  );
919  $form['traspaso'] = array(
920    '#type' => 'checkbox',
921    '#title' => t('Traspaso'),
922    '#default_value' => (isset($reformula['tipo']) && $reformula['tipo'] == 1),
923  );
924
925
926  $form['variaciont'] = array(
927    '#type' => 'textfield',
928    '#title' => t('Monto Total de la Modificación'),
929    '#default_value' => $min + $valor,
930    '#size' => 30,
931    '#attributes' => array('class' => 'campo-bloqueado field-variacion-total number1'),
932  );
933  $form['#state_creation'] = -1;
934  //get first state
935  if (module_exists('workflow')) {
936    $estados = _proyectos_operativos_reformulacion_obtiene_estados();
937    $estado_inicial = variable_get('proyectos_operativos_state_reformulacion', 0);
938    if ($estados['wid']) {
939      if ($estado_inicial && $estados['states'][$estado_inicial]) {
940        $form['#state_creation'] = $estado_inicial;
941      }
942      else {
943        $form['#state_creation'] = _workflow_creation_state($estados['wid']);
944      }
945    }
946  }
947  $form['#node'] = $node;
948  $form['#ftypes'] = $ftypes;
949  $form['#grupos'] = $grupos;
950  $form['#unidadesm'] = $unidadesm;
951  $form['#variaciones'] = $variaciones;
952  $form['#reformula'] = $reformula;
953  $form['#id_ref'] = $id_ref;
954  $form['#total_accion'] = $total_accion;
955  $mes_inicio = 0;
956  $mes_fin = 12;
957  if (!variable_get('proyectos_operativos_reformulacion_meses', TRUE)) {
958    $f_aux = explode(' ', $node->field_proyecto_fecha_i[0]['value']);
959    $f_aux = explode('-', $f_aux[0]);
960    $mes_inicio = (int) $f_aux[1];
961    $f_aux = explode(' ', $node->field_proyecto_fecha_f[0]['value']);
962    $f_aux = explode('-', $f_aux[0]);
963    $mes_fin = (int) $f_aux[1];
964  }
965  $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;
966  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
967  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
968  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
969  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
970  $format_number = array(
971    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
972    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
973    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
974  );
975  $form['#format_number'] = array('format_number' => $format_number);
976  drupal_add_js($form['#format_number'], 'setting');
977  $i = 1;
978  $sumafisica = 0;
979  $sumaT = 0;
980  $sumaTv = 0;
981  $sumaplanm = array();
982  foreach($ftypes as $id_field => $texto) {
983    $clase = '';
984    if ($form['#mes'] >= $i) {
985      $clase .= 'campo-bloqueado ';
986    }
987    elseif($mes_inicio > $i) {
988      $clase .= 'campo-bloqueado ';
989    }
990    elseif($mes_fin < $i) {
991      $clase .= 'campo-bloqueado ';
992    }
993    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
994    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
995    $total_accion += $min;
996    $valor = isset($reformula['field_proyecto_meta_fisica'][0][$id_field])? $reformula['field_proyecto_meta_fisica'][0][$id_field] : 0;
997    $sumafisica += $valor;
998    $sumaT += $min + $valor;
999    $idformuj = str_replace('_', '-', 'field_proyecto_meta_fisica_' . $id_field);
1000    if (!isset($sumaplanm[$id_field])) {
1001      $sumaplanm[$id_field] = 0;
1002    }
1003    $sumaTv += $min;
1004    $sumaplanm[$id_field] = $min;
1005    $form['field_proyecto_meta_fisica_' . $id_field] = array(
1006      '#type' => 'textfield',
1007      '#default_value' => $valor,
1008      '#size' => 15,
1009      '#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')"),
1010    );
1011    $form['field_proyecto_meta_fisica_to_' . $id_field] = array(
1012      '#type' => 'textfield',
1013      '#default_value' => $min + $valor,
1014      '#size' => 15,
1015      '#attributes' => array('class' => 'campo-bloqueado subtotales subtotal-' . $id_field . '-total number1'),
1016    );
1017    $i++;
1018  }
1019  $form['field_proyecto_meta_fisica_total'] = array(
1020    '#type' => 'textfield',
1021    '#default_value' => $sumafisica,
1022    '#size' => 15,
1023    '#attributes' => array('class' => 'campo-bloqueado field-proyecto-meta-fisica-r-total number1'),
1024  );
1025  $form['field_proyecto_meta_fisica_totalt'] = array(
1026    '#type' => 'textfield',
1027    '#default_value' => $sumaT,
1028    '#size' => 15,
1029    '#attributes' => array('class' => 'campo-bloqueado subtotales-total number1'),
1030  );
1031  $sumaacciones = 0;
1032  $sumaaccionm = array();
1033  $sumaaccionv = 0;
1034  foreach($grupos as $nid => $ae) {
1035    $i = 1;
1036    $sumaP = 0;
1037    $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'];
1038    $form[$nid . '_field_accion_esp_metaf_unidadm'] = array(
1039      '#title' => t('Unidad de Medida Nueva'),
1040      '#type' => 'select',
1041      '#options' => $options,
1042      '#default_value' => $valor_unidad,
1043    );
1044    foreach($ftypes as $id_field => $texto) {
1045      $clase = '';
1046      if ($form['#mes'] >= $i) {
1047        $clase = 'campo-bloqueado ';
1048      }
1049      elseif($mes_inicio > $i) {
1050        $clase .= 'campo-bloqueado ';
1051      }
1052      elseif($mes_fin < $i) {
1053        $clase .= 'campo-bloqueado ';
1054      }
1055      $idformuj = str_replace('_', '-', $nid . '_field_accion_esp_metaf_' . $id_field);
1056      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1057      $min = $ae->field_accion_esp_metaf[0][$id_field] + $varia;
1058      $total_accion += $min;
1059      $valor = isset($reformula['field_accion_esp_metaf_' . $nid][0][$id_field])? $reformula['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1060      $sumaacciones += $min + $valor;
1061      $sumaP += $valor;
1062      if (!isset($sumaaccionm[$id_field])) {
1063        $sumaaccionm[$id_field] = 0;
1064      }
1065      $sumaaccionv += $min;
1066      $sumaaccionm[$id_field] += $min;
1067      $form[$nid . '_field_accion_esp_metaf_' . $id_field] = array(
1068        '#type' => 'textfield',
1069        '#default_value' => $valor,
1070        '#size' => 15,
1071        '#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 . ");"),
1072      );
1073      $i++;
1074    }
1075    $form[$nid . '_field_accion_esp_metaf_t'] = array(
1076      '#type' => 'textfield',
1077      '#default_value' => $sumaP,
1078      '#size' => 15,
1079      '#attributes' => array('class' => 'campo-bloqueado ' . $nid . '-field-accion-esp-metaf-total number1'),
1080    );
1081  }
1082  foreach($ftypes as $id_field => $texto) {
1083    $form['field_accion_esp_metaft_' . $id_field] = array(
1084      '#type' => 'textfield',
1085      '#default_value' => $sumaaccionm[$id_field],
1086      '#size' => 15,
1087      '#attributes' => array('class' => 'campo-bloqueado subtotales1 subtotal1-' . $id_field . '-total number1'),
1088    );
1089  }
1090  $form['field_accion_esp_metaftt'] = array(
1091    '#type' => 'textfield',
1092    '#default_value' => $sumaacciones,
1093    '#size' => 15,
1094    '#attributes' => array('class' => 'campo-bloqueado subtotales1-total number1'),
1095  );
1096  $jse = array(
1097    'sumatotal' => $sumaTv,
1098    'sumaplan' => $sumaplanm,
1099    'sumaacciones' => $sumaaccionv,
1100    'sumaaccion' => $sumaaccionm,
1101    'variacion' => $suma_variacion,
1102  );
1103  $form['#jse'] = $jse;
1104  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
1105  $form['buttons'] = array(
1106    '#prefix' => '<div class="container-inline">',
1107    '#suffix' => '</div>',
1108  );
1109  $form['buttons']['registrar'] = array(
1110    '#type' => 'submit',
1111    '#default_value' => t('Guardar'),
1112    '#weight' => 100,
1113  );
1114  $form['buttons']['cancelar'] = array(
1115    '#type' => 'submit',
1116    '#default_value' => t('Cancelar'),
1117    '#weight' => 101,
1118  );
1119  return $form;
1120}
1121
1122/*
1123 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
1124 */
1125function proyectos_reformulacion_reformula_tab_page_form_validate($form, &$form_state) {
1126  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1127  if ($op == t('Cancelar')) {
1128    return;
1129  }
1130  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
1131  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
1132  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
1133  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
1134  drupal_add_js($form['#format_number'], 'setting');
1135  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
1136  $start = $form_state['values']['variacion'];
1137  $value = preg_replace('@[^-0-9]@', '', $start);
1138  if ($start != $value) {
1139    form_set_error('variacion', t('Solo números enteros son permitidos en la variación presupuestaria.'));
1140  }
1141  $ftypes = $form['#ftypes'];
1142  foreach($ftypes as $id_field => $texto) {
1143    $start = $form_state['values']['field_proyecto_meta_fisica_' . $id_field];
1144    $value = preg_replace('@[^-0-9]@', '', $start);
1145    if ($start != $value) {
1146      form_set_error('field_proyecto_meta_fisica_' . $id_field, t('Solo números enteros son permitidos en la meta física.'));
1147    }
1148
1149    if ($form_state['values']['field_proyecto_meta_fisica_' . $id_field] + $form['#jse']['sumaplan'][$id_field] < 0) {
1150      form_set_error('field_proyecto_meta_fisica_' . $id_field, t('El valor para modificar la meta física no puede ser menor que cero'));
1151    }
1152  }
1153  foreach($form['#grupos'] as $nid => $grupo) {
1154    foreach($ftypes as $id_field => $texto) {
1155      $start = $form_state['values'][$nid . '_field_accion_esp_metaf_' . $id_field];
1156      $value = preg_replace('@[^-0-9]@', '', $start);
1157      if ($start != $value) {
1158        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.'));
1159      }
1160    }
1161  }
1162}
1163
1164/*
1165 * Implementation of proyectos_reformulacion_reformula_tab_page_form_submit()
1166 */
1167function proyectos_reformulacion_reformula_tab_page_form_submit($form, &$form_state) {
1168  global $user;
1169  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1170  if ($op == t('Cancelar')) {
1171    drupal_set_message(t('La modificación ha sido cancelada.'));
1172    if ($form['#id_ref']) {
1173      $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref'] . '/view';
1174    }
1175    else {
1176      $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular';
1177    }
1178    return;
1179  }
1180  $fecha_onapre = mktime(0, 0, 0, $form_state['values']['fecha_onapre']['month'], $form_state['values']['fecha_onapre']['day'], $form_state['values']['fecha_onapre']['year']);
1181  $ftypes = $form['#ftypes'];
1182  $id_ref = $form['#id_ref'];
1183  $campos = array();
1184  $justificacion = check_plain($form_state['values']['justificacion']);
1185  $campos[] = "field_name = 'field_proyecto_meta_fisica'";
1186  foreach($form['#grupos'] as $nid => $grupo) {
1187    $campos[] = "'field_accion_esp_metaf_" . $nid . "'";
1188  }
1189  db_query("DELETE FROM {proyectos_reformula} WHERE nid = %d AND id_ref = %d AND ae = 0", $form['#node']->nid, $id_ref);
1190  if(!$id_ref) {
1191    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);
1192    $id_ref = db_last_insert_id('proyectos_reformular', 'id_ref');
1193  }
1194  $field = array();
1195  $field[] = $id_ref;
1196  $field[] = 'field_proyecto_meta_fisica';
1197  $field[] = 0;
1198  $field[] = $form['#node']->nid;
1199  foreach($ftypes as $id_field => $texto) {
1200    $field[] = $form_state['values']['field_proyecto_meta_fisica_' . $id_field];
1201  }
1202  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);
1203  foreach($form['#grupos'] as $nid => $grupo) {
1204    $field = array();
1205    $field[] = $id_ref;
1206    $field[] = 'field_accion_esp_metaf_' . $nid;
1207    $field[] = 0;
1208    $field[] = $form['#node']->nid;
1209    foreach($ftypes as $id_field => $texto) {
1210      $field[] = $form_state['values'][$nid . '_field_accion_esp_metaf_' . $id_field];
1211    }
1212    $field[] = $form_state['values'][$nid . '_field_accion_esp_metaf_unidadm'];
1213    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);
1214  }
1215  drupal_set_message(t('La modificación fue actualizada'));
1216  $tipo = 1;
1217  if (!$form_state['values']['traspaso'] && $form_state['values']['variacion'] < 0){
1218    $tipo = 3;
1219  }
1220  elseif(!$form_state['values']['traspaso'] && $form_state['values']['variacion'] > 0) {
1221    $tipo = 2;
1222  }
1223  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);
1224  $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $id_ref . '/view';
1225}
1226
1227/*
1228 * Implementation of _proyectos_reformulacion_load()
1229 */
1230function _proyectos_reformulacion_load($node, $id_ref = 0) {
1231  $reformula_load = proyectosop_menu_reformulacion_load($id_ref, $node);
1232  $reformula = array();
1233  $inputs = array();
1234  $sql = "SELECT * FROM {proyectos_reformula} WHERE nid = %d";
1235  $sql1 = "SELECT * FROM {proyectos_reformula_fuente} WHERE nid = %d";
1236  $inputs[] = $node->nid;
1237  if ($reformula_load) {
1238    $reformula['total'] = $reformula_load->variacion;
1239    $reformula['unidad'] = $reformula_load->unidad;
1240    $reformula['fecha_onapre'] = $reformula_load->fecha_onapre;
1241    $reformula['justificacion'] = $reformula_load->justificacion;
1242    $reformula['estado'] = $reformula_load->estado;
1243    $reformula['tipo'] = $reformula_load->tipo;
1244    $sql .= ' AND id_ref = %d';
1245    $sql1 .= ' AND id_ref = %d';
1246    $inputs[] = $id_ref;
1247    $result = db_query($sql, $inputs);
1248    while($partida = db_fetch_array($result)) {
1249      $reformula[$partida['field_name']][$partida['partida']] = $partida;
1250    }
1251    $result = db_query($sql1, $inputs);
1252    while($partida = db_fetch_array($result)) {
1253      $reformula[$partida['field_name']][0] = $partida;
1254    }
1255  }
1256  return $reformula;
1257}
1258
1259/*
1260 * Implementation of _proyectos_reformula_all_load()
1261 */
1262function _proyectos_reformula_all_load($node, $id_ref = 0) {
1263  $reformulaciones = array();
1264  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1265  $result = db_query("SELECT * FROM {proyectos_reformular} WHERE nid = %d AND estado = %d ORDER BY id_ref DESC", $node->nid, $estado_aprobado);
1266  while($reformula = db_fetch_array($result)) {
1267    $reformulaciones[$reformula['id_ref']] = $reformula;
1268  }
1269  return $reformulaciones;
1270}
1271
1272/*
1273 * Implementation of _proyectos_reformulacion_reformula_all_partidas_load()
1274 */
1275function _proyectos_reformula_all_partidas_load($node, $id_ref = 0) {
1276  $variaciones = array();
1277  $ftypes = array(
1278    'value' => t('January'),
1279    'value_1' => t('February'),
1280    'value_2' => t('March'),
1281    'value_3' => t('April'),
1282    'value_4' => t('May'),
1283    'value_5' => t('June'),
1284    'value_6' => t('July'),
1285    'value_7' => t('August'),
1286    'value_8' => t('September'),
1287    'value_9' => t('Octuber'),
1288    'value_10' => t('November'),
1289    'value_11' => t('December'),
1290    'unidad' => t('Unidad'),
1291  );
1292  $load_reformulaciones = array();
1293  $reformulaciones = _proyectos_reformula_all_load($node, $id_ref);
1294  if ($id_ref) {
1295    foreach($reformulaciones as $id => $value) {
1296      if ($id < $id_ref) {
1297        $load_reformulaciones[$id] = $values;
1298      }
1299    }
1300  }
1301  else {
1302    $load_reformulaciones = $reformulaciones;
1303  }
1304  $current_id = 0;
1305  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1306  if(count($load_reformulaciones)) {
1307    foreach($load_reformulaciones as $id => $value) {
1308      $nueva_variacion = _proyectos_reformulacion_load($node, $id);
1309      if ($estado_aprobado == $nueva_variacion['estado'] && !$current_id) {
1310        $current_id = $id;
1311      }
1312      elseif($estado_aprobado == $nueva_variacion['estado'] && $current_id && $id > $current_id) {
1313        $current_id = $id;
1314      }
1315      if(count($nueva_variacion)) {
1316        foreach($nueva_variacion as $id_campo => $campo) {
1317          if ($id_campo != 'total' && $id_campo != 'unidad') {
1318            if(is_array($campo) && count($campo)) {
1319              foreach($campo as $id_partida => $partida) {
1320                if (!isset($variaciones[$id_campo][$id_partida]['partida'])) {
1321                  $variaciones[$id_campo][$id_partida]['partida'] = $partida['partida'];
1322                }
1323                foreach($ftypes as $idc => $valor) {
1324                  if (!isset($variaciones[$id_campo][$id_partida][$idc])) {
1325                    $variaciones[$id_campo][$id_partida][$idc] = 0;
1326                  }
1327                  if ($idc == 'unidad') {
1328                    if ($current_id == $id) {
1329                      $variaciones[$id_campo][$id_partida][$idc] = $partida[$idc];
1330                    }
1331                  }
1332                  else {
1333                    $variaciones[$id_campo][$id_partida][$idc] += $partida[$idc];
1334                  }
1335                }
1336              }
1337            }
1338          }
1339          else {
1340            if ($id_campo == 'total') {
1341              if (!isset($variaciones['total'])) {
1342                $variaciones['total'] = 0;
1343              }
1344              $variaciones['total'] += $campo;
1345            }
1346            else {
1347              $variaciones['unidad'] = $campo;
1348            }
1349          }
1350        }
1351      }
1352    }
1353  }
1354  return $variaciones;
1355}
1356
1357/*
1358 * Implementation of theme_proyectos_reformulacion_reformula_tab_page_form()
1359 */
1360function theme_proyectos_reformulacion_reformula_tab_page_form($form) {
1361  $node = $form['#node'];
1362  $variaciones = $form['#variaciones'];
1363  $reformula = $form['#reformula'];
1364  $planificado = t('planificado');
1365  $total_AE_text = t('Total AE');
1366  $variacion = t('variación');
1367  $reformula = _proyectos_reformulacion_load($node, $id_ref);
1368  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
1369  $output = '<p align="justify">Condiciones de las modificaciones de los proyectos:</p>
1370<ol>
1371<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>
1372<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>
1373<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>
1374<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>';
1375  $output .= '<fieldset><legend>' . t('Monto Total del Proyecto') . '</legend>';
1376  $rows = array();
1377  $row = array();
1378  $row[] = array('data' => drupal_render($form['fecha_onapre']) . drupal_render($form['traspaso']));
1379  $row[] = array('data' => drupal_render($form['justificacion']));
1380  $rows[] = $row;
1381  $row = array();
1382  $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);
1383  $rows[] = $row;
1384  $row = array();
1385  $row[] = array('data' => drupal_render($form['variacion']), );
1386  $row[] = array('data' => drupal_render($form['variaciont']), );
1387  $rows[] = $row;
1388  $output .= theme('table', array(), $rows) . '</fieldset>';
1389  $output .= '<fieldset><legend>' . t('Distribución de la Meta Física') . '</legend>';
1390  $output .= '<fieldset><legend>' . t('Meta Física del Proyecto') . '</legend>';
1391  $output .= drupal_render($form['field_proyecto_unidadm_ant']);
1392  $output .= drupal_render($form['field_proyecto_unidadm']);
1393  $header = array();
1394  $header[] = array('data' => t('Meta Física del Proyecto'));
1395  $rows = array();
1396  $row = array();
1397  $row1 = array();
1398  $row2 = array();
1399  $row[] = array('data' => $planificado, );
1400  $row1[] = array('data' => $variacion, );
1401  $row2[] = array('data' => '<b>' . t('TOTAL') . '</b>', );
1402  $min_planificado = 0;
1403  foreach($form['#ftypes'] as $id_field => $texto) {
1404    $header[] = array('data' => $texto);
1405    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
1406    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
1407    $min_planificado += $min;
1408    $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1409    $row1[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_' . $id_field]), );
1410    $row2[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_to_' . $id_field]), );
1411  }
1412  $row[] = array('data' => number_format($min_planificado, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1413  $row1[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_total']), );
1414  $row2[] = array('data' => drupal_render($form['field_proyecto_meta_fisica_totalt']), );
1415  $rows[] = $row;
1416  $rows[] = $row1;
1417  $rows[] = $row2;
1418  $header[] = array('data' => t('TOTAL'));
1419  $output .= theme('table', $header, $rows);
1420  $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>';
1421  $output .= '</fieldset>';
1422  $output .= '<fieldset><legend>' . t('Meta Física de las Acciones Específicas') . '</legend>';
1423  $header = array();
1424  $header[] = array('data' => t('Meta Física de las AEs'));
1425  $header[] = array('data' => t('Unidad de Medida'));
1426  $header[] = array('data' => t('% de la AEs'),);
1427  $header[] = array('data' => '-',);
1428  foreach($form['#ftypes'] as $id_field => $texto) {
1429    $header[] = array('data' => $texto);
1430  }
1431  $header[] = array('data' => t('TOTAL'));
1432  $rows = array();
1433  $rowsF = array();
1434  $i = 0;
1435    $rowF = array();
1436    $rowF[] = array('data' => '<b>' . t('Número') . '</b>', 'align' => center,);
1437    $rowF[] = array('data' => '<b>' . t('Nombre') . '</b>', 'align' => center,);
1438    $rowsF[] = $rowF;
1439  foreach($form['#grupos'] as $nid => $grupo) {
1440    $i++;
1441    $row = array();
1442    $rowF = array();
1443    $row1 = array();
1444    $row2 = array();
1445    $rowF[] = array('data' => t('AE %numero', array('%numero' => $i)));
1446    $rowF[] = array('data' => $grupo->titulo_asignado);
1447    $rowsF[] = $rowF;
1448    $row[] = array('data' => t('AE %numero', array('%numero' => $i)), 'rowspan' => 3);
1449    $row[] = array('data' => $form['#unidadesm'][$grupo->field_accion_esp_unidadm[0]['value']] . drupal_render($form[$nid . '_field_accion_esp_metaf_unidadm']), 'rowspan' => 3);
1450    $row[] = array('data' => $grupo->field_accion_esp_ponderacion[0]['value'], 'rowspan' => 3);
1451    $row[] = array('data' => $planificado, );
1452    $row1[] = array('data' => $variacion, );
1453    $row2[] = array('data' => $total_AE_text, );
1454    $min_planificado = 0;
1455    $total_AE = 0;
1456    $min_partida = 0;
1457    foreach($form['#ftypes'] as $id_field => $texto) {
1458      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1459      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1460      $min_partida += $min;
1461    }
1462    foreach($form['#ftypes'] as $id_field => $texto) {
1463      $idformuj = str_replace('_', '-', $nid . '_field_accion_esp_metaf_' . $id_field);
1464      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1465      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1466      $min_planificado += $min;
1467      $total_AE += $min + $form[$nid . '_field_accion_esp_metaf_' . $id_field]['#value'];
1468      $form[$nid . '_field_accion_esp_metaf_' . $id_field]['#attributes']['onchange'] .= "sumatotalAE('" . $nid . '-field-accion-esp-metaf-t' . "', " . $min_partida . ");";
1469      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1470      $row1[] = array('data' => drupal_render($form[$nid . '_field_accion_esp_metaf_' . $id_field]), );
1471      $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>', );
1472    }
1473    $row[] = array('data' => number_format($min_planificado, 0, ',', '.'), );
1474    $row1[] = array('data' => drupal_render($form[$nid . '_field_accion_esp_metaf_t']), );
1475    $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>', );
1476    $rows[] = $row;
1477    $rows[] = $row1;
1478    $rows[] = $row2;
1479  }
1480  $row = array();
1481  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 4, 'align' => 'right');
1482  foreach($form['#ftypes'] as $id_field => $texto) {
1483    $row[] = array('data' => drupal_render($form['field_accion_esp_metaft_' . $id_field]), );
1484  }
1485  $row[] = array('data' => drupal_render($form['field_accion_esp_metaftt']), );
1486  $rows[] = $row;
1487  $output .= theme('table', $header, $rows);
1488  $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>';
1489  $header = array();
1490  $header[] = array('data' => t('Detalles de las Acciones Específicas'), 'colspan' => 2, 'align' => center);
1491  $output .= theme('table', $header, $rowsF);
1492  $output .= '</fieldset>';
1493  $output .= '</fieldset>';
1494  $output .= '<div id="acciones-centralizadas-form-acciones">' . drupal_render($form) .'</div>';
1495  return $output;
1496}
1497
1498/**
1499 * Implementation of _proyectos_operativos_reformula_obtiene_estados().
1500 * Obtiene los estados del tipo de contenido proyecto.
1501 */
1502function _proyectos_operativos_reformulacion_obtiene_estados() {
1503  $estados = array();
1504  $wid = 0;
1505  if (module_exists('workflow')) {
1506    $wid = workflow_get_workflow_for_type('proyectos_operativos');
1507    if ($wid){
1508      $estados = workflow_get_states($wid);
1509    }
1510  }
1511  return array(
1512    'wid' => $wid,
1513    'states' => $estados,
1514  );
1515}
1516
1517/*
1518 * Implementation of _proyectos_reformulacion_reformula_list_page()
1519 */
1520function _proyectos_reformulacion_reformula_list_page($node) {
1521  drupal_set_title(t('Modificaciones del Proyecto'));
1522  $output = '';
1523  $output .= _proyectos_reformulacion_reformula_obtiene_list_page($node, TRUE);
1524  return $output;
1525}
1526
1527/*
1528 * Implementation of _proyectos_reformulacion_reformula_obtiene_list_page()
1529 */
1530function _proyectos_reformulacion_reformula_obtiene_list_page($node, $muestra = TRUE) {
1531  global $user;
1532  $format_number = array(
1533    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1534    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1535    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1536  );
1537  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1538  $breadcrumb = array();
1539  $breadcrumb[] = l(t('Home'), '<front>');
1540  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
1541  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
1542  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
1543  $breadcrumb[] = drupal_get_title();
1544  // Set Breadcrumbs
1545  drupal_set_breadcrumb($breadcrumb);
1546  $current_time = time();
1547  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
1548  $tipo_plan = 'proyectos_operativos_reformular';
1549  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
1550  $fecha = FALSE;
1551  $ente = usuario_tiene_ente($user->uid);
1552  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1553    $fecha = TRUE;
1554  }
1555  if (!$fecha) {
1556    if ($muestra) {
1557      muestra_mensaje($tipo_plan, $ente_planificador->tipo);
1558    }
1559  }
1560  else {
1561    if ($ente->nid == $ente_planificador->nid) {
1562      $fecha = TRUE;
1563      if ($muestra) {
1564        muestra_mensaje($tipo_plan, $ente_planificador->tipo, 0);
1565      }
1566    }
1567    elseif (!user_access('admin planificador')) {
1568      $fecha = FALSE;
1569    }
1570  }
1571  $tipos = array(
1572    1 => t('Traspaso'),
1573    2 => t('Incremento'),
1574    3 => t('Disminución'),
1575  );
1576  $enlaces_estados = TRUE;
1577  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
1578    $enlaces_estados = FALSE;
1579  }
1580  $states = _proyectos_operativos_reformulacion_obtiene_estados();
1581  $first_state = 0;
1582  if ($states['wid']) {
1583    $first_state = _workflow_creation_state($states['wid']);
1584  }
1585  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
1586  $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);
1587  $header = array();
1588  $header[] = array('data' => t('Fecha'));
1589  $header[] = array('data' => t('Estado Actual'));
1590  $header[] = array('data' => t('Estado Anterior'));
1591  $header[] = array('data' => t('Fecha de Aprobación'));
1592  $header[] = array('data' => t('Monto (Bs)'));
1593  $header[] = array('data' => t('Variación (Bs)'));
1594  $header[] = array('data' => t('Tipo'));
1595  $header[] = array('data' => t('Total monto (Bs)'));
1596  $header[] = array('data' => t('Usuario'));
1597  $header[] = array('data' => t('Acción'));
1598  $rows = array();
1599  $i = 1;
1600  $roles = array_keys($user->roles);
1601  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1602  $editar = ($node->_workflow == $estado_aprobado);
1603  while($reformular = db_fetch_object($result)) {
1604    if ($user->uid == 1) {
1605      // Superuser is special.
1606      $roles_transition = 'ALL';
1607    }
1608    else {
1609      $roles_transition = $roles;
1610      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
1611        $roles_transition += array('author' => 'author');
1612      }
1613    }
1614    $transitions = array();
1615    if ($states['wid']) {
1616      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
1617    }
1618    unset($transitions[$reformular->estado]);
1619    $acciones = array();
1620    $row = array();
1621    $row[] = array('data' => format_date($reformular->date),);
1622    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
1623    $row[] = array('data' => $estado,);
1624    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
1625    $row[] = array('data' => $estado,);
1626    $row[] = array('data' => date( 'd/m/Y', $reformular->fecha_onapre),);
1627    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1628    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1629    $tipo = isset($tipos[$reformular->tipo]) ? $tipos[$reformular->tipo] : 'N/A';
1630    $row[] = array('data' => $tipo,);
1631    $total = $reformular->monto + $reformular->variacion;
1632    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1633    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid),);
1634    //display options
1635    if ($editar) {
1636      $acciones[] = l(t('Ver'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view');
1637    }
1638    if ($add_reformular) {
1639      $acciones[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add');
1640    }
1641    if ($editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
1642      $acciones[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit');
1643    }
1644    if ($enlaces_estados && count($transitions) && $reformular->estado != $estado_aprobado) {
1645      foreach($transitions as $id => $transition) {
1646        $acciones[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/workflow/' . $id);
1647      }
1648    }
1649    $row[] = array('data' =>  theme('item_list', $acciones),);
1650    $rows[] = $row;
1651    $i++;
1652  }
1653  if (!count($rows)) {
1654    $row[] = array('data' => 'No existen reformulaciones para este proyecto', 'colspan' => 10);
1655    $rows[] = $row;
1656  }
1657  $output = '';
1658  if ($node->field_acciones_ente[0]['nid']) {
1659    $output = '<fieldset><legend>' . t('Datos de la Acción Centralizada') . '</legend>';
1660    $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1661    $output .= '<div class="field"><div class="field-label">' . t('Ente') . ':</div>' . l($ente_planificador->title, 'proyectosop/' . $ente_planificador->nid) . '</div>';
1662    $output .= '<div class="field"><div class="field-label">' . t('Año') . ':</div>' . $node->anhoproyectos_operativos . '</div>';
1663    $output .= '<div class="field"><div class="field-label">' . t('Autor') . ':</div>' . l($node->name, 'user/' . $node->uid)  . '</div>';
1664    $output .= '<div class="field"><div class="field-label">' . t('Fecha de creación') . ':</div>' . format_date($node->created)  . '</div>';       
1665    $output .= '<div class="field"><div class="field-label">' . t('Fecha de la última actualización') . ':</div>' . format_date($node->changed)  . '</div>';         
1666    if (module_exists('workflow')) {
1667      $states = _proyectos_operativos_reformulacion_obtiene_estados();
1668      $first_state = _workflow_creation_state($states['wid']);
1669      $estado = $node->_workflow == $first_state ? t('Ingresado') : $states['states'][$node->_workflow];
1670      $output .= '<div class="field"><div class="field-label">' . t('Estado del proyecto') . ':</div>' . $estado . '</div>';
1671    }
1672    $output .= '</fieldset>';
1673  }
1674  $output .= '<fieldset><legend>' . t('Modificaciones del proyecto') . '</legend>';
1675  $output .= theme('table', $header, $rows) . '</fieldset>';
1676  return $output;
1677}
1678
1679/*
1680 * Implementation of total_reformulado_ae()
1681 * Obtiene el monto total de las partidas de las acciones especificas
1682 */
1683function total_reformulado_ae($node, $reformula, $exclude = array()) {
1684  $ae_l = array();
1685  $suma_r_ae = 0;
1686  $ftypes = array(
1687    'value' => t('January'),
1688    'value_1' => t('February'),
1689    'value_2' => t('March'),
1690    'value_3' => t('April'),
1691    'value_4' => t('May'),
1692    'value_5' => t('June'),
1693    'value_6' => t('July'),
1694    'value_7' => t('August'),
1695    'value_8' => t('September'),
1696    'value_9' => t('Octuber'),
1697    'value_10' => t('November'),
1698    'value_11' => t('December'),
1699  );
1700  if ($node->field_proyecto_accion_esp[0]['nid']) {
1701    foreach($node->field_proyecto_accion_esp as $ae) {
1702      $ae_l[$ae['nid']] = $ae['nid'];
1703      if (!isset($exclude[$ae['nid']])) {
1704
1705        if (array_key_exists('field_accion_esp_programacion_' . $ae['nid'], $reformula)) {
1706          foreach($reformula['field_accion_esp_programacion_' . $ae['nid']] as $montos_accion) {
1707            foreach ($ftypes as $clave => $valor) {
1708              $suma_r_ae += $montos_accion[$clave];
1709            }
1710          }
1711        }
1712      }
1713    }
1714  }
1715  return $suma_r_ae;
1716}
1717
1718/*
1719 * Implementation of _proyectos_reformulacion_reformula_tab_page_ver()
1720 */
1721function _proyectos_reformulacion_reformula_tab_page_ver($node, $reformulacion_load = 0, $show_variacion = TRUE, $muestra = TRUE) {
1722  drupal_set_title(t('Consultar Modificación'));
1723  global $user;
1724  $format_number = array(
1725    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1726    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1727    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1728  );
1729  $ftypes = array(
1730    'value' => t('January'),
1731    'value_1' => t('February'),
1732    'value_2' => t('March'),
1733    'value_3' => t('April'),
1734    'value_4' => t('May'),
1735    'value_5' => t('June'),
1736    'value_6' => t('July'),
1737    'value_7' => t('August'),
1738    'value_8' => t('September'),
1739    'value_9' => t('Octuber'),
1740    'value_10' => t('November'),
1741    'value_11' => t('December'),
1742  );
1743  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
1744  $breadcrumb = array();
1745  $breadcrumb[] = l(t('Home'), '<front>');
1746  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
1747  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
1748  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
1749  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
1750  $breadcrumb[] = 'Ver Modificación';
1751  // Set Breadcrumbs
1752  drupal_set_breadcrumb($breadcrumb);
1753  $current_time = time();
1754  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
1755  $tipo_plan = 'proyectos_operativos_reformular';
1756  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
1757  $fecha = FALSE;
1758  $ente = usuario_tiene_ente($user->uid);
1759  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1760    $fecha = TRUE;
1761  }
1762  if (!$fecha) {
1763    if ($muestra) {
1764      muestra_mensaje($tipo_plan, $ente_planificador->tipo);
1765    }
1766  }
1767  else {
1768    if ($ente->nid == $ente_planificador->nid) {
1769      $fecha = TRUE;
1770      if ($muestra) {
1771        muestra_mensaje($tipo_plan, $ente_planificador->tipo, 0);
1772      }
1773    }
1774    elseif (!user_access('admin planificador')) {
1775      $fecha = FALSE;
1776    }
1777  }
1778  $enlaces_estados = TRUE;
1779  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
1780    $enlaces_estados = FALSE;
1781  }
1782  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
1783  $editar = ($node->_workflow == $estado_aprobado);
1784  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
1785  $reformula = _proyectos_reformulacion_load($node, $id_ref);
1786  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
1787  //obtiene el total de las variaciones de las acciones especificas
1788  $ae_l = array();
1789  $suma_r_ae = total_reformulado_ae($node, $reformula);
1790  $field = content_fields('field_proyecto_unidadm', 'proyectos_operativos');
1791  $unidad_ant = $node->field_proyecto_unidadm[0]['value'];
1792  $text_unidad = t('N/A');
1793  $tree = taxonomy_get_tree($field['vid']);
1794  $planificado = t('planificado');
1795  $variacion = t('variación');
1796  $options = array();
1797  if ($tree) {
1798    foreach ($tree as $term) {
1799      if ($term->tid == $unidad_ant) {
1800        $text_unidad = $term->name;
1801      }
1802      $choice = new stdClass();
1803      $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
1804      $options[] = $choice;
1805    }
1806  }
1807  $field = content_fields('field_accion_esp_unidadm', 'accion_especifica');
1808  $unidadesm = array();
1809  $tree = taxonomy_get_tree($field['vid']);
1810  if ($tree) {
1811    foreach ($tree as $term) {
1812      $unidadesm[$term->tid] = $term->name;
1813    }
1814  }
1815  $grupos = array();
1816  if ($node->field_proyecto_accion_esp[0]['nid']) {
1817    foreach($node->field_proyecto_accion_esp as $ae) {
1818      $grupos[$ae['nid']] = node_load($ae['nid']);
1819    }
1820  }
1821  $varia = isset($variaciones['total']) ? $variaciones['total'] : 0;
1822  $min = $node->field_proyecto_monto_anual[0]['value'] + $varia;
1823  $valor = isset($reformula['total'])? $reformula['total'] : 0;
1824  $total_accion = $min;
1825  if (module_exists('workflow')) {
1826    $estados = _proyectos_operativos_reformulacion_obtiene_estados();
1827  }
1828  $mes = 2;
1829  $planificado = t('planificado');
1830  $variacion = t('variación');
1831  $subtotal = t('Total AE');
1832  $output = '';
1833  if ($suma_r_ae != $reformula['total']) {
1834    $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>';
1835  }
1836  $output .= '<fieldset><legend>' . t('Resumen del Proyecto') . '</legend>';
1837  $output .= '<div class="field"><div class="field-label">' . t('Código Único del Proyecto') . ':</div>' . $node->field_proyecto_codigo[0]['value'] . '</div>';
1838  $output .= '<div class="field"><div class="field-label">' . t('Nombre del Proyecto') . ':</div>' . $node->titulo_asignado . '</div>';
1839  $output .= '<div class="field"><div class="field-label">' . t('Organismo') . ':</div>' . $ente_planificador->title . '</div>';
1840  $output .= '</fieldset>';
1841  $output .= '<fieldset><legend>' . t('Datos de la Reformulación') . '</legend>';
1842  $states = array();
1843  if (module_exists('workflow')) {
1844    $states = _proyectos_operativos_reformulacion_obtiene_estados();
1845    $header = array();
1846    $header[] = array('data' => t('Fecha'),);
1847    $header[] = array('data' => t('Estado'),);
1848    $header[] = array('data' => t('Estado anterior'),);
1849    $header[] = array('data' => t('Comentario'),);
1850    $header[] = array('data' => t('Usuario'),);
1851    $rows = array();
1852    $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);
1853    while($history = db_fetch_object($result)) {
1854      $row = array();
1855      $row[] = array('data' => format_date($history->date),);
1856      $row[] = array('data' => $states['states'][$history->estado],);
1857      $row[] = array('data' => $states['states'][$history->estado_ant],);
1858      $row[] = array('data' => $history->comentario,);
1859      $row[] = array('data' => l($history->name, 'user/' . $history->uid),);
1860      $rows[] = $row;
1861    }
1862    if (count($rows)) {
1863      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . theme('table', $header, $rows) . '</div>';     
1864    }
1865    else {
1866      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . t('No existe historial para esta modificación') . '</div>';     
1867    }
1868  }
1869  $output .= '</fieldset>';
1870  $output .= '<fieldset><legend>' . t('Monto Total del Proyecto') . '</legend>';
1871  $rows = array();
1872  $row = array();
1873  $row[] = array('data' => t('<b>Fecha de Aprobación:</b> %fecha_onapre', array('%fecha_onapre' => date( 'd/m/Y', $reformula['fecha_onapre']))), 'align' => 'left');
1874  $row[] = array('data' => t('<b>Justificación:</b> %justificacion', array('%justificacion' => $reformula['justificacion'])), 'align' => 'left');
1875  $rows[] = $row;
1876  $row = array();
1877  $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);
1878  $rows[] = $row;
1879  $row = array();
1880  $signo = '';
1881  if ($reformulacion_load->variacion > 0) {
1882    $signo = '+';
1883  }
1884  $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']))), );
1885  $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']))), );
1886  $rows[] = $row;
1887  $output .= theme('table', array(), $rows) . '</fieldset>';
1888  $output .= '<fieldset><legend>' . t('Distribución de la Meta Física') . '</legend>';
1889  $output .= '<fieldset><legend>' . t('Meta Física del Proyecto') . '</legend>';
1890  $output .= '<div class="field"><div class="field-label">' . t('Unidad de Medida Anterior') . ':</div>' . $unidadesm[$node->field_proyecto_unidadm[0]['value']] . '</div>';
1891  $output .= '<div class="field"><div class="field-label">' . t('Unidad de Medida Nueva') . ':</div>' . $unidadesm[$reformulacion_load->unidad] . '</div>';
1892  $header = array();
1893  $header[] = array('data' => t('Meta Física del Proyecto'));
1894  $rows = array();
1895  $row = array();
1896  $row1 = array();
1897  $row2 = array();
1898  $row[] = array('data' => $planificado, );
1899  $row1[] = array('data' => $variacion, );
1900  $row2[] = array('data' => '<b>' . t('TOTAL') . '</b>', );
1901  $total = 0;
1902  $total1 = 0;
1903  foreach($ftypes as $id_field => $texto) {
1904    $header[] = array('data' => $texto);
1905    $varia = isset($variaciones['field_proyecto_meta_fisica'][0][$id_field]) ? $variaciones['field_proyecto_meta_fisica'][0][$id_field] : 0;
1906    $min = $node->field_proyecto_meta_fisica[0][$id_field] + $varia;
1907    $valor = isset($reformula['field_proyecto_meta_fisica'][0][$id_field])? $reformula['field_proyecto_meta_fisica'][0][$id_field] : 0;
1908    $signo = '';
1909    if ($valor > 0) {
1910      $signo = '+';
1911    }
1912    $total += $min;
1913    $total1 += $valor;
1914    $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1915    $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1916    $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1917  }
1918  $row[] = array('data' => number_format($total, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1919  $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1920  $row2[] = array('data' => number_format($total + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1921  $rows[] = $row;
1922  $rows[] = $row1;
1923  $rows[] = $row2;
1924  $header[] = array('data' => t('TOTAL'));
1925  $output .= theme('table', $header, $rows);
1926  $output .= '</fieldset>';
1927  $output .= '<fieldset><legend>' . t('Meta Física de las Acciones Específicas') . '</legend>';
1928  $header = array();
1929  $header[] = array('data' => t('Meta Física de las AEs'));
1930  $header[] = array('data' => t('Unidad de Medida'));
1931  $header[] = array('data' => t('% de la AEs'),);
1932  $header[] = array('data' => '-',);
1933  foreach($ftypes as $id_field => $texto) {
1934    $header[] = array('data' => $texto);
1935  }
1936  $header[] = array('data' => t('TOTAL'));
1937  $rows = array();
1938  $rowsF = array();
1939  $i = 0;
1940    $rowF = array();
1941    $rowF[] = array('data' => '<b>' . t('Número') . '</b>', 'align' => center,);
1942    $rowF[] = array('data' => '<b>' . t('Nombre') . '</b>', 'align' => center,);
1943    $rowF[] = array('data' => '<b>' . t('Acción') . '</b>', 'align' => center,);
1944    $rowsF[] = $rowF;
1945  $totalA = array();
1946  $totalT;
1947  foreach($grupos as $nid => $grupo) {
1948    $i++;
1949    $row = array();
1950    $rowF = array();
1951    $row1 = array();
1952    $row2 = array();
1953    $rowF[] = array('data' => t('AE %numero', array('%numero' => $i)));
1954    $rowF[] = array('data' => $grupo->titulo_asignado);
1955    $links = array();
1956    $links[] = l(t('Ver modificación'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/ae/' . $grupo->nid);
1957    if (_proyectos_reformulacion_reformula_node_edit_tab_access($node, $reformulacion_load)) {
1958      $links[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/ae/' . $grupo->nid . '/edit');
1959    }
1960    $rowF[] = array('data' => theme('item_list', $links),);
1961    $rowsF[] = $rowF;
1962    $row[] = array('data' => t('AE %numero', array('%numero' => $i)), 'rowspan' => 3);
1963    $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);
1964    $row[] = array('data' => $grupo->field_accion_esp_ponderacion[0]['value'], 'rowspan' => 3);
1965    $row[] = array('data' => $planificado, );
1966    $row1[] = array('data' => $variacion, );
1967    $row2[] = array('data' => $subtotal);
1968    $total = 0;
1969    $total1 = 0;
1970    foreach($ftypes as $id_field => $texto) {
1971      $varia = isset($variaciones['field_accion_esp_metaf_' . $nid][0][$id_field]) ? $variaciones['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1972      $min = $grupo->field_accion_esp_metaf[0][$id_field] + $varia;
1973      $valor = isset($reformula['field_accion_esp_metaf_' . $nid][0][$id_field])? $reformula['field_accion_esp_metaf_' . $nid][0][$id_field] : 0;
1974      $signo = '';
1975      if ($valor > 0) {
1976        $signo = '+';
1977      }
1978      $total += $min;
1979      $total1 += $valor;
1980      if (!isset($totalA[$id_field])) {
1981        $totalA[$id_field] = 0;
1982      }
1983      $totalA[$id_field] += $min + $valor;
1984      $totalT += $min + $valor;
1985      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1986      $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1987      $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1988    }
1989    $row[] = array('data' => number_format($total, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1990    $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1991    $row2[] = array('data' => number_format($total + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
1992    $rows[] = $row;
1993    $rows[] = $row1;
1994    $rows[] = $row2;
1995  }
1996  $row = array();
1997  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 4, 'align' => 'right');
1998  foreach($ftypes as $id_field => $texto) {
1999    $row[] = array('data' => number_format($totalA[$id_field], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2000  }
2001  $row[] = array('data' => number_format($totalT, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2002  $rows[] = $row;
2003  $output .= theme('table', $header, $rows);
2004  $header = array();
2005  $header[] = array('data' => t('Detalles de las Acciones Específicas'), 'colspan' => 3, 'align' => center);
2006  $output .= theme('table', $header, $rowsF);
2007  $output .= '</fieldset>';
2008  $output .= '</fieldset>';
2009  if ($show_variacion) {
2010    $links = array();
2011    if ($editar) {
2012      $links[] = l(t('Modificaciones'), 'proyectosop/' . $node->nid . '/reformular');
2013    }
2014    if ($add_reformular) {
2015      $links[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add');
2016    }
2017    if (isset($states['wid'])) {
2018      $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
2019      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) {
2020        $links[] = l(t('Modificar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/edit');
2021      }
2022      $first_state = 0;
2023      if ($states['wid']) {
2024        $first_state = _workflow_creation_state($states['wid']);
2025      }
2026      if ($user->uid == 1) {
2027        // Superuser is special.
2028        $roles = 'ALL';
2029      }
2030      else {
2031        $roles = array_keys($user->roles);
2032        $roles_transition = $roles;
2033        if ($user->uid == $reformulacion_load->uid && $reformulacion_load->uid > 0) {
2034          $roles += array('author' => 'author');
2035        }
2036      }
2037      $transitions = array();
2038      if ($states['wid']) {
2039        $transitions = workflow_allowable_transitions($reformulacion_load->estado, 'to', $roles);
2040      }
2041      unset($transitions[$reformulacion_load->estado]);
2042      if ($suma_r_ae == $reformula['total'] && $enlaces_estados && count($transitions) && $estado_aprobado != $reformulacion_load->estado) {
2043        foreach($transitions as $id => $transition) {
2044          $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'proyectosop/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/workflow/' . $id);
2045        }
2046      }
2047    }
2048    $output .= '<div class="field"><div class="field-label">' . t('Acciones') . ':</div>' . implode(' | ', $links) . '</div>';
2049  }
2050  return $output;
2051}
2052
2053/*
2054 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form()
2055 * Formulario para reformular las acciones especificas
2056 */
2057function proyectos_reformulacion_reformula_tab_page_ae_form($form_state, $node, $reformulacion_load = 0, $ae = 0) {
2058  drupal_set_title(t('Modificar A.E.'));
2059  $form = array();
2060  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2061  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2062  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
2063  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
2064  $ftypes = array(
2065    'value' => t('January'),
2066    'value_1' => t('February'),
2067    'value_2' => t('March'),
2068    'value_3' => t('April'),
2069    'value_4' => t('May'),
2070    'value_5' => t('June'),
2071    'value_6' => t('July'),
2072    'value_7' => t('August'),
2073    'value_8' => t('September'),
2074    'value_9' => t('Octuber'),
2075    'value_10' => t('November'),
2076    'value_11' => t('December'),
2077  );
2078  $partidas_nodo = array();
2079  foreach ($ae->field_accion_esp_programacion as $partida) {
2080    if(!empty($partida['tid'])) {
2081      $partidas_nodo[$partida['tid']] = $partida;
2082    }
2083  }
2084  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2085  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2086  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2087  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2088  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2089  $field = content_fields('field_accion_esp_programacion', 'accion_especifica');
2090  $tree = taxonomy_get_tree($field['vid']);
2091  $vtid = $field['vtid'];
2092  $partidas = array();
2093  if ($tree) {
2094    foreach ($tree as $term) {
2095      if (isset($vtid[$term->tid])) {
2096        $partidas[$term->tid] = $term->name;
2097      }
2098    }
2099  }
2100  //$form['#mes'] = variable_get('accion_especifica_de_proyecto_seguimiento_mes_seguimiento', 0);
2101  $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;
2102  $format_number = array(
2103    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2104    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2105    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2106  );
2107  $form['#format_number'] = array('format_number' => $format_number);
2108  drupal_add_js($form['#format_number'], 'setting');
2109  $totales = array();
2110  $totalT = 0;
2111  $plant = array();
2112  $sumaplan = 0;
2113  $sumaplanm = array();
2114  foreach($partidas as $tid => $term) {
2115    $total = 0;
2116    $total1 = 0;
2117    $i = 1;
2118    foreach($ftypes as $id_field => $texto) {
2119      $varia = isset($variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field]) ? $variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2120      $min = $partidas_nodo[$tid][$id_field] + $varia;
2121      $valor = isset($reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field])? $reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2122      $total1 += $valor;
2123      $totalT += $min + $valor;
2124      if (!isset($plant[$tid])) {
2125        $plant[$tid] = 0;
2126      }
2127      $plant[$tid] += $min;
2128      $sumaplan += $min;
2129      if (!isset($totales[$id_field])) {
2130        $totales[$id_field] = 0;
2131      }
2132      if (!isset($sumaplanm[$id_field])) {
2133        $sumaplanm[$id_field] = 0;
2134      }
2135      $sumaplanm[$id_field] += $min;
2136      $totales[$id_field] += $min + $valor;
2137      $idformu = $ae->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2138      $idformuj = str_replace('_', '-', $idformu);
2139      $clase = '';
2140      if ($form['#mes'] >= $i) {
2141        $clase = 'campo-bloqueado ';
2142      }
2143      $form[$idformu] = array(
2144        '#type' => 'textfield',
2145        '#default_value' => $valor,
2146        '#size' => 15,
2147        '#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),
2148      );
2149      $i++;
2150    }
2151    $form[$ae->nid . '_field_accion_esp_programacion_' . $tid . '_t'] = array(
2152      '#type' => 'textfield',
2153      '#default_value' => $total1,
2154      '#size' => 15,
2155      '#attributes' => array('class' => 'number1 campo-bloqueado field-accion-esp-programacion-r-' . $tid . '-total'),
2156    );
2157  }
2158  foreach($ftypes as $id_field => $texto) {
2159    $form[$ae->nid . '_field_accion_esp_programacion_t_' . $id_field] = array(
2160      '#type' => 'textfield',
2161      '#default_value' => $totales[$id_field],
2162      '#size' => 15,
2163      '#attributes' => array('class' => 'number1 campo-bloqueado subtotales subtotal-' . $id_field . '-total'),
2164    );
2165  }
2166  $form[$ae->nid . '_field_accion_esp_programacion_t'] = array(
2167    '#type' => 'textfield',
2168    '#default_value' => $totalT,
2169    '#size' => 15,
2170    '#attributes' => array('class' => 'number1 campo-bloqueado subtotales-total'),
2171  );
2172  //financiamiento
2173  $arreglo_financiamiento = array();
2174  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
2175  for($i = 0; $i < $accion_especifica_number_fields; $i++) {
2176    $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
2177    $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
2178  }
2179
2180  $form['#plant'] = $plant;
2181  $form['#partidas_nodo'] = $partidas_nodo;
2182  $form['#arreglo'] = $arreglo_financiamiento_fields;
2183  $form['#ftypes'] = $ftypes;
2184  $form['#partidas'] = $partidas;
2185  $form['#node'] = $node;
2186  $form['#variaciones'] = $variaciones;
2187  $form['#reformula'] = $reformula;
2188  $form['#id_ref'] = $id_ref;
2189  $form['#ae'] = $ae;
2190  $form['#reformula_load'] = $reformulacion_load;
2191  $suma_r_ae = total_reformulado_ae($node, $reformula, array($ae->nid => 1));
2192  $monto_asignar = $form['#reformula_load']->variacion - $suma_r_ae;
2193  $form['#monto_asignar'] = $monto_asignar;
2194  $total = 0;
2195  $sumafinm = array();
2196  $sumatotalf = 0;
2197  foreach($arreglo_financiamiento as $id_items => $titulo) {
2198    $form[$id_items] = array(
2199      '#type' => 'fieldset',
2200      '#title' => $titulo,
2201    );
2202    $total1 = 0;
2203    foreach($arreglo_financiamiento_fields[$id_items] as $id1) {
2204      if ($id1) {
2205        $id_items1 = str_replace('_', '-', $id_items);
2206        $varia = isset($variaciones[$id1 . '_' . $ae->nid][0]['value']) ? $variaciones[$id1 . '_' . $ae->nid][0]['value'] : 0;
2207        $min = $ae->{$id1}[0]['value'] + $varia;
2208        if (!isset($sumafinm[$id_items1])) {
2209          $sumafinm[$id_items1] = 0;
2210        }
2211        $valor = isset($reformula[$id1 . '_' . $ae->nid][0]['value'])? $reformula[$id1 . '_' . $ae->nid][0]['value'] : 0;
2212        $sumafinm[$id_items1] += $min;
2213        $sumatotalf += $min;
2214        $field = content_fields($id1, 'accion_especifica');
2215        $total1 += $valor;
2216        $total += $valor;
2217        $idformuj = str_replace('_', '-', $id1);
2218        $form[$id_items][$id1] = array(
2219          '#type' => 'textfield',
2220          '#default_value' => $valor,
2221          '#size' => 20,
2222          '#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>',
2223          '#attributes' => array('class' => 'number subtotalff-' . $id_items1, 'onchange' => "prvalminimo('" . $idformuj . "', '" . $min . "');prsumaref2('" . 'subtotalff-' . $id_items1 . "', 'financia', '" . $id_items1 . "'); prsumaref('subtotalesf')"),
2224        );
2225      }
2226    }
2227
2228    $form['totalf_' . $id_items] = array(
2229      '#type' => 'textfield',
2230      '#default_value' => $sumafinm[$id_items1],
2231      '#size' => 20,
2232      '#attributes' => array('class' => 'number1 campo-bloqueado subtotalesf subtotalff-' . $id_items1 . '-total'),
2233    );
2234  }
2235  $form['total_financiamiento'] = array(
2236    '#type' => 'textfield',
2237    '#default_value' => $sumatotalf,
2238    '#size' => 20,
2239    '#attributes' => array('class' => 'number1 campo-bloqueado subtotalesf-total'),
2240  );
2241  $jse = array(
2242    'sumatotal' => $sumaplan,
2243    'sumaplan' => $sumaplanm,
2244    'financia' => $sumafinm,
2245    'sumatotalf' => $sumatotalf,
2246  );
2247  $form['#jse'] = $jse;
2248  drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
2249  $form['buttons'] = array(
2250    '#prefix' => '<div class="container-inline">',
2251    '#suffix' => '</div>',
2252  );
2253  $form['buttons']['registrar'] = array(
2254    '#type' => 'submit',
2255    '#default_value' => t('Guardar'),
2256    '#weight' => 100,
2257  );
2258  $form['buttons']['cancelar'] = array(
2259    '#type' => 'submit',
2260    '#default_value' => t('Cancelar'),
2261    '#weight' => 101,
2262  );
2263  return $form;
2264}
2265
2266/*
2267 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
2268 */
2269function proyectos_reformulacion_reformula_tab_page_ae_form_validate($form, &$form_state) {
2270  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2271  if ($op == t('Cancelar')) {
2272    return;
2273  }
2274  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2275  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2276  $proyectos_reformulacion_path = drupal_get_path('module', 'proyectos_reformulacion');
2277  drupal_add_js($proyectos_reformulacion_path . '/js/proyectos_reformulacion.js');
2278  //drupal_add_js($form['#format_number'], 'setting');
2279  //drupal_add_js(array('proyectos_reformulacion' => array('mfisicas' => $form['#jse'])), 'setting');
2280  //se obtienen la suma de la meta fisica
2281  $mf = $form['#jse']['sumatotal'];
2282  foreach($form['#partidas'] as $tid => $grupo) {
2283    foreach($form['#ftypes'] as $id_field => $texto) {
2284      $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;
2285      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2286      $start = $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2287      $value = preg_replace('@[^-0-9]@', '', $start);
2288      if ($start != $value) {
2289        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])));
2290      }
2291      if ($form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field] + $min < 0) {
2292        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])));
2293      }
2294      $mf += $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2295    }
2296  }
2297  $finan = $form['#jse']['sumatotalf'];
2298  //se obtiene la suma del financiamiento
2299  foreach($form['#arreglo'] as $id => $arreglo1) {
2300    foreach($arreglo1 as $id1) {
2301      $varia = isset($form['#variaciones'][$id1 . '_' . $form['#ae']->nid][0]['value']) ? $form['#variaciones'][$id1 . '_' . $form['#ae']->nid][0]['value'] : 0;
2302      $min = $form['#ae']->{$id1}[0]['value'] + $varia;
2303      $start = $form_state['values'][$id1];
2304      $value = preg_replace('@[^-0-9]@', '', $start);
2305      if ($start != $value) {
2306        form_set_error($id1, t('Solo números enteros son permitidos en la fuente de financiamiento #nombre.', array('#nombre' => $form[$id1]['#title'])));
2307      }
2308      if ($form_state['values'][$id1] + $min < 0) {
2309        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'])));
2310      }
2311      $finan += $form_state['values'][$id1];
2312    }
2313  }
2314  if ($mf != $finan) {
2315    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)));
2316  }
2317}
2318
2319/*
2320 * Implementation of proyectos_reformulacion_reformula_tab_page_ae_form_validate()
2321 */
2322function proyectos_reformulacion_reformula_tab_page_ae_form_submit($form, &$form_state) {
2323  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2324  if ($op == t('Cancelar')) {
2325    drupal_set_message(t('La modificación ha sido cancelada.'));
2326    $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref']. '/ae/' . $form['#ae']->nid;
2327    return;
2328  }
2329  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);
2330  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);
2331  foreach($form['#partidas'] as $tid => $grupo) {
2332    $suma = 0;
2333    $field = array();
2334    $field[] = $form['#id_ref'];
2335    $field[] = 'field_accion_esp_programacion_' . $form['#ae']->nid;
2336    $field[] = $tid;
2337    $field[] = $form['#node']->nid;
2338    foreach($form['#ftypes'] as $id_field => $texto) {
2339      $suma += $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2340      $field[] = $form_state['values'][$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field];
2341    }
2342    if ($suma) {
2343      $field[] = $form['#ae']->nid;
2344      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);
2345    }
2346  }
2347  foreach($form['#arreglo'] as $id => $arreglo1) {
2348    foreach($arreglo1 as $id1) {
2349      if ($form_state['values'][$id1]) {
2350        $field = array();
2351        $field[] = $form['#id_ref'];
2352        $field[] = $id1 . '_' . $form['#ae']->nid;
2353        $field[] = $form['#node']->nid;
2354        $field[] = $form['#ae']->nid;
2355        $field[] = $form_state['values'][$id1];
2356        db_query("INSERT INTO {proyectos_reformula_fuente} (id_ref, field_name, nid, ae, value) VALUES (%d, '%s', %d, %d, %f)", $field);
2357      }
2358    }
2359  }
2360  drupal_set_message(t('Se modifico la formulación de la acción específica @nombre', array('@nombre' => $form['#ae']->titulo_asignado)));
2361  $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid . '/reformular/' . $form['#id_ref'] . '/ae/' . $form['#ae']->nid;
2362}
2363
2364/*
2365 * Implementation of theme_proyectos_reformulacion_reformula_tab_page_form()
2366 */
2367function theme_proyectos_reformulacion_reformula_tab_page_ae_form($form) {
2368  $planificado = t('planificado');
2369  $variacion = t('variación');
2370  $totalAEtexto = t('Total AE');
2371  $output = '';
2372  if ($form['#monto_asignar'] != 0) {
2373    $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>';
2374  }
2375  else {
2376    $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>';
2377  }
2378  $output .= '<fieldset><legend>' . t('Resumen Financiero de las Acciones') . '</legend>';
2379  $header = array();
2380  $header[] = array('data' => t('Partidas'), 'colspan' => 2);
2381  foreach($form['#ftypes'] as $id_field => $texto) {
2382    $header[] = array('data' => $texto);
2383  }
2384  $header[] = array('data' => t('TOTAL'));
2385  $rows = array();
2386  $rowsF = array();
2387  $i = 0;
2388  foreach($form['#partidas'] as $tid => $grupo) {
2389    $i++;
2390    $row = array();
2391    $row1 = array();
2392    $row2 = array();
2393    $row[] = array('data' => $grupo, 'rowspan' => 3);
2394    $row[] = array('data' => $planificado, );
2395    $row1[] = array('data' => $variacion, );
2396    $row2[] = array('data' => $totalAEtexto, );
2397    $totales_partida = 0;
2398    foreach($form['#ftypes'] as $id_field => $texto) {
2399      $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;
2400      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2401      $totales_partida += $min;
2402    }
2403    foreach($form['#ftypes'] as $id_field => $texto) {
2404      $idformu = $form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2405      $idformuj = str_replace('_', '-', $idformu);
2406      $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;
2407      $min = $form['#partidas_nodo'][$tid][$id_field] + $varia;
2408      $form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]['#attributes']['onchange'] .= ";sumatotalAE('" . $idformuj . "'," . $min . ")";
2409      $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 . ");";
2410      $form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]['#attributes']['total_partida'] = $totales_partida;
2411      $row[] = array('data' => number_format($min, 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), );
2412      $row1[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field]), );
2413      $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>', );
2414    }
2415    $row[] = array('data' => number_format($form['#plant'][$tid], 0, $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), );
2416    $row1[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_' . $tid . '_t']), );
2417    $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>', );
2418    $rows[] = $row;
2419    $rows[] = $row1;
2420    $rows[] = $row2;
2421  }
2422  $row = array();
2423  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 2, 'align' => 'right');
2424  foreach($form['#ftypes'] as $id_field => $texto) {
2425    $row[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_t_' . $id_field]), );
2426  }
2427  $row[] = array('data' => drupal_render($form[$form['#ae']->nid . '_field_accion_esp_programacion_t']), );
2428  $rows[] = $row;
2429  $output .= theme('table', $header, $rows);
2430  $output .= '</fieldset>';
2431  $rows = array();
2432  $row = array();
2433  $row1 = array();
2434  foreach($form['#arreglo'] as $id => $arreglo1) {
2435    $row[] = array('data' => drupal_render($form[$id]), );
2436    $row1[] = array('data' => drupal_render($form['totalf_' . $id]), );
2437  }
2438  $rows[] = $row;
2439  $rows[] = $row1;
2440  $row = array();
2441  $row[] = array('data' => '<b>' . t('TOTAL') . ':</b>', 'colspan' => 3, 'align' => 'right');
2442  $row[] = array('data' => drupal_render($form['total_financiamiento']), );
2443  $rows[] = $row;
2444  $output .= '<fieldset><legend>' . t('Distribución por fuentes de Financiamiento') . '</legend>' . theme('table', array(), $rows) . '</fieldset>';
2445  $output .= '<div id="proyectos-reformulacion-form-acciones">' . drupal_render($form) .'</div>';
2446  return $output;
2447}
2448
2449/*
2450 * Implementation of _proyectos_reformulacion_reformula_tab_page_ver_ae()
2451 */
2452function _proyectos_reformulacion_reformula_tab_page_ver_ae($node, $reformulacion_load = 0, $ae = 0) {
2453  drupal_set_title(t('Consultar Modificación de A.E.'));
2454  $planificado = t('planificado');
2455  $format_number = array(
2456    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2457    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2458    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2459  );
2460  $variacion = t('variación');
2461  $subtotal = t('Total AE');
2462  $ftypes = array(
2463    'value' => t('January'),
2464    'value_1' => t('February'),
2465    'value_2' => t('March'),
2466    'value_3' => t('April'),
2467    'value_4' => t('May'),
2468    'value_5' => t('June'),
2469    'value_6' => t('July'),
2470    'value_7' => t('August'),
2471    'value_8' => t('September'),
2472    'value_9' => t('Octuber'),
2473    'value_10' => t('November'),
2474    'value_11' => t('December'),
2475  );
2476  $partidas_nodo = array();
2477  foreach ($ae->field_accion_esp_programacion as $partida) {
2478    if(!empty($partida['tid'])) {
2479      $partidas_nodo[$partida['tid']] = $partida;
2480    }
2481  }
2482  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2483  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
2484  $breadcrumb = array();
2485  $breadcrumb[] = l(t('Home'), '<front>');
2486  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
2487  $breadcrumb[] = l($ente_planificador->title, 'node/' . $ente_planificador->nid);
2488  $breadcrumb[] = l($node->title, 'proyectosop/' . $node->nid);
2489  $breadcrumb[] = l('Modificaciones', 'proyectosop/' . $node->nid . '/reformular');
2490  $breadcrumb[] = l('Ver Modificación', 'proyectosop/' . $node->nid . '/reformular/' . $id_ref . '/view');
2491  $breadcrumb[] = t('Consultar Modificación de A.E.');
2492  // Set Breadcrumbs
2493  drupal_set_breadcrumb($breadcrumb);
2494  $reformula = _proyectos_reformulacion_load($node, $id_ref);
2495  $variaciones = _proyectos_reformula_all_partidas_load($node, $id_ref);
2496  $field = content_fields('field_accion_esp_programacion', 'accion_especifica');
2497  $tree = taxonomy_get_tree($field['vid']);
2498  $vtid = $field['vtid'];
2499  $partidas = array();
2500  $suma_r_ae = total_reformulado_ae($node, $reformula);
2501  if ($tree) {
2502    foreach ($tree as $term) {
2503      if (isset($vtid[$term->tid])) {
2504        $partidas[$term->tid] = $term->name;
2505      }
2506    }
2507  }
2508  //financiamiento
2509  $arreglo_financiamiento = array();
2510  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
2511  for($i = 0; $i < $accion_especifica_number_fields; $i++) {
2512    $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
2513    $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
2514  }
2515
2516/*
2517  $arreglo = array();
2518  $titles = array(
2519    'ordinarios' => t('Recursos Ordinarios'),
2520    'propios' => t('Recursos Propios'),
2521    'transferencias' => t('Donaciones'),
2522    'otros' => t('Otros'),
2523  );
2524  $titles_field = array(
2525    'field_accion_esp_transferencias' => t('Recursos Ordinarios'),
2526    'field_accion_esp_creditosa' => t('Recursos Propios'),
2527    'transferencias' => t('Donaciones'),
2528    'otros' => t('Otros'),
2529  );
2530  $arreglo['ordinarios'] = array(
2531    'field_accion_esp_transferencias' => 'field_accion_esp_transferencias',
2532    'field_accion_esp_creditosa' => 'field_accion_esp_creditosa',
2533    'field_accion_esp_mcti' => 'field_accion_esp_mcti',
2534  );
2535  $arreglo['propios'] = array(
2536    'field_accion_esp_venta_act' => 'field_accion_esp_venta_act',
2537    'field_accion_esp_activos' => 'field_accion_esp_activos',
2538    'field_accion_esp_flujocaja' => 'field_accion_esp_flujocaja',
2539    'field_accion_esp_ventapro' => 'field_accion_esp_ventapro',
2540  );
2541  $arreglo['transferencias'] = array(
2542    'field_accion_esp_donaciones' => 'field_accion_esp_donaciones',
2543  );
2544  $arreglo['otros'] = array(
2545    'field_accion_esp_gobernacion' => 'field_accion_esp_gobernacion',
2546    'field_accion_esp_misionc' => 'field_accion_esp_misionc',
2547    'field_accion_esp_bid_fona' => 'field_accion_esp_bid_fona',
2548    'field_accion_esp_fonacit' => 'field_accion_esp_fonacit',
2549    'field_accion_esp_fonden' => 'field_accion_esp_fonden',
2550    'field_accion_esp_locti' => 'field_accion_esp_locti',
2551    'field_accion_esp_fondoidi' => 'field_accion_esp_fondoidi',
2552    'field_accion_esp_capitalrie' => 'field_accion_esp_capitalrie',
2553    'field_accion_esp_infocentro' => 'field_accion_esp_infocentro',
2554    'field_accion_esp_fidetel' => 'field_accion_esp_fidetel',
2555  );
2556*/
2557  $output = '';
2558  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
2559  if ($suma_r_ae != $reformula['total']) {
2560    $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>';
2561  }
2562  $output .= '<fieldset><legend>' . t('Resumen del Proyecto') . '</legend>';
2563  $output .= '<div class="field"><div class="field-label">' . t('Código Único del Proyecto') . ':</div>' . $node->field_proyecto_codigo[0]['value'] . '</div>';
2564  $output .= '<div class="field"><div class="field-label">' . t('Nombre del Proyecto') . ':</div>' . $node->titulo_asignado . '</div>';
2565  $output .= '<div class="field"><div class="field-label">' . t('Organismo') . ':</div>' . $ente_planificador->title . '</div>';
2566  $output .= '</fieldset>';
2567  $output .= '<fieldset><legend>' . t('Resumen Financiero de las Acciones') . '</legend>';
2568  $header = array();
2569  $header[] = array('data' => t('Partidas'), 'colspan' => 2);
2570  foreach($ftypes as $id_field => $texto) {
2571    $header[] = array('data' => $texto);
2572  }
2573  $header[] = array('data' => t('TOTAL'));
2574  $rows = array();
2575  $rowsF = array();
2576  $i = 0;
2577  $totales = array();
2578  $totalT = 0;
2579  $plant = array();
2580  $sumaplan = 0;
2581  $sumaplanm = array();
2582  foreach($partidas as $tid => $grupo) {
2583    $i++;
2584    $total = 0;
2585    $total1 = 0;
2586    $row = array();
2587    $row1 = array();
2588    $row2 = array();
2589    $row[] = array('data' => $grupo, 'rowspan' => 3);
2590    $row[] = array('data' => $planificado, );
2591    $row1[] = array('data' => $variacion, );
2592    $row2[] = array('data' => $subtotal, );
2593    foreach($ftypes as $id_field => $texto) {
2594      $varia = isset($variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field]) ? $variaciones['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2595      $min = $partidas_nodo[$tid][$id_field] + $varia;
2596      $valor = isset($reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field])? $reformula['field_accion_esp_programacion_' . $ae->nid][$tid][$id_field] : 0;
2597      $signo = '';
2598      if ($valor > 0) {
2599        $signo = '+';
2600      }
2601      $total1 += $valor;
2602      $totalT += $min + $valor;
2603      if (!isset($plant[$tid])) {
2604        $plant[$tid] = 0;
2605      }
2606      $plant[$tid] += $min;
2607      $sumaplan += $min;
2608      if (!isset($totales[$id_field])) {
2609        $totales[$id_field] = 0;
2610      }
2611      if (!isset($sumaplanm[$id_field])) {
2612        $sumaplanm[$id_field] = 0;
2613      }
2614      $sumaplanm[$id_field] += $min;
2615      $totales[$id_field] += $min + $valor;
2616      $idformu = $ae->nid . '_field_accion_esp_programacion_' . $tid . '_' . $id_field;
2617      $idformuj = str_replace('_', '-', $idformu);
2618      $row[] = array('data' => number_format($min, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2619      $row1[] = array('data' => $signo . number_format($valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2620      $row2[] = array('data' => number_format($min + $valor, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2621    }
2622    $row[] = array('data' => number_format($plant[$tid], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2623    $row1[] = array('data' => number_format($total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2624    $row2[] = array('data' => number_format($plant[$tid] + $total1, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2625    $rows[] = $row;
2626    $rows[] = $row1;
2627    $rows[] = $row2;
2628  }
2629  $row = array();
2630  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => 2, 'align' => 'right');
2631  foreach($ftypes as $id_field => $texto) {
2632    $row[] = array('data' => number_format($totales[$id_field], 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2633  }
2634  $row[] = array('data' => number_format($totalT, 0, $format_number['dec_point'], $format_number['thousands_sep']), );
2635  $rows[] = $row;
2636  $output .= theme('table', $header, $rows);
2637  $output .= '</fieldset>';
2638  $rows = array();
2639  $row = array();
2640  $row1 = array();
2641  $sumalT = 0;
2642  foreach($arreglo_financiamiento as $id_items => $titulo) {
2643    $sumal = 0;
2644    $output1 = '';
2645    foreach($arreglo_financiamiento_fields[$id_items] as $id1) {
2646      if ($id1) {
2647        $field = content_fields($id1, 'accion_especifica');
2648        $varia = isset($variaciones[$id1 . '_' . $ae->nid][0]['value']) ? $variaciones[$id1 . '_' . $ae->nid][0]['value'] : 0;
2649        $min = $ae->{$id1}[0]['value'] + $varia;
2650        if (!isset($sumafinm[$id_items])) {
2651          $sumafinm[$id_items] = 0;
2652        }
2653        $sumafinm[$id_items] += $min;
2654        $sumatotalf += $min;
2655        $field = content_fields($id1, 'accion_especifica');
2656        $valor = isset($reformula[$id1 . '_' . $ae->nid][0]['value'])? $reformula[$id1 . '_' . $ae->nid][0]['value'] : 0;
2657        $total1 += $valor;
2658        $total += $valor;
2659        $sumal += $min + $valor;
2660        $sumalT += $min + $valor;
2661        $idformuj = str_replace('_', '-', $id1);
2662        $signo = '';
2663        if ($valor > 0) {
2664          $signo = '+';
2665        }
2666        $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>';
2667      }
2668    }
2669    $row[] = array('data' => $output1, );
2670    $row1[] = array('data' => number_format($sumal, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
2671  }
2672  $rows[] = $row;
2673  $rows[] = $row1;
2674  $row = array();
2675  $row[] = array('data' => '<b>' . t('TOTAL') . ':</b>', 'colspan' => 3, 'align' => 'right');
2676  $row[] = array('data' => number_format($sumalT, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), );
2677  $rows[] = $row;
2678  $output .= '<fieldset><legend>' . t('Distribución por fuentes de Financiamiento') . '</legend>' . theme('table', array(), $rows) . '</fieldset>';
2679  return $output;
2680}
2681
2682/**
2683 * Implementation of proyectos_reformulacion_search_ac_display_not_approved().
2684 * Muestra la lista de las reformulaciones disponibles que no han sido aprobados.
2685 */
2686function proyectos_reformulacion_search_ac_display_not_approved() {
2687  global $user;
2688  $format_number = array(
2689    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2690    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2691    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2692  );
2693  $current_time = time();
2694  $add_reformular = _proyectos_reformulacion_reformula_node_add_tab_access($node);
2695  $tipo_plan = 'proyectos_operativos_reformular';
2696  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
2697  $fecha = FALSE;
2698  $ente = usuario_tiene_ente($user->uid);
2699  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2700    $fecha = TRUE;
2701  }
2702  if (!$fecha) {
2703    if ($muestra) {
2704      muestra_mensaje($tipo_plan, $ente->tipo);
2705    }
2706  }
2707  else {
2708    if ($ente->nid) {
2709      $fecha = TRUE;
2710      if ($muestra) {
2711        muestra_mensaje($tipo_plan, $ente->tipo, 0);
2712      }
2713    }
2714    elseif (!user_access('admin planificador')) {
2715      $fecha = FALSE;
2716    }   
2717  }
2718  $enlaces_estados = TRUE;
2719  if ($ente->nid && !user_access('admin planificador')) {
2720    $enlaces_estados = FALSE;
2721  }
2722  $states = _proyectos_operativos_reformulacion_obtiene_estados();
2723  $first_state = 0;
2724  if ($states['wid']) {
2725    $first_state = _workflow_creation_state($states['wid']);
2726  }
2727  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
2728  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
2729  $result = db_query('SELECT re.*, u.name, u.uid FROM {proyectos_reformular} re INNER JOIN {users} u ON u.uid = re.uid WHERE estado <> %d AND estado <> %d ORDER BY id_ref DESC', $estado_naprobado, $estado_aprobado);
2730  $header = array();
2731  $header[] = array('data' => t('Proyecto'));
2732  $header[] = array('data' => t('Fecha'));
2733  $header[] = array('data' => t('Estado Actual'));
2734  $header[] = array('data' => t('Fecha de Aprobación'));
2735  $header[] = array('data' => t('Monto (Bs)'));
2736  $header[] = array('data' => t('Variación (Bs)'));
2737  $header[] = array('data' => t('Total monto (Bs)'));
2738  $header[] = array('data' => t('Usuario'));
2739  $header[] = array('data' => t('Acción'));
2740  $rows = array();
2741  $i = 1;
2742  $roles = array_keys($user->roles);
2743  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
2744  while($reformular = db_fetch_object($result)) {
2745    $node = node_load($reformular->nid);
2746    $editar = ($node->_workflow == $estado_aprobado);
2747    if ($user->uid == 1) {
2748      // Superuser is special.
2749      $roles_transition = 'ALL';
2750    }
2751    else {
2752      $roles_transition = $roles;
2753      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
2754        $roles_transition += array('author' => 'author');
2755      }
2756    }
2757    $transitions = array();
2758    if ($states['wid']) {
2759      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
2760    }
2761    $color = variable_get('proyectos_operativos_state_color_' . $reformular->estado, array());
2762    unset($transitions[$reformular->estado]);
2763    $acciones = array();
2764    $row = array();
2765    $row[] = array('data' => $node->title, 'style' => 'background:' . $color,);
2766    $row[] = array('data' => format_date($reformular->date), 'style' => 'background:' . $color,);
2767    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
2768    $row[] = array('data' => $estado, 'style' => 'background:' . $color,);
2769    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
2770    $row[] = array('data' => date( 'd/m/Y', $reformular->fecha_onapre), 'style' => 'background:' . $color,);
2771    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2772    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2773    $total = $reformular->monto + $reformular->variacion;
2774    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'style' => 'background:' . $color,);
2775    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid), 'style' => 'background:' . $color,);
2776    //display options
2777    if ($editar) {
2778      $acciones[] = l(t('Ver'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view');
2779    }
2780    if ($add_reformular) {
2781      $acciones[] = l(t('Agregar nueva modificación'), 'proyectosop/' . $node->nid . '/reformular/add');
2782    }
2783    if ($editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2784      $acciones[] = l(t('Actualizar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit');
2785    }
2786    if ($enlaces_estados && count($transitions) && $reformular->estado != $estado_aprobado) {
2787      foreach($transitions as $id => $transition) {
2788        $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'));
2789      }
2790      if (_proyectos_reformulacion_reformula_node_edit_tab_access($node) && $editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
2791        $links[] = l(t('Actualizar'), 'proyectosop/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit');
2792      }
2793    }
2794    $row[] = array('data' =>  theme('item_list', $acciones), 'style' => 'background:' . $color,);
2795    $rows[] = $row;
2796    $i++;
2797  }
2798  if (!count($rows)) {
2799    $row[] = array('data' => 'No existen modificaciones en el sistema', 'colspan' => 9);
2800    $rows[] = $row;
2801  }
2802  $output = '';
2803  $output .= theme('table', $header, $rows) . '</fieldset>';
2804  return $output;
2805}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.