source: sipes/0.3-modules/acciones_centralizadas/acciones_centralizadas.module @ eb502b4

stable
Last change on this file since eb502b4 was 5432193, checked in by Sipes Apn <root@…>, 7 años ago

se modifico el menu de planificacion para que no mostrara el progreso de las distintas etapas

  • Propiedad mode establecida a 100755
File size: 170.7 KB
Línea 
1<?php
2  /**
3  * Sistema Integral de Planificación y Presupuesto (SIPP)
4  * @file acciones_centralizadas.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-02-02 // (a&#241;o-mes-dia)
24  * @version 0.1 // (0.1)
25  *
26  */
27
28/*
29 * Implementation of hook_node_info()
30 */
31function acciones_centralizadas_node_info() {
32  return array(
33    'accion_centralizada' => array(
34      'name' => t('Acciones Centralizadas'),
35      'description' => '',
36      'has_title' => TRUE,
37      'title_label' => 'Acciones Centralizadas',
38      'has_body' => FALSE,
39      'body_label' => 'Cuerpo',
40      'module' => 'acciones_centralizadas',
41    ),
42  );
43}
44
45/*
46 * Implementation of hook_form()
47 */
48function acciones_centralizadas_form(&$node, $form_state) {
49  $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
50  drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
51  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
52  $format_number = array(
53    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
54    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
55    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
56  );
57  drupal_add_js(array('format_number' => $format_number), 'setting');
58  $current_time = time();
59  $tipo_plan = 'acciones_centralizadas_formular';
60  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
61  $fecha = FALSE;
62  $ente = usuario_tiene_ente($user->uid);
63  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
64    $fecha = TRUE;
65  }
66  if (!$fecha) {
67    muestra_mensaje($tipo_plan, $ente_planificador);
68  }
69  else {
70    if ($ente->nid == $ente_planificador->nid) {
71      muestra_mensaje($tipo_plan, $ente_planificador, 0);
72      $fecha = TRUE;
73    }
74    elseif (!user_access('admin planificador')) {
75      return FALSE;
76    }
77  }
78  if (!$fecha) {
79    return FALSE;
80  }
81  return node_content_form($node, $form_state);
82}
83
84/*
85 * Implementation of hook_access()
86 */
87function acciones_centralizadas_access($op, $node, $account) {
88  global $user;
89  if ($op == 'view') {
90    return user_access('ver planificador') || user_access('admin planificador');
91  }
92  if ($op == 'create') {
93    $current_time = time();
94    $tipo_plan = 'acciones_centralizadas_formular';
95    $ente = usuario_tiene_ente($user->uid);
96    $ente_planificador = 0;
97    if ($ente && $ente->nid) {
98      $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
99    }
100    elseif (user_access('admin planificador') && $enteagregar) {
101      $ente_planificador = ente_planificador_leer_ente_planificadores($enteagregar);
102    }
103    if (!$ente_planificador) {
104      return FALSE;
105    }
106    $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
107    $fecha = FALSE;
108
109    if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
110      $fecha = TRUE;
111    }
112    if (!$fecha) {
113      return FALSE;
114    }
115    if ($user->entes) {
116      $result = db_query("SELECT ac.nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND year = %d AND w.sid <> %d", $user->entes, variable_get('acciones_centralizadas_anho_creacion', 0), variable_get('acciones_centralizadas_state_naprobado', NULL));
117      $acciones_centralizadas = db_fetch_object($result);
118      return !$acciones_centralizadas;
119    }
120    elseif(user_access('admin planificador')) {
121      $entes = array();
122      $result = db_query('SELECT e.nid FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1');
123      while($ente = db_fetch_object($result)) {
124        $entes[$ente->nid] = $ente->nid;
125      }
126      $result = db_query("SELECT ac.ente as nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE year = %d AND w.sid <> %d", variable_get('acciones_centralizadas_anho_creacion', 0), variable_get('acciones_centralizadas_state_naprobado', NULL));
127      while($ente = db_fetch_object($result)) {
128        if (isset($entes[$ente->nid])) {
129          unset($entes[$ente->nid]);
130        }
131      }
132      return count($entes);
133    }
134    return FALSE;
135  }
136  if ($op == 'update') {
137    $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
138    if ($node->_workflow == $estado_aprobado) {
139      return FALSE;
140    }
141    if ($node->anhoaccion_centralizada != variable_get('acciones_centralizadas_anho_creacion', 0)) {
142      return FALSE;
143    }
144    $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
145    $current_time = time();
146    $add_reformular = _acciones_centralizadas_reformula_node_add_tab_access($node);
147    $tipo_plan = 'acciones_centralizadas_formular';
148    $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
149    $fecha = FALSE;
150    $ente = usuario_tiene_ente($user->uid);
151    if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
152      $fecha = TRUE;
153    }
154    if ($fecha) {
155      if ($ente->nid == $ente_planificador->nid) {
156        $fecha = TRUE;
157      }
158      elseif (!user_access('admin planificador')) {
159        $fecha = FALSE;
160      }
161    }
162    $roles_perm = TRUE;
163    if ($fecha && !user_access('admin planificador')) {
164      $roles_perm = FALSE;
165      $roles_allow = variable_get('acciones_centralizadas_state_m_' . $node->_workflow, array());
166      $roles = array_keys($user->roles);
167      if (count($roles)) {
168        foreach($roles as $rol) {
169          if($roles_allow[$rol]) {
170            $roles_perm = TRUE;
171          }
172        }
173      }
174    }
175    return $fecha && $roles_perm;
176  }
177  //solo deje al administrador borrar
178  if ($op == 'delete') {
179    return (user_access('admin planificador'));
180  }
181}
182
183/*
184 * Implementation of _acciones_centralizadas_reformula_obtiene_estados()
185 * Obtiene estados del flujo de trabajo para acciones centralizadas
186 */
187function _acciones_centralizadas_reformula_obtiene_estados() {
188  $estados = array();
189  $wid = 0;
190  if (module_exists('workflow')) {
191    $wid = workflow_get_workflow_for_type('accion_centralizada');
192    if ($wid){
193      $estados = workflow_get_states($wid);
194    }
195  }
196  return array(
197    'wid' => $wid,
198    'states' => $estados,
199  );
200}
201
202/*
203 * Implementation of hook_ente_procesos_alter()
204 */
205function acciones_centralizadas_ente_procesos_alter(&$procesos, $type) {
206/*
207  if ($type == 'status') {
208    $procesos['acciones_centralizadas'] = array(
209      'title' => t('Acciones Centralizadas'),
210      'description' => t('Definición de Proyectos Direccionales'),
211      'weight' => -9,
212    );
213  }
214  else {
215    $procesos['acciones_centralizadas_formular'] = array(
216      'title' => t('Formular Acciones Centralizadas'),
217      'description' => t('Permite agregar, modificar y eliminar posibles las Acciones Centralizadas'),
218      'message' => 'Se podrá registrar y/o modificar las acciones centralizadas desde %fecha hasta la fecha %fecha1',
219      'message_expire' => 'Registrar y/o modificar las acciones centralizadas no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
220      'weight' => 3,
221      'proceso' => 'acciones_centralizadas',
222    );
223    $procesos['acciones_centralizadas_reformular'] = array(
224      'title' => t('Reformular Acciones Centralizadas'),
225      'description' => t('Permite reformular las acciones centralizadas'),
226      'message' => 'Se podrá registrar y/o modificar la reformulación de las acciones centralizadas desde %fecha hasta la fecha %fecha1',
227      'message_expire' => 'Registrar y/o modificar la reformulación de las acciones centralizadas no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
228      'weight' => 3,
229      'proceso' => 'acciones_centralizadas',
230    );
231    $procesos['acciones_centralizadas_seguimiento'] = array(
232      'title' => t('Seguimiento Acciones Centralizadas'),
233      'description' => t('Permite el seguimiento de las Acciones Centralizadas'),
234      'message' => 'Se podrá registrar y/o modificar el seguimiento de las Acciones Centralizadas desde %fecha hasta la fecha %fecha1',
235      'message_expire' => 'Registrar y/o modificar el seguimiento de las Acciones Centralizadas no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
236      'weight' => 3,
237      'proceso' => 'acciones_centralizadas',
238    );
239  }
240*/
241}
242
243/*
244 * Implementation of acciones_centralizadas_status_planificacion_acciones_centralizadas()
245 */
246function acciones_centralizadas_status_planificacion_acciones_centralizadas($ente_planificador, $tipo = 2) {
247  $datos_acciones_centralizadas_status = array();
248  $tipo_plan = 'acciones_centralizadas_formular';
249  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
250  $new_ente_planificador = node_load($ente_planificador);
251  $year = variable_get('acciones_centralizadas_anho_creacion', 0);
252  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
253  $result = db_query("SELECT ac.nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND year = %d AND w.sid = %d", $ente_planificador, $year, $estado_aprobado);
254  $acciones_centralizadas = db_fetch_object($result);
255  //se verifica que exista la planificacion, si existe al menos los datos de familiarizacion fueron ingresados
256  $datos_acciones_centralizadas_status['acciones_centralizadas_formular']['value'] = isset($acciones_centralizadas->nid) ? 1 : 0;
257  $datos_acciones_centralizadas_status['acciones_centralizadas_formular']['title'] = t('Registrar Acciones Centralizadas para el año @year', array('@year' => $year));
258  $datos_acciones_centralizadas_status['acciones_centralizadas_formular']['link'] = isset($acciones_centralizadas->nid) ? 'node/' . $acciones_centralizadas->nid  : 'node/add/accion-centralizada';
259  $datos_acciones_centralizadas_status['acciones_centralizadas_formular']['mylink'] = isset($acciones_centralizadas->nid) ? 'node/' . $acciones_centralizadas->nid  : 'node/add/accion-centralizada';
260  $datos_acciones_centralizadas_status['acciones_centralizadas_formular']['weight'] = -10;
261  $funciones = array();
262  //si existe al menos una reformulacion en estado aprobado la reformulacion se puede considerar terminado
263  $reformular = FALSE;
264  if (isset($acciones_centralizadas->nid)) {
265    $result = db_query('SELECT COUNT(id_ref) AS cantidad FROM {accion_reformular} re INNER JOIN {users} u ON u.uid = re.uid WHERE nid = %d AND estado <> %d', $acciones_centralizadas->nid, $estado_naprobado);
266    $reformular = db_fetch_object($result);
267  }
268  $datos_acciones_centralizadas_status['acciones_centralizadas_reformular']['value'] = $reformular && $reformular->cantidad  ? 1 : 0;
269  $datos_acciones_centralizadas_status['acciones_centralizadas_reformular']['title'] = t('Reformulaciones para el año @year', array('@year' => $year));
270  $datos_acciones_centralizadas_status['acciones_centralizadas_reformular']['link'] = isset($acciones_centralizadas->nid) ? 'node/' . $acciones_centralizadas->nid . '/reformular' : 'node/add/accion-centralizada';
271  $datos_acciones_centralizadas_status['acciones_centralizadas_reformular']['mylink'] = isset($acciones_centralizadas->nid) ? 'node/' . $acciones_centralizadas->nid . '/reformular' : 'node/add/accion-centralizada';
272  $datos_acciones_centralizadas_status['acciones_centralizadas_reformular']['weight'] = -9;
273  //Seguimiento
274  $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
275  $mes_segu = variable_get('acciones_centralizadas_mes_seguimiento', 0);
276  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
277  if ($ente_planificador) {
278    $result = db_query("SELECT max(ase.id_seg) AS id FROM {accion_seguimiento} AS ase INNER JOIN {accion_centralizada} AS ac ON ac.nid = ase.nid  WHERE ac.ente = %d AND ac.year = %d AND ase.mes = %d AND ase.estado <> %d", $ente_planificador, $year, $mes, $mes_segu, $estado_naprobado);
279    $seguimiento_id = db_fetch_object($result);
280    $seguimiento = NULL;
281    if ($seguimiento_id->id) {
282      $result = db_query("SELECT * FROM {accion_seguimiento} WHERE id_seg = %d", $seguimiento_id->id);
283      $seguimiento = db_fetch_object($result);
284    }
285    else {
286      $result = db_query("SELECT ac.* FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND ac.year = %d AND w.sid <> %d ORDER BY ac.nid DESC", $ente_planificador, $year, $estado_naprobado);
287      $seguimiento = db_fetch_object($result);
288    }
289  }
290  $ftypes = array(
291    0 => t('Seleccione'),
292    '1' => t('January'),
293    '2' => t('February'),
294    '3' => t('March'),
295    '4' => t('April'),
296    '5' => t('May'),
297    '6' => t('June'),
298    '7' => t('July'),
299    '8' => t('August'),
300    '9' => t('September'),
301    '10' => t('Octuber'),
302    '11' => t('November'),
303    '12' => t('December'),
304  );
305  $datos_acciones_centralizadas_status['acciones_centralizadas_seguimiento']['value'] = $seguimiento && $seguimiento_id->id && isset($seguimiento->nid)  ? 1 : 0;
306  $datos_acciones_centralizadas_status['acciones_centralizadas_seguimiento']['title'] = t('Seguimiento para el mes: @mes, año: @year', array('@year' => $year, '@mes' => $ftypes[$mes_segu]));
307  $datos_acciones_centralizadas_status['acciones_centralizadas_seguimiento']['link'] = $seguimiento && isset($seguimiento->nid) ? 'node/' . $seguimiento->nid . '/seguimiento' : 'node/add/accion-centralizada';
308  $datos_acciones_centralizadas_status['acciones_centralizadas_seguimiento']['mylink'] = $seguimiento && isset($seguimiento->nid) ? 'node/' . $seguimiento->nid . '/seguimiento' : 'node/add/accion-centralizada';
309  $datos_acciones_centralizadas_status['acciones_centralizadas_seguimiento']['weight'] = -9;
310  return $datos_acciones_centralizadas_status;
311}
312
313/**
314 * Menu access control callback. Determine access to reformulacion tab.
315 */
316function _acciones_centralizadas_reformula_node_add_tab_access($node = NULL) {
317  global $user;
318  $year = variable_get('acciones_centralizadas_anho_creacion', 0);
319  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
320  if ($node->type != 'accion_centralizada' || $node->anhoaccion_centralizada != $year) {
321    return FALSE;
322  }
323  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
324    return FALSE;
325  }
326  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
327  $current_time = time();
328  $tipo_plan = 'acciones_centralizadas_reformular';
329  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
330  $fecha = FALSE;
331  $ente = usuario_tiene_ente($user->uid);
332  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
333    $fecha = TRUE;
334  }
335  if ($fecha) {
336    if ($ente->nid == $ente_planificador->nid) {
337      $fecha = TRUE;
338    }
339    elseif (!user_access('admin planificador')) {
340      return FALSE;
341    }
342  }
343   if (!$fecha) {
344    return FALSE;
345  }
346  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
347  $result = db_query("SELECT count(ar.id_ref) AS cantidad FROM {accion_centralizada} AS ac INNER JOIN {accion_reformular} AS ar ON ar.nid = ac.nid WHERE (ar.estado <> %d AND ar.estado <> %d) AND ac.ente = %d AND ac.year = %d", $estado_aprobado, $estado_naprobado, $node->field_acciones_ente[0]['nid'], $year);
348  $accion_centralizada = db_fetch_array($result);
349  return !$accion_centralizada['cantidad'];
350}
351
352/**
353 * Menu access control callback. Determine access to editar reformulacion tab.
354 */
355function _acciones_centralizadas_reformula_node_edit_tab_access($node = NULL, $reformulacion) {
356  global $user;
357  $year = variable_get('acciones_centralizadas_anho_creacion', 0);
358  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
359  if ($node->type != 'accion_centralizada' || $node->anhoaccion_centralizada != $year) {
360    return FALSE;
361  }
362  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
363    return FALSE;
364  }
365  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
366  $current_time = time();
367  $tipo_plan = 'acciones_centralizadas_reformular';
368  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
369  $fecha = FALSE;
370  $ente = usuario_tiene_ente($user->uid);
371  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
372    $fecha = TRUE;
373  }
374  if ($fecha) {
375    if ($ente->nid == $ente_planificador->nid) {
376      $fecha = TRUE;
377    }
378    elseif (!user_access('admin planificador')) {
379      return FALSE;
380    }
381  }
382  if (!$fecha) {
383    return FALSE;
384  }
385  if ($reformulacion->estado == $estado_aprobado) {
386    return FALSE;
387  }
388  $roles_allow = variable_get('acciones_centralizadas_state_r_' . $reformulacion->estado, array());
389  if ($user->uid == 1 || ($user->uid == $reformulacion->uid && $roles_allow[-1])) {
390    return TRUE;
391  }
392  $roles = array_keys($user->roles);
393  if (count($roles)) {
394    foreach($roles as $rol) {
395      if($roles_allow[$rol]) {
396        return TRUE;
397      }
398    }
399  }
400  return FALSE;
401}
402
403/**
404 * Menu access control callback. Determine access to reformula tab.
405 */
406function _acciones_centralizadas_reformula_node_tab_access($node = NULL) {
407  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
408  return ($node->type == 'accion_centralizada' && $node->_workflow == $estado_aprobado);
409}
410
411/**
412 * Menu access control callback. Determine access to seguimiento tab.
413 */
414function _acciones_centralizadas_seguimiento_node_tab_access($node = NULL) {
415  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
416  return ($node->type == 'accion_centralizada');
417}
418
419/**
420 * Menu access control callback. Determine access to seguimiento mes tab.
421 */
422function _acciones_centralizadas_seguimiento_node_tab_mes_access($node, $campo = '', $mes) {
423  global $user;
424  $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
425  if ($node->anhoaccion_centralizada != $year || $node->type != 'accion_centralizada') {
426   return FALSE;
427  }
428  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
429  if ($node->_workflow != $estado_aprobado) {
430    return FALSE;
431  }
432  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
433  $current_time = time();
434  $tipo_plan = 'acciones_centralizadas_seguimiento';
435  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
436  $fecha = FALSE;
437  $ente = usuario_tiene_ente($user->uid);
438  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
439    $fecha = TRUE;
440  }
441  if ($fecha) {
442    if ($ente->nid == $ente_planificador->nid) {
443      $fecha = TRUE;
444    }
445    elseif (!user_access('admin planificador')) {
446      $fecha = FALSE;
447    }
448  }
449  $acceso = FALSE;
450  $mes_segu = variable_get('acciones_centralizadas_mes_seguimiento', 0);
451  $workflow = variable_get('acciones_centralizadas_state_seguimiento', NULL) ? variable_get('acciones_centralizadas_state_seguimiento', NULL) : FALSE;
452  if ($fecha && $mes == $mes_segu - 1) {
453    $acceso = TRUE;
454  }
455  $result = db_query("SELECT * FROM {accion_seguimiento} WHERE nid = %d AND mes = %d", $node->nid, $mes);
456  $seguimiento = db_fetch_array($result);
457  if (!isset($seguimiento['estado'])) {
458  $states = _acciones_centralizadas_reformula_obtiene_estados();
459  $first_state = 0;
460    if ($states['wid']) {
461      $seguimiento['estado'] = _workflow_creation_state($states['wid']);
462    }
463  }
464  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
465  if ($seguimiento['estado'] == $estado_naprobado || $seguimiento['estado'] == $estado_aprobado) {
466    return FALSE;
467  }
468  $valor_texto = $mes == 0 ? 'value' : 'value_' . $mes;
469  $suma = 0;
470  if ($campo && !is_array($campo) && $node->{$campo}[0]['tid']) {
471    $campo = acciones_centralizadas_menu_campo_load($campo);
472  }
473$hay_campos = FALSE;
474  if (is_array($campo) && isset($campo['values']) && count($campo['values'])) {
475    foreach($campo['values'] as $partida) {
476$hay_campos = TRUE;
477      $suma += $partida[$valor_texto];
478    }
479  }
480 if (!$hay_campos) {
481    return FALSE;
482  }
483
484  $roles_allow = variable_get('acciones_centralizadas_state_s_' . $seguimiento['estado'], array());
485  if ($user->uid == 1) {
486    return TRUE;
487  }
488  $roles = array_keys($user->roles);
489  $proles = FALSE;
490  if (count($roles)) {
491    foreach($roles as $rol) {
492      if($roles_allow[$rol]) {
493        $proles = TRUE;
494      }
495    }
496  }
497  return $fecha && $acceso && $proles;
498}
499
500/**
501 * Menu access control callback. Determine access to wk tab.
502 */
503function _acciones_centralizadas_reformula_wk_node_tab_access($node = NULL, $reformulacion, $state = 0) {
504  global $user;
505  $year = variable_get('acciones_centralizadas_anho_creacion', 0);
506  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
507  if ($node->type != 'accion_centralizada' || $node->anhoaccion_centralizada != $year) {
508    return FALSE;
509  }
510  if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
511    return FALSE;
512  }
513  $ente = usuario_tiene_ente($user->uid);
514  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
515  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
516    return FALSE;
517  }
518  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
519  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
520
521  if ($reformulacion->estado == $estado_naprobado) {
522    return FALSE;
523  }
524
525  $states = _acciones_centralizadas_reformula_obtiene_estados();
526  $first_state = 0;
527  if ($states['wid']) {
528    $first_state = _workflow_creation_state($states['wid']);
529  }
530  $roles = array_keys($user->roles);
531  if ($user->uid == 1) {
532    // Superuser is special.
533    $roles_transition = 'ALL';
534  }
535  else {
536    $roles_transition = $roles;
537    if ($user->uid == $reformulacion->uid && $reformulacion->uid > 0) {
538      $roles_transition += array('author' => 'author');
539    }
540  }
541  $transitions = array();
542  if ($states['wid']) {
543    $transitions = workflow_allowable_transitions($reformulacion->estado, 'to', $roles_transition);
544  }
545  if ($first_state && $reformulacion->estado == $first_state) {
546    unset($transitions[$reformulacion->estado]);
547  }
548  if (isset($transitions[$state])) {
549    return TRUE;
550  }
551  return FALSE;
552}
553
554/*
555 * Implementation of hook_nodeapi()
556 */
557function acciones_centralizadas_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
558  switch ($op) {
559    case 'insert':
560      if ($node->type == 'accion_centralizada') {
561        $year = variable_get('acciones_centralizadas_anho_creacion', 0) ? variable_get('acciones_centralizadas_anho_creacion', 0) : date("Y");
562        db_query('INSERT INTO {accion_centralizada} (nid, year, ente) VALUES (%d, %d, %d)', $node->nid, $year, $node->field_acciones_ente[0]['nid']);
563      }
564    break;
565    case 'load':
566      if ($node->type == 'accion_centralizada') {
567        $result = db_query("SELECT year FROM {accion_centralizada} WHERE nid = %d", $node->nid);
568        if (!($accion_centralizada = db_fetch_array($result))){
569          $year = variable_get('acciones_centralizadas_anho_creacion', 0) ? variable_get('acciones_centralizadas_anho_creacion', 0) : date("Y");
570          db_query('INSERT INTO {accion_centralizada} (nid, year) VALUES (%d, %d)', $node->nid, $year);
571          $result = db_query("SELECT year FROM {accion_centralizada} WHERE nid = %d", $node->nid);
572          $accion_centralizada = db_fetch_array($result);
573        }
574        $node->anhoaccion_centralizada = $accion_centralizada['year'];
575      }
576    case 'view':
577      if ($node->type == 'accion_centralizada') {
578        $node_aux = $node;
579        if ($node_aux->field_acciones_ente[0]['nid']) {
580          $output1 = '<fieldset><legend>' . t('Datos de la Acción Centralizada') . '</legend>';
581          $ente_planificador = node_load($node_aux->field_acciones_ente[0]['nid']);
582          $output1 .= '<div class="field"><div class="field-label">' . t('Ente') . ':</div>' . l($ente_planificador->title, 'node/' . $ente_planificador->nid) . '</div>';
583          $output1 .= '<div class="field"><div class="field-label">' . t('Año') . ':</div>' . $node->anhoaccion_centralizada . '</div>';
584          $output1 .= '<div class="field"><div class="field-label">' . t('Autor') . ':</div>' . l($node->name, 'user/' . $node->uid)  . '</div>';
585          $output1 .= '<div class="field"><div class="field-label">' . t('Fecha de creación') . ':</div>' . format_date($node->created)  . '</div>';       
586          $output1 .= '<div class="field"><div class="field-label">' . t('Fecha de la última actualización') . ':</div>' . format_date($node->changed)  . '</div>';         
587          if (module_exists('workflow')) {
588            $states = _acciones_centralizadas_reformula_obtiene_estados();
589            $first_state = _workflow_creation_state($states['wid']);
590            $estado = $node->_workflow == $first_state ? t('Ingresado') : $states['states'][$node->_workflow];
591            $output1 .= '<div class="field"><div class="field-label">' . t('Estado de la Acción Centralizada') . ':</div>' . $estado . '</div>';
592          }
593          $output1 .= '</fieldset>';
594          $node->content['acciones_centralizadas_ver'] = array(
595            '#value' => $output1,
596            '#weight' => 0,
597          );
598        }
599        if ($page) {
600        $node->content['acciones_centralizadas_partidas'] = array(
601          '#value' => '<fieldset><legend>' . t('Partidas de la Acción Especifica') . '</legend>' . _acciones_centralizadas_reformula_tab_page_ver($node_aux, 0, FALSE, FALSE) . '</fieldset>',
602          '#weight' => 1,
603        );
604        }
605      }
606    break;
607    case 'validate':
608      if ($node->type == 'accion_centralizada') {
609        $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
610        drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
611        $format_number = array(
612          'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
613          'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
614          'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
615        );
616        drupal_add_js(array('format_number' => $format_number), 'setting');
617        $array = array(
618          'field_ac_ac1_ae1',
619          'field_ac_ac1_ae2',
620          'field_ac_ac2_ae2',
621          'field_ac_ac2_ae3',
622          'field_ac_ac3_ae1',
623          'field_ac_ac4_ae1',
624        );
625        $ftypes = array(
626          'value' => t('January'),
627          'value_1' => t('February'),
628          'value_2' => t('March'),
629          'value_3' => t('April'),
630          'value_4' => t('May'),
631          'value_5' => t('June'),
632          'value_6' => t('July'),
633          'value_7' => t('August'),
634          'value_8' => t('September'),
635          'value_9' => t('Octuber'),
636          'value_10' => t('November'),
637          'value_11' => t('December'),
638        );
639        $un_campo = FALSE;
640        $campo_a = '';
641        foreach($array as $campo) {
642          $campo_a = $campo;
643          foreach($node->{$campo} as $valores) {
644            if ($valores['tid'] != 0) {
645              foreach($ftypes as $mes => $nombre) {
646                if ($valores[$mes]) {
647                  $un_campo = TRUE;
648                }
649              }
650            }
651          }
652        }
653        if (!$un_campo && $campo_a) {
654          form_set_error($campo_a, t('Debe ingresar al menos una partida.'));
655        }
656      }
657    break;
658    case 'delete':
659      db_query('DELETE FROM {accion_centralizada} WHERE nid = %d', $node->nid);
660      db_query('DELETE FROM {accion_reformula} WHERE nid = %d', $node->nid);
661      db_query('DELETE FROM {accion_reformular_state} WHERE nid = %d', $node->nid);
662      db_query('DELETE FROM {accion_seguimiento} WHERE nid = %d', $node->nid);
663      db_query('DELETE FROM {accion_segu_partida} WHERE nid = %d', $node->nid);
664      db_query('DELETE FROM {accion_seguimiento_state} WHERE nid = %d', $node->nid);
665    break;
666  }
667}
668
669/*
670 * Implementation of hook_menu()
671 */
672function acciones_centralizadas_menu() {
673  $items = array();
674  $items['acciones_centralizadas'] = array(
675    'title' => t('Ver Acciones Centralizadas'),
676    'page callback' => 'acciones_centralizadas_search_ac_display',
677    'access arguments' => array('ver planificador'),
678    'type' => MENU_NORMAL_ITEM,
679  );
680  $items['node/%node/reformular'] = array(
681    'title' => 'Reformular',
682    'type' => MENU_LOCAL_TASK,
683    'access callback' => '_acciones_centralizadas_reformula_node_tab_access',
684    'access arguments' => array(1),
685    'page callback' => '_acciones_centralizadas_reformula_list_page',
686    'page arguments' => array(1),
687    'weight' => 2,
688  );
689  $items['node/%node/reformular/list'] = array(
690    'title' => 'Reformulaciones',
691    'type' => MENU_DEFAULT_LOCAL_TASK,
692    'weight' => -10
693  );
694  $items['node/%node/reformular/add'] = array(
695    'title' => 'Agregar',
696    'type' => MENU_LOCAL_TASK,
697    'access callback' => '_acciones_centralizadas_reformula_node_add_tab_access',
698    'access arguments' => array(1),
699    'page callback' => 'drupal_get_form',
700    'page arguments' => array('acciones_centralizadas_reformula_tab_page_form', 1),
701    'weight' => 2,
702  );
703  $items['node/%node/reformular/%acciones_centralizadas_menu_reformulacion/view'] = array(
704    'title' => 'Ver',
705    'type' => MENU_LOCAL_TASK,
706    'access callback' => '_acciones_centralizadas_reformula_node_tab_access',
707    'access arguments' => array(1),
708    'page callback' => '_acciones_centralizadas_reformula_tab_page_ver',
709    'page arguments' => array(1, 3),
710    'weight' => 2,
711  );
712  $items['node/%node/reformular/%acciones_centralizadas_menu_reformulacion/edit'] = array(
713    'title' => 'Editar',
714    'type' => MENU_LOCAL_TASK,
715    'access callback' => '_acciones_centralizadas_reformula_node_edit_tab_access',
716    'access arguments' => array(1, 3),
717    'page callback' => 'drupal_get_form',
718    'page arguments' => array('acciones_centralizadas_reformula_tab_page_form', 1, 3),
719    'weight' => 3,
720  );
721  $items['node/%node/reformular/%acciones_centralizadas_menu_reformulacion/workflow/%acciones_centralizadas_wk_menu'] = array(
722    'title' => 'Workflow',
723    'type' => MENU_LOCAL_TASK,
724    'access callback' => '_acciones_centralizadas_reformula_wk_node_tab_access',
725    'access arguments' => array(1, 3, 5),
726    'page callback' => 'drupal_get_form',
727    'page arguments' => array('acciones_centralizadas_reformula_wk_tab_page_form', 1, 3, 5),
728    'weight' => 3,
729  );
730  $items['node/%node/seguimiento'] = array(
731    'title' => 'Seguimiento',
732    'type' => MENU_LOCAL_TASK,
733    'access callback' => '_acciones_centralizadas_seguimiento_node_tab_access',
734    'access arguments' => array(1),
735    'page callback' => 'acciones_centralizadas_seguimiento_tab_page',
736    'page arguments' => array(1),
737    'weight' => 2,
738  );
739  $items['node/%node/seguimiento/fase/%acciones_centralizadas_menu_mes'] = array(
740    'title' => 'Fase de Seguimiento',
741    'type' => MENU_CALLBACK,
742    'access callback' => '_acciones_centralizadas_seguimiento_node_tab_access',
743    'access arguments' => array(1),
744    'page callback' => 'acciones_centralizadas_seguimiento_nodo_fase_seguimiento',
745    'page arguments' => array(1, 4),
746  );
747  $items['node/%node/seguimiento/%acciones_centralizadas_menu_campo/%acciones_centralizadas_menu_mes'] = array(
748    'title' => 'Seguimiento',
749    'type' => MENU_LOCAL_TASK,
750    'access callback' => '_acciones_centralizadas_seguimiento_node_tab_access',
751    'access arguments' => array(1),
752    'page callback' => 'acciones_centralizadas_seguimiento_partida_tab_page',
753    'page arguments' => array(1, 3, 4),
754    'weight' => 2,
755  );
756  $items['node/%node/seguimiento/%acciones_centralizadas_menu_campo/%acciones_centralizadas_menu_mes/view'] = array(
757    'title' => 'Seguimiento',
758    'type' => MENU_DEFAULT_LOCAL_TASK,
759    'weight' => -10
760  );
761  $items['node/%node/seguimiento/%acciones_centralizadas_menu_campo/%acciones_centralizadas_menu_mes/edit'] = array(
762    'title' => 'Seguimiento',
763    'type' => MENU_LOCAL_TASK,
764    'access callback' => '_acciones_centralizadas_seguimiento_node_tab_mes_access',
765    'access arguments' => array(1, 3, 4),
766    'page callback' => 'drupal_get_form',
767    'page arguments' => array('acciones_centralizadas_seguimiento_tab_page_form', 1, 3, 4),
768    'weight' => 2,
769  );
770  $items['node/%node/seguimiento/%acciones_centralizadas_menu_campo/%acciones_centralizadas_menu_mes/workflow/%acciones_centralizadas_wk_menu'] = array(
771    'title' => 'Seguimiento',
772    'type' => MENU_LOCAL_TASK,
773    'access callback' => '_acciones_centralizadas_seguimiento_wk_node_tab_mes_access',
774    'access arguments' => array(1, 3, 4, 6),
775    'page callback' => 'drupal_get_form',
776    'page arguments' => array('acciones_centralizadas_seguimiento_wk_tab_page_form', 1, 3, 4, 6),
777    'weight' => 2,
778  );
779  $items['admin/settings/ente_planificador/acciones_centralizadas'] = array(
780    'title' => t('Acciones Centralizadas'),
781    'page callback' => 'drupal_get_form',
782    'page arguments' => array('acciones_centralizadas_admin_settings'),
783    'access arguments' => array('admin planificador'),
784    'weight' => -6,
785    'type' => MENU_LOCAL_TASK,
786    'file' => 'acciones_centralizadas.admin.inc',
787  );
788  return $items;
789}
790
791/*
792 * Implementation of _acciones_centralizadas_reformula_obtiene_list_page()
793 */
794function _acciones_centralizadas_reformula_obtiene_list_page($node, $muestra = TRUE) {
795  global $user;
796  $format_number = array(
797    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
798    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
799    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
800  );
801  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
802  $current_time = time();
803  $add_reformular = _acciones_centralizadas_reformula_node_add_tab_access($node);
804  $tipo_plan = 'acciones_centralizadas_reformular';
805  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
806  $fecha = FALSE;
807  $ente = usuario_tiene_ente($user->uid);
808  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
809    $fecha = TRUE;
810  }
811  if (!$fecha) {
812    if ($muestra) {
813      muestra_mensaje($tipo_plan, $ente_planificador);
814    }
815  }
816  else {
817    if ($ente->nid == $ente_planificador->nid) {
818      $fecha = TRUE;
819      if ($muestra) {
820        muestra_mensaje($tipo_plan, $ente_planificador, 0);
821      }
822    }
823    elseif (!user_access('admin planificador')) {
824      $fecha = FALSE;
825    }
826  }
827  $enlaces_estados = TRUE;
828  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
829    $enlaces_estados = FALSE;
830  }
831  $states = _acciones_centralizadas_reformula_obtiene_estados();
832  $first_state = 0;
833  if ($states['wid']) {
834    $first_state = _workflow_creation_state($states['wid']);
835  }
836  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
837  $result = db_query('SELECT re.*, u.name, u.uid FROM {accion_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);
838  $header = array();
839  $header[] = array('data' => t('Fecha'));
840  $header[] = array('data' => t('Estado Actual'));
841  $header[] = array('data' => t('Estado Anterior'));
842  $header[] = array('data' => t('Monto (Bs)'));
843  $header[] = array('data' => t('Variación (Bs)'));
844  $header[] = array('data' => t('Total monto (Bs)'));
845  $header[] = array('data' => t('Usuario'));
846  $header[] = array('data' => t('Acción'));
847  $rows = array();
848  $i = 1;
849  $roles = array_keys($user->roles);
850  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
851  $editar = ($node->_workflow == $estado_aprobado);
852  while($reformular = db_fetch_object($result)) {
853    if ($user->uid == 1) {
854      // Superuser is special.
855      $roles_transition = 'ALL';
856    }
857    else {
858      $roles_transition = $roles;
859      if ($user->uid == $reformular->uid && $reformular->uid > 0) {
860        $roles_transition += array('author' => 'author');
861      }
862    }
863    $transitions = array();
864    if ($states['wid']) {
865      $transitions = workflow_allowable_transitions($reformular->estado, 'to', $roles_transition);
866    }
867    unset($transitions[$reformular->estado]);
868    $acciones = array();
869    $row = array();
870    $row[] = array('data' => format_date($reformular->date),);
871    $estado = isset($states['states'][$reformular->estado]) ? $states['states'][$reformular->estado] : 'N/A';
872    $row[] = array('data' => $estado,);
873    $estado = isset($states['states'][$reformular->estado_ant]) ? $states['states'][$reformular->estado_ant] : 'N/A';
874    $row[] = array('data' => $estado,);
875    $row[] = array('data' => number_format($reformular->monto, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
876    $row[] = array('data' => number_format($reformular->variacion, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
877    $total = $reformular->monto + $reformular->variacion;
878    $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
879    $row[] = array('data' => l($reformular->name, 'user/' . $reformular->uid),);
880    //display options
881    if ($editar) {
882      $acciones[] = l(t('Ver'), 'node/' . $node->nid . '/reformular/' . $reformular->id_ref . '/view');
883    }
884    if ($add_reformular) {
885      $acciones[] = l(t('Agregar nueva reformulación'), 'node/' . $node->nid . '/reformular/add');
886    }
887    if ($editar && $fecha && $reformular->estado != $estado_naprobado &&  $reformular->estado != $estado_aprobado && $reformular->id_ref) {
888      $acciones[] = l(t('Modificar'), 'node/' . $node->nid . '/reformular/' . $reformular->id_ref . '/edit');
889    }
890    if ($enlaces_estados && count($transitions)) {
891      foreach($transitions as $id => $transition) {
892        $acciones[] = l(t('Enviar a @state', array('@state' => $transition)), 'node/' . $node->nid . '/reformular/' . $reformular->id_ref . '/workflow/' . $id);
893      }
894    }
895    $row[] = array('data' =>  theme('item_list', $acciones),);
896    $rows[] = $row;
897    $i++;
898  }
899  if (!count($rows)) {
900    $row[] = array('data' => 'No existen reformulaciones para este ente', 'colspan' => 8);
901    $rows[] = $row;
902  }
903  $output = '';
904  if ($node->field_acciones_ente[0]['nid']) {
905    $output = '<fieldset><legend>' . t('Datos de la Acción Centralizada') . '</legend>';
906    $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
907    $output .= '<div class="field"><div class="field-label">' . t('Ente') . ':</div>' . l($ente_planificador->title, 'node/' . $ente_planificador->nid) . '</div>';
908    $output .= '<div class="field"><div class="field-label">' . t('Año') . ':</div>' . $node->anhoaccion_centralizada . '</div>';
909    $output .= '<div class="field"><div class="field-label">' . t('Autor') . ':</div>' . l($node->name, 'user/' . $node->uid)  . '</div>';
910    $output .= '<div class="field"><div class="field-label">' . t('Fecha de creación') . ':</div>' . format_date($node->created)  . '</div>';       
911    $output .= '<div class="field"><div class="field-label">' . t('Fecha de la última actualización') . ':</div>' . format_date($node->changed)  . '</div>';         
912    if (module_exists('workflow')) {
913      $states = _acciones_centralizadas_reformula_obtiene_estados();
914      $first_state = _workflow_creation_state($states['wid']);
915      $estado = $node->_workflow == $first_state ? t('Ingresado') : $states['states'][$node->_workflow];
916      $output .= '<div class="field"><div class="field-label">' . t('Estado de la Acción Centralizada') . ':</div>' . $estado . '</div>';
917    }
918    $output .= '</fieldset>';
919  }
920  $output .= '<fieldset><legend>' . t('Reformulaciones de la Acción Centralizada') . '</legend>';
921  $output .= theme('table', $header, $rows) . '</fieldset>';
922  return $output;
923}
924
925/*
926 * Implementation of _acciones_centralizadas_reformula_tab_page_ver()
927 */
928function _acciones_centralizadas_reformula_tab_page_ver($node, $reformulacion_load = 0, $show_variacion = TRUE, $muestra = TRUE) {
929  global $user;
930  $format_number = array(
931    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
932    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
933    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
934  );
935  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
936  $current_time = time();
937  $add_reformular = _acciones_centralizadas_reformula_node_add_tab_access($node);
938  $tipo_plan = 'acciones_centralizadas_reformular';
939  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
940  $fecha = FALSE;
941  $ente = usuario_tiene_ente($user->uid);
942  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
943    $fecha = TRUE;
944  }
945  if (!$fecha) {
946    if ($muestra) {
947      muestra_mensaje($tipo_plan, $ente_planificador);
948    }
949  }
950  else {
951    if ($ente->nid == $ente_planificador->nid) {
952      $fecha = TRUE;
953      if ($muestra) {
954        muestra_mensaje($tipo_plan, $ente_planificador, 0);
955      }
956    }
957    elseif (!user_access('admin planificador')) {
958      $fecha = FALSE;
959    }
960  }
961  $enlaces_estados = TRUE;
962  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
963    $enlaces_estados = FALSE;
964  }
965  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
966  $format_number = array(
967    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
968    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
969    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
970  );
971  //drupal_add_js(array('format_number' => $format_number), 'setting');
972  drupal_set_title(t('Acciones Centralizadas'));
973  if ($show_variacion) {
974    $planificado = t('planificado');
975    $variacion = t('variación');
976    $total_texto = t('total');
977  }
978  $reformula = _acciones_centralizadas_reformula_load($node, $id_ref);
979  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
980  $mes = date('n');
981  $grupos = fieldgroup_groups('accion_centralizada');
982  $grupos_form = array();
983  $grupos_fields = array();
984  foreach($grupos as $id => $grupo) {
985    if (count($grupo['fields'])) {
986      foreach($grupo['fields'] as $id_field => $field) {
987        $grupos_fields[$id_field] = $id;
988      }
989    }
990  }
991  $array = array(
992    'field_ac_ac1_ae1',
993    'field_ac_ac1_ae2',
994    'field_ac_ac2_ae2',
995    'field_ac_ac2_ae3',
996    'field_ac_ac3_ae1',
997    'field_ac_ac4_ae1',
998  );
999  $ftypes = array(
1000    'value' => t('January'),
1001    'value_1' => t('February'),
1002    'value_2' => t('March'),
1003    'value_3' => t('April'),
1004    'value_4' => t('May'),
1005    'value_5' => t('June'),
1006    'value_6' => t('July'),
1007    'value_7' => t('August'),
1008    'value_8' => t('September'),
1009    'value_9' => t('Octuber'),
1010    'value_10' => t('November'),
1011    'value_11' => t('December'),
1012  );
1013  $valores = array();
1014  foreach($ftypes as $id_field => $texto) {
1015    $valores[$id_field] = 0;
1016
1017  }
1018  $partidas_nodo = array();
1019  foreach ($array as $id) {
1020    if (count($node->{$id})) {
1021      foreach($node->{$id} as $partida) {
1022        if(!empty($partida['tid'])) {
1023          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
1024        }
1025      }
1026    }
1027  }
1028  if (count($variaciones)) {
1029    foreach($variaciones as $field_l => $partidas) {
1030      if (count($partidas)) {
1031        foreach($partidas as $tid => $partida) {
1032          if (!isset($partidas_nodo[$field_l][$tid])) {
1033            $valores['tid'] = $tid;
1034            $node->{$field_l}[] = $valores;
1035            $partidas_nodo[$field_l][$tid] = $tid;
1036          }
1037        }
1038      }
1039    }
1040  }
1041  if (count($reformula)) {
1042    foreach($reformula as $field_l => $partidas) {
1043      if (count($partidas)) {
1044        foreach($partidas as $tid => $partida) {
1045          if (!isset($partidas_nodo[$field_l][$tid])) {
1046            $valores['tid'] = $tid;
1047            $node->{$field_l}[] = $valores;
1048            $partidas_nodo[$field_l][$tid] = $tid;
1049          }
1050        }
1051      }
1052    }
1053  }
1054  $fields_title = array();
1055  $field_form = array();
1056  $total_accion = 0;
1057  $headers = array();
1058  $header = array();
1059  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
1060  $editar = ($node->_workflow == $estado_aprobado);
1061  if ($show_variacion) {
1062    $header[] = array('data' => t('Partidas'), 'colspan' => '2');
1063  }
1064  else {
1065    $header[] = array('data' => t('Partidas'),);
1066  }
1067  foreach($ftypes as $texto) {
1068    $header[] = array('data' => $texto);
1069  }
1070  $output = '';
1071  $outputs = array();
1072  $header[] = array('data' => t('Total'));
1073  foreach ($array as $id) {
1074    if (count($node->{$id})) {
1075      $field_load = content_fields($id, 'accion_centralizada');
1076      $fields_title[$id] = $field_load['widget']['label'];
1077      $rows = array();
1078      $totales_partidas = array();
1079      foreach($ftypes as $id_field => $texto) {
1080        $totales_partidas[$id_field] = 0;
1081      }
1082      $totales_partidas_total = 0;
1083      foreach($node->{$id} as $partida) {
1084        if(!empty($partida['tid'])) {
1085          $term = taxonomy_get_term($partida['tid']);
1086          $partida['term'] = $term;
1087          $field_form[$id][] = $partida;
1088          $row = array();
1089          $row1 = array();
1090          $row2 = array();
1091          if ($show_variacion) {
1092            $row[] = array('data' => $partida['term']->name, 'rowspan' => '3');
1093            $row[] = array('data' => $planificado,);
1094            $row1[] = array('data' => $variacion,);
1095            $row2[] = array('data' => $total_texto,);
1096          }
1097          else {
1098            $row[] = array('data' => $partida['term']->name,);
1099          }
1100          $total = 0;
1101          $total1 = 0;
1102          $i = 1;
1103          foreach($ftypes as $id_field => $texto) {
1104            $varia = isset($variaciones[$id][$partida['tid']][$id_field]) ? $variaciones[$id][$partida['tid']][$id_field] : 0;
1105            $min = isset($partida[$id_field]) ? $partida[$id_field] : 0;
1106            $min += $varia;
1107            $total += $min;
1108            $total_accion += $min;
1109            $valor = isset($reformula[$id][$partida['tid']][$id_field])? $reformula[$id][$partida['tid']][$id_field] : 0;
1110            $total1 += $valor;
1111            //$row[] = array('data' => number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1112            $totales_partidas[$id_field] += (float) $min;
1113            $totales_partidas[$id_field] += (float) $valor;
1114            $totales_partidas_total += (float) $min;
1115            $totales_partidas_total += (float) $valor;
1116
1117            if (!$show_variacion) {
1118              $row[] = array('data' => number_format($min + $valor, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1119            }
1120            else {
1121              $sing = '';
1122              if ($valor > 0) {
1123                $sing = '+';
1124              }
1125              $row[] = array('data' => number_format($min, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1126              $row1[] = array('data' => $sing . number_format($valor, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1127             // $totales_partidas_total += (float) $valor;
1128              $row2[] = array('data' => number_format($min + $valor, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1129            }
1130            $i++;
1131          }
1132          $row[] = array('data' => number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1133          $rows[] = $row;
1134          if ($show_variacion) {
1135            $row1[] = array('data' => number_format($total1, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1136            $rows[] = $row1;
1137            $row2[] = array('data' => number_format($total + $total1, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1138            $rows[] = $row2;
1139          }
1140        }
1141      }
1142      if (!isset($outputs[$grupos_fields[$id]])) {
1143        $outputs[$grupos_fields[$id]] = array();
1144      }
1145      if(count($rows)) {
1146        $row = array();
1147
1148        $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right', 'colspan' => $show_variacion ? 2 : 1);
1149        foreach($ftypes as $id_field => $texto) {
1150          $row[] = array('data' => number_format($totales_partidas[$id_field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1151        }
1152        $row[] = array('data' => number_format($totales_partidas_total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
1153        $rows[] = $row;
1154        $outputs[$grupos_fields[$id]][] = '<div class="field-label">' . $fields_title[$id] . '</div>' . theme('table', $header, $rows);
1155$rows = array();
1156      }
1157    }
1158  }
1159  foreach($grupos as $id => $grupo) {
1160    if (isset($outputs[$id]) && count($outputs[$id])) {
1161      $output .= '<fieldset><legend>' . $grupo['label'] . '</legend>' . implode('', $outputs[$id]). '</fieldset>';
1162    }
1163  }
1164  $states = array();
1165  if (module_exists('workflow')) {
1166    $states = _acciones_centralizadas_reformula_obtiene_estados();
1167    $header = array();
1168    $header[] = array('data' => t('Fecha'),);
1169    $header[] = array('data' => t('Estado'),);
1170    $header[] = array('data' => t('Estado anterior'),);
1171    $header[] = array('data' => t('Comentario'),);
1172    $header[] = array('data' => t('Usuario'),);
1173    $rows = array();
1174    $result = db_query('SELECT re.*, u.name, u.uid FROM {accion_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);
1175    while($history = db_fetch_object($result)) {
1176      $row = array();
1177      $row[] = array('data' => format_date($history->date),);
1178      $row[] = array('data' => $states['states'][$history->estado],);
1179      $row[] = array('data' => $states['states'][$history->estado_ant],);
1180      $row[] = array('data' => $history->comentario,);
1181      $row[] = array('data' => l($history->name, 'user/' . $history->uid),);
1182      $rows[] = $row;
1183    }
1184    if (count($rows)) {
1185      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . theme('table', $header, $rows) . '</div>';     
1186    }
1187    else {
1188      $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . t('No existe historial para esta reformulación') . '</div>';     
1189    }
1190  }
1191  if ($show_variacion) {
1192    $links = array();
1193    if ($editar) {
1194      $links[] = l(t('Reformulaciones'), 'node/' . $node->nid . '/reformular');
1195    }
1196    if ($add_reformular) {
1197      $links[] = l(t('Agregar nueva reformulación'), 'node/' . $node->nid . '/reformular/add');
1198    }
1199    if (isset($states['wid'])) {
1200      $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
1201      if ($editar && $fecha && $reformulacion_load->estado != $estado_naprobado &&  $reformulacion_load->estado != $estado_aprobado && $reformulacion_load->id_ref) {
1202        $links[] = l(t('Modificar'), 'node/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/edit');
1203      }
1204      $first_state = 0;
1205      if ($states['wid']) {
1206        $first_state = _workflow_creation_state($states['wid']);
1207      }
1208      if ($user->uid == 1) {
1209        // Superuser is special.
1210        $roles = 'ALL';
1211      }
1212      else {
1213        $roles = array_keys($user->roles);
1214        $roles_transition = $roles;
1215        if ($user->uid == $reformulacion_load->uid && $reformulacion_load->uid > 0) {
1216          $roles += array('author' => 'author');
1217        }
1218      }
1219      $transitions = array();
1220      if ($states['wid']) {
1221        $transitions = workflow_allowable_transitions($reformulacion_load->estado, 'to', $roles);
1222      }
1223      unset($transitions[$reformulacion_load->estado]);
1224      if ($enlaces_estados && count($transitions)) {
1225        foreach($transitions as $id => $transition) {
1226          $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'node/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/workflow/' . $id);
1227        }
1228      }
1229    }
1230    $output .= '<div class="field"><div class="field-label">' . t('Acciones') . ':</div>' . implode(' | ', $links) . '</div>';
1231  }
1232  return $output;
1233}
1234
1235/*
1236 * Implementation of _accion_centralizada_obtiene_campos()
1237 */
1238function _accion_centralizada_obtiene_campos() {
1239  $fields = array();
1240  $node_type = content_types('accion_centralizada');
1241  if (count($node_type['fields'])) {
1242    foreach($node_type['fields'] as $field) {
1243      if ($field['type'] == 'cck_plan_fields_field') {
1244        $fields[$field['field_name']] = $field['field_name'];
1245      }
1246    }
1247  }
1248  return $fields;
1249}
1250
1251/*
1252 * Implementation of _acciones_centralizadas_reformula_list_page()
1253 */
1254function _acciones_centralizadas_reformula_list_page($node) {
1255  $output = '';
1256  $output .= _acciones_centralizadas_reformula_obtiene_list_page($node, TRUE);
1257  return $output;
1258}
1259
1260/**
1261 * Implementation of acciones_centralizadas_menu_mes_load().
1262 * Menu loader callback. Load a mes.
1263 */
1264function acciones_centralizadas_menu_mes_load($mes = 0) {
1265  settype($mes, "integer");
1266  if ($mes >= 0 && $mes < 12) {
1267    return $mes;
1268  }
1269  return FALSE;
1270}
1271
1272/**
1273 * Implementation of acciones_centralizadas_menu_reformulacion_load().
1274 * Menu loader callback. Load a mes.
1275 */
1276function acciones_centralizadas_menu_reformulacion_load($id_ref = 0) {
1277  $reformula = FALSE;
1278  if ($id_ref && arg(1) && is_numeric(arg(1))) {
1279    $result = db_query("SELECT * FROM {accion_reformular} WHERE nid = %d AND id_ref = %d", arg(1), $id_ref);
1280    $reformula = db_fetch_object($result);
1281  }
1282  return $reformula;
1283}
1284
1285/**
1286 * Implementation of acciones_centralizadas_menu_campo_load().
1287 * Menu loader callback. Load a accion.
1288 */
1289function acciones_centralizadas_menu_campo_load($campo = '') {
1290  $array = array(
1291    'field_ac_ac1_ae1' => 'field_ac_ac1_ae1',
1292    'field_ac_ac1_ae2' => 'field_ac_ac1_ae2',
1293    'field_ac_ac2_ae2' => 'field_ac_ac2_ae2',
1294    'field_ac_ac2_ae3' => 'field_ac_ac2_ae3',
1295    'field_ac_ac3_ae1' => 'field_ac_ac3_ae1',
1296    'field_ac_ac4_ae1' => 'field_ac_ac4_ae1',
1297  );
1298  if ($campo && array_key_exists($campo, $array) && is_numeric(arg(1)) && $node_load = node_load(arg(1))) {
1299    if (isset($node_load->{$campo})) {
1300      $campos = array(
1301        'field' => $campo,
1302        'values' => $node_load->{$campo},
1303      );
1304      return $campos;
1305    }
1306  }
1307  return FALSE;
1308}
1309
1310/*
1311 * Implementation of acciones_centralizadas_wk_menu_load()
1312 */
1313function acciones_centralizadas_wk_menu_load($state = 0) {
1314  $states = _acciones_centralizadas_reformula_obtiene_estados();
1315  if (isset($states['states'][$state])) {
1316    return $state;
1317  }
1318  return FALSE;
1319}
1320
1321/**
1322 * Implementation of hook_theme().accion_centralizada_node_form
1323 */
1324function acciones_centralizadas_theme() {
1325  return array(
1326    'acciones_centralizadas_reformula_tab_page_form' => array(
1327      'arguments' => array('form' => NULL),
1328    ),
1329    'acciones_centralizadas_seguimiento_tab_page_form' => array(
1330      'arguments' => array('form' => NULL),
1331    ),
1332    'accion_centralizada_node_form' => array(
1333      'arguments' => array('form' => NULL),
1334    ),
1335  );
1336}
1337
1338/*
1339 * Implementation of _acciones_centralizadas_reformula_all_partidas_load()
1340 */
1341function _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref = 0) {
1342  $variaciones = array();
1343  $ftypes = array(
1344    'value' => t('January'),
1345    'value_1' => t('February'),
1346    'value_2' => t('March'),
1347    'value_3' => t('April'),
1348    'value_4' => t('May'),
1349    'value_5' => t('June'),
1350    'value_6' => t('July'),
1351    'value_7' => t('August'),
1352    'value_8' => t('September'),
1353    'value_9' => t('Octuber'),
1354    'value_10' => t('November'),
1355    'value_11' => t('December'),
1356  );
1357  $load_reformulaciones = array();
1358  $reformulaciones = _acciones_centralizadas_reformula_all_load($node, $id_ref);
1359  if ($id_ref) {
1360    foreach($reformulaciones as $id => $value) {
1361      if ($id < $id_ref) {
1362        $load_reformulaciones[$id] = $values;
1363      }
1364    }
1365  }
1366  else {
1367    $load_reformulaciones = $reformulaciones;
1368  }
1369  if(count($load_reformulaciones)) {
1370    foreach($load_reformulaciones as $id => $value) {
1371      $nueva_variacion = _acciones_centralizadas_reformula_load($node, $id);
1372      if(count($nueva_variacion)) {
1373        foreach($nueva_variacion as $id_campo => $campo) {
1374          if(count($campo)) {
1375            foreach($campo as $id_partida => $partida) {
1376              if($partida['partida']) {
1377                if (!isset($variaciones[$id_campo][$id_partida]['partida'])) {
1378                  $variaciones[$id_campo][$id_partida]['partida'] = $partida['partida'];
1379                }
1380                foreach($ftypes as $idc => $valor) {
1381                  if (!isset($variaciones[$id_campo][$id_partida][$idc])) {
1382                    $variaciones[$id_campo][$id_partida][$idc] = 0;
1383                  }
1384                  $variaciones[$id_campo][$id_partida][$idc] += $partida[$idc];
1385                }
1386              }
1387            }
1388          }
1389        }
1390      }
1391    }
1392  }
1393  return $variaciones;
1394}
1395
1396/*
1397 * Implementation of _acciones_centralizadas_reformula_all_load()
1398 */
1399function _acciones_centralizadas_reformula_all_load($node, $id_ref = 0) {
1400  $reformulaciones = array();
1401  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
1402  $result = db_query("SELECT * FROM {accion_reformular} WHERE nid = %d AND estado = %d ORDER BY id_ref DESC", $node->nid, $estado_aprobado);
1403  while($reformula = db_fetch_array($result)) {
1404    $reformulaciones[$reformula['id_ref']] = $reformula;
1405  }
1406  return $reformulaciones;
1407}
1408
1409/*
1410 * Implementation of _acciones_centralizadas_reformula_load()
1411 */
1412function _acciones_centralizadas_reformula_load($node, $id_ref = 0) {
1413  $reformula = array();
1414  $inputs = array();
1415  $sql = "SELECT * FROM {accion_reformula} WHERE nid = %d";
1416  $inputs[] = $node->nid;
1417  if ($id_ref) {
1418    $sql .= ' AND id_ref = %d';
1419    $inputs[] = $id_ref;
1420    $result = db_query($sql, $inputs);
1421    while($partida = db_fetch_array($result)) {
1422      $reformula[$partida['field_name']][$partida['partida']] = $partida;
1423    }
1424  }
1425  return $reformula;
1426}
1427
1428/*
1429 * Implementation of _acciones_centralizadas_seguimiento_load()
1430 */
1431function _acciones_centralizadas_seguimiento_load($node, $campo = '', $mes = 0) {
1432  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
1433  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
1434  $result = db_query("SELECT max(a.id_seg) AS id FROM {accion_seguimiento} AS a INNER JOIN {accion_centralizada} AS ac ON a.nid = ac.nid WHERE a.nid = %d AND a.mes = %d AND a.campo = '%s' AND a.estado <> %d AND ac.year = %d", $node->nid, $mes, $campo, $estado_naprobado, $node->anhoaccion_centralizada);
1435  $seguimiento = array();
1436  $seg = db_fetch_array($result);
1437  if ($seg['id']) {
1438    $result = db_query("SELECT * FROM {accion_seguimiento} WHERE nid = %d AND id_seg = %d", $node->nid, $seg['id']);
1439    $seg_load = db_fetch_array($result);
1440    $result = db_query("SELECT * FROM {accion_segu_partida} WHERE id_seg = %d", $seg['id']);
1441    $seguimiento['values'] = $seg_load;
1442    $valor = $mes > 0 ? 'value_' . $mes : 'value';
1443    while($partida = db_fetch_array($result)) {
1444      $seguimiento['comprometido'][$campo][$partida['partida']][$valor] = $partida['comprometido'];
1445      $seguimiento['causado'][$campo][$partida['partida']][$valor] = $partida['causado'];
1446      $seguimiento['pagado'][$campo][$partida['partida']][$valor] = $partida['pagado'];
1447    }
1448  }
1449  return $seguimiento;
1450}
1451
1452/*
1453 * Implementation of acciones_centralizadas_reformula_tab_page_form()
1454 */
1455function acciones_centralizadas_reformula_tab_page_form($form_state, $node, $reformulacion_load = 0) {
1456  global $user;
1457  $form = array();
1458  $node_type = content_types('accion_centralizada');
1459  $fields = $node_type['fields'];
1460  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
1461  $current_time = time();
1462  $add_reformular = _acciones_centralizadas_reformula_node_add_tab_access($node);
1463  $tipo_plan = 'acciones_centralizadas_reformular';
1464  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
1465  $fecha = FALSE;
1466  $ente = usuario_tiene_ente($user->uid);
1467  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1468    $fecha = TRUE;
1469  }
1470  if (!$fecha) {
1471    muestra_mensaje($tipo_plan, $ente_planificador);
1472  }
1473  else {
1474    if ($ente->nid == $ente_planificador->nid) {
1475      $fecha = TRUE;
1476      muestra_mensaje($tipo_plan, $ente_planificador, 0);
1477    }
1478    elseif (!user_access('admin planificador')) {
1479      $fecha = FALSE;
1480    }
1481  }
1482  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
1483  $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
1484  drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
1485  drupal_set_title(t('Acciones Centralizadas'));
1486  $format_number = array(
1487    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
1488    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
1489    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
1490  );
1491  $form['#format_number'] = array('format_number' => $format_number);
1492  drupal_add_js($form['#format_number'], 'setting');
1493  $reformula = _acciones_centralizadas_reformula_load($node, $id_ref);
1494  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
1495  $mes = variable_get('acciones_centralizadas_anho_seguimiento', 0) == $node->anhoaccion_centralizada ? variable_get('acciones_centralizadas_mes_seguimiento', 0) + 1 : 1;
1496  $grupos = fieldgroup_groups('accion_centralizada');
1497  $grupos_form = array();
1498  $grupos_fields = array();
1499  foreach($grupos as $id => $grupo) {
1500    if (count($grupo['fields'])) {
1501      foreach($grupo['fields'] as $id_field => $field) {
1502        $grupos_fields[$id_field] = $id;
1503      }
1504    }
1505  }
1506  $array = array(
1507    'field_ac_ac1_ae1',
1508    'field_ac_ac1_ae2',
1509    'field_ac_ac2_ae2',
1510    'field_ac_ac2_ae3',
1511    'field_ac_ac3_ae1',
1512    'field_ac_ac4_ae1',
1513  );
1514  $ftypes = array(
1515    'value' => t('January'),
1516    'value_1' => t('February'),
1517    'value_2' => t('March'),
1518    'value_3' => t('April'),
1519    'value_4' => t('May'),
1520    'value_5' => t('June'),
1521    'value_6' => t('July'),
1522    'value_7' => t('August'),
1523    'value_8' => t('September'),
1524    'value_9' => t('Octuber'),
1525    'value_10' => t('November'),
1526    'value_11' => t('December'),
1527  );
1528  $exclude_partidas = array();
1529  foreach ($array as $id) {
1530    if (count($node->{$id})) {
1531      $field_load = content_fields($id, 'accion_centralizada');
1532      $fields_title[$id] = $field_load['widget']['label'];
1533      foreach($node->{$id} as $partida) {
1534        if(!empty($partida['tid'])) {
1535          $exclude_partidas[$id][$partida['tid']] = $partida['tid'];
1536        }
1537      }
1538    }
1539  }
1540  $partidas_nodo = array();
1541  foreach ($array as $id) {
1542    if (count($node->{$id})) {
1543      foreach($node->{$id} as $partida) {
1544        if(!empty($partida['tid'])) {
1545          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
1546        }
1547      }
1548    }
1549  }
1550  $valores = array();
1551  foreach($ftypes as $id_field => $texto) {
1552    $valores[$id_field] = 0;
1553  }
1554  if (count($variaciones)) {
1555    foreach($variaciones as $field_l => $partidas) {
1556      if (count($partidas)) {
1557        foreach($partidas as $tid => $partida) {
1558          if (!isset($partidas_nodo[$field_l][$tid])) {
1559            $valores['tid'] = $tid;
1560            $node->{$field_l}[] = $valores;
1561            $partidas_nodo[$field_l][$tid] = $tid;
1562          }
1563        }
1564      }
1565    }
1566  }
1567  if (count($reformula)) {
1568    foreach($reformula as $field_l => $partidas) {
1569      if (count($partidas)) {
1570        foreach($partidas as $tid => $partida) {
1571          if (!isset($partidas_nodo[$field_l][$tid])) {
1572            $valores['tid'] = $tid;
1573            $node->{$field_l}[] = $valores;
1574            $partidas_nodo[$field_l][$tid] = $tid;
1575          }
1576        }
1577      }
1578    }
1579  }
1580  $fields_title = array();
1581  $field_form = array();
1582  $total_accion = 0;
1583  foreach ($array as $id) {
1584    if (count($node->{$id})) {
1585      $field_load = content_fields($id, 'accion_centralizada');
1586      $fields_title[$id] = $field_load['widget']['label'];
1587      foreach($node->{$id} as $partida) {
1588        if(!empty($partida['tid'])) {
1589          $term = taxonomy_get_term($partida['tid']);
1590          $partida['term'] = $term;
1591          $field_form[$id][] = $partida;
1592          $total = 0;
1593          $total1 = 0;
1594          $i = 1;
1595          foreach($ftypes as $id_field => $texto) {
1596            $disabled = FALSE;
1597//          $disabled = ($i < $mes)? TRUE : FALSE;
1598            $total += $partida[$id_field];
1599            $varia = isset($variaciones[$id][$partida['tid']][$id_field]) ? $variaciones[$id][$partida['tid']][$id_field] : 0;
1600            $min = $partida[$id_field] + $varia;
1601            $total_accion += $min;
1602            $valor = isset($reformula[$id][$partida['tid']][$id_field])? $reformula[$id][$partida['tid']][$id_field] : 0;
1603            $total1 += $valor;
1604            $idformu = $id . '_' . $partida['tid'] . 'r_' . $id_field;
1605            $idformuj = str_replace('_', '-', $idformu);
1606            $form[$idformu] = array(
1607              '#type' => 'textfield',
1608              '#default_value' => $valor,
1609              '#size' => 15,
1610              '#disabled' => $disabled,
1611              '#attributes' => array('class' => $id . '_m' . ($i - 1) . 'p_' . $partida['tid'] . '_field ' . $id . '_' . $partida['tid'] . 'r ' . $id . '_m' . ($i - 1) . '_field ' . $id . '_dato_field numberref', 'onchange' => "valminimo('" . $idformuj . "', '" . $min . "');sumaref('" . $id . '_' . $partida['tid'] . 'r' . "');sumatexto('" . $id . '_m' . ($i - 1) . 'p_' . $partida['tid'] . '_field' . "');sumatexto('" . $id . '_m' . ($i - 1) . '_field' . "');sumatexto('" . $id . '_dato_field' . "');sumatoria_textos('" . $id .'p' . $partida['tid'] . '_field' . "');", 'valor' => $min, 'partida_campo' => $id . '_m' . ($i - 1) . 'p_' . $partida['tid'] . '_field'),
1612            );
1613            $i++;
1614
1615          }
1616          $form[$id . '_' . $partida['tid'] . 'r_total'] = array(
1617            '#type' => 'textfield',
1618            '#default_value' => $total1,
1619            '#size' => 15,
1620            '#disabled' => TRUE,
1621            '#attributes' => array('class' => $id . '_' . $partida['tid'] . 'r' . '_total totales'),
1622          );
1623        }
1624      }
1625    }
1626  }
1627  $accion_aux = new stdClass();
1628  $accion_aux->type = 'accion_centralizada';
1629  $accion_aux->title = '';
1630  $node_type = content_types('accion_centralizada');
1631  $fields = $node_type['fields'];
1632  $field_form1 = array();
1633  $fields_form = array();
1634  $arreglo1 = array(
1635    'field_ac_ac1_ae1' => 'field_ac_ac1_ae1',
1636    'field_ac_ac1_ae2' => 'field_ac_ac1_ae2',
1637    'field_ac_ac2_ae2' => 'field_ac_ac2_ae2',
1638    'field_ac_ac2_ae3' => 'field_ac_ac2_ae3',
1639    'field_ac_ac3_ae1' => 'field_ac_ac3_ae1',
1640    'field_ac_ac4_ae1' => 'field_ac_ac4_ae1',
1641  );
1642  if (is_array($fields) && count($fields)) {
1643    foreach($fields as $field_id => $field) {
1644      if (array_key_exists($field_id, $arreglo1)) {
1645        $field_form1[] = $field_id;
1646        $fields_form[] = $field_id;
1647      }
1648      elseif (variable_get('accion_centralizada_aR_' . $field_id, FALSE)) {
1649        $field_form1[] = $field_id;
1650        $fields_form[] = $field_id;
1651      }
1652    }
1653  }
1654  $form['#node'] = $accion_aux;
1655  if (is_array($field_form1) && count($field_form1)) {
1656    module_load_include('inc', 'content', 'includes/content.node_form');
1657    foreach ($field_form1 as $field_id) {
1658      $field = content_fields($field_id, 'accion_centralizada');
1659      $form['#field_info'][$field_id] = $field;
1660      $form += (array) content_field_form($form, $form_state, $field);
1661    }
1662  }
1663  $form['#total_accion'] = $total_accion;
1664  $form['#id_ref'] = $id_ref;
1665  $form['#node'] = $node;
1666  $form['#variaciones'] = $variaciones;
1667  $form['#field_form'] = $field_form;
1668  $form['#grupos_fields'] = $grupos_fields;
1669  $form['#grupos'] = $grupos;
1670  $form['#fields_title'] = $fields_title;
1671  $form['#mes'] = $mes;
1672  $form['#reformula'] = $reformula;
1673  $form['#state_creation'] = -1;
1674  //get first state
1675  if (module_exists('workflow')) {
1676    $wid = workflow_get_workflow_for_type('accion_centralizada');
1677    if ($wid) {
1678      $form['#state_creation'] = _workflow_creation_state($wid);
1679    }
1680  }
1681  if (count($field_form)) {
1682    $form['buttons'] = array(
1683      '#prefix' => '<div class="container-inline">',
1684      '#suffix' => '</div>',
1685    );
1686    $form['buttons']['submit'] = array(
1687      '#type' => 'submit',
1688      '#value' => t('Crear Reformulación'),
1689    );
1690    $cancel = $id_ref ? 'node/' . $form['#node']->nid . '/reformular/' . $id_ref . '/view' : 'node/' . $form['#node']->nid . '/reformular';
1691    $form['buttons']['cancel'] = array('#value' => l('Cancelar', $cancel));
1692  }
1693  return $form;
1694}
1695
1696/*
1697 * Implementation of theme_accion_centralizada_node_form()
1698 * Tema para el formulario del formulario de las acciones centralizadas
1699 */
1700function theme_accion_centralizada_node_form($form) {
1701  $ftypes = array(
1702    'tid' => t('Account'),
1703    'value' => t('Ene'),
1704    'value_1' => t('Feb'),
1705    'value_2' => t('Mar'),
1706    'value_3' => t('Abr'),
1707    'value_4' => t('May'),
1708    'value_5' => t('Jun'),
1709    'value_6' => t('Jul'),
1710    'value_7' => t('Aug'),
1711    'value_8' => t('Sep'),
1712    'value_9' => t('Oct'),
1713    'value_10' => t('Nov'),
1714    'value_11' => t('Dic'),
1715  );
1716  $output = '';
1717  $output .= '<fieldset><legend>' . $form['group_ac_ac1']['#title'] . '</legend>';
1718  $output .= drupal_render($form['group_ac_ac1']['field_ac_ac1_ae1']);
1719  unset($form['group_ac_ac1']);
1720  $output .= '<div style="width:2250px">';
1721  $i = -1;
1722  foreach ($ftypes as $ftype => $label) {
1723    if($ftype != 'tid') {
1724      $output .= '<div class = "field_ac_ac1_ae1_m' . $i . '_field_total field_ac_ac1_ae1_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1725    }
1726    else {
1727      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1728    }
1729    $i++;
1730  }
1731  $output .= '<div class = "field_ac_ac1_ae1_dato_field_total number1" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">5000</div>';
1732  $output .= '</div></fieldset>';
1733  $form_aux['field_ac_ac2_ae2'] = $form['group_ac_ac2']['field_ac_ac2_ae2'];
1734  $form_aux['field_ac_ac2_ae3'] = $form['group_ac_ac2']['field_ac_ac2_ae3'];
1735  $output .= '<fieldset><legend>' . $form['group_ac_ac2']['#title'] . '</legend>';
1736  $output .= drupal_render($form['group_ac_ac2']['field_ac_ac1_ae2']);
1737  $output .= '<div style="width:2250px">';
1738  $i = -1;
1739  foreach ($ftypes as $ftype => $label) {
1740    if($ftype != 'tid') {
1741      $output .= '<div class = "field_ac_ac1_ae2_m' . $i . '_field_total field_ac_ac1_ae2_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1742    }
1743    else {
1744      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1745    }
1746    $i++;
1747  }
1748  $output .= '<div class = "field_ac_ac1_ae2_dato_field_total" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1749  $output .= '</div>';
1750  $output .= '<div style="clear:both; height:30px"></div>';
1751  $output .= drupal_render($form['group_ac_ac2']['field_ac_ac2_ae2']);
1752  $output .= '<div style="width:2250px">';
1753  $i = -1;
1754  foreach ($ftypes as $ftype => $label) {
1755    if($ftype != 'tid') {
1756      $output .= '<div class = "field_ac_ac2_ae2_m' . $i . '_field_total field_ac_ac2_ae2_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1757    }
1758    else {
1759      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1760    }
1761    $i++;
1762  }
1763  $output .= '<div class = "field_ac_ac2_ae2_dato_field_total" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1764  $output .= '</div>';
1765  $output .= '<div style="clear:both; height:30px"></div>';
1766  $output .= drupal_render($form['group_ac_ac2']['field_ac_ac2_ae3']);
1767  $output .= '<div style="width:2250px">';
1768  $i = -1;
1769  foreach ($ftypes as $ftype => $label) {
1770    if($ftype != 'tid') {
1771      $output .= '<div class = "field_ac_ac2_ae3_m' . $i . '_field_total field_ac_ac2_ae3_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1772    }
1773    else {
1774      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1775    }
1776    $i++;
1777  }
1778  $output .= '<div class = "field_ac_ac2_ae3_dato_field_total" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1779  unset($form['group_ac_ac2']);
1780  $output .= '</div></fieldset>';
1781  $output .= '<fieldset><legend>' . $form['group_ac_ac3']['#title'] . '</legend>';
1782  $output .= drupal_render($form['group_ac_ac3']['field_ac_ac3_ae1']);
1783  unset($form['group_ac_ac3']);
1784  $output .= '<div style="width:2250px">';
1785  $i = -1;
1786  foreach ($ftypes as $ftype => $label) {
1787    if($ftype != 'tid') {
1788      $output .= '<div class = "field_ac_ac3_ae1_m' . $i . '_field_total field_ac_ac3_ae1_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1789    }
1790    else {
1791      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1792    }
1793    $i++;
1794  }
1795  $output .= '<div class = "field_ac_ac3_ae1_dato_field_total" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1796  $output .= '</div></fieldset>';
1797  $output .= '<fieldset><legend>' . $form['group_ac_ac4']['#title'] . '</legend>';
1798  $output .= drupal_render($form['group_ac_ac4']['field_ac_ac4_ae1']);
1799unset($form['group_ac_ac4']);
1800  $output .= '<div style="width:2250px">';
1801  $i = -1;
1802  foreach ($ftypes as $ftype => $label) {
1803    if($ftype != 'tid') {
1804      $output .= '<div class = "field_ac_ac4_ae1_m' . $i . '_field_total field_ac_ac4_ae1_totales" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1805    }
1806    else {
1807      $output .= '<div style = "width:170px;float:left;margin-left:18px;text-align:right"><b>' . t('TOTAL') . '</b></div>';
1808    }
1809    $i++;
1810  }
1811  $output .= '<div class = "field_ac_ac4_ae1_dato_field_total" style = "width:140px;float:left;margin-left:13px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">0</div>';
1812  $output .= '</div></fieldset>';
1813  $output .= drupal_render($form['field_acciones_ente']);
1814  return $output . drupal_render($form);
1815}
1816
1817/*
1818 * Implementation of theme_acciones_centralizadas_reformula_tab_page_form()
1819 */
1820function theme_acciones_centralizadas_reformula_tab_page_form($form) {
1821  $planificado = t('planificado');
1822  $variacion = t('variación');
1823  $total_texto = t('total');
1824  $field_form = $form['#field_form'];
1825  $fields_title = $form['#fields_title'];
1826  $grupos_fields = $form['#grupos_fields'];
1827  $grupos = $form['#grupos'];
1828  $ftypes = array(
1829    'value' => t('January'),
1830    'value_1' => t('February'),
1831    'value_2' => t('March'),
1832    'value_3' => t('April'),
1833    'value_4' => t('May'),
1834    'value_5' => t('June'),
1835    'value_6' => t('July'),
1836    'value_7' => t('August'),
1837    'value_8' => t('September'),
1838    'value_9' => t('Octuber'),
1839    'value_10' => t('November'),
1840    'value_11' => t('December'),
1841  );
1842  $headers = array();
1843  $header = array();
1844  $header[] = array('data' => t('Partidas'), 'colspan' => '2');
1845  foreach($ftypes as $texto) {
1846    $header[] = array('data' => $texto);
1847  }
1848  $output = '';
1849  $outputs = array();
1850  $header[] = array('data' => t('Total')); 
1851  $variaciones = $form['#variaciones'];
1852  $totales_partidas = array();
1853  if (count($field_form)) {
1854    foreach($field_form as $id_field => $fields) {
1855      if (!isset($totales_partidas[$id_field])) {
1856        $totales_partidas[$id_field] = array();
1857      }
1858      $rows = array();
1859      foreach($fields as $field) {
1860        $row = array();
1861        $row1 = array();
1862        $row2 = array();
1863        $row[] = array('data' => $field['term']->name, 'rowspan' => '3');
1864        $row[] = array('data' => $planificado,);
1865        $row1[] = array('data' => $variacion,);
1866        $row2[] = array('data' => $total_texto,);
1867        $total = 0;
1868        $total1 = 0;
1869        $total2 = 0;
1870        $i = 0;
1871        foreach($ftypes as $id =>$texto) {
1872          if (!isset($totales_partidas[$id_field][$id])) {
1873            $totales_partidas[$id_field][$id] = 0;
1874          }
1875          $varia = isset($variaciones[$id_field][$field['tid']][$id]) ? $variaciones[$id_field][$field['tid']][$id] : 0;
1876          $min = $field[$id] + $varia;
1877          $total += $min;
1878          $row[] = array('data' => number_format($min, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), 'align' => 'center');
1879          $value_box = $form[$id_field . '_' . $field['tid'] . 'r_' . $id]['#default_value'];
1880          $totales_partidas[$id_field][$id] += $min + $value_box;
1881          $row1[] = array('data' => drupal_render($form[$id_field . '_' . $field['tid'] . 'r_' . $id]),);
1882          $total2 += $min + $value_box;
1883          $row2[] = array('data' => '<div class = "' . $id_field . '_m' . $i . 'p_' . $field['tid'] . '_field_total ' . $id_field . '_totales ' . $id_field . 'p' . $field['tid'] . '_field_totalesR' . '" style = "width:140px;float:left;margin-left:1px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">' . number_format($min + $value_box, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>',);
1884          $i++;
1885        }
1886        $row[] = array('data' => number_format($total, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']),);
1887        $row1[] = array('data' => drupal_render($form[$id_field . '_' . $field['tid'] . 'r_total']),);
1888        $row2[] = array('data' => '<div class = "' . $id_field . 'p_' . $field['tid'] . '_dato_field_total ' . $id_field . 'p' . $field['tid'] . '_field_dato_field_total' . '" style = "width:140px;float:left;margin-left:1px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">' . number_format($total2, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>',);
1889        $rows[] = $row;
1890        $rows[] = $row1;
1891        $rows[] = $row2;
1892      }
1893      if (!isset($outputs[$grupos_fields[$id_field]])) {
1894        $outputs[$grupos_fields[$id_field]] = array();
1895      }
1896      $suma_partida = 0;
1897      if (count($rows)) {
1898        $row = array();
1899        $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'colspan' => '2', 'align' => 'right');
1900        $i = 0;
1901        foreach($ftypes as $id =>$texto) {
1902           $suma_partida += $totales_partidas[$id_field][$id];
1903           $row[] = array('data' => '<div class = "' . $id_field . '_m' . $i . '_field_total ' . $id_field . '_totales ' . $id_field . '_totalesR" style = "width:140px;float:left;margin-left:1px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">' . number_format($totales_partidas[$id_field][$id], $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>',);
1904           $i++;
1905        }
1906        $row[] = array('data' => '<div class = "' . $id_field . '_dato_field_total" style = "width:140px;float:left;margin-left:1px; border: 1px solid #D5D5D5;text-align:center;overflow:auto">' . number_format($suma_partida, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '</div>',);
1907        $rows[] = $row;
1908      }
1909     
1910      $outputs[$grupos_fields[$id_field]][] = '<div class="field-label">' . $fields_title[$id_field] . '</div>' . theme('table', $header, $rows);
1911    }
1912  }
1913  $output2 = '';
1914  foreach($grupos as $id => $grupo) {
1915    if (isset($outputs[$id]) && count($outputs[$id])) {
1916      $output .= '<fieldset><legend>' . $grupo['label'] . '</legend>' . implode('', $outputs[$id]). '</fieldset>';
1917    }
1918    if (count($grupo['fields'])) {
1919      if ($output2 == '') {
1920        $output2 .= '<fieldset><legend>' . t('Nuevas partidas') . '</legend>';
1921      }
1922      $output2 .= '<fieldset><legend>' . $grupo['label'] . '</legend>';
1923      foreach($grupo['fields'] as $id_field => $field) {
1924        $output2 .= drupal_render($form[$id_field]);
1925      }
1926      $output2 .= '</fieldset>';
1927    }
1928  }
1929  if ($output2 != '') {
1930    $output2 .= '</fieldset>';
1931    $output .= $output2;
1932  }
1933  $output .= '<div id="acciones-centralizadas-form-acciones">' . drupal_render($form) .'</div>';
1934  return $output;
1935}
1936
1937/*
1938 * Implementation of acciones_centralizadas_reformula_tab_page_form_validate()
1939 */
1940function acciones_centralizadas_reformula_tab_page_form_validate($form, &$form_state) {
1941  $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
1942  drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
1943  $ftypes = array(
1944    'value' => t('January'),
1945    'value_1' => t('February'),
1946    'value_2' => t('March'),
1947    'value_3' => t('April'),
1948    'value_4' => t('May'),
1949    'value_5' => t('June'),
1950    'value_6' => t('July'),
1951    'value_7' => t('August'),
1952    'value_8' => t('September'),
1953    'value_9' => t('Octuber'),
1954    'value_10' => t('November'),
1955    'value_11' => t('December'),
1956  );
1957  drupal_add_js($form['#format_number'], 'setting');
1958  $valida_valor = FALSE;
1959  $campo_valor = '';
1960  foreach($form['#field_form'] as $id => $partidas) {
1961    $check_partidas = array();
1962    foreach($partidas as $partida) {
1963      $check_partidas[$partida['tid']] = $partida['tid'];
1964      $i = 1;
1965      foreach($ftypes as $ids =>$texto) {
1966        $disabled = TRUE;
1967//        $disabled = ($i >= $form['#mes'])? TRUE : FALSE;
1968        if ($disabled) {
1969          $start = $form_state['values'][$id . '_' . $partida['tid'] .'r_' . $ids];
1970          $value = preg_replace('@[^-0-9]@', '', $start);
1971          if ($start != $value) {
1972            form_set_error($id . '_' . $partida['tid'] .'r_' . $ids, t('Solo números enteros son permitidos.'));
1973          }
1974          $campo_valor = $id . '_' . $partida['tid'] .'r_' . $ids;
1975          if ($value) {
1976            $valida_valor = TRUE;
1977          }
1978        }
1979        if ($disabled && !is_numeric($form_state['values'][$id . '_' . $partida['tid'] .'r_' . $ids])) {
1980          form_set_error($id . '_' . $partida['tid'] .'r_' . $ids, t('Amount should be a number'));
1981        }
1982        elseif($disabled && ($form_state['values'][$id . '_' . $partida['tid'] .'r_' . $ids] + $partida[$ids] < 0)) {
1983          form_set_error($id . '_' . $partida['tid'] .'r_' . $ids, t('Amount should be min'));
1984        }
1985        $i++;
1986      }
1987    }
1988    foreach($form_state['values'][$id] as $idf => $partida) {
1989      if (isset($check_partidas[$partida['tid']])) {
1990        $existe = FALSE;
1991        foreach($ftypes as $ids =>$texto) {
1992          if ($partida[$ids] && is_numeric($partida[$ids])) {
1993            $existe = TRUE;
1994          }
1995        }
1996        if ($existe) {
1997          form_set_error($id . '][' . $idf . '][tid', t('La nueva partida ya se encuentra en la planificación'));
1998        }
1999      }
2000      else {
2001        foreach($ftypes as $ids =>$texto) {
2002          if ($partida[$ids] && is_numeric($partida[$ids])) {
2003            $valida_valor = TRUE;
2004          }
2005        }
2006      }
2007    }
2008  }
2009  if (!$valida_valor) {
2010    form_set_error($campo_valor, t('Debe ingresar al menos un valor para alguna partida para registrar una reformulación.'));
2011  }
2012}
2013
2014/*
2015 * Implementation of acciones_centralizadas_reformula_tab_page_form_submit()
2016 */
2017function acciones_centralizadas_reformula_tab_page_form_submit($form, &$form_state) {
2018  global $user;
2019  $ftypes = array(
2020    'value' => t('January'),
2021    'value_1' => t('February'),
2022    'value_2' => t('March'),
2023    'value_3' => t('April'),
2024    'value_4' => t('May'),
2025    'value_5' => t('June'),
2026    'value_6' => t('July'),
2027    'value_7' => t('August'),
2028    'value_8' => t('September'),
2029    'value_9' => t('Octuber'),
2030    'value_10' => t('November'),
2031    'value_11' => t('December'),
2032  );
2033  $id_ref = $form['#id_ref'];
2034  db_query("DELETE FROM {accion_reformula} WHERE nid = %d AND id_ref = %d", $form['#node']->nid, $id_ref);
2035  if(!$id_ref) {
2036    db_query("INSERT INTO {accion_reformular} (uid, nid, estado, date, estado_ant, monto, variacion) VALUES (%d, %d, %d, %d, 0, %f, -1)", $user->uid, $form['#node']->nid, $form['#state_creation'], time(), $form['#total_accion']);
2037    $id_ref = db_last_insert_id('accion_reformular', 'id_ref');
2038  }
2039  $total_accion = 0;
2040  foreach($form['#field_form'] as $id => $partidas) {
2041    foreach($partidas as $partida) {
2042      $field = array();
2043      $field[] = $id_ref;
2044      $field[] = $id;
2045      $field[] = $partida['tid'];
2046      $field[] = $form['#node']->nid;
2047      $i = 1;
2048      foreach($ftypes as $ids =>$texto) {
2049        $disabled = TRUE;
2050//        $disabled = ($i >= $form['#mes'])? TRUE : FALSE;
2051        $reformula = isset($form['#reformula'][$id][$partida['tid']][$ids]) ? $form['#reformula'][$id][$partida['tid']][$ids] : 0;
2052        $total = $disabled ? $form_state['values'][$id . '_' . $partida['tid'] .'r_' . $ids] : $reformula;
2053        $field[] = $total;
2054        $total_accion += $total;
2055        $i++;
2056      }
2057      db_query("INSERT INTO {accion_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) VALUES (%d, '%s', %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f)", $field);
2058    }
2059  }
2060  $arreglo1 = array(
2061    'field_ac_ac1_ae1' => 'field_ac_ac1_ae1',
2062    'field_ac_ac1_ae2' => 'field_ac_ac1_ae2',
2063    'field_ac_ac2_ae2' => 'field_ac_ac2_ae2',
2064    'field_ac_ac2_ae3' => 'field_ac_ac2_ae3',
2065    'field_ac_ac3_ae1' => 'field_ac_ac3_ae1',
2066    'field_ac_ac4_ae1' => 'field_ac_ac4_ae1',
2067  );
2068  foreach($arreglo1 as $id) {
2069    foreach($form_state['values'][$id] as $idf => $partida) {
2070      $total = 0;
2071      if ($partida['tid']) {
2072        $field = array();
2073        $field[] = $id_ref;
2074        $field[] = $id;
2075        $field[] = $partida['tid'];
2076        $field[] = $form['#node']->nid;
2077        $existe = FALSE;
2078        foreach($ftypes as $ids =>$texto) {
2079          $total += $partida[$ids];
2080          $field[] = $partida[$ids];
2081          if ($partida[$ids] && is_numeric($partida[$ids])) {
2082            $existe = TRUE;
2083          }
2084        }
2085        if ($existe) {
2086          $total_accion += $total;
2087          db_query("INSERT INTO {accion_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) VALUES (%d, '%s', %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f)", $field);
2088        }
2089      }
2090    }
2091  }
2092  db_query('UPDATE {accion_reformular} SET variacion = %d WHERE nid = %d AND id_ref = %d', $total_accion, $form['#node']->nid, $id_ref);
2093  $form_state['redirect'] = 'node/' . $form['#node']->nid . '/reformular/' . $id_ref . '/view';
2094}
2095
2096/*
2097 * Implementation of _display_acciones_centralizadas_seguimiento_tab_page()
2098 */
2099function _display_acciones_centralizadas_seguimiento_tab_page($node) {
2100  global $user;
2101  $format_number = array(
2102    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
2103    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
2104    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
2105  );
2106  $states = _acciones_centralizadas_reformula_obtiene_estados();
2107  $acciones_centralizadas_seguimiento_node_tab_access = _acciones_centralizadas_seguimiento_node_tab_access($node);
2108  if (module_exists('workflow')) {
2109    if (isset($states['wid'])) {
2110      $first_state = 0;
2111      if ($states['wid']) {
2112        $first_state = _workflow_creation_state($states['wid']);
2113      }
2114      if ($user->uid == 1) {
2115        // Superuser is special.
2116        $roles = 'ALL';
2117      }
2118      else {
2119        $roles = array_keys($user->roles);
2120      }
2121    }
2122  }
2123  $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
2124  $mes_segu = variable_get('acciones_centralizadas_mes_seguimiento', 0);
2125  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
2126  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
2127  $output = '';
2128  $ftypes = array(
2129    'value' => t('January'),
2130    'value_1' => t('February'),
2131    'value_2' => t('March'),
2132    'value_3' => t('April'),
2133    'value_4' => t('May'),
2134    'value_5' => t('June'),
2135    'value_6' => t('July'),
2136    'value_7' => t('August'),
2137    'value_8' => t('September'),
2138    'value_9' => t('Octuber'),
2139    'value_10' => t('November'),
2140    'value_11' => t('December'),
2141  );
2142  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2143  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
2144  $reformula = _acciones_centralizadas_reformula_load($node);
2145  $actual = array();
2146  $meses = array(
2147    0 => t('January'),
2148    1 => t('February'),
2149    2 => t('March'),
2150    3 => t('April'),
2151    4 => t('May'),
2152    5 => t('June'),
2153    6 => t('July'),
2154    7 => t('August'),
2155    8 => t('September'),
2156    9 => t('Octuber'),
2157    10 => t('November'),
2158    11 => t('December'),
2159  );
2160  $array = array(
2161    'field_ac_ac1_ae1' => 'field_ac_ac1_ae1',
2162    'field_ac_ac1_ae2' => 'field_ac_ac1_ae2',
2163    'field_ac_ac2_ae2' => 'field_ac_ac2_ae2',
2164    'field_ac_ac2_ae3' => 'field_ac_ac2_ae3',
2165    'field_ac_ac3_ae1' => 'field_ac_ac3_ae1',
2166    'field_ac_ac4_ae1' => 'field_ac_ac4_ae1',
2167  );
2168  $valores = array();
2169  foreach($ftypes as $id_field => $texto) {
2170    $valores[$id_field] = 0;
2171  }
2172  $vacio = array();
2173  $partidas_nodo = array();
2174  foreach ($array as $id) {
2175    if (!$node->{$id}[0]['tid']) {
2176      $node->{$id} = array();
2177    }
2178    if (count($node->{$id})) {
2179      foreach($node->{$id} as $partida) {
2180        if(!empty($partida['tid'])) {
2181          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
2182        }
2183      }
2184    }
2185  }
2186  if (count($variaciones)) {
2187    foreach($variaciones as $field_l => $partidas) {
2188      if (count($partidas)) {
2189        foreach($partidas as $tid => $partida) {
2190          if (!isset($partidas_nodo[$field_l][$tid])) {
2191            if (empty($node->{$field_l}[0]['tid']) || !$node->{$field_l}[0]['tid']) {
2192              $node->{$field_l} = array();
2193            }
2194            $valores['tid'] = $tid;
2195            $node->{$field_l}[] = $valores;
2196            $partidas_nodo[$field_l][$tid] = $tid;
2197          }
2198        }
2199      }
2200    }
2201  }
2202  if (count($reformula)) {
2203    foreach($reformula as $field_l => $partidas) {
2204      if (count($partidas)) {
2205        foreach($partidas as $tid => $partida) {
2206          if (!isset($partidas_nodo[$field_l][$tid])) {
2207            if (empty($node->{$field_l}[0]['tid']) || !$node->{$field_l}[0]['tid']) {
2208              $node->{$field_l} = array();
2209            }
2210            $valores['tid'] = $tid;
2211            $node->{$field_l}[] = $valores;
2212            $partidas_nodo[$field_l][$tid] = $tid;
2213          }
2214        }
2215      }
2216    }
2217  }
2218  $currents_estados = array();
2219  foreach($meses as $mes => $nombre) {
2220    $valor = $mes > 0 ? 'value_' . $mes : 'value';
2221    foreach($array as $ids) {
2222      $actualP = _acciones_centralizadas_seguimiento_load($node, $ids, $mes);
2223      $mensajes[$ids][$valor] =  $actualP['values'];
2224      if (isset($actualP['comprometido'][$ids])) {
2225        foreach($actualP['comprometido'][$ids] as $tid => $value) {
2226          $actual['comprometido'][$ids][$tid][$valor] = $value[$valor];
2227        }
2228        foreach($actualP['pagado'][$ids] as $tid => $value) {
2229          $actual['pagado'][$ids][$tid][$valor] = $value[$valor];
2230        }
2231        foreach($actualP['causado'][$ids] as $tid => $value) {
2232          $actual['causado'][$ids][$tid][$valor] = $value[$valor];
2233        }
2234        $currents_estados[$ids][$actualP['values']['mes']]['value'] = isset($actualP['values']) && isset($actualP['values']['estado']) ? $actualP['values']['estado'] : -1;
2235        $currents_estados[$ids][$actualP['values']['mes']]['texto'] = isset($states['states'][$currents_estados[$ids][$actualP['values']['mes']]['value']]) ? $states['states'][$currents_estados[$ids][$actualP['values']['mes']]['value']] : t('No ingresado');
2236      }
2237      $author[$ids][$actualP['values']['mes']] = isset($actualP['values']) && isset($actualP['values']['uid']) ? $actualP['values']['uid'] : 0;
2238
2239    }
2240  }
2241  $comprometido = isset($actual['comprometido']) ? $actual['comprometido'] : array();
2242  $causado = isset($actual['causado']) ? $actual['causado'] : array();
2243  $pagado = isset($actual['pagado']) ? $actual['pagado'] : array();
2244  $grupos = fieldgroup_groups('accion_centralizada');
2245  $header = array();
2246  $header[] = array('data' => t('Mes'));
2247  $header[] = array('data' => t('Asignado'));
2248  $header[] = array('data' => t('Comprometido'));
2249  $header[] = array('data' => t('Causado'));
2250  $header[] = array('data' => t('Pagado'));
2251  $header[] = array('data' => t('% de inversión'));
2252  $header[] = array('data' => t('Estatus de la inversión'));
2253  $header[] = array('data' => t('Información complementaria'));
2254  $header[] = array('data' => t('Estado'));
2255  $header[] = array('data' => t('Opciones Disponibles'),);
2256  $grupos_form = array();
2257  $grupos_fields = array();
2258  $colores = array();
2259  $colores[0] = array(
2260    'texto' => variable_get('acciones_centralizadas_texto_default', 'No hay planificación'),
2261    'tcolor' => variable_get('acciones_centralizadas_colort_default', '#FFFFFF'),
2262    'color' => variable_get('acciones_centralizadas_color_default', '#633303'),
2263  );
2264  $colores[1] = array(
2265    'texto' => variable_get('acciones_centralizadas_texto_critica', 'Zona crítica'),
2266    'tcolor' => variable_get('acciones_centralizadas_colort_critica', '#FFFFFF'),
2267    'color' => variable_get('acciones_centralizadas_color_critica', '#fd0002'),
2268  );
2269  $colores[2] = array(
2270    'texto' => variable_get('acciones_centralizadas_texto_discreta', 'Zona discreta'),
2271    'tcolor' => variable_get('acciones_centralizadas_colort_discreta', '#FFFFFF'),
2272    'color' => variable_get('acciones_centralizadas_color_discreta', '#cc6733'),
2273  );
2274  $colores[3] = array(
2275    'texto' => variable_get('acciones_centralizadas_texto_moderada', 'Zona moderada'),
2276    'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
2277    'color' => variable_get('acciones_centralizadas_color_moderada', '#fdff00'),
2278  );
2279  $colores[4] = array(
2280    'texto' => variable_get('acciones_centralizadas_texto_optima', 'Zona optima'),
2281    'tcolor' => variable_get('acciones_centralizadas_colort_optima', '#000000'),
2282    'color' => variable_get('acciones_centralizadas_color_optima', '#20ff21'),
2283  );
2284  $colores[5] = array(
2285    'texto' => variable_get('acciones_centralizadas_texto_sejecucion', 'Sobre ejecución'),
2286    'tcolor' => variable_get('acciones_centralizadas_colort_sejecucion', '#000000'),
2287    'color' => variable_get('acciones_centralizadas_color_sejecucion', '#9966cd'),
2288  );
2289  $output = '';
2290  foreach($grupos as $id => $grupo) {
2291    $tablas = array();
2292    if (count($grupo['fields'])) {
2293      foreach($grupo['fields'] as $id_field => $field) {
2294        $rows = array();
2295        $suma = array();
2296        $sumaC = array();
2297        $sumaCa = array();
2298        $sumaP = array();
2299        $sumaT = 0;
2300        $sumaTC = 0;
2301        $sumaTCa = 0;
2302        $sumaTP = 0;
2303        $field_load = content_fields($id_field, 'accion_centralizada');
2304        if (array_key_exists($id_field, $array) && $node->{$id_field}[0]['tid']) {
2305          foreach($node->{$id_field} as $values) {
2306            foreach($ftypes as $ids =>$texto) {
2307              if (!isset($suma[$ids])) {
2308                $suma[$ids] = 0;
2309              }
2310              $comprometido[$id_field][$values['tid']][$ids] = isset($comprometido[$id_field]) && isset($comprometido[$id_field][$values['tid']]) ? $comprometido[$id_field][$values['tid']][$ids] : 0;
2311              $causado[$id_field][$values['tid']][$ids] = isset($causado[$id_field]) && isset($causado[$id_field][$values['tid']]) ? $causado[$id_field][$values['tid']][$ids] : 0;
2312              $pagado[$id_field][$values['tid']][$ids] = isset($pagado[$id_field]) && isset($pagado[$id_field][$values['tid']]) ? $pagado[$id_field][$values['tid']][$ids] : 0;
2313              $varia[$id_field][$values['tid']][$ids] = isset($variaciones[$id_field][$values['tid']][$ids]) ? $variaciones[$id_field][$values['tid']][$ids] : 0;
2314              $sumaC[$ids] += $comprometido[$id_field][$values['tid']][$ids];
2315              $sumaCa[$ids] += $causado[$id_field][$values['tid']][$ids];
2316              $sumaP[$ids] += $pagado[$id_field][$values['tid']][$ids];
2317              $valor = $values[$ids] + $varia[$id_field][$values['tid']][$ids];
2318              $suma[$ids] += $valor;
2319            }
2320          }
2321        }
2322        if (count($suma)) {
2323          $rows = array();
2324          $i = 0;
2325          foreach($ftypes as $ids =>$texto) {
2326            $zonacritica = $suma[$ids] ? $sumaCa[$ids]/$suma[$ids] : -1;
2327            $porczonacritica = $zonacritica >= 0 ? ($zonacritica * 100) . '%' : -1;
2328            $colorzona = $colores[0]['color'];
2329            $colorfontzona = $colores[0]['tcolor'];
2330            $textozona = $colores[0]['texto'];
2331            if ($porczonacritica >= 0 &&  $porczonacritica < 11) {
2332              $colorzona = $colores[1]['color'];
2333              $colorfontzona = $colores[1]['tcolor'];
2334              $textozona = $colores[1]['texto'];
2335            }
2336            elseif ($porczonacritica >= 11 &&  $porczonacritica < 51) {
2337              $colorzona = $colores[2]['color'];
2338              $colorfontzona = $colores[2]['tcolor'];
2339              $textozona = $colores[2]['texto'];
2340            }
2341            elseif ($porczonacritica >= 51 &&  $porczonacritica < 80) {
2342              $colorzona = $colores[3]['color'];
2343              $colorfontzona = $colores[3]['tcolor'];
2344              $textozona = $colores[3]['texto'];
2345            }
2346            elseif ($porczonacritica >= 51 &&  $porczonacritica <= 100) {
2347              $colorzona = $colores[4]['color'];
2348              $colorfontzona = $colores[4]['tcolor'];
2349              $textozona = $colores[4]['texto'];
2350            }
2351            elseif ($porczonacritica > 100) {
2352              $colorzona = $colores[5]['color'];
2353              $colorfontzona = $colores[5]['tcolor'];
2354              $textozona = $colores[5]['texto'];
2355            }
2356            if ($porczonacritica < 0) {
2357              $porczonacritica = 'N/A';
2358            }
2359            else {
2360              $porczonacritica = number_format($porczonacritica, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
2361            }
2362            $row = array();
2363            $row[] = array('data' => $texto,);
2364            $row[] = array('data' => number_format($suma[$ids], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2365            $row[] = array('data' => number_format($sumaC[$ids], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2366            $row[] = array('data' => number_format($sumaCa[$ids], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2367            $row[] = array('data' => number_format($sumaP[$ids], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2368            $row[] = array('data' => $porczonacritica,);
2369            $row[] = array('data' => $textozona, 'style' => 'font-weight: bold;background:' . $colorzona . '; color:' . $colorfontzona);
2370            $mensaje = isset($mensajes[$id_field][$ids]['comentario']) ? $mensajes[$id_field][$ids]['comentario'] : '';
2371            $row[] = array('data' => $mensaje,);
2372            $style_estado = '';
2373            if ($node->anhoaccion_centralizada == $year && $mes_segu == ($i + 1) && isset($currents_estados[$id_field][$i]['value']) && $currents_estados[$id_field][$i]['value'] != $estado_aprobado && $currents_estados[$id_field][$i]['value'] != $estado_naprobado) {
2374              $style_estado = 'color:red';
2375            }
2376            $estado = isset($currents_estados[$id_field][$i]['texto']) ? $currents_estados[$id_field][$i]['texto'] : 'No ingresado';
2377            $row[] = array('data' => '<div style="' . $style_estado . '">' . $estado . '</div>',);
2378            $links = array();
2379            $links[] = l(t('Consultar Seguimiento'), 'node/' . $node->nid . '/seguimiento/' . $id_field . '/' . $i . '/view');
2380            if ($acciones_centralizadas_seguimiento_node_tab_access && $node->anhoaccion_centralizada == $year && $mes_segu == ($i + 1)) {
2381              $links[] = l(t('Fase de Seguimiento (@nombre_mes)', array('@nombre_mes' => $meses[$i])), 'node/' . $node->nid . '/seguimiento/fase/' . $i);
2382            }
2383            if ($suma[$ids] && $node->anhoaccion_centralizada == $year && $mes_segu == ($i + 1) && _acciones_centralizadas_seguimiento_node_tab_mes_access($node, $id_field,$i)) {
2384              $links[] = l(t('Modificar el Seguimiento'), 'node/' . $node->nid . '/seguimiento/'. $id_field . '/' . ($mes_segu - 1) . '/edit', array('query' => array('destination' => $_GET['q'])));
2385            }
2386            $current_estado = isset($currents_estados[$id_field][$i]['value']) ? $currents_estados[$id_field][$i]['value'] : -1;
2387            if ($suma[$ids] && $node->anhoaccion_centralizada == $year && $mes_segu == ($i + 1)) {
2388              if ($states['wid']) {
2389                $roles1 = (array) $roles;
2390echo $author[$id_field][$i];
2391                if ($user->uid != 1 && $user->uid == $author[$id_field][$i] && $author[$id_field][$i] > 0) {
2392                  $roles1 += array('author' => 'author');
2393                }
2394                $transitions = workflow_allowable_transitions($current_estado, 'to', $roles1);
2395              }
2396              unset($transitions[$current_estado]);
2397              if (count($transitions) && $estado_aprobado != $current_estado) {
2398                foreach($transitions as $id => $transition) {
2399                  $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'node/' . $node->nid . '/seguimiento/' . $id_field . '/' . $mes . '/workflow/' . $id, array('query' => array('destination' => $_GET['q'])));
2400                }
2401              }
2402            }
2403            $row[] = array('data' => theme('item_list', $links),);
2404            $sumaT += $suma[$ids];
2405            $sumaTC += $sumaC[$ids];
2406            $sumaTCa += $sumaCa[$ids];
2407            $sumaTP += $sumaP[$ids];
2408            $rows[] = $row;
2409            $i++;
2410          }
2411          $row = array();
2412          $row[] = array('data' => t('Acumulado'),);
2413          $row[] = array('data' => number_format($sumaT, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2414          $row[] = array('data' => number_format($sumaTC, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2415          $row[] = array('data' => number_format($sumaTCa, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2416          $row[] = array('data' => number_format($sumaTP, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2417          $row[] = array('data' => '', 'colspan' => 5);
2418          $sumaT += $suma[$ids];
2419          $sumaTC += $sumaC[$ids];
2420          $sumaTCa += $sumaCa[$ids];
2421          $sumaTP += $sumaP[$ids];
2422          $rows[] = $row;
2423          $tablas[]= '<div class="field-label">' . $field_load['widget']['label'] . '</div>' . theme('table', $header, $rows);
2424        }
2425      }
2426    }
2427    if (count($tablas)) {
2428      $output .= '<fieldset><legend>' . $grupo['label'] . '</legend>' . implode('', $tablas). '</fieldset>';
2429      $descripcion = array(
2430        0 => '',
2431        1 => '(' . t('De 0 a 10.99 %') . ')',
2432        2 => '(' . t('De 11 a 50.99 %') . ')',
2433        3 => '(' . t('De 51 a 79.99 %') . ')',
2434        4 => '(' . t('De 80 a 100 %') . ')',
2435        5 => '(' . t('Mas de 100 %') . ')',
2436      );
2437      $output .= '<table id="leyenda">';
2438      for($i = 0; $i < 6; $i++) {
2439        $output .= '<tr><td style="font-weight: bold">' . $colores[$i]['texto'] . ' ' . $descripcion[$i] . '</td><td style="background:' . $colores[$i]['color'] . ';" width="50px">' . '</td><tr>';
2440      }
2441      $output .= '</table><br />';
2442    }
2443  }
2444  if ($output == '') {
2445    $output .= t('La acción Centralizada no tiene partidas asignadas.');
2446  }
2447  return $output;
2448}
2449
2450/*
2451 * Implementation of acciones_centralizadas_seguimiento_tab_page()
2452 */
2453function acciones_centralizadas_seguimiento_tab_page($node) {
2454  global $user;
2455  drupal_set_title(t('Seguimiento y Control de Acción Centralizada'));
2456  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
2457  $current_time = time();
2458  $tipo_plan = 'acciones_centralizadas_seguimiento';
2459  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
2460  $fecha = FALSE;
2461  $ente = usuario_tiene_ente($user->uid);
2462  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2463    $fecha = TRUE;
2464  }
2465  if (!$fecha) {
2466    muestra_mensaje($tipo_plan, $ente_planificador);
2467  }
2468  else {
2469    if ($ente->nid == $ente_planificador->nid) {
2470      $fecha = TRUE;
2471      muestra_mensaje($tipo_plan, $ente_planificador, 0);
2472    }
2473    elseif (!user_access('admin planificador')) {
2474      $fecha = FALSE;
2475    }
2476  }
2477  $output = _display_acciones_centralizadas_seguimiento_tab_page($node);
2478  return $output;
2479}
2480
2481/*
2482 * Implementation of acciones_centralizadas_seguimiento_partida_tab_page()
2483 */
2484function acciones_centralizadas_seguimiento_partida_tab_page($node, $campo = '', $mes = 0) {
2485  $acciones_centralizadas_seguimiento_node_tab_access = _acciones_centralizadas_seguimiento_node_tab_access($node);
2486  global $user;
2487  $format_number = array(
2488    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
2489    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
2490    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
2491  );
2492  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
2493  $current_time = time();
2494  $tipo_plan = 'acciones_centralizadas_seguimiento';
2495  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
2496  $fecha = FALSE;
2497  $ente = usuario_tiene_ente($user->uid);
2498  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2499    $fecha = TRUE;
2500  }
2501  if (!$fecha) {
2502    muestra_mensaje($tipo_plan, $ente_planificador);
2503  }
2504  else {
2505    if ($ente->nid == $ente_planificador->nid) {
2506      $fecha = TRUE;
2507      muestra_mensaje($tipo_plan, $ente_planificador, 0);
2508    }
2509    elseif (!user_access('admin planificador')) {
2510      $fecha = FALSE;
2511    }
2512  }
2513  drupal_set_title(t('Seguimiento y Control de Acción Centralizada'));
2514  $year = variable_get('acciones_centralizadas_anho_creacion', 0);
2515  $output = '';
2516  $meses = array(
2517    0 => t('January'),
2518    1 => t('February'),
2519    2 => t('March'),
2520    3 => t('April'),
2521    4 => t('May'),
2522    5 => t('June'),
2523    6 => t('July'),
2524    7 => t('August'),
2525    8 => t('September'),
2526    9 => t('Octuber'),
2527    10 => t('November'),
2528    11 => t('December'),
2529  );
2530  $ftypes = array(
2531    'value' => t('January'),
2532    'value_1' => t('February'),
2533    'value_2' => t('March'),
2534    'value_3' => t('April'),
2535    'value_4' => t('May'),
2536    'value_5' => t('June'),
2537    'value_6' => t('July'),
2538    'value_7' => t('August'),
2539    'value_8' => t('September'),
2540    'value_9' => t('Octuber'),
2541    'value_10' => t('November'),
2542    'value_11' => t('December'),
2543  );
2544  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2545  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
2546  $reformula = _acciones_centralizadas_reformula_load($node);
2547  $array = array(
2548    'field_ac_ac1_ae1',
2549    'field_ac_ac1_ae2',
2550    'field_ac_ac2_ae2',
2551    'field_ac_ac2_ae3',
2552    'field_ac_ac3_ae1',
2553    'field_ac_ac4_ae1',
2554  );
2555  $valores = array();
2556  foreach($ftypes as $id_field => $texto) {
2557    $valores[$id_field] = 0;
2558  }
2559  $partidas_nodo = array();
2560  foreach ($array as $id) {
2561    if (count($node->{$id})) {
2562      foreach($node->{$id} as $partida) {
2563        if(!empty($partida['tid'])) {
2564          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
2565        }
2566      }
2567    }
2568  }
2569  if (count($variaciones)) {
2570    foreach($variaciones as $field_l => $partidas) {
2571      if (count($partidas)) {
2572        foreach($partidas as $tid => $partida) {
2573          if (!isset($partidas_nodo[$field_l][$tid])) {
2574            $valores['tid'] = $tid;
2575            $node->{$field_l}[] = $valores;
2576            if ($field_l == $campo['field']) {
2577              $campo['values'][] = $valores;
2578            }
2579          }
2580        }
2581      }
2582    }
2583  }
2584  if (count($reformula)) {
2585    foreach($reformula as $field_l => $partidas) {
2586      if (count($partidas)) {
2587        foreach($partidas as $tid => $partida) {
2588          if (!isset($partidas_nodo[$field_l][$tid])) {
2589            $valores['tid'] = $tid;
2590            $node->{$field_l}[] = $valores;
2591            if ($field_l == $campo['field']) {
2592              $campo['values'][] = $valores;
2593            }
2594          }
2595        }
2596      }
2597    }
2598  }
2599  $actual = _acciones_centralizadas_seguimiento_load($node, $campo['field'], $mes);
2600  $comprometido = isset($actual['comprometido']) ? $actual['comprometido'] : array();
2601  $causado = isset($actual['causado']) ? $actual['causado'] : array();
2602  $pagado = isset($actual['pagado']) ? $actual['pagado'] : array();
2603  $grupos = fieldgroup_groups('accion_centralizada');
2604  $header = array();
2605  $header[] = array('data' => t('Partida'));
2606  $header[] = array('data' => t('Asignado'));
2607  $header[] = array('data' => t('Comprometido'));
2608  $header[] = array('data' => t('Causado'));
2609  $header[] = array('data' => t('Pagado'));
2610  $header[] = array('data' => t('% de inversión'));
2611  $header[] = array('data' => t('Estatus de la inversión'));
2612  $grupos = fieldgroup_groups('accion_centralizada');
2613  $grupos_fields = array();
2614  foreach($grupos as $id => $grupo) {
2615    if (count($grupo['fields'])) {
2616      foreach($grupo['fields'] as $id_field => $field) {
2617        if ($id_field == $campo['field']) {
2618          $grupos_fields = $grupos[$id];
2619        }
2620      }
2621    }
2622  }
2623  $field_load = content_fields($campo['field'], 'accion_centralizada');
2624  $colores = array();
2625  $colores[0] = array(
2626    'texto' => variable_get('acciones_centralizadas_texto_default', 'No hay planificación'),
2627    'tcolor' => variable_get('acciones_centralizadas_colort_default', '#FFFFFF'),
2628    'color' => variable_get('acciones_centralizadas_color_default', '#633303'),
2629  );
2630  $colores[1] = array(
2631    'texto' => variable_get('acciones_centralizadas_texto_critica', 'Zona crítica'),
2632    'tcolor' => variable_get('acciones_centralizadas_colort_critica', '#FFFFFF'),
2633    'color' => variable_get('acciones_centralizadas_color_critica', '#fd0002'),
2634  );
2635  $colores[2] = array(
2636    'texto' => variable_get('acciones_centralizadas_texto_discreta', 'Zona discreta'),
2637    'tcolor' => variable_get('acciones_centralizadas_colort_discreta', '#FFFFFF'),
2638    'color' => variable_get('acciones_centralizadas_color_discreta', '#cc6733'),
2639  );
2640  $colores[3] = array(
2641    'texto' => variable_get('acciones_centralizadas_texto_moderada', 'Zona moderada'),
2642    'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
2643    'color' => variable_get('acciones_centralizadas_color_moderada', '#fdff00'),
2644  );
2645  $colores[4] = array(
2646    'texto' => variable_get('acciones_centralizadas_texto_optima', 'Zona optima'),
2647    'tcolor' => variable_get('acciones_centralizadas_colort_optima', '#000000'),
2648    'color' => variable_get('acciones_centralizadas_color_optima', '#20ff21'),
2649  );
2650  $colores[5] = array(
2651    'texto' => variable_get('acciones_centralizadas_texto_sejecucion', 'Sobre ejecución'),
2652    'tcolor' => variable_get('acciones_centralizadas_colort_sejecucion', '#000000'),
2653    'color' => variable_get('acciones_centralizadas_color_sejecucion', '#9966cd'),
2654  );
2655  foreach ($campo['values'] as $partida) {
2656    if ($partida['tid']) {
2657      $term = taxonomy_get_term($partida['tid']);
2658      // If this term's vocabulary supports localization.
2659      if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
2660        $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
2661      }
2662      $valor = $mes > 0 ? 'value_' . $mes : 'value';
2663      $varia = isset($variaciones[$campo['field']][$partida['tid']][$valor]) ? $variaciones[$campo['field']][$partida['tid']][$valor] : 0;
2664      $comprometidov = isset($comprometido[$campo['field']]) && isset($comprometido[$campo['field']][$partida['tid']]) ? $comprometido[$campo['field']][$partida['tid']][$valor] : 0;
2665      $causadov = isset($causado[$campo['field']]) && isset($causado[$campo['field']][$partida['tid']]) ? $causado[$campo['field']][$partida['tid']][$valor] : 0;
2666      $pagadov = isset($pagado[$campo['field']]) && isset($pagado[$campo['field']][$partida['tid']]) ? $pagado[$campo['field']][$partida['tid']][$valor] : 0;
2667      $sumaC += $comprometidov;
2668      $sumaCa += $causadov;
2669      $sumaP += $pagadov;
2670      $valorreal = (string) ($partida[$valor] + $varia);
2671      $suma += $valorreal;
2672      $zonacritica = $valorreal ? $causadov/$valorreal : -1;
2673      $porczonacritica = $zonacritica >= 0 ? ($zonacritica * 100) . '%' : -1;
2674      $colorzona = $colores[0]['color'];
2675      $colorfontzona = $colores[0]['tcolor'];
2676      $textozona = $colores[0]['texto'];
2677      if ($porczonacritica >= 0 &&  $porczonacritica < 11) {
2678        $colorzona = $colores[1]['color'];
2679        $colorfontzona = $colores[1]['tcolor'];
2680        $textozona = $colores[1]['texto'];
2681      }
2682      elseif ($porczonacritica >= 11 &&  $porczonacritica < 51) {
2683        $colorzona = $colores[2]['color'];
2684        $colorfontzona = $colores[2]['tcolor'];
2685        $textozona = $colores[2]['texto'];
2686      }
2687      elseif ($porczonacritica >= 51 &&  $porczonacritica < 80) {
2688        $colorzona = $colores[3]['color'];
2689        $colorfontzona = $colores[3]['tcolor'];
2690        $textozona = $colores[3]['texto'];
2691      }
2692      elseif ($porczonacritica >= 51 &&  $porczonacritica <= 100) {
2693        $colorzona = $colores[4]['color'];
2694        $colorfontzona = $colores[4]['tcolor'];
2695        $textozona = $colores[4]['texto'];
2696      }
2697      elseif ($porczonacritica > 100) {
2698        $colorzona = $colores[5]['color'];
2699        $colorfontzona = $colores[5]['tcolor'];
2700        $textozona = $colores[5]['texto'];
2701      }
2702      if ($porczonacritica < 0) {
2703        $porczonacritica = 'N/A';
2704      }
2705      else {
2706        $porczonacritica = number_format($porczonacritica, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
2707      }
2708      $row = array();
2709      $row[] = array('data' => $term->name,);
2710      $row[] = array('data' => number_format($valorreal, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2711      $row[] = array('data' => number_format($comprometidov, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2712      $row[] = array('data' => number_format($causadov, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2713      $row[] = array('data' => number_format($pagadov, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2714      $row[] = array('data' => $porczonacritica,);
2715      $row[] = array('data' => $textozona, 'style' => 'font-weight: bold;background:' . $colorzona . '; color:' . $colorfontzona);
2716      $rows[] = $row;
2717    }
2718  }
2719  $row = array();
2720  $row[] = array('data' => t('Acumulado'),);
2721  $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2722  $row[] = array('data' => number_format($sumaC, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2723  $row[] = array('data' => number_format($sumaCa, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']),);
2724  $row[] = array('data' => $sumaP,);
2725  $row[] = array('data' => '', 'colspan' => 2);
2726  $rows[] = $row;
2727  $output = '';
2728  $grupo = explode('-', $grupos_fields['label']);
2729  $output .= '<fieldset><legend>' . t('Datos de la Acción Centralizada a la que pertenece la acción especifica') . '</legend>' .   '<div class="field-label"><b>' . t('Código de la AC:') . '</b> ' . $grupo[0] . '</div>' . '<div class="field-label"><b>' . t('Nombre de la AC:') . '</b> ' . $grupo[1] . '</div>' . '</fieldset>';
2730  $output .= '<fieldset><legend>' . t('Datos de la Acción') . '</legend>' . '<div class="field-label"><b>' . t('Nombre de la Acción Especifica:') . '</b> ' . $field_load['widget']['label'] . '</div>'. '</fieldset>';
2731  $output .= '<fieldset><legend>' . t('Seguimiento de partidas de la Acción Especifica') . '</legend>' . '<div class="field-label"><b>' . t('Mes de Seguimiento Actual:') . '</b> ' . $meses[$mes] . '</div>' . theme('table', $header, $rows) . '</fieldset>';
2732  $acceso = _acciones_centralizadas_seguimiento_node_tab_mes_access($node, $campo['field'], $mes);
2733  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
2734  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
2735  $current_estado = isset($actual['values']) && isset($actual['values']['estado']) ? $actual['values']['estado'] : -1;
2736  $cid_seg = isset($actual['values']) && isset($actual['values']['id_seg']) ? $actual['values']['id_seg'] : 0;
2737  $states = _acciones_centralizadas_reformula_obtiene_estados();
2738  if (module_exists('workflow')) {
2739    $states = _acciones_centralizadas_reformula_obtiene_estados();
2740    if ($cid_seg) {
2741      $header = array();
2742      $header[] = array('data' => t('Fecha'),);
2743      $header[] = array('data' => t('Estado'),);
2744      $header[] = array('data' => t('Estado anterior'),);
2745      $header[] = array('data' => t('Comentario'),);
2746      $header[] = array('data' => t('Usuario'),);
2747      $rows = array();
2748      $result = db_query('SELECT re.*, u.name, u.uid FROM {accion_seguimiento_state} re INNER JOIN {users} u ON u.uid = re.uid WHERE nid = %d AND id_seg = %d ORDER BY date DESC', $node->nid, $cid_seg);
2749      while($history = db_fetch_object($result)) {
2750        $row = array();
2751        $row[] = array('data' => format_date($history->date),);
2752        $row[] = array('data' => $states['states'][$history->estado],);
2753        $row[] = array('data' => $states['states'][$history->estado_ant],);
2754        $row[] = array('data' => $history->comentario,);
2755        $row[] = array('data' => l($history->name, 'user/' . $history->uid),);
2756        $rows[] = $row;
2757      }
2758      if (count($rows)) {
2759        $output .= '<div class="field"><div class="field-label">' . t('Historial') . ':</div>' . theme('table', $header, $rows) . '</div>';
2760        $row[] = array('data' => t('No existe historial para este mes de seguimiento'), 'colspan' => 5);
2761      }
2762    }
2763  }
2764  $descripcion = array(
2765    0 => '',
2766    1 => '(' . t('De 0 a 10.99 %') . ')',
2767    2 => '(' . t('De 11 a 50.99 %') . ')',
2768    3 => '(' . t('De 51 a 79.99 %') . ')',
2769    4 => '(' . t('De 80 a 100 %') . ')',
2770    5 => '(' . t('Mas de 100 %') . ')',
2771
2772  );
2773  $output .= '<table id="leyenda">';
2774  for($i = 0; $i < 6; $i++) {
2775    $output .= '<tr><td style="font-weight: bold">' . $colores[$i]['texto'] . ' ' . $descripcion[$i] . '</td><td style="background:' . $colores[$i]['color'] . ';" width="50px">' . '</td><tr>';
2776  }
2777  $output .= '</table>';
2778  $links = array();
2779  if ($fecha && $current_estado != $estado_aprobado && $current_estado != $estado_naprobado &&  $acceso) {
2780    $links[] = l(t('Modificar seguimiento'), 'node/' . $node->nid . '/seguimiento/' . $campo['field'] . '/' . $mes . '/edit');
2781  }
2782  $author = isset($actual['values']) && isset($actual['values']['uid']) ? $actual['values']['uid'] : 0;
2783  if ($suma > 0 && module_exists('workflow')) {
2784    if (isset($states['wid'])) {
2785      $first_state = 0;
2786      if ($states['wid']) {
2787        $first_state = _workflow_creation_state($states['wid']);
2788      }
2789      if ($user->uid == 1) {
2790        // Superuser is special.
2791        $roles = 'ALL';
2792      }
2793      else {
2794        $roles = array_keys($user->roles);
2795        if ($user->uid == $author && $author > 0) {
2796          $roles += array('author' => 'author');
2797        }
2798      }
2799      $transitions = array();
2800      if ($states['wid']) {
2801        $transitions = workflow_allowable_transitions($current_estado, 'to', $roles);
2802      }
2803      unset($transitions[$current_estado]);
2804      if (count($transitions) && $estado_aprobado != $current_estado) {
2805        foreach($transitions as $id => $transition) {
2806          $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'node/' . $node->nid . '/seguimiento/' . $campo['field'] . '/' . $mes . '/workflow/' . $id);
2807        }
2808      }
2809    }
2810  }
2811  if ($acciones_centralizadas_seguimiento_node_tab_access) {
2812    $links[] = l(t('Fase de Seguimiento (@nombre_mes)', array('@nombre_mes' => $meses[$mes])), 'node/' . $node->nid . '/seguimiento/fase/' . $mes);
2813    $links[] = l(t('Seguimiento de la AC'), 'node/' . $node->nid . '/seguimiento');
2814  }
2815  $header = array();
2816  $header[] = array('data' => t('Opciones Disponibles'),);
2817  $rows = array();
2818  $row = array();
2819  $row[] = array('data' =>  implode(' | ', $links),);
2820  $rows[] = $row;
2821  $output .= theme('table', $header, $rows);
2822  $texto = array();
2823  if($mes > 0 && $mes < 12) {
2824    $texto[] = l(t('Consultar mes anterior'), 'node/' . $node->nid . '/seguimiento/' . $campo['field'] . '/' . ($mes - 1) . '/view');
2825    if ($mes < 11) {
2826      $texto[] = l(t('Consultar mes proximo'), 'node/' . $node->nid . '/seguimiento/' . $campo['field'] . '/' . ($mes + 1) . '/view');
2827    }
2828  }
2829  elseif ($mes == 0) {
2830    $texto[] = l(t('Consultar mes proximo'), 'node/' . $node->nid . '/seguimiento/' . $campo['field'] . '/' . ($mes + 1) . '/view');
2831  }
2832  $output = '<p>' . implode(' | ', $texto) . "</p>" . $output;
2833  return $output;
2834}
2835
2836/*
2837 * Implementation of acciones_centralizadas_seguimiento_tab_page_form()
2838 */
2839function acciones_centralizadas_seguimiento_tab_page_form($form_state, $node, $campo = '', $mes = 0) {
2840  global $user;
2841  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
2842  $current_time = time();
2843  $tipo_plan = 'acciones_centralizadas_seguimiento';
2844  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
2845  $fecha = FALSE;
2846  $ente = usuario_tiene_ente($user->uid);
2847  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2848    $fecha = TRUE;
2849  }
2850  if (!$fecha) {
2851    muestra_mensaje($tipo_plan, $ente_planificador);
2852  }
2853  else {
2854    if ($ente->nid == $ente_planificador->nid) {
2855      $fecha = TRUE;
2856      muestra_mensaje($tipo_plan, $ente_planificador, 0);
2857    }
2858    elseif (!user_access('admin planificador')) {
2859      $fecha = FALSE;
2860    }
2861  }
2862  $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
2863  drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
2864  $settings['acciones_centralizadas'] = array(
2865    0 => array(
2866      'color' => variable_get('acciones_centralizadas_color_default', '#633303'),
2867      'tcolor' => variable_get('acciones_centralizadas_colort_default', '#FFFFFF'),
2868      'texto' => variable_get('acciones_centralizadas_texto_default', 'No hay planificación'),
2869    ),
2870    1 => array(
2871      'color' => variable_get('acciones_centralizadas_color_critica', '#fd0002'),
2872      'tcolor' => variable_get('acciones_centralizadas_colort_critica', '#FFFFFF'),
2873      'texto' => variable_get('acciones_centralizadas_texto_critica', 'Zona crítica'),
2874    ),
2875    2 => array(
2876      'color' => variable_get('acciones_centralizadas_color_discreta', '#cc6733'),
2877      'tcolor' => variable_get('acciones_centralizadas_colort_discreta', '#FFFFFF'),
2878      'texto' => variable_get('acciones_centralizadas_texto_discreta', 'Zona discreta'),
2879    ),
2880    3 => array(
2881      'color' => variable_get('acciones_centralizadas_color_moderada', '#fdff00'),
2882      'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
2883      'texto' => variable_get('acciones_centralizadas_texto_moderada', 'Zona moderada'),
2884    ),
2885    4 => array(
2886      'color' => variable_get('acciones_centralizadas_color_optima', '#20ff21'),
2887      'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
2888      'texto' => variable_get('acciones_centralizadas_texto_optima', 'Zona optima'),
2889    ),
2890    5 => array(
2891      'color' => variable_get('acciones_centralizadas_color_sejecucion', '#9966cd'),
2892      'tcolor' => variable_get('acciones_centralizadas_colort_sejecucion', '#000000'),
2893      'texto' => variable_get('acciones_centralizadas_texto_sejecucion', 'Sobre ejecución'),
2894    ),
2895  );
2896  drupal_add_js($settings, 'setting');
2897  drupal_set_title(t('Seguimiento y Control de Acción Específica de Acción Centralizada'));
2898  $form = array();
2899  $format_number = array(
2900    'decimals' => variable_get('acciones_centralizadas_number_decimals', 0),
2901    'dec_point' => variable_get('acciones_centralizadas_number_dec_point', ','),
2902    'thousands_sep' => variable_get('acciones_centralizadas_number_thousands_sep', '.'),
2903  );
2904  $form['#format_number'] = array('format_number' => $format_number);
2905  drupal_add_js($form['#format_number'], 'setting');
2906  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
2907  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
2908  $reformula = _acciones_centralizadas_reformula_load($node);
2909  $grupos = fieldgroup_groups('accion_centralizada');
2910  $grupos_fields = array();
2911  foreach($grupos as $id => $grupo) {
2912    if (count($grupo['fields'])) {
2913      foreach($grupo['fields'] as $id_field => $field) {
2914        if ($id_field == $campo['field']) {
2915          $grupos_fields = $grupos[$id];
2916        }
2917      }
2918    }
2919  }
2920  $form['#field_load'] = content_fields($campo['field'], 'accion_centralizada');
2921  $form['#grupo'] = $grupos_fields;
2922  $form['#ftypes'] = array(
2923    'value' => t('January'),
2924    'value_1' => t('February'),
2925    'value_2' => t('March'),
2926    'value_3' => t('April'),
2927    'value_4' => t('May'),
2928    'value_5' => t('June'),
2929    'value_6' => t('July'),
2930    'value_7' => t('August'),
2931    'value_8' => t('September'),
2932    'value_9' => t('Octuber'),
2933    'value_10' => t('November'),
2934    'value_11' => t('December'),
2935  );
2936  $output = '';
2937  $reformula = _acciones_centralizadas_reformula_load($node);
2938  $actual = _acciones_centralizadas_seguimiento_load($node, $campo['field'], $mes);
2939  $estado = (isset($actual['values']) && isset($actual['values']['estado'])) ? $actual['values']['estado'] : -1;
2940  $form['#state_creation'] = $estado;
2941  $form['#id_seg'] = (isset($actual['values']) && isset($actual['values']['id_seg'])) ? $actual['values']['id_seg'] : 0;
2942  //get first state
2943  if ($estado == -1 && module_exists('workflow')) {
2944    $wid = workflow_get_workflow_for_type('accion_centralizada');
2945    if ($wid) {
2946      $form['#state_creation'] = _workflow_creation_state($wid);
2947    }
2948  }
2949  $comprometido = isset($actual['comprometido']) ? $actual['comprometido'] : array();
2950  $causado = isset($actual['causado']) ? $actual['causado'] : array();
2951  $pagado = isset($actual['pagado']) ? $actual['pagado'] : array();
2952  $header = array();
2953  $header[] = array('data' => t('Partida'));
2954  $header[] = array('data' => t('Asignado'));
2955  $header[] = array('data' => t('Comprometido'));
2956  $header[] = array('data' => t('Causado'));
2957  $header[] = array('data' => t('Pagado'));
2958  $header[] = array('data' => t('% de inversión'));
2959  $header[] = array('data' => t('Estatus de la inversión'));
2960  $header[] = array('data' => t('Información complementaria'));
2961  $grupos_form = array();
2962  $valores = array();
2963  $array = array(
2964    'field_ac_ac1_ae1',
2965    'field_ac_ac1_ae2',
2966    'field_ac_ac2_ae2',
2967    'field_ac_ac2_ae3',
2968    'field_ac_ac3_ae1',
2969    'field_ac_ac4_ae1',
2970  );
2971  foreach($form['#ftypes'] as $id_field => $texto) {
2972    $valores[$id_field] = 0;
2973  }
2974  $partidas_nodo = array();
2975  foreach ($array as $id) {
2976    if (count($node->{$id})) {
2977      foreach($node->{$id} as $partida) {
2978        if(!empty($partida['tid'])) {
2979          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
2980        }
2981      }
2982    }
2983  }
2984  if (count($variaciones)) {
2985    foreach($variaciones as $field_l => $partidas) {
2986      if (count($partidas)) {
2987        foreach($partidas as $tid => $partida) {
2988          if (!isset($partidas_nodo[$field_l][$tid])) {
2989
2990            $valores['tid'] = $tid;
2991            $node->{$field_l}[] = $valores;
2992            if ($field_l == $campo['field']) {
2993              $campo['values'][] = $valores;
2994            }
2995          }
2996        }
2997      }
2998    }
2999  }
3000  $form['#acciones_centralizadas'] = $settings['acciones_centralizadas'];
3001  $form['#node'] = $node;
3002  $form['#campo'] = $campo;
3003  $form['#mes'] = $mes;
3004  if (count($reformula)) {
3005    foreach($reformula as $field_l => $partidas) {
3006      if (count($partidas)) {
3007        foreach($partidas as $tid => $partida) {
3008          if (!isset($partidas_nodo[$field_l][$tid])) {
3009            $valores['tid'] = $tid;
3010            $node->{$field_l}[] = $valores;
3011            if ($field_l == $campo['field']) {
3012              $campo['values'][] = $valores;
3013            }
3014          }
3015        }
3016      }
3017    }
3018  }
3019  foreach ($campo['values'] as $partida) {
3020    if ($partida['tid']) {
3021      $term = taxonomy_get_term($partida['tid']);
3022      // If this term's vocabulary supports localization.
3023      if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
3024        $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
3025      }
3026      $valor = $mes > 0 ? 'value_' . $mes : 'value';
3027      $comprometidov = isset($comprometido[$campo['field']]) && isset($comprometido[$campo['field']][$partida['tid']]) ? $comprometido[$campo['field']][$partida['tid']][$valor] : 0;
3028      $causadov = isset($causado[$campo['field']]) && isset($causado[$campo['field']][$partida['tid']]) ? (float) $causado[$campo['field']][$partida['tid']][$valor] : 0;
3029      $pagadov = isset($pagado[$campo['field']]) && isset($pagado[$campo['field']][$partida['tid']]) ? (float) $pagado[$campo['field']][$partida['tid']][$valor] : 0;
3030      $varia = isset($variaciones[$campo['field']][$partida['tid']][$valor]) ? (float) $variaciones[$campo['field']][$partida['tid']][$valor] : 0;
3031      $sumaC += $comprometidov;
3032      $sumaCa += $causadov;
3033      $sumaP = $pagadov;
3034
3035      $valor = (float) $partida[$valor];
3036      $valor += (float) $varia;
3037
3038      $suma += $valor;
3039      $zonacritica = $valor ? $causadov/$valor : -1;
3040      $porczonacritica = $zonacritica >= 0 ? number_format(($zonacritica * 100), $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']) . '%' : -1;
3041      $form[$partida['tid'] . '_asignado'] = array(
3042        '#type' => 'textfield',
3043        '#default_value' => number_format($valor, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']),
3044        '#size' => 5,
3045        '#attributes' => array('class' => 'campo-asignado'),
3046      );
3047      $disabled = $valor == 0 ? TRUE : FALSE;
3048$disabled = FALSE;
3049      $form[$partida['tid'] . '_comprometido'] = array(
3050        '#type' => 'textfield',
3051        '#default_value' => $comprometidov,
3052        '#size' => 5,
3053        '#disabled' => $disabled,
3054        '#attributes' => array('onchange' => "valpositivo('" . $partida['tid'] . '-comprometido' . "');", 'class' => 'number'),
3055      );
3056      $form[$partida['tid'] . '_causado'] = array(
3057        '#type' => 'textfield',
3058        '#default_value' => $causadov,
3059        '#size' => 5,
3060        '#disabled' => $disabled,
3061        '#attributes' => array('onchange' => "valpositivo('" . $partida['tid'] . '-causado' . "');calculaporc('" . $partida['tid'] . "');", 'class' => 'number'),
3062      );
3063      $form[$partida['tid'] . '_pagado'] = array(
3064        '#type' => 'textfield',
3065        '#default_value' => $pagadov,
3066        '#size' => 5,
3067        '#disabled' => $disabled,
3068        '#attributes' => array('onchange' => "valpositivo('" . $partida['tid'] . '-pagado' . "');", 'class' => 'number'),
3069      );
3070      $form[$partida['tid'] . '_porcen'] = array(
3071        '#type' => 'textfield',
3072        '#default_value' => $porczonacritica,
3073        '#size' => 5,
3074        '#attributes' => array('class' => 'campo-asignado'),
3075      );
3076    }
3077  }
3078  $form['comentario'] = array(
3079    '#title' => t('Comentario'),
3080    '#type' => 'textarea',
3081    '#default_value' => '',
3082  );
3083  $form['buttons'] = array(
3084    '#prefix' => '<div class="container-inline">',
3085    '#suffix' => '</div>',
3086  );
3087  $form['buttons']['submit'] = array(
3088    '#type' => 'submit',
3089    '#value' => t('Guardar'),
3090  );
3091  $redirect = isset($_GET['destination']) ? l('Cancelar', $_GET['destination']) : l('Cancelar', 'node/' . $form['#node']->nid . '/seguimiento/' . $form['#campo']['field'] . '/' . $form['#mes'] . '/view');
3092  $form['buttons']['cancel'] = array('#value' => $redirect);
3093  return $form;
3094}
3095
3096/*
3097 * Implementation of theme_acciones_centralizadas_seguimiento_tab_page_form()
3098 */
3099function theme_acciones_centralizadas_seguimiento_tab_page_form($form) {
3100  $meses = array(
3101    0 => t('January'),
3102    1 => t('February'),
3103    2 => t('March'),
3104    3 => t('April'),
3105    4 => t('May'),
3106    5 => t('June'),
3107    6 => t('July'),
3108    7 => t('August'),
3109    8 => t('September'),
3110    9 => t('Octuber'),
3111    10 => t('November'),
3112    11 => t('December'),
3113  );
3114  $header = array();
3115  $header[] = array('data' => t('Partida'));
3116  $header[] = array('data' => t('Asignado'));
3117  $header[] = array('data' => t('Comprometido'));
3118  $header[] = array('data' => t('Causado'));
3119  $header[] = array('data' => t('Pagado'));
3120  $header[] = array('data' => t('% de inversión'));
3121  $header[] = array('data' => t('Estatus de la inversión'));
3122  $campo = $form['#campo'];
3123  $rows = array();
3124  foreach ($campo['values'] as $partida) {
3125    if ($partida['tid']) {
3126      $term = taxonomy_get_term($partida['tid']);
3127      // If this term's vocabulary supports localization.
3128      if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
3129        $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
3130      }
3131      $porczonacritica = $form[$partida['tid'] . '_porcen']['#value'];
3132      $colorzona = $form['#acciones_centralizadas'][0]['color'];
3133      $colorfontzona = $form['#acciones_centralizadas'][0]['tcolor'];
3134      $textozona = $form['#acciones_centralizadas'][0]['texto'];
3135      if ($porczonacritica >= 0 &&  $porczonacritica < 11) {
3136        $colorzona = $form['#acciones_centralizadas'][1]['color'];
3137        $textozona = $form['#acciones_centralizadas'][1]['texto'];
3138        $colorfontzona = $form['#acciones_centralizadas'][1]['tcolor'];
3139      }
3140      elseif ($porczonacritica >= 11 &&  $porczonacritica < 51) {
3141        $colorzona = $form['#acciones_centralizadas'][2]['color'];
3142        $textozona = $form['#acciones_centralizadas'][2]['texto'];
3143        $colorfontzona = $form['#acciones_centralizadas'][2]['tcolor'];
3144      }
3145      elseif ($porczonacritica >= 51 &&  $porczonacritica < 80) {
3146        $colorzona = $form['#acciones_centralizadas'][3]['color'];
3147        $textozona = $form['#acciones_centralizadas'][3]['texto'];
3148        $colorfontzona = $form['#acciones_centralizadas'][3]['tcolor'];
3149      }
3150      elseif ($porczonacritica >= 51 &&  $porczonacritica <= 100) {
3151        $colorzona = $form['#acciones_centralizadas'][4]['color'];
3152        $textozona = $form['#acciones_centralizadas'][4]['texto'];
3153        $colorfontzona = $form['#acciones_centralizadas'][4]['tcolor'];
3154      }
3155      elseif ($porczonacritica > 100) {
3156        $colorzona = $form['#acciones_centralizadas'][5]['color'];
3157        $textozona = $form['#acciones_centralizadas'][5]['texto'];
3158        $colorfontzona = $form['#acciones_centralizadas'][5]['tcolor'];
3159      }
3160      if ($porczonacritica < 0) {
3161        $porczonacritica = 'N/A';
3162        $form[$partida['tid'] . '_porcen']['#value'] = 'N/A';
3163      }
3164      $row = array();
3165      $row[] = array('data' => $term->name,);
3166      $row[] = array('data' => drupal_render($form[$partida['tid'] . '_asignado']),);
3167      $row[] = array('data' => drupal_render($form[$partida['tid'] . '_comprometido']),);
3168      $row[] = array('data' => drupal_render($form[$partida['tid'] . '_causado']),);
3169      $row[] = array('data' => drupal_render($form[$partida['tid'] . '_pagado']),);
3170      $row[] = array('data' => drupal_render($form[$partida['tid'] . '_porcen']),);
3171      $row[] = array('data' => $textozona, 'style' => 'font-weight: bold;background:' . $colorzona . '; color:' . $colorfontzona, 'id' => $partida['tid'] . '-inversion-form',);
3172      $rows[] = $row;
3173    }
3174  }
3175  $output = '';
3176  $grupo = explode('-', $form['#grupo']['label']);
3177  $output .= '<fieldset><legend>' . t('Datos de la Acción Centralizada a la que pertenece la acción especifica') . '</legend>' .   '<div class="field-label"><b>' . t('Código de la AC:') . '</b> ' . $grupo[0] . '</div>' . '<div class="field-label"><b>' . t('Nombre de la AC:') . '</b> ' . $grupo[1] . '</div>' . '</fieldset>';
3178  $output .= '<fieldset><legend>' . t('Datos de la Acción') . '</legend>' . '<div class="field-label"><b>' . t('Nombre de la Acción Especifica:') . '</b> ' . $form['#field_load']['widget']['label'] . '</div>'. '</fieldset>';
3179  $output .= '<fieldset><legend>' . t('Seguimiento de partidas de la Acción Especifica') . '</legend>' . '<div class="field-label"><b>' . t('Mes de Seguimiento Actual:') . '</b> ' . $meses[$form['#mes']] . '</div>' . theme('table', $header, $rows) . '</fieldset>';
3180  //SE MUESTRA LA LEYENDA
3181  $output .= '<p>' . t('<b>Nota</b>: La relación entre las cantidades debe ser:
3182<b>\'Comprometido\' >= \'Causado\' >= \'Pagado\'</b>') . '</p>';
3183  $descripcion = array(
3184    0 => '',
3185    1 => '(' . t('De 0 a 10.99 %') . ')',
3186    2 => '(' . t('De 11 a 50.99 %') . ')',
3187    3 => '(' . t('De 51 a 79.99 %') . ')',
3188    4 => '(' . t('De 80 a 100 %') . ')',
3189    5 => '(' . t('Mas de 100 %') . ')',
3190  );
3191  $output .= '<table id="leyenda">';
3192  for($i = 0; $i < 6; $i++) {
3193    $output .= '<tr><td style="font-weight: bold">' . $form['#acciones_centralizadas'][$i]['texto'] . ' ' . $descripcion[$i] . '</td><td style="background:' . $form['#acciones_centralizadas'][$i]['color'] . ';" width="50px">' . '</td><tr>';
3194  }
3195  $output .= '</table>';
3196  $output .= drupal_render($form);
3197  return $output;
3198}
3199
3200/*
3201 * Implementation of acciones_centralizadas_seguimiento_tab_page_form_validate()
3202 */
3203function acciones_centralizadas_seguimiento_tab_page_form_validate($form, &$form_state) {
3204  $acciones_centralizadas_path = drupal_get_path('module', 'acciones_centralizadas');
3205  drupal_add_js($acciones_centralizadas_path . '/js/acciones_centralizadas.js');
3206  drupal_add_js($form['#format_number'], 'setting');
3207  $settings['acciones_centralizadas'] = array(
3208    0 => array(
3209      'color' => variable_get('acciones_centralizadas_color_default', '#633303'),
3210      'tcolor' => variable_get('acciones_centralizadas_colort_default', '#FFFFFF'),
3211      'texto' => variable_get('acciones_centralizadas_texto_default', 'No hay planificación'),
3212    ),
3213    1 => array(
3214      'color' => variable_get('acciones_centralizadas_color_critica', '#fd0002'),
3215      'tcolor' => variable_get('acciones_centralizadas_colort_critica', '#FFFFFF'),
3216      'texto' => variable_get('acciones_centralizadas_texto_critica', 'Zona crítica'),
3217    ),
3218    2 => array(
3219      'color' => variable_get('acciones_centralizadas_color_discreta', '#cc6733'),
3220      'tcolor' => variable_get('acciones_centralizadas_colort_discreta', '#FFFFFF'),
3221      'texto' => variable_get('acciones_centralizadas_texto_discreta', 'Zona discreta'),
3222    ),
3223    3 => array(
3224      'color' => variable_get('acciones_centralizadas_color_moderada', '#fdff00'),
3225      'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
3226      'texto' => variable_get('acciones_centralizadas_texto_moderada', 'Zona moderada'),
3227    ),
3228    4 => array(
3229      'color' => variable_get('acciones_centralizadas_color_optima', '#20ff21'),
3230      'tcolor' => variable_get('acciones_centralizadas_colort_moderada', '#000000'),
3231      'texto' => variable_get('acciones_centralizadas_texto_optima', 'Zona optima'),
3232    ),
3233    5 => array(
3234      'color' => variable_get('acciones_centralizadas_color_sejecucion', '#9966cd'),
3235      'tcolor' => variable_get('acciones_centralizadas_colort_sejecucion', '#000000'),
3236      'texto' => variable_get('acciones_centralizadas_texto_sejecucion', 'Sobre ejecución'),
3237    ),
3238  );
3239  drupal_add_js($settings, 'setting');
3240  foreach ($form['#campo']['values'] as $partida) {
3241    $start = $form_state['values'][$partida['tid'] . '_comprometido'];
3242    $value = preg_replace('@[^-0-9]@', '', $start);
3243    if ($start != $value) {
3244      form_set_error($partida['tid'] . '_comprometido', t('Solo números enteros son permitidos.'));
3245    }
3246    if ($form_state['values'][$partida['tid'] . '_comprometido'] < 0) {
3247      form_set_error($partida['tid'] . '_comprometido', t('El valor comprometido deberia ser mayor o igual a cero'));
3248    }
3249    $start = $form_state['values'][$partida['tid'] . '_causado'];
3250    $value = preg_replace('@[^-0-9]@', '', $start);
3251    if ($start != $value) {
3252      form_set_error($partida['tid'] . '_causado', t('Solo números enteros son permitidos.'));
3253    }
3254    if ($form_state['values'][$partida['tid'] . '_causado'] < 0) {
3255      form_set_error($partida['tid'] . '_causado', t('El valor causado deberia ser mayor o igual a cero'));
3256    }
3257    $start = $form_state['values'][$partida['tid'] . '_pagado'];
3258    $value = preg_replace('@[^-0-9]@', '', $start);
3259    if ($start != $value) {
3260      form_set_error($partida['tid'] . '_pagado', t('Solo números enteros son permitidos.'));
3261    }
3262    if ($form_state['values'][$partida['tid'] . '_pagado'] < 0) {
3263      form_set_error($partida['tid'] . '_pagado', t('El valor pagado deberia ser mayor o igual a cero'));
3264    }
3265    //se valida que comprometido sea mayor o igual que causado
3266    if ($form_state['values'][$partida['tid'] . '_comprometido'] < $form_state['values'][$partida['tid'] . '_causado']) {
3267      form_set_error($partida['tid'] . '_causado', t('El valor causado deberia ser menor o igual al comprometido'));
3268    }
3269    //se valida que comprometido sea mayor o igual que causado
3270    if ($form_state['values'][$partida['tid'] . '_causado'] < $form_state['values'][$partida['tid'] . '_pagado']) {
3271      form_set_error($partida['tid'] . '_causado', t('El valor pagado deberia ser menor o igual al causado'));
3272    }
3273  }
3274}
3275
3276/*
3277 * Implementation of acciones_centralizadas_seguimiento_tab_page_form_submit()
3278 */
3279function acciones_centralizadas_seguimiento_tab_page_form_submit($form, &$form_state) {
3280  global $user;
3281  db_query("INSERT INTO {accion_seguimiento} (nid, mes, comentario, campo, fecha, estado, uid) VALUES (%d, %d, '%s', '%s', %d, %d, %d)", $form['#node']->nid, $form['#mes'], check_plain($form_state['values']['comentario']), $form['#campo']['field'], time(), $form['#state_creation'], $user->uid);
3282  $id_seg = db_last_insert_id('accion_seguimiento', 'id_seg');
3283  foreach ($form['#campo']['values'] as $partida) {
3284    $suma = $form_state['values'][$partida['tid'] . '_comprometido'] + $form_state['values'][$partida['tid'] . '_causado'] +$form_state['values'][$partida['tid'] . '_pagado'];
3285    if ($partida['tid']) {
3286      db_query("INSERT INTO {accion_segu_partida} (id_seg, partida, comprometido, causado, pagado, nid) VALUES (%d, %d, %f, %f, %f, %d)", $id_seg, $partida['tid'], $form_state['values'][$partida['tid'] . '_comprometido'], $form_state['values'][$partida['tid'] . '_causado'], $form_state['values'][$partida['tid'] . '_pagado'], $form['#node']->nid);
3287    }
3288  }
3289  //herede los estados anteriores del seguimiento
3290  if ($form['#id_seg']) {
3291    db_query('UPDATE {accion_seguimiento_state} SET id_seg = %d WHERE id_seg = %d', $id_seg, $form['#id_seg']);
3292  }
3293
3294  if (!$_REQUEST['destination']) {
3295    // add redirect
3296    $form_state['redirect'] = 'node/' . $form['#node']->nid . '/seguimiento/' . $form['#campo']['field'] . '/' . $form['#mes'] . '/view';
3297  }
3298}
3299
3300/*
3301 * Implementation of hook_form_alter()
3302 */
3303function acciones_centralizadas_form_alter(&$form, $form_state, $form_id) {
3304  if ($form_id == 'workflow_tab_form') {
3305    if (isset($form['#wf']->name) && isset($form['workflow'][$form['#wf']->name]['#options'])) {
3306      $form['workflow'][$form['#wf']->name]['#title'] = t('Enviar a');
3307    }
3308  }
3309  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id && $form['type']['#value'] == 'accion_centralizada'){
3310    //just remove title field
3311    $form['buttons']['#weight'] = 1200;
3312    $form['title']['#value'] = 'Accion Centralizada';
3313    $form['title']['#type'] = 'value';
3314    $form['title']['#required'] = FALSE;
3315    $form['buttons']['#prefix'] = '<div class="container-inline">';
3316    $form['buttons']['#suffix'] = '</div>';
3317    $form['buttons']['preview']['#access'] = FALSE;
3318    $form['buttons']['cancel'] = array('#weight' => 120, '#value' => l('Cancelar', 'node/' . $form['#node']->nid));
3319    if (isset($form['#node']->nid)){
3320      $form['field_acciones_ente']['#access'] = FALSE;
3321    }
3322    else{
3323      $form['field_acciones_ente']['#pre_render'][] = 'acciones_centralizadas_nodereference_field_pre_render';
3324    }
3325  }
3326}
3327
3328/*
3329 * Implementation of acciones_centralizadas_nodereference_field_pre_render()
3330 * Change element
3331 */
3332function acciones_centralizadas_nodereference_field_pre_render($element) {
3333  global $user;
3334  if (!((user_access('edit all planificador'))||(user_access('admin
3335planificador')))) {
3336    $entes = obtener_mis_ente_planificador($user->uid);
3337    $options = array();
3338    if (count($entes)) {
3339      foreach($entes as $ente){
3340        $options[$ente['nid']] = $element['nid']['nid']['#options'][$ente['nid']];
3341      }
3342    }
3343    $element['nid']['nid']['#options'] = $options;
3344  }
3345  else {
3346    $options = $element['nid']['nid']['#options'];
3347    $result = db_query("SELECT ac.ente AS nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE year = %d AND w.sid <> %d", variable_get('acciones_centralizadas_anho_creacion', 0), variable_get('acciones_centralizadas_state_naprobado', NULL));
3348    while($ente = db_fetch_object($result)) {
3349      if (isset($options[$ente->nid])) {
3350        unset($options[$ente->nid]);
3351      }
3352    }
3353    $element['nid']['nid']['#options'] = $options;
3354  }
3355  return $element;
3356}
3357
3358/*
3359 * Implementation of acciones_centralizadas_reformula_wk_tab_page_form()
3360 */
3361function acciones_centralizadas_reformula_wk_tab_page_form($form_state, $node, $reformulacion_load = 0, $state = 0) {
3362  $estados = _acciones_centralizadas_reformula_obtiene_estados();
3363  $form = array();
3364  $form['#node'] = $node;
3365  $form['#nuevo_estado'] = $state;
3366  $form['#estados'] = $estados['states'];
3367  $form['#reformulacion'] = $reformulacion_load;
3368  $form['comentario'] = array(
3369    '#title' => t('Comentario'),
3370    '#type' => 'textarea',
3371    '#default_value' => '',
3372  );
3373  $message = t('Esta seguro de cambiar la reformulación al estado %nombre_estado?', array('%nombre_estado' => $estados['states'][$state]));
3374  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
3375  $return_path = 'node/' . $node->nid . '/reformular/' . $reformulacion_load->id_ref . '/view';
3376  return confirm_form($form, $message, $return_path, $caption, t('Cambiar'));
3377  return $form;
3378}
3379
3380/**
3381 * Implementation of acciones_centralizadas_reformula_wk_tab_page_form_submit().
3382 * Process funcion delete confirm form.
3383 */
3384function acciones_centralizadas_reformula_wk_tab_page_form_submit($form, &$form_state) {
3385  global $user;
3386  $nuevo_estado = $form['#datos_institucionales_funcion'];
3387  db_query('UPDATE {accion_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);
3388  db_query("INSERT INTO {accion_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);
3389  //REMOVE DATA
3390    drupal_set_message(t('La reformulación fue cambiada al estado @nombre_estado', array('@nombre_estado' => $form['#estados'][$form['#nuevo_estado']])));
3391  $form_state['redirect'] = 'node/' . $form['#node']->nid . '/reformular/' . $form['#reformulacion']->id_ref . '/view';
3392}
3393
3394/*
3395 * Implementation of _acciones_centralizadas_seguimiento_wk_node_tab_mes_access()
3396 */
3397function _acciones_centralizadas_seguimiento_wk_node_tab_mes_access($node, $campo = '', $mes = 0, $state = 0) {
3398  global $user;
3399  $actual = _acciones_centralizadas_seguimiento_load($node, $campo['field'], $mes);
3400  if (!isset($actual['values'])) {
3401    return FALSE;
3402  }
3403  $estado = (isset($actual['values']) && isset($actual['values']['estado'])) ? $actual['values']['estado'] : -1;
3404  $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
3405  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
3406  if ($node->type != 'accion_centralizada' || $node->anhoaccion_centralizada != $year) {
3407    if ($estado_aprobado && $node->_workflow != $estado_aprobado) {
3408      return FALSE;
3409    }
3410  }
3411  $ente = usuario_tiene_ente($user->uid);
3412  $ente_planificador = node_load($node->field_acciones_ente[0]['nid']);
3413  if ($ente->nid != $ente_planificador->nid && !user_access('admin planificador')) {
3414    return FALSE;
3415  }
3416  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
3417  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
3418  if ($estado == $estado_naprobado || $estado == $estado_aprobado) {
3419    return FALSE;
3420  }
3421  $states = _acciones_centralizadas_reformula_obtiene_estados();
3422  $first_state = 0;
3423  if ($states['wid']) {
3424    $first_state = _workflow_creation_state($states['wid']);
3425  }
3426  $roles = array_keys($user->roles);
3427  if ($user->uid == 1) {
3428    // Superuser is special.
3429    $roles_transition = 'ALL';
3430  }
3431  else {
3432    $roles_transition = $roles;
3433    if ($user->uid == $actual['values']['uid'] && $actual['values']['uid'] > 0) {
3434      $roles_transition += array('author' => 'author');
3435    }
3436  }
3437  $transitions = array();
3438  if ($states['wid']) {
3439    $transitions = workflow_allowable_transitions($estado, 'to', $roles_transition);
3440  }
3441  if ($first_state && $estado == $first_state) {
3442    unset($transitions[$estado]);
3443  }
3444  if (isset($transitions[$state])) {
3445    return TRUE;
3446  }
3447  return FALSE;
3448}
3449
3450/*
3451 * Implementation of acciones_centralizadas_seguimiento_wk_tab_page_form()
3452 */
3453function acciones_centralizadas_seguimiento_wk_tab_page_form($form_state, $node, $campo = '', $mes = 0, $state) {
3454  $estados = _acciones_centralizadas_reformula_obtiene_estados();
3455  $actual = _acciones_centralizadas_seguimiento_load($node, $campo['field'], $mes);
3456  $form = array();
3457  $form['#node'] = $node;
3458  $form['#actual'] = $actual['values'];
3459  $form['#nuevo_estado'] = $state;
3460  $form['#estados'] = $estados['states'];
3461  $form['#campo'] = $campo;
3462  $form['#mes'] = $mes;
3463  $form['comentario'] = array(
3464    '#title' => t('Comentario'),
3465    '#type' => 'textarea',
3466    '#default_value' => '',
3467  );
3468  $message = t('Esta seguro de cambiar el seguimiento al estado %nombre_estado?', array('%nombre_estado' => $estados['states'][$state]));
3469  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
3470  $return_path = 'node/' . $node->nid . '/seguimiento/' . $form['#campo']['field'] . '/' . $form['#mes'] . '/view';
3471  return confirm_form($form, $message, $return_path, $caption, t('Cambiar'));
3472}
3473
3474/**
3475 * Implementation of acciones_centralizadas_seguimiento_wk_tab_page_form_submit().
3476 * Process funcion delete confirm form.
3477 */
3478function acciones_centralizadas_seguimiento_wk_tab_page_form_submit($form, &$form_state) {
3479  global $user;
3480  $nuevo_estado = $form['#datos_institucionales_funcion'];
3481  db_query('UPDATE {accion_seguimiento} SET estado = %d, estado_ant = %d WHERE nid = %d AND id_seg = %d', $form['#nuevo_estado'], $form['#actual']['estado'], $form['#node']->nid, $form['#actual']['id_seg']);
3482  db_query("INSERT INTO {accion_seguimiento_state} (nid, estado, estado_ant, comentario, date, id_seg, uid) VALUES (%d, %d, %d, '%s', %d, %d, %d)", $form['#node']->nid, $form['#nuevo_estado'], $form['#actual']['estado'], check_plain($form_state['values']['comentario']), time(), $form['#actual']['id_seg'], $user->uid);
3483  drupal_set_message(t('El seguimiento fue cambiado al estado @nombre_estado', array('@nombre_estado' => $form['#estados'][$form['#nuevo_estado']])));
3484  $form_state['redirect'] = 'node/' . $form['#node']->nid . '/seguimiento/' . $form['#campo']['field'] . '/' . $form['#mes'] . '/view';
3485}
3486
3487/*
3488 * Implementation of acciones_centralizadas_search_ac_display()
3489 */
3490function acciones_centralizadas_search_ac_display() {
3491  global $user;
3492  $current_time = time();
3493  $ente = usuario_tiene_ente($user->uid);
3494  $tipo_plan = 'acciones_centralizadas_formular';
3495  $ente_planificador = 0;
3496  if ($ente && $ente->nid) {
3497    $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
3498  }
3499  elseif (user_access('admin planificador') && $enteagregar) {
3500    $ente_planificador = ente_planificador_leer_ente_planificadores($enteagregar);
3501  }
3502  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
3503  $fecha = FALSE;
3504  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
3505    $fecha = TRUE;
3506  }
3507  if (!$fecha) {
3508    muestra_mensaje($tipo_plan, $ente_planificador);
3509  }
3510  if ($fecha && $user->entes) {
3511    muestra_mensaje($tipo_plan, $ente_planificador);
3512    $result = db_query("SELECT ac.nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND year = %d AND w.sid <> %d", $user->entes, variable_get('acciones_centralizadas_anho_creacion', 0), variable_get('acciones_centralizadas_state_naprobado', NULL));
3513    $acciones_centralizadas = db_fetch_object($result);
3514    $fecha = !$acciones_centralizadas;
3515  }
3516  elseif($fecha && user_access('admin planificador')) {
3517    $entes = array();
3518    $result = db_query('SELECT e.nid FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1');
3519    while($ente = db_fetch_object($result)) {
3520      $entes[$ente->nid] = $ente->nid;
3521    }
3522    $result = db_query("SELECT ac.ente as nid FROM {accion_centralizada} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE year = %d AND w.sid <> %d", variable_get('acciones_centralizadas_anho_creacion', 0), variable_get('acciones_centralizadas_state_naprobado', NULL));
3523    while($ente = db_fetch_object($result)) {
3524      if (isset($entes[$ente->nid])) {
3525        unset($entes[$ente->nid]);
3526      }
3527    }
3528    $fecha = count($entes);
3529  }
3530  $states = array();
3531  $first_state = 0;
3532  if (module_exists('workflow')) {
3533    $states = _acciones_centralizadas_reformula_obtiene_estados();
3534    if ($states['wid']) {
3535      $first_state = _workflow_creation_state($states['wid']);
3536    }
3537  }
3538  $output = drupal_get_form('acciones_centralizadas_search_ac_form');
3539  $inputs = array();
3540  $sql = '';
3541  if (!user_access('admin planificador') && $user->entes) {
3542    $inputs[] = $user->entes;
3543    $inputs[] = variable_get('acciones_centralizadas_state_naprobado', NULL);
3544    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, u.name, n.uid, e.title AS ente FROM {accion_centralizada} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND w.sid <> %d";
3545  }
3546  elseif (user_access('admin planificador')) {
3547    $inputs[] = variable_get('acciones_centralizadas_state_naprobado', NULL);
3548    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, u.name, n.uid, e.title AS enten FROM {accion_centralizada} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE w.sid <> %d";
3549    $acciones_centralizadas_search_ac_ente = isset($_SESSION['acciones_centralizadas']) && isset($_SESSION['acciones_centralizadas']['ente']) ? $_SESSION['acciones_centralizadas']['ente'] : 0;
3550    if ($acciones_centralizadas_search_ac_ente) {
3551      $inputs[] = $acciones_centralizadas_search_ac_ente;
3552      $sql .= ' AND ac.ente = %d';
3553    }
3554  }
3555  $acciones_centralizadas_search_ac_anho_creacion = isset($_SESSION['acciones_centralizadas']) && isset($_SESSION['acciones_centralizadas']['anho']) ? $_SESSION['acciones_centralizadas']['anho'] : 0;
3556  if ($acciones_centralizadas_search_ac_anho_creacion) {
3557    $sql .= ' AND ac.year = %d';
3558    $inputs[] = $acciones_centralizadas_search_ac_anho_creacion;
3559  }
3560  $sql .= ' ORDER BY ac.year DESC, ac.ente';
3561  $header = array();
3562  $cab = 6;
3563  if (user_access('admin planificador')) {
3564    $header[] = array('data' => t('Ente.'));
3565    $cab++;
3566  }
3567  $header[] = array('data' => t('Año'));
3568  $header[] = array('data' => t('Estado'));
3569  $header[] = array('data' => t('Fecha de creación'));
3570  $header[] = array('data' => t('Autor'));
3571  $header[] = array('data' => t('Acción'));
3572  $result = db_query($sql, $inputs);
3573  $rows = array();
3574  while($ac = db_fetch_object($result)) {
3575    $row = array();
3576    if (user_access('admin planificador')) {
3577      $row[] = array('data' => l($ac->enten, 'node/' . $ac->ente),);
3578    }
3579    $row[] = array('data' => $ac->year,);
3580    $estad0 = $ac->sid == $first_state? t('Ingresado') : $states['states'][$ac->sid];
3581    $row[] = array('data' => $estad0,);
3582    $row[] = array('data' => format_date($ac->created),);
3583    $row[] = array('data' => l($ac->name, 'user/' . $ac->uid),);
3584    $links = array();
3585    drupal_alter('acciones_obtiene_links', $links, $ac, $fecha);
3586    $row[] = array('data' => theme('item_list', $links),);
3587    $rows[] = $row;
3588  }
3589  if (!count($rows)) {
3590    $row[] = array('data' => 'No existen Acciones centralizadas', 'colspan' => $cab);
3591    $rows[] = $row;
3592  }
3593  $output .= theme('table', $header, $rows);
3594  if ($fecha) {
3595    $output .= '<p>' . l('Agregar Acción Centralizada', 'node/add/accion-centralizada') . '</p>';
3596  }
3597  return $output;
3598}
3599
3600
3601/*
3602 * Implementation of hook_acciones_obtiene_links_alter()
3603 */
3604function acciones_centralizadas_acciones_obtiene_links_alter(&$links, $accion_centralizada, $acceso = FALSE) {
3605  $node_accion = node_load($accion_centralizada->nid);
3606  if(node_access('view', $node_accion)){
3607    $links[] = array(
3608      'data' => l(t('Consultar'), 'node/' . $accion_centralizada->nid),
3609      'class' => 'acciones-centralizadas-ver',
3610    );
3611  }
3612  if(node_access('create', $node_accion)){
3613    $links[] = array(
3614      'data' => l(t('Crear Acción Centralizada'), 'node/add'),
3615      'class' => 'acciones-centralizadas-agregar',
3616    );
3617  }
3618  if(node_access('update', $node_accion)){
3619    $links[] = array(
3620      'data' => l(t('Modificar'), 'node/' . $accion_centralizada->nid . '/edit'),
3621      'class' => 'acciones-centralizadas-modificar',
3622    );
3623  }
3624  if(node_access('delete', $node_accion)){
3625    $links[] = array(
3626      'data' => l(t('Eliminar'), 'node/' . $accion_centralizada->nid . '/delete'),
3627      'class' => 'acciones-centralizadas-eliminar',
3628    );
3629  }
3630  if (workflow_node_tab_access($node_accion)) {
3631    $links[] = array(
3632      'data' => l(t('Cambiar el estado'), 'node/' . $accion_centralizada->nid . '/workflow'),
3633      'class' => 'proyectos-operativos-estado',
3634    );
3635  }
3636  if (_acciones_centralizadas_reformula_node_tab_access($node_accion)) {
3637    $links[] = array(
3638      'data' => l(t('Fase de reformulación'), 'node/' . $accion_centralizada->nid . '/reformular'),
3639      'class' => 'acciones-centralizadas-reformular',
3640    );
3641
3642  }
3643  if (_acciones_centralizadas_reformula_node_add_tab_access($node_accion)) {
3644    $links[] = array(
3645      'data' => l(t('Agregar nueva reformulación'), 'node/' . $accion_centralizada->nid . '/reformular/add'),
3646      'class' => 'acciones-centralizadas-reformular',
3647    );
3648  }
3649
3650  if (_acciones_centralizadas_seguimiento_node_tab_access($node_accion)) {
3651    $meses = array(
3652      0 => t('January'),
3653      1 => t('February'),
3654      2 => t('March'),
3655      3 => t('April'),
3656      4 => t('May'),
3657      5 => t('June'),
3658      6 => t('July'),
3659      7 => t('August'),
3660      8 => t('September'),
3661      9 => t('Octuber'),
3662      10 => t('November'),
3663      11 => t('December'),
3664    );
3665    $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
3666    $mes_segu = variable_get('acciones_centralizadas_mes_seguimiento', 0) - 1;
3667    if ($year == $node_accion->anhoaccion_centralizada) {
3668      $links[] = array(
3669        'data' => l(t('Fase de Seguimiento (@mes)', array('@mes' => $meses[$mes_segu])), 'node/' . $accion_centralizada->nid . '/seguimiento/fase/' . $mes_segu),
3670        'class' => 'acciones-centralizadas-fase-seguimiento',
3671      );
3672    }
3673    $links[] = array(
3674      'data' => l(t('Seguimiento de la AC'), 'node/' . $accion_centralizada->nid . '/seguimiento'),
3675      'class' => 'acciones-centralizadas-seguimiento',
3676    );
3677  }
3678}
3679
3680/*
3681 * Implementation of acciones_centralizadas_search_ac_form()
3682 */
3683function acciones_centralizadas_search_ac_form($form_state) {
3684  $form = array();
3685  if (user_access('admin planificador')) {
3686    $entes = array();
3687    $result = db_query('SELECT e.nid, n.title FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1');
3688    $entes[] = t('Todos');
3689    while($ente = db_fetch_object($result)) {
3690      $entes[$ente->nid] = $ente->title;
3691    }
3692    $acciones_centralizadas_search_ac_ente = isset($_SESSION['acciones_centralizadas']) && isset($_SESSION['acciones_centralizadas']['ente']) ? $_SESSION['acciones_centralizadas']['ente'] : 0;
3693    $form['acciones_centralizadas_search_ac_ente'] = array(
3694      '#title' => t('Ente Planificador'),
3695      '#type' => 'select',
3696      '#default_value' => $acciones_centralizadas_search_ac_ente,
3697      '#options' => $entes,
3698    );
3699  }
3700  $current_year = date("Y");
3701  $years = array();
3702  $years[] = t('Todos');
3703  for($i = $current_year - 10; $i <= $current_year; $i++) {
3704    $years[$i] = $i;
3705  }
3706  $acciones_centralizadas_search_ac_anho_creacion = isset($_SESSION['acciones_centralizadas']) && isset($_SESSION['acciones_centralizadas']['anho']) ? $_SESSION['acciones_centralizadas']['anho'] : 0;
3707  $form['acciones_centralizadas_search_ac_anho_creacion'] = array(
3708    '#title' => t('Acción centralizada para el año'),
3709    '#type' => 'select',
3710    '#default_value' => $acciones_centralizadas_search_ac_anho_creacion,
3711    '#options' => $years,
3712  );
3713  $form['buttons'] = array(
3714    '#prefix' => '<div class="container-inline">',
3715    '#suffix' => '</div>',
3716  );
3717  $form['buttons']['submit'] = array(
3718    '#type' => 'submit',
3719    '#value' => t('Buscar'),
3720  );
3721  return $form;
3722}
3723
3724/*
3725 * Implementation of acciones_centralizadas_search_ac_form_submit()
3726 */
3727function acciones_centralizadas_search_ac_form_submit($form, &$form_state) {
3728  $_SESSION['acciones_centralizadas'] = array();
3729  if (user_access('admin planificador')) {
3730    $_SESSION['acciones_centralizadas']['ente'] = $form_state['values']['acciones_centralizadas_search_ac_ente'];
3731  }
3732  $_SESSION['acciones_centralizadas']['anho'] = $form_state['values']['acciones_centralizadas_search_ac_anho_creacion'];
3733}
3734
3735/**
3736 * Implementation of hook_planner_items_toolbar().
3737*/
3738function acciones_centralizadas_planner_items_toolbar($ente_planificador, $handler_icon) {
3739  $link = array();
3740  $icon_path = entes_planificadores_toolbar_get_icon_path('planner', 'accionescentralizadas', $handler_icon);
3741  $link[] = array(
3742    'path' => 'acciones_centralizadas',
3743    'icon_path' => $icon_path,
3744    'icon' => theme('image', $icon_path, t('Consultar Información de las acciones centralizadas del actor planificador'), t('Consultar Información de los acciones centralizadas del actor planificador'), array('class' => 'handler-icon-' . $handler_icon)),
3745    'title' => t('Proyectos operativos'),
3746    'description' => t('Consultar Información de las acciones centralizadas del actor planificador'),
3747    'category' => 'planner',
3748  );
3749  return $link;
3750}
3751
3752/**
3753 * Implementation of hook_admin_items_toolbar().
3754*/
3755function acciones_centralizadas_admin_items_toolbar($handler_icon) {
3756  $link = array();
3757  $icon_path = entes_planificadores_toolbar_get_icon_path('admin', 'accionescentralizadas', $handler_icon);
3758  $link[] = array(
3759    'path' => 'acciones_centralizadas',
3760    'icon_path' => $icon_path,
3761    'icon' => theme('image', $icon_path, t('Consultar Información de las acciones centralizadas del actor planificador'), t('Consultar Información de los acciones centralizadas del actor planificador'), array('class' => 'handler-icon-' . $handler_icon)),
3762    'title' => t('Proyectos operativos'),
3763    'description' => t('Consultar Información de las acciones centralizadas del actor planificador'),
3764    'category' => 'planner',
3765  );
3766  return $link;
3767}
3768
3769
3770function acciones_centralizadas_seguimiento_nodo_fase_seguimiento($node, $mes = 0) {
3771  global $user;
3772  $estado_aprobado = variable_get('acciones_centralizadas_state_aprobado', NULL);
3773  $estado_naprobado = variable_get('acciones_centralizadas_state_naprobado', NULL);
3774  $year = variable_get('acciones_centralizadas_anho_seguimiento', 0);
3775  $mes_segu = variable_get('acciones_centralizadas_mes_seguimiento', 0);
3776  $meses = array(
3777    0 => t('January'),
3778    1 => t('February'),
3779    2 => t('March'),
3780    3 => t('April'),
3781    4 => t('May'),
3782    5 => t('June'),
3783    6 => t('July'),
3784    7 => t('August'),
3785    8 => t('September'),
3786    9 => t('Octuber'),
3787    10 => t('November'),
3788    11 => t('December'),
3789  );
3790  $ftypes = array(
3791    'value' => t('January'),
3792    'value_1' => t('February'),
3793    'value_2' => t('March'),
3794    'value_3' => t('April'),
3795    'value_4' => t('May'),
3796    'value_5' => t('June'),
3797    'value_6' => t('July'),
3798    'value_7' => t('August'),
3799    'value_8' => t('September'),
3800    'value_9' => t('Octuber'),
3801    'value_10' => t('November'),
3802    'value_11' => t('December'),
3803  );
3804  $mes_texto = $meses[$mes];
3805  $array = array(
3806    'field_ac_ac1_ae1' => 'field_ac_ac1_ae1',
3807    'field_ac_ac1_ae2' => 'field_ac_ac1_ae2',
3808    'field_ac_ac2_ae2' => 'field_ac_ac2_ae2',
3809    'field_ac_ac2_ae3' => 'field_ac_ac2_ae3',
3810    'field_ac_ac3_ae1' => 'field_ac_ac3_ae1',
3811    'field_ac_ac4_ae1' => 'field_ac_ac4_ae1',
3812  );
3813  $id_ref = $reformulacion_load ? $reformulacion_load->id_ref : 0;
3814  $variaciones = _acciones_centralizadas_reformula_all_partidas_load($node, $id_ref);
3815  $reformula = _acciones_centralizadas_reformula_load($node);
3816  $valores = array();
3817  foreach($ftypes as $id_field => $texto) {
3818    $valores[$id_field] = 0;
3819  }
3820  $vacio = array();
3821  $partidas_nodo = array();
3822  foreach ($array as $id) {
3823      if (!$node->{$id}[0]['tid']) {
3824        $node->{$id} = array();
3825      }
3826    if (count($node->{$id})) {
3827      foreach($node->{$id} as $partida) {
3828        if(!empty($partida['tid'])) {
3829          $partidas_nodo[$id][$partida['tid']] = $partida['tid'];
3830        }
3831      }
3832    }
3833  }
3834  if (count($variaciones)) {
3835    foreach($variaciones as $field_l => $partidas) {
3836      if (count($partidas)) {
3837        foreach($partidas as $tid => $partida) {
3838          if (!isset($partidas_nodo[$field_l][$tid])) {
3839            if (empty($node->{$field_l}[0]['tid']) || !$node->{$field_l}[0]['tid']) {
3840              $node->{$field_l} = array();
3841            }
3842            $valores['tid'] = $tid;
3843            $node->{$field_l}[] = $valores;
3844            $partidas_nodo[$field_l][$tid] = $tid;
3845          }
3846        }
3847      }
3848    }
3849  }
3850  $header = array();
3851  $header[] = array('data' => t('Mes'), 'align' => 'center');
3852  $header[] = array('data' => t('Estado'), 'align' => 'center', 'colspan' => 2);
3853  $header[] = array('data' => t('Opciones Disponibles'), 'align' => 'center');
3854  $grupos = fieldgroup_groups('accion_centralizada');
3855  $output = t('Estimado(a) Usuario(a), para ingresar el Seguimiento de las Acciones Centralizadas.');
3856  $states = _acciones_centralizadas_reformula_obtiene_estados();
3857  if (module_exists('workflow')) {
3858    if (isset($states['wid'])) {
3859      $first_state = 0;
3860      if ($states['wid']) {
3861        $first_state = _workflow_creation_state($states['wid']);
3862      }
3863      if ($user->uid == 1) {
3864        // Superuser is special.
3865        $roles = 'ALL';
3866      }
3867      else {
3868        $roles = array_keys($user->roles);
3869        if ($user->uid == $author && $author > 0) {
3870          $roles += array('author' => 'author');
3871        }
3872      }
3873    }
3874  }
3875  $mensaje = '';
3876  if ($mes != $mes_segu -1 || $node->anhoaccion_centralizada != $year) {
3877    $mensaje = '<div class ="nota-complementaria"><b>' . t('Nota complementaria') . ':</b> ' . t('Mes fuera del período de duración de la acción centralizada.') . '</div>';
3878  }
3879  $mensaje .= t('Para consultar las partidas de esta Acción Centralizada en el mes actual ir a ');
3880  foreach($grupos as $id => $grupo) {
3881    $tablas = array();
3882    if (count($grupo['fields'])) {
3883      foreach($grupo['fields'] as $id_field => $field) {
3884        $suma = array();
3885        if (array_key_exists($id_field, $array) && $node->{$id_field}[0]['tid']) {
3886          foreach($node->{$id_field} as $values) {
3887            foreach($ftypes as $ids =>$texto) {
3888              if (!isset($suma[$ids])) {
3889                $suma[$ids] = 0;
3890              }
3891              $varia[$id_field][$values['tid']][$ids] = isset($variaciones[$id_field][$values['tid']][$ids]) ? $variaciones[$id_field][$values['tid']][$ids] : 0;
3892              $valor = $values[$ids] + $varia[$id_field][$values['tid']][$ids];
3893              $suma[$ids] += $valor;
3894            }
3895          }
3896        }
3897        $field_load = content_fields($id_field, 'accion_centralizada');
3898        $rows = array();
3899        $actual = _acciones_centralizadas_seguimiento_load($node, $id_field, $mes);
3900        $current_estado = isset($actual['values']) && isset($actual['values']['estado']) ? $actual['values']['estado'] : -1;
3901        $row = array();
3902        $estado = isset($states['states'][$current_estado]) ? $states['states'][$current_estado] : t('No ingresado');
3903        $row[] = array('data' => $mes_texto, 'align' => 'center',);
3904        $etiquetas = isset($states['states'][$current_estado]) ? '<div class="semaforo semaforo' . $current_estado . '">•</div>' : '-';
3905        $row[] = array('data' => $etiquetas, 'align' => 'center',);
3906        $row[] = array('data' => $estado, 'align' => 'center',);
3907        $links = array();
3908        $transitions = array();
3909        $texto_value = $mes == 0 ? 'value' : 'value_' . $mes;
3910        if (_acciones_centralizadas_seguimiento_node_tab_mes_access($node, $id_field, $mes)) {
3911           $links[] = l(t('Modificar seguimiento'), 'node/' . $node->nid . '/seguimiento/' . $id_field . '/' . $mes . '/edit', array('query' => array('destination' => $_GET['q'])));
3912        }
3913        if ($states['wid']) {
3914          $transitions = workflow_allowable_transitions($current_estado, 'to', $roles);
3915        }
3916        unset($transitions[$current_estado]);
3917        if (count($transitions) && $estado_aprobado != $current_estado) {
3918          foreach($transitions as $id => $transition) {
3919            $links[] = l(t('Enviar a @state', array('@state' => $transition)), 'node/' . $node->nid . '/seguimiento/' . $id_field . '/' . $mes . '/workflow/' . $id, array('query' => array('destination' => $_GET['q'])));
3920          }
3921        }
3922        $row[] = array('data' => theme('item_list', $links),);
3923        $rows[] = $row;
3924     
3925        $tablas[]= '<div class="field-label">' . $field_load['widget']['label'] . '</div>' . theme('table', $header, $rows) . $mensaje . l(t('Seguimiento de la Acción Centralizada'), 'node/' . $node->nid . '/seguimiento/' . $id_field . '/' . $mes . '/view') . '<br>';
3926      }
3927    }
3928    if (count($tablas)) {
3929      $output .= '<fieldset><legend>' . $grupo['label'] . '</legend>' . implode('', $tablas). '</fieldset>';
3930    }
3931  }
3932  if ($output == '') {
3933    $output .= t('La acción Centralizada no tiene partidas asignadas.');
3934  }
3935  return $output;
3936}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.