source: sipp/modules/acciones_centralizadas/acciones_centralizadas.module @ 06ed391

drupal-7.x
Last change on this file since 06ed391 was 06ed391, checked in by Luis Peña <lpena@…>, 11 años ago

Actualizando enlace de Acciones Centralizadas

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