source: sipes/0.3-modules/acciones_centralizadas/acciones_centralizadas.module @ 983139c

stableversion-3.0
Last change on this file since 983139c was 1e95969, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se modifico el acceso a las acciones centralizadas

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