package com.dacrt.SBIABackend.controler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.dacrt.SBIABackend.dto.EvalProccesRecordDto;
import com.dacrt.SBIABackend.dto.EvalProccesSuppliRecordDto;
import com.dacrt.SBIABackend.dto.EvalUnitQuantitiesDto;
import com.dacrt.SBIABackend.dto.EvalUnitRangesDto;
import com.dacrt.SBIABackend.dto.OperationlineDto;
import com.dacrt.SBIABackend.dto.RtoRecordSupplierDto;
import com.dacrt.SBIABackend.dto.StrategiesRecordDto;
import com.dacrt.SBIABackend.dto.StrategyDetDto;
import com.dacrt.SBIABackend.dto.TypeStrategiDetDto;
import com.dacrt.SBIABackend.dto.TypesUnitDto;
import com.dacrt.SBIABackend.dto.UnitsUsersDto;
import com.dacrt.SBIABackend.dto.requestDto.EvalProcessesRecordRequestDto;
import com.dacrt.SBIABackend.dto.requestDto.EvalUnitsPositionRequestDto;
import com.dacrt.SBIABackend.dto.responseDto.EvalProcessesRecordResponseDto;
import com.dacrt.SBIABackend.dto.responseDto.EvalUnitPositionResponseDto;
import com.dacrt.SBIABackend.dto.responseDto.EvalUnitsEntryResponseDto;
import com.dacrt.SBIABackend.dto.responseDto.EvalUnitsListResponseDto;
import com.dacrt.SBIABackend.entity.Applications;
import com.dacrt.SBIABackend.entity.Evalprocapps;
import com.dacrt.SBIABackend.entity.Evalprocesses;
import com.dacrt.SBIABackend.entity.Evalprocrecords;
import com.dacrt.SBIABackend.entity.Evalunitpos;
import com.dacrt.SBIABackend.entity.Evalunits;
import com.dacrt.SBIABackend.entity.Positions;
import com.dacrt.SBIABackend.repository.ApplicationsRepository;
import com.dacrt.SBIABackend.repository.CampaignsRepository;
import com.dacrt.SBIABackend.repository.EvalprocappsRepository;
import com.dacrt.SBIABackend.repository.EvalprocessesRepository;
import com.dacrt.SBIABackend.repository.EvalprocrecordsRepository;
import com.dacrt.SBIABackend.repository.EvalunitposRepository;
import com.dacrt.SBIABackend.repository.EvalunitsRepository;
import com.dacrt.SBIABackend.repository.PositionsRepository;
 
import com.dacrt.SBIABackend.security.dto.AuditRequestDto;
import com.dacrt.SBIABackend.security.dto.ParamsDto;
import com.dacrt.SBIABackend.security.dto.ParamsResponseDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesDto;
import com.dacrt.SBIABackend.security.dto.RespuestaDto;
import com.dacrt.SBIABackend.security.dto.RespuestaMsgDto;
import com.dacrt.SBIABackend.security.dto.RespuestaValueDto;
import com.dacrt.SBIABackend.security.entity.Params;
import com.dacrt.SBIABackend.security.entity.Roles;
import com.dacrt.SBIABackend.security.entity.Users;
import com.dacrt.SBIABackend.security.repository.AuditRepository;
import com.dacrt.SBIABackend.security.repository.ParamsRepository;
import com.dacrt.SBIABackend.security.repository.RolesPrivilegesRepository;
import com.dacrt.SBIABackend.security.repository.UsersRepository;
import com.dacrt.SBIABackend.security.service.MenuService;
import com.dacrt.SBIABackend.security.service.ParamsService;
import com.dacrt.SBIABackend.security.service.SecurityService;
import com.dacrt.SBIABackend.security.service.UsersService;
import com.dacrt.SBIABackend.utils.HttpReqRespUtils;

@RestController
@CrossOrigin(origins = "*")
public class EvalunitposController {
	
	@Autowired
	private ParamsRepository paramsRepository;
	
	@Autowired
	private UsersRepository usersRepository;
	
	@Autowired
	private AuditRepository auditRepository;
	
	@Autowired
	private RolesPrivilegesRepository rolesPrivilegesRepository;
	
	@Autowired
	UsersService usersService;
	
	@Autowired
	ParamsService paramsService;
	
	@Autowired
	SecurityService securityService;
	
	@Autowired
	MenuService menuService;
	
	@Autowired
	ApplicationsRepository applicationsRepository;
	
	@Autowired
	EvalprocrecordsRepository evalprocrecordsRepository;
	
	@Autowired
	EvalprocappsRepository evalprocappsRepository;
	
	@Autowired
	CampaignsRepository campaignsRepository;
	
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
	@Value("${var.ambiente}")
	private String urlAmbiente;
	
	@Value("${spring.datasource.url}")
	private String conexion;
	
	@Value("${spring.datasource.username}")
	private String userbd;
	
	@Value("${spring.datasource.password}")
	private String passbd;
	
	
	@PersistenceContext
    private EntityManager entityManager;
	
	@Autowired
	EvalunitsRepository evalunitsRepository;
	
	@Autowired
	PositionsRepository positionsRepository;
	
	@Autowired
	EvalunitposRepository evalunitposRepository;

	
	
	
	@GetMapping("/evalunits/{evalunitid}/positions/{evalunitposid}")
   	public ResponseEntity<?> getOneUnitsPosition(HttpServletRequest request, @PathVariable("evalunitid") final Integer evalunitid,@PathVariable("evalunitposid") final Integer evalunitposid)
	   			throws ParseException {	
   				RespuestaDto respuesta = new RespuestaDto("", false);
   				HttpStatus estatus = HttpStatus.FORBIDDEN;
   				EvalProcessesRecordResponseDto evalProcessesRecordResponseDto = new EvalProcessesRecordResponseDto();
   				//EvalUnitsListResponseDto evalUnitPositionResponseDto = new EvalUnitsListResponseDto();
   				
   				EvalUnitPositionResponseDto evalUnitPositionResponseDto = new EvalUnitPositionResponseDto();
   			
   				RtoRecordSupplierDto detallerto;
   				RtoRecordSupplierDto detallerpo;
   				
   				EvalProccesSuppliRecordDto detalleEvalProccesSuppliDto;
   				EvalUnitsListResponseDto detalleEvalUnitPosition;
   				EvalUnitsEntryResponseDto evalUnitPosiEntryResponseDto = new EvalUnitsEntryResponseDto();
   				EvalUnitRangesDto detalleRanges;
   				EvalUnitRangesDto detalleRanges2;
   				EvalUnitRangesDto detalleRanges3;
   				EvalUnitRangesDto detalleRanges4;
   				EvalUnitRangesDto detalleRanges5;
   				EvalUnitRangesDto detalleRanges6;
   				EvalUnitRangesDto detalleRanges7;
   				EvalUnitRangesDto detalleRanges8;
   				EvalUnitRangesDto detalleRanges9;
   				EvalUnitRangesDto detalleRanges10;
   				EvalUnitRangesDto detalleRanges11;
   				List<EvalUnitRangesDto> listasRanges = new ArrayList<>();
   				List<EvalUnitsListResponseDto> listRecord = new ArrayList<>();
   				EvalUnitQuantitiesDto detalleQuantities;
   				EvalUnitsListResponseDto detalleRecordPosition;
   				
   			
   			  
   			     Long cuantosregistro = (long) 0;
   			        				 
   				 String sessionid = request.getHeader("Authorization");
   				  Date fecha = new Date();
   				    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   			        String dataFormattata = formatter.format(fecha);
   			        Date fechaDate = formatter.parse(dataFormattata);
   			        AuditRequestDto  auditDto=new AuditRequestDto();
   			        int idUser;
   			  
		    	  
   			        int rolisvalidDRP;			       
   			        int idrol,searchIdStrategyGeneral,searchUnitid;
   			        OperationlineDto detalleStatUnit = null;
   			   	
   					  
   			     // String searchModule = "";
   				  int searchStatus = 0;
   				  int searchVP,searchFacility,searchType;
   				  String fechaComoCadena;
   				 int orderIn = 0;
   				 int offsetIn = 0;
   				 int numofrecordsIn = 0;
   				 Optional<Params> deSessDuration=paramsRepository.findByParamname("SESSION_DURATION");
   				 String SessionDuration=deSessDuration.get().getValue();
   				 int duracionSession = Integer.parseInt(SessionDuration);
   				 Date fecha2 = new Date();
   				 int idsupplier=0;
   				 int idworker=0;
   				 Optional<Users> encontreSessionUsuario;
   				
   			
   				 
   					if (sessionid==null) {
   						String var = "";
   						boolean bloked = false;
   						RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
   						respuestaDto.setBlocked(bloked);
   						respuestaDto.setMsg("Sesión expirada o inválida");
   						//Error 400
   						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
   					} else   {
   						 
   						   sessionid = sessionid.substring(7);
   						   encontreSessionUsuario =usersRepository.getBySessionid(sessionid);
   						   idUser = encontreSessionUsuario.get().getId();
   						   
   						  
   						  
   						   if (encontreSessionUsuario.isPresent()) {
   							   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 

   							   fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
   							 
   							    if (fechaComoCadena=="") {								   								  
   								   
   								   String var = "";
   									boolean bloked = false;
   									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
   									//respuestaDto.setBlocked(bloked);
   									respuestaDto.setMsg("Sesión expirada o inválida"); 
   									return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   									//return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   								   
   							    }
   							   
   							   
   							   // Este proceso permite obtener un listado de las unidades. (Priv 110)
   							   Roles roles = encontreSessionUsuario.get().getRolid();
   							    idrol = roles.getId();
   							   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 210);
   							   //validando privilegio de DRP
   							  //  rolisvalidDRP = auditRepository.getCantbyRolAndPrivi(idrol, 314);
   							 // rolisvalid = 3;
   							   
   							   if (rolisvalid==0) {
   								   
   								   String var = "";
   									boolean bloked = false;
   									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
   									//respuestaDto.setBlocked(bloked);
   									respuestaDto.setMsg("No tiene los Privilegios"); 
   									return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
   									
   							   }
   							  
   							
   						 } else {
   								String var = "";
   								boolean bloked = false;
   								RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
   								respuestaDto.setBlocked(bloked);
   								respuestaDto.setMsg("Sesión expirada o inválida");
   								//Error 400
   								return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   						 }
   					}
   					
   												
   				try {								

   				 boolean existePos =  evalunitposRepository.existsById(evalunitposid);
   				
   					String SentenciaBase1 = "  SELECT ep.positionst,es.id idposition,ep.id ideva,es.condition,es.note,es.qtytotal,qtykey, "
   							   + " es.qtyrange1,es.qtyrange2,es.qtyrange3,es.qtyrange4,es.qtyrange5,es.qtyrange6, "
                               + "     es.qtyrange7,es.qtyrange8,es.qtyrange9,es.qtyrange10,es.qtyrange11,p.name,p.id  "
				               + "     FROM main.evalunits ep "
				               + "     LEFT JOIN main.evalunitpos es ON ep.id = es.evalunitid  "
				               +"      LEFT JOIN main.positions p ON es.positionid = p.id "
				               + "    WHERE "
				               + "   ep.id = " + evalunitid; 
				             //  + "   ORDER BY es.id ASC" ;
   					
   					String StringPos =  "  AND es.id = " + evalunitposid + " ";
   					String order =  " ORDER BY p.name ASC";
   									
   					 String QueryTotal = "";
   					// QueryTotal = SentenciaBase1;
   					 String SentenciaBase="";
   					 
	                 if (!existePos) {
						
						if (evalunitposid==0) {
							SentenciaBase = SentenciaBase1 + StringPos + order;
							
						} else
						{
							  String var = "";
								boolean bloked = false;
								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
								//respuestaDto.setBlocked(bloked);
								respuestaDto.setMsg("Registro no encontrado"); 
								return new ResponseEntity(respuestaDto, HttpStatus.NOT_FOUND);
						}
						
						//SentenciaBase = SentenciaBase1 + order;
					} else {
						SentenciaBase = SentenciaBase1 + StringPos + order;
						
					}
	 				
   					  QueryTotal = "";
   				    	 QueryTotal = SentenciaBase;
    					
   					 	 
   					  Query query = entityManager.createNativeQuery(QueryTotal);
   					     cuantosregistro = (long) jdbcTemplate.queryForList(QueryTotal).size();
   					       
   					       query = entityManager.createNativeQuery(QueryTotal);
   					       //query.setFirstResult(offsetIn);
   						   //query.setMaxResults(numofrecordsIn);
   						   List<Object[]> listacompleta = query.getResultList();
   					    //	listEvalProccesRecordDto= new ArrayList<>();
   					    	int codigoestatusdefault;
   					    	String descestatusdefault;
   					    	
   					    	/*if (cuantosregistro==0) {
   					    		codigoestatusdefault = 0;
   					    		descestatusdefault = "Activa";
   					    		detalleStatUnit= new  OperationlineDto();
   					    		detalleStatUnit.setId(codigoestatusdefault);
   					    		detalleStatUnit.setName(descestatusdefault);
   					    		
   					    	}*/
   					    	
   					    	
   					    	detalleRecordPosition = null;
   					    	//List<EvalUnitRangesDto> listasRanges = new ArrayList<>();
   					    //if (cuantosregistro!=0) {	
   				    		   for (Object[] reg : listacompleta) {
   				    			listasRanges= new ArrayList<>();
   				    			 detalleRecordPosition =new EvalUnitsListResponseDto();
   				    			
   				    			 detalleRanges = new EvalUnitRangesDto();
   				    			 detalleQuantities = new EvalUnitQuantitiesDto();
   				    		
   				    		   detallerpo = new  RtoRecordSupplierDto();   				    		
   				    	       detalleStatUnit= new  OperationlineDto();
   				    	       detalleEvalUnitPosition= new EvalUnitsListResponseDto();
   			   				   detalleRanges = new EvalUnitRangesDto();
   			   		    	   detalleRanges2 = new EvalUnitRangesDto();
   			   		 	       detalleRanges3 = new EvalUnitRangesDto();
   			   		           detalleRanges4 = new EvalUnitRangesDto();
   			   	               detalleRanges5 = new EvalUnitRangesDto();
   			   	               detalleRanges6 = new EvalUnitRangesDto();
   			   	               detalleRanges7 = new EvalUnitRangesDto();
   			   	               detalleRanges8 = new EvalUnitRangesDto();
   			                   detalleRanges9 = new EvalUnitRangesDto();
   			                   detalleRanges10 = new EvalUnitRangesDto();
   			                   detalleRanges11 = new EvalUnitRangesDto();
   			   				   detalleQuantities= new EvalUnitQuantitiesDto();
   			   				   detalleRecordPosition = new EvalUnitsListResponseDto();

   				    		   
   				    	     /*  detalleStatUnit.setId((int) reg[0]);
 				    		   if ((int) reg[0]==1) {
 				    			  detalleStatUnit.setName("Cerrada");
				    			   
				    		   } else
				    		   {
				    			   detalleStatUnit.setName("Activa");
				    		   }*/
 				    		   String label = "0 a 2 Hrs";
 				    		   Integer weigth = 1;
 				    		   detalleRanges.setId(1);
 				    		   detalleRanges.setLabel(label);
 				    		   detalleRanges.setWeight(weigth);
 				    		   detalleRanges.setQty((int) reg[7]);
 				    		  listasRanges.add(detalleRanges);
 				    		  
 				    		  String label2 = "2 a 4 Hrs";
				    		  // Integer weigth = 1;
				    		   detalleRanges2.setId(2);
				    		   detalleRanges2.setLabel(label2);
				    		   detalleRanges2.setWeight(weigth);
				    		   detalleRanges2.setQty((int) reg[8]);
				    		   listasRanges.add(detalleRanges2);
				    		   
				    		   String label3 = "4 a 8 Hrs";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges3.setId(3);
				    		   detalleRanges3.setLabel(label3);
				    		   detalleRanges3.setWeight(weigth);
				    		   detalleRanges3.setQty((int) reg[9]);
				    		   listasRanges.add(detalleRanges3);
				    		   
				    		   String label4 = "8 a 12 Hrs";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges4.setId(4);
				    		   detalleRanges4.setLabel(label4);
				    		   detalleRanges4.setWeight(weigth);
				    		   detalleRanges4.setQty((int) reg[10]);
				    		   listasRanges.add(detalleRanges4);
				    		   
				    		   Integer weigth2 = 24;
				    		   String label5 = "Día 1";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges5.setId(5);
				    		   detalleRanges5.setLabel(label5);
				    		   detalleRanges5.setWeight(weigth2);
				    		   detalleRanges5.setQty((int) reg[11]);
				    		   listasRanges.add(detalleRanges5);
				    		   
				    		   String label6 = "Día 2";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges6.setId(6);
				    		   detalleRanges6.setLabel(label6);
				    		   detalleRanges6.setWeight(weigth2);
				    		   detalleRanges6.setQty((int) reg[12]);
				    		   listasRanges.add(detalleRanges6);
				    		   
				    		   String label7 = "Día 3";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges7.setId(7);
				    		   detalleRanges7.setLabel(label7);
				    		   detalleRanges7.setWeight(weigth2);
				    		   detalleRanges7.setQty((int) reg[13]);
				    		   listasRanges.add(detalleRanges7);
				    		   
				    		   String label8 = "Día 4";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges8.setId(8);
				    		   detalleRanges8.setLabel(label8);
				    		   detalleRanges8.setWeight(weigth2);
				    		   detalleRanges8.setQty((int) reg[14]);
				    		   listasRanges.add(detalleRanges8);
				    		   
				    		   String label9 = "Día 5";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges9.setId(9);
				    		   detalleRanges9.setLabel(label9);
				    		   detalleRanges9.setWeight(weigth2);
				    		   detalleRanges9.setQty((int) reg[15]);
				    		   listasRanges.add(detalleRanges9);
				    		   
				    		   String label10 = "Día 6";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges10.setId(10);
				    		   detalleRanges10.setLabel(label10);
				    		   detalleRanges10.setWeight(weigth2);
				    		   detalleRanges10.setQty((int) reg[16]);
				    		   listasRanges.add(detalleRanges10);
				    		   
				    		   String label11 = "Día 7";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges11.setId(11);
				    		   detalleRanges11.setLabel(label11);
				    		   detalleRanges11.setWeight(weigth2);
				    		   detalleRanges11.setQty((int) reg[17]);
				    		   listasRanges.add(detalleRanges11);
				    		   
				    		   
				    		   detalleQuantities.setTotal((int) reg[5]);
				    		   detalleQuantities.setKey((int) reg[6]);
				    		   detalleQuantities.setRanges(listasRanges);
				    		   
				    		   detalleRecordPosition.setId((int) reg[1]);
				    		   detalleRecordPosition.setCondition((String) reg[3]);
				    		   detalleRecordPosition.setName((String) reg[18]);
				    		   detalleRecordPosition.setNote((String) reg[4]);
				    		   detalleRecordPosition.setPositionid((int) reg[19]);
				    		   detalleRecordPosition.setQuantities(detalleQuantities);				    		    				    		   				    		       				    	  	    				    		       				    	        				    		   				    	   				    		   
   					    	  
				    		  // listRecord.add(detalleRecordPosition);
   				    	   }
   				    		      				    								     						   						       						    						          				    					    					    	
   				    		  // evalUnitPositionResponseDto.setNumofrecords(cuantosregistro);
   				    		  // evalUnitPositionResponseDto.setSessionvalidthru(fechaComoCadena);
   				    		   evalUnitPosiEntryResponseDto.setEntry(detalleRecordPosition);
   				    		   //evalUnitPositionResponseDto.setRecords(listRecord);
   				    		   
   		                return ResponseEntity.ok(evalUnitPosiEntryResponseDto);
   					   
   				
   		       
   				} catch (Exception e) {
   		            // Manejo de excepciones
   					respuesta= new RespuestaDto("Error interno del servidor", false);
   					estatus=HttpStatus.INTERNAL_SERVER_ERROR;  
   					
   		        } finally {
   			        if (entityManager != null && entityManager.isOpen()) {
   			            entityManager.close();
   			        }
   			    }
   				
   				return new ResponseEntity(respuesta, estatus);
   			
   			}
 	

	
	
	@GetMapping("/evalunits/{evalunitid}/positions")
   	public ResponseEntity<?> getListPositionevalUnits(HttpServletRequest request, @PathVariable("evalunitid") final Integer evalunitid)
   			throws ParseException {
   				RespuestaDto respuesta = new RespuestaDto("", false);
   				HttpStatus estatus = HttpStatus.FORBIDDEN;
   				EvalProcessesRecordResponseDto evalProcessesRecordResponseDto = new EvalProcessesRecordResponseDto();
   				//EvalUnitsListResponseDto evalUnitPositionResponseDto = new EvalUnitsListResponseDto();
   				
   				EvalUnitPositionResponseDto evalUnitPositionResponseDto = new EvalUnitPositionResponseDto();
   			
   				RtoRecordSupplierDto detallerto;
   				RtoRecordSupplierDto detallerpo;
   				
   				EvalProccesSuppliRecordDto detalleEvalProccesSuppliDto;
   				EvalUnitsListResponseDto detalleEvalUnitPosition;
   				EvalUnitRangesDto detalleRanges;
   				EvalUnitRangesDto detalleRanges2;
   				EvalUnitRangesDto detalleRanges3;
   				EvalUnitRangesDto detalleRanges4;
   				EvalUnitRangesDto detalleRanges5;
   				EvalUnitRangesDto detalleRanges6;
   				EvalUnitRangesDto detalleRanges7;
   				EvalUnitRangesDto detalleRanges8;
   				EvalUnitRangesDto detalleRanges9;
   				EvalUnitRangesDto detalleRanges10;
   				EvalUnitRangesDto detalleRanges11;
   				List<EvalUnitRangesDto> listasRanges = new ArrayList<>();
   				List<EvalUnitsListResponseDto> listRecord = new ArrayList<>();
   				EvalUnitQuantitiesDto detalleQuantities;
   				EvalUnitsListResponseDto detalleRecordPosition;
   				
   			
   			  
   			     Long cuantosregistro = (long) 0;
   			        				 
   				 String sessionid = request.getHeader("Authorization");
   				  Date fecha = new Date();
   				    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   			        String dataFormattata = formatter.format(fecha);
   			        Date fechaDate = formatter.parse(dataFormattata);
   			        AuditRequestDto  auditDto=new AuditRequestDto();
   			        int idUser;
   			  
		    	  
   			        int rolisvalidDRP;			       
   			        int idrol,searchIdStrategyGeneral,searchUnitid;
   			        OperationlineDto detalleStatUnit = null;
   			   	
   					  
   			     // String searchModule = "";
   				  int searchStatus = 0;
   				  int searchVP,searchFacility,searchType;
   				  String fechaComoCadena;
   				 int orderIn = 0;
   				 int offsetIn = 0;
   				 int numofrecordsIn = 0;
   				 Optional<Params> deSessDuration=paramsRepository.findByParamname("SESSION_DURATION");
   				 String SessionDuration=deSessDuration.get().getValue();
   				 int duracionSession = Integer.parseInt(SessionDuration);
   				 Date fecha2 = new Date();
   				 int idsupplier=0;
   				 int idworker=0;
   				 Optional<Users> encontreSessionUsuario;
   				
   			
   				 
   					if (sessionid==null) {
   						String var = "";
   						boolean bloked = false;
   						RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
   						respuestaDto.setBlocked(bloked);
   						respuestaDto.setMsg("Sesión expirada o inválida");
   						//Error 400
   						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
   					} else   {
   						 
   						   sessionid = sessionid.substring(7);
   						   encontreSessionUsuario =usersRepository.getBySessionid(sessionid);
   						   idUser = encontreSessionUsuario.get().getId();
   						   
   						  
   						  
   						   if (encontreSessionUsuario.isPresent()) {
   							   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 

   							   fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
   							 
   							    if (fechaComoCadena=="") {								   								  
   								   
   								   String var = "";
   									boolean bloked = false;
   									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
   									//respuestaDto.setBlocked(bloked);
   									respuestaDto.setMsg("Sesión expirada o inválida"); 
   									return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   									//return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   								   
   							    }
   							   
   							   
   							   // Este proceso permite obtener un listado de las unidades. (Priv 110)
   							   Roles roles = encontreSessionUsuario.get().getRolid();
   							    idrol = roles.getId();
   							   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 210);
   							   //validando privilegio de DRP
   							  //  rolisvalidDRP = auditRepository.getCantbyRolAndPrivi(idrol, 314);
   							//  rolisvalid = 3;
   							   
   							   if (rolisvalid==0) {
   								   
   								   String var = "";
   									boolean bloked = false;
   									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
   									//respuestaDto.setBlocked(bloked);
   									respuestaDto.setMsg("No tiene los Privilegios"); 
   									return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
   									
   							   }
   							  
   							
   						 } else {
   								String var = "";
   								boolean bloked = false;
   								RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
   								respuestaDto.setBlocked(bloked);
   								respuestaDto.setMsg("Sesión expirada o inválida");
   								//Error 400
   								return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
   						 }
   					}
   					
   												
   				try {								

   					
   				
   					//String SentenciaBase = "  SELECT ep.positionst,es.id idposition,ep.id ideva,es.condition,es.note,es.qtytotal,qtykey, "
   					  String SentenciaBase = "  SELECT ep.positionst,coalesce(es.id,0) idposition,ep.id ideva,es.condition,es.note, "
   							                    + "  coalesce(es.qtytotal,0) qtytotal, "
   							                    + "   coalesce(es.qtykey,0) qtykey, "
   						                        + "   coalesce(es.qtyrange1,0) qtyrange1, "
   						                        + "  coalesce(es.qtyrange2,0) qtyrange2, "
   						                        + "  coalesce(es.qtyrange3,0) qtyrange3, "
   						                        + "  coalesce(es.qtyrange4,0) qtyrange4, "
   						                        + "  coalesce(es.qtyrange5,0) qtyrange5, "
   						                        + " coalesce(es.qtyrange6,0) qtyrange6, "
   						                        + "  coalesce(es.qtyrange7,0) qtyrange7, "
   						                        + "  coalesce(es.qtyrange8,0) qtyrange8, "
   						                        + "  coalesce(es.qtyrange9,0) qtyrange9, "
   						                        + "  coalesce(es.qtyrange10,0) qtyrange10, "
   						                        + "  coalesce(es.qtyrange11,0) qtyrange11,p.name,coalesce(p.id,0) "
   							   //+ "     es.qtyrange1,es.qtyrange2,es.qtyrange3,es.qtyrange4,es.qtyrange5,es.qtyrange6, "
   							 //  + "       coalesce(es.qtyrange1,0),coalesce(es.qtyrange2,0),coalesce(es.qtyrange3,0),coalesce(es.qtyrange4,0),coalesce(es.qtyrange5,0),coalesce(es.qtyrange6,0) "
                             //  + "     es.qtyrange7,es.qtyrange8,es.qtyrange9,es.qtyrange10,es.qtyrange11,p.name,p.id  "
				               + "     FROM main.evalunits ep "
				               + "     INNER JOIN main.evalunitpos es ON ep.id = es.evalunitid  "
				               +"      LEFT JOIN main.positions p ON es.positionid = p.id "
				               + "    WHERE "
				               + "   ep.id = " + evalunitid
				               + "   ORDER BY es.id ASC" ;
   					
   					//    coalesce(STRING_AGG(DISTINCT CAST(u.id AS TEXT), ','),'') AS idunits, "
   					String SentenciaBaseStatus = " select positionst,resourcest from main.evalunits where id = " + evalunitid ;
   									
   					 String QueryTotal = "";
   					 QueryTotal = SentenciaBase;
    					
   					 	 
   					 Query query = entityManager.createNativeQuery(QueryTotal);
   					  cuantosregistro = (long) jdbcTemplate.queryForList(QueryTotal).size();
   					       
   					       query = entityManager.createNativeQuery(QueryTotal);
   					       //query.setFirstResult(offsetIn);
   						   //query.setMaxResults(numofrecordsIn);
   						   List<Object[]> listacompleta = query.getResultList();
   					    //	listEvalProccesRecordDto= new ArrayList<>();
   					    	int codigoestatusdefault;
   					    	String descestatusdefault;
   					    	detalleStatUnit= new  OperationlineDto();
   					    	//Integer estatusevalposition;
   					         Integer estatusevalposition = (int) 0;
   					    	
   					    	if (cuantosregistro==0) {
   					    	 Query query2 = entityManager.createNativeQuery(SentenciaBaseStatus);
   					       	List<Object[]> listacompletastatus = query2.getResultList();
   					          for (Object[] regsta : listacompletastatus) {
   					        	             estatusevalposition = (int) regsta[0];
   					    	 
   					          }
   					    		//codigoestatusdefault = 0;
   					    		//descestatusdefault = "Activa";
   					             if (estatusevalposition!=0) {
   					               	//detalleStatUnit= new  OperationlineDto();
	   					    		detalleStatUnit.setId(1);
	   					    		detalleStatUnit.setName("Completado");
   					            	 
   					             } else
   					             {
   					            	//detalleStatUnit= new  OperationlineDto();
   	   					    		detalleStatUnit.setId(0);
   	   					    		detalleStatUnit.setName("Abierta");
   					            
   					             }   					            	 
   					          
   					    		
   					    		
   					    	}
   					    	
   					    	
   					    	
   					    	//List<EvalUnitRangesDto> listasRanges = new ArrayList<>();
   					    if (cuantosregistro!=0) {	
   				    		   for (Object[] reg : listacompleta) {
   				    			listasRanges= new ArrayList<>();
   				    			 detalleRecordPosition =new EvalUnitsListResponseDto();
   				    			 detalleRanges = new EvalUnitRangesDto();
   				    			 detalleQuantities = new EvalUnitQuantitiesDto();
   				    		
   				    		   detallerpo = new  RtoRecordSupplierDto();   				    		
   				    	       detalleStatUnit= new  OperationlineDto();
   				    	       detalleEvalUnitPosition= new EvalUnitsListResponseDto();
   			   				   detalleRanges = new EvalUnitRangesDto();
   			   		    	   detalleRanges2 = new EvalUnitRangesDto();
   			   		 	       detalleRanges3 = new EvalUnitRangesDto();
   			   		           detalleRanges4 = new EvalUnitRangesDto();
   			   	               detalleRanges5 = new EvalUnitRangesDto();
   			   	               detalleRanges6 = new EvalUnitRangesDto();
   			   	               detalleRanges7 = new EvalUnitRangesDto();
   			   	               detalleRanges8 = new EvalUnitRangesDto();
   			                   detalleRanges9 = new EvalUnitRangesDto();
   			                   detalleRanges10 = new EvalUnitRangesDto();
   			                   detalleRanges11 = new EvalUnitRangesDto();
   			   				   detalleQuantities= new EvalUnitQuantitiesDto();
   			   				   detalleRecordPosition = new EvalUnitsListResponseDto();

   				    		   
   				    	       detalleStatUnit.setId((int) reg[0]);
 				    		   if ((int) reg[0]==1) {
 				    			  detalleStatUnit.setName("Completado");
				    			   
				    		   } else
				    		   {
				    			   detalleStatUnit.setName("Abierta");
				    		   }
 				    		   String label = "0 a 2 Hrs";
 				    		   Integer weigth = 1;
 				    		   detalleRanges.setId(1);
 				    		   detalleRanges.setLabel(label);
 				    		   detalleRanges.setWeight(weigth);
 				    		   detalleRanges.setQty((int) reg[7]);
 				    		  listasRanges.add(detalleRanges);
 				    		  
 				    		  String label2 = "2 a 4 Hrs";
				    		  // Integer weigth = 1;
				    		   detalleRanges2.setId(2);
				    		   detalleRanges2.setLabel(label2);
				    		   detalleRanges2.setWeight(weigth);
				    		   detalleRanges2.setQty((int) reg[8]);
				    		   listasRanges.add(detalleRanges2);
				    		   
				    		   String label3 = "4 a 8 Hrs";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges3.setId(3);
				    		   detalleRanges3.setLabel(label3);
				    		   detalleRanges3.setWeight(weigth);
				    		   detalleRanges3.setQty((int) reg[9]);
				    		   listasRanges.add(detalleRanges3);
				    		   
				    		   String label4 = "8 a 12 Hrs";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges4.setId(4);
				    		   detalleRanges4.setLabel(label4);
				    		   detalleRanges4.setWeight(weigth);
				    		   detalleRanges4.setQty((int) reg[10]);
				    		   listasRanges.add(detalleRanges4);
				    		   
				    		   Integer weigth2 = 24;
				    		   String label5 = "Día 1";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges5.setId(5);
				    		   detalleRanges5.setLabel(label5);
				    		   detalleRanges5.setWeight(weigth2);
				    		   detalleRanges5.setQty((int) reg[11]);
				    		   listasRanges.add(detalleRanges5);
				    		   
				    		   String label6 = "Día 2";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges6.setId(6);
				    		   detalleRanges6.setLabel(label6);
				    		   detalleRanges6.setWeight(weigth2);
				    		   detalleRanges6.setQty((int) reg[12]);
				    		   listasRanges.add(detalleRanges6);
				    		   
				    		   String label7 = "Día 3";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges7.setId(7);
				    		   detalleRanges7.setLabel(label7);
				    		   detalleRanges7.setWeight(weigth2);
				    		   detalleRanges7.setQty((int) reg[13]);
				    		   listasRanges.add(detalleRanges7);
				    		   
				    		   String label8 = "Día 4";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges8.setId(8);
				    		   detalleRanges8.setLabel(label8);
				    		   detalleRanges8.setWeight(weigth2);
				    		   detalleRanges8.setQty((int) reg[14]);
				    		   listasRanges.add(detalleRanges8);
				    		   
				    		   String label9 = "Día 5";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges9.setId(9);
				    		   detalleRanges9.setLabel(label9);
				    		   detalleRanges9.setWeight(weigth2);
				    		   detalleRanges9.setQty((int) reg[15]);
				    		   listasRanges.add(detalleRanges9);
				    		   
				    		   String label10 = "Día 6";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges10.setId(10);
				    		   detalleRanges10.setLabel(label10);
				    		   detalleRanges10.setWeight(weigth2);
				    		   detalleRanges10.setQty((int) reg[16]);
				    		   listasRanges.add(detalleRanges10);
				    		   
				    		   String label11 = "Día 7";
				    		   //Integer weigth3 = 1;
				    		   detalleRanges11.setId(11);
				    		   detalleRanges11.setLabel(label11);
				    		   detalleRanges11.setWeight(weigth2);
				    		   detalleRanges11.setQty((int) reg[17]);
				    		   listasRanges.add(detalleRanges11);
				    		   
				    		   
				    		   detalleQuantities.setTotal((int) reg[5]);
				    		   detalleQuantities.setKey((int) reg[6]);
				    		   detalleQuantities.setRanges(listasRanges);
				    		   
				    		   detalleRecordPosition.setId((int) reg[1]);
				    		   detalleRecordPosition.setCondition((String) reg[3]);
				    		   detalleRecordPosition.setName((String) reg[18]);
				    		   detalleRecordPosition.setNote((String) reg[4]);
				    		   detalleRecordPosition.setPositionid((int) reg[19]);
				    		   detalleRecordPosition.setQuantities(detalleQuantities);				    		    				    		   				    		       				    	  	    				    		       				    	        				    		   				    	   				    		   
   					    	  
				    		   listRecord.add(detalleRecordPosition);
   				    	   }
   				    		 
   					    } 	   
   				    		   evalUnitPositionResponseDto.setNumofrecords(cuantosregistro);
   				    		   evalUnitPositionResponseDto.setSessionvalidthru(fechaComoCadena);
   				    		   evalUnitPositionResponseDto.setStatus(detalleStatUnit);
   				    		   evalUnitPositionResponseDto.setRecords(listRecord);
   				    		   
   		                return ResponseEntity.ok(evalUnitPositionResponseDto);
   					   
   				
   		       
   				} catch (Exception e) {
   		            // Manejo de excepciones
   					respuesta= new RespuestaDto("Error interno del servidor", false);
   					estatus=HttpStatus.INTERNAL_SERVER_ERROR;  
   					
   		        } finally {
   			        if (entityManager != null && entityManager.isOpen()) {
   			            entityManager.close();
   			        }
   			    }
   				
   				return new ResponseEntity(respuesta, estatus);
   			
   			}
 	

	//evalunits/evalunitid/positions/evalunitposid
	  @PostMapping("/evalunits/{evalunitid}/positions/{evalunitposid}")
	 	public ResponseEntity<ParamsResponseDto> UpsertEvalUnitPosition(HttpServletRequest request,@RequestBody EvalUnitsPositionRequestDto datosEvalUnits,@PathVariable("evalunitid") final Integer evalprocessid,@PathVariable("evalunitposid") final Integer evalprocrecid) throws ParseException {
	 		
	 		
	 		RespuestaValueDto respuestaValueDto;
	 		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
	 		HttpStatus estatus = HttpStatus.FORBIDDEN;
	 		ParamsResponseDto paramsResponseDto = new ParamsResponseDto();
	 		ParamsDto detalleParams;
	 		PrivilegesDto detallePrivilege;
	 	     List<ParamsDto> listasParams = new ArrayList<>();
	 	     List<PrivilegesDto> listasPrivelege = new ArrayList<>();
	 	         String queryInsertProcesses = "";
	 	         String queryInsertUnidades= "";
	 	         
	 		 int idparametroEval = evalprocessid;
	 		 int idparametroEvalRecord = evalprocrecid;
	 		 
	 		 Optional<Users> encontreSessionUsuario;
	 		 Optional<Evalprocapps> encontreEvalProcessesApp;
	 		 Positions encontrePos;
	 		 
	 		 Evalunitpos encontreEvalProcesses;
	 		 Evalunits encontreEvalUnits;
	 		 
	 		 int valor = idparametroEval;
	 		 int valor2 = idparametroEvalRecord;
	 		 int idmensaje=0; 
	 		 String sessionid = request.getHeader("Authorization");
	 		 String queryUpdate;
	 		  Date fecha = new Date();
	 		    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 	        String dataFormattata = formatter.format(fecha);
	 	        Date fechaDate = formatter.parse(dataFormattata);
	 	        AuditRequestDto  auditDto=new AuditRequestDto();
	 	        boolean existeRec = false;	       	       	  		
	 		   Date fecha2 = new Date();
	 		   Calendar calendar = Calendar.getInstance();
	 	
	 		 
	 			if (sessionid==null) {
	 				String var = "";
	 				boolean bloked = false;
	 				RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 				//respuestaDto.setBlocked(bloked);
	 				respuestaDto.setMsg("Llamada al servicio malformado");
	 				//Error 400
	 				return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
	 			} else   {
	 				
	 				//int statusCampaigns =campaignsRepository.findStatusCampaignByProcessId(evalprocessid);
	 			 
	 				int statusCampaigns =campaignsRepository.findStatusCampaignByEvalUnitId(evalprocessid);
	 				//int statusCampaigns = 3;
					 if (statusCampaigns==0) {
						 
						 String var = "";
							boolean bloked = false;
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							//respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("No tiene los privilegios");
							//Error 400
							return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
						 
					  } 
	 				
	 				  if (datosEvalUnits.getPositionid()==0) {
	 					  String var = "";
	 						boolean bloked = false;
	 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 						//respuestaDto.setBlocked(bloked);
	 						respuestaDto.setMsg("Llamada al servicio malformado");
	 						//Error 400
	 						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
	 					  
	 				  }
	 				  
	 				  
	 				  boolean valid1 = esEnteroPositivo(datosEvalUnits.getRange01());
	 				  boolean valid2 = esEnteroPositivo(datosEvalUnits.getRange02());
	 				  boolean valid3 = esEnteroPositivo(datosEvalUnits.getRange03());
	 				  boolean valid4 = esEnteroPositivo(datosEvalUnits.getRange04());
	 				  boolean valid5 = esEnteroPositivo(datosEvalUnits.getRange05());
	 				  boolean valid6 = esEnteroPositivo(datosEvalUnits.getRange06());
	 				  boolean valid7 = esEnteroPositivo(datosEvalUnits.getRange07());
	 				  boolean valid8 = esEnteroPositivo(datosEvalUnits.getRange08());
	 				  boolean valid9 = esEnteroPositivo(datosEvalUnits.getRange09());
	 				  boolean valid10 = esEnteroPositivo(datosEvalUnits.getRange10());
	 				  boolean valid11 = esEnteroPositivo(datosEvalUnits.getRange11());
	 				  
	 				 if (valid1==false || valid2==false || valid3==false || valid4==false|| valid5==false || valid6==false || valid7==false || valid8==false || valid9==false || valid10==false || valid11==false) {
	 					  
	 					 String var = "";
	 						boolean bloked = false;
	 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 						//respuestaDto.setBlocked(bloked);
	 						respuestaDto.setMsg("Llamada al servicio malformado - Valores deben ser enteros positivos.");
	 						//Error 400
	 						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
					  
	 				  }
	 				  
	 				  
	 				  
	 				  
	 				//Integer.compare(a, b)
	 				  //validacion de los totales por rango el 02 no puedes ser mayor que el 01, el 03 no puede ser mayor al 02 y asi sucesivamente
	 				  Integer compa1 = Integer.compare(datosEvalUnits.getRange01(), datosEvalUnits.getRange02());
	 				  Integer compa2 = Integer.compare(datosEvalUnits.getRange02(), datosEvalUnits.getRange03());
	 				  Integer compa3 = Integer.compare(datosEvalUnits.getRange03(), datosEvalUnits.getRange04());
	 				  Integer compa4 = Integer.compare(datosEvalUnits.getRange04(), datosEvalUnits.getRange05());
	 				  Integer compa5 = Integer.compare(datosEvalUnits.getRange05(), datosEvalUnits.getRange06());
	 				  Integer compa6 = Integer.compare(datosEvalUnits.getRange06(), datosEvalUnits.getRange07());
	 				  Integer compa7 = Integer.compare(datosEvalUnits.getRange07(), datosEvalUnits.getRange08());
	 				  Integer compa8 = Integer.compare(datosEvalUnits.getRange08(), datosEvalUnits.getRange09());
	 			  	  Integer compa9 = Integer.compare(datosEvalUnits.getRange09(), datosEvalUnits.getRange10());
	 				  Integer compa10 = Integer.compare(datosEvalUnits.getRange10(), datosEvalUnits.getRange11());
	 				  
	 				 //validacion de las personas claves antes el total del staff, no puede ser mayor el clave al total
	 				  Integer compatotalkey = Integer.compare(datosEvalUnits.getQtytotal(), datosEvalUnits.getQtykey());
	 				  
	 				  if (compatotalkey==-1) {
	 					  
	 					  
		 					 String var = "";
		 						boolean bloked = false;
		 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
		 						//respuestaDto.setBlocked(bloked);
		 						respuestaDto.setMsg("Llamada al servicio malformado - Personal clave superior a la Plantilla.");
		 						//Error 400
		 						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
	 					  
	 				  }
	 				  
	 				  //Integer compa11 = Integer.compare(datosEvalUnits.getRange01(), datosEvalUnits.getRange02());
	 				
	 				  if (compa1==1 || compa2==1 || compa3==1 || compa4==1 || compa5==1 || compa6==1 || compa7==1 || compa8==1 || compa9==1 || compa10==1 ) {
	 					  
	 					 String var = "";
	 						boolean bloked = false;
	 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 						//respuestaDto.setBlocked(bloked);
	 						respuestaDto.setMsg("Llamada al servicio mal formado");
	 						//Error 400
	 						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
	 					  
	 				  }
	 				  
	 				
	 				  boolean existeEvalidApp =  evalunitsRepository.existsById(idparametroEval);
					   if (!existeEvalidApp) {
						   String var = "";
							boolean bloked = false;
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							//respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("Llamada al servicio mal formado");
							//Error 400
							return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
				    	  
				       } 		
	 				
	 				 
	 				   sessionid = sessionid.substring(7);
	 				   encontreSessionUsuario =usersRepository.getBySessionid(sessionid);
	 		           String fechaComoCadena;
	 				   
	 				   if (encontreSessionUsuario.isPresent()) {
	 					   
	 					   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 
	   					   //Llamada a la funcion que validad el tiempo de Session, retorna la fecha sumandole el tiempo de session activa, y vacio si no esta activa
	   					   
	   					  //  fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2);
	   					   fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
	   					    if (fechaComoCadena=="") {  						     						   
	   						   
	   						   String var = "";
	   							boolean bloked = false;
	   							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	   							//respuestaDto.setBlocked(bloked);
	   							respuestaDto.setMsg("Sesión expirada o inválida"); 
	   							return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
	   						   
	   					    }
	   					    
	   					  if (datosEvalUnits.getQtykey()==0 &&
	 								 datosEvalUnits.getCondition()!="") {
									respuesta.setMsg("Condición Clave debe estar vacía");
									estatus = HttpStatus.BAD_REQUEST;
									return new ResponseEntity(respuesta, estatus);
								}
						
	   					   
	 					 //Actualiza o Incluye un registro de un usuario. (Si el unitid es 0 se incluye). (priv 111 MOD Y 112 INC)
	 					   if (idparametroEvalRecord==0) {
	 						   
	 					 	   Roles roles = encontreSessionUsuario.get().getRolid();
	 						   int idrol = roles.getId();
	 						   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol,212);
	 						//  rolisvalid = 3;
	 						   if (rolisvalid==0) {
	 							   
	 							   String var = "";
	 								boolean bloked = false;
	 								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 								//respuestaDto.setBlocked(bloked);
	 								respuestaDto.setMsg("No tiene los Privilegios"); 
	 								return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
	 							   
	 						     }
	 						
	 						   
	 					   } else {
	 						   //EvalunitposRepository
	 						  existeRec =  evalunitposRepository.existsById(idparametroEvalRecord);
	 						   if (!existeRec) {
	 					    	    String var = "";
	 								boolean bloked = false;
	 								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 								//respuestaDto.setBlocked(bloked);
	 								respuestaDto.setMsg("Registro no encontrado"); 
	 								return new ResponseEntity(respuestaDto, HttpStatus.NOT_FOUND);
	 					    	  
	 					      } 	
	 						   
	 						   
	 						
	 						   
	 					   
	 					   Roles roles = encontreSessionUsuario.get().getRolid();
	 					   int idrol = roles.getId();
	 					   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol,211);
	 					   
	 					  // rolisvalid = 3;
	 					   if (rolisvalid==0) {
	 						   
	 						   String var = "";
	 							boolean bloked = false;
	 							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 							//respuestaDto.setBlocked(bloked);
	 							respuestaDto.setMsg("No tiene los Privilegios"); 
	 							return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
	 						   
	 					     }
	 					   } 					   					 											 
	 						 
	 					  
						    String SalidaCond= usersService.verificarCaracteresValidosConRegex(datosEvalUnits.getCondition());
						    String SalidaNota = usersService.verificarCaracteresValidosConRegex(datosEvalUnits.getNote());
						   // String SalidaCod = usersService.verificarCaracteresValidosConRegex(datosUnidad.getRef());
						    
						    if (SalidaCond=="NOOK" || SalidaNota=="NOOK") {
								  String var = "";
									boolean bloked = false;
									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
									//respuestaDto.setBlocked(bloked);
									respuestaDto.setMsg("Caracteres no permitidos en la busqueda"); 
									return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
							  }  
	 				   
	 				 } else {
	 						String var = "";
	 						boolean bloked = false;
	 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 						//respuestaDto.setBlocked(bloked);
	 						respuestaDto.setMsg("Sesión expirada o inválida");
	 						//Error 400
	 						return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
	 				 }
	 			}
	 			
	 			
	 		
	 		try {
	 			String valorParamsStraDepe = "";					 				  				
	 			if (idparametroEvalRecord==0) {
	 							
	 				Evalunitpos evalunitRec = new Evalunitpos();
	 				
	 				
	 				try {
	 					
	 					 // encontreEvalProcessesApp;
	 					encontreEvalUnits = evalunitsRepository.getById(idparametroEval);
	 					encontrePos = positionsRepository.getById(datosEvalUnits.getPositionid());
	 					 
	 					
	 					//evalunitRec.setEvalprocessid(encontreEvalProcesses);
	 					evalunitRec.setEvalunitid(encontreEvalUnits);
	 					evalunitRec.setPositionid(encontrePos);
	 					evalunitRec.setCondition(datosEvalUnits.getCondition());
	 					evalunitRec.setNote(datosEvalUnits.getNote());
	 					evalunitRec.setQtykey(datosEvalUnits.getQtykey());
	 					evalunitRec.setQtytotal(datosEvalUnits.getQtytotal());
	 					evalunitRec.setQtyrange1(datosEvalUnits.getRange01());
	 					evalunitRec.setQtyrange2(datosEvalUnits.getRange02());
	 					evalunitRec.setQtyrange3(datosEvalUnits.getRange03());
	 					evalunitRec.setQtyrange4(datosEvalUnits.getRange04());
	 					evalunitRec.setQtyrange5(datosEvalUnits.getRange05());
	 					evalunitRec.setQtyrange6(datosEvalUnits.getRange06());
	 					evalunitRec.setQtyrange7(datosEvalUnits.getRange07());
	 					evalunitRec.setQtyrange8(datosEvalUnits.getRange08());
	 					evalunitRec.setQtyrange9(datosEvalUnits.getRange09());
	 					evalunitRec.setQtyrange10(datosEvalUnits.getRange10());
	 					evalunitRec.setQtyrange11(datosEvalUnits.getRange11());
	 					evalunitRec.setCreatedat(fechaDate);
	 					evalunitRec.setModifiedat(fechaDate);
	 					
	 					evalunitposRepository.save(evalunitRec);
	 					
	 					int maxiInsertado = evalunitposRepository.getMaxRecord();
	 					//int idInsertado =  nuevoinsertado.get().getId();
	 					idmensaje = maxiInsertado;
	 					//Connection conexion = null;
	 					Connection conexion2 = DriverManager.getConnection(conexion,userbd, passbd);
	 					//(PreparedStatement sentenciaPreparada = conexion2.prepareStatement(sql))
	 					Statement sentenciaPreparada = null;
	 					sentenciaPreparada = conexion2.createStatement();
	 					 
	   
	 			         
	 			        //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////
	 				     String module = "Evaluación por Unidad";
	 				     String Descmodule = "Se agregó Cargo en Evaluación de Unidad con Id: " + idmensaje;
	 				    
	 			         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());			        
	 			         
	 			         String singo1 = "(";
	 			         String singo2 = ")";
	 			         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
	 			         auditDto.setUserref(usryemail);
	 			         auditDto.setModule(module);
	 			         auditDto.setDesc(Descmodule);
	 			         auditDto.setCreatedat(fechaDate);
	 			 		   usersService.registrarAuditSesion(auditDto); 
	 			 		   
	 						respuestaValueDto= new RespuestaValueDto(idmensaje);
	 					
	 						estatus=HttpStatus.OK;
	 						return new ResponseEntity(respuestaValueDto, estatus);
	                     	
	 			     } catch (DataIntegrityViolationException ex) {
				    	    Throwable rootCause = ex.getRootCause();
				    	    String mensajeError = "Error al guardar.";
				    	    HttpStatus estatusError = HttpStatus.CONFLICT;

				    	    if (rootCause instanceof SQLException) {
				    	        SQLException sqlEx = (SQLException) rootCause;
				    	        if (sqlEx.getSQLState() != null && sqlEx.getSQLState().equals("23505")) {
				    	            mensajeError = "Registro Duplicado.";
				    	        } else {
				    	           // mensajeError = "Error de base de datos: " + sqlEx.getMessage();
				    	            mensajeError = "Registro Duplicado: ";
				    	            estatusError = HttpStatus.CONFLICT; // O el estatus que consideres apropiado
				    	            ex.printStackTrace(); // Loguea la excepción para depuración
				    	        }
				    	    } else {
				    	     //   mensajeError = "Registro Duplicado: " + ex.getMessage();
				    	    	 mensajeError = "Registro Duplicado: ";
				    	        estatusError = HttpStatus.CONFLICT; // O el estatus que consideres apropiado
				    	        ex.printStackTrace(); // Loguea la excepción para depuración
				    	    }

				    		respuesta= new RespuestaMsgDto(mensajeError);
							estatus=estatusError;
							return new ResponseEntity(respuesta, estatus);

				} catch (Exception e) {
				    	    respuesta= new RespuestaMsgDto("Error interno del servidor: " + e.getMessage());
							estatus=HttpStatus.INTERNAL_SERVER_ERROR;
							e.printStackTrace(); // Loguea la excepción para depuración
							return new ResponseEntity(respuesta, estatus);
				}
	 				
	 		        
	 	         

	 			} else {
	 				
	 				//Strategiesdet strategies = new Strategiesdet();
	 				//Strategiesdet strategies2 = new Strategiesdet();
	 				Evalunitpos evalprocRec;
	 		
	 				
	 		
	 				try {
	 					
	 					 // encontreEvalProcessesApp;
	 					encontreEvalUnits = evalunitsRepository.getById(idparametroEval);
	 					 // encontreApp = applicationsRepository.getById(datosEvalProcesses.getApplicationid());
	 				     evalprocRec = evalunitposRepository.getById(valor2);
	 				
	 				    int maxiInsertado = evalprocRec.getId();
	 				    
	 				
	 				    
	 					encontreEvalUnits = evalunitsRepository.getById(idparametroEval);
	 					encontrePos = positionsRepository.getById(datosEvalUnits.getPositionid());
	 					 
	 					
	 					//evalunitRec.setEvalprocessid(encontreEvalProcesses);
	 					evalprocRec.setEvalunitid(encontreEvalUnits);
	 					evalprocRec.setPositionid(encontrePos);
	 					evalprocRec.setCondition(datosEvalUnits.getCondition());
	 					evalprocRec.setNote(datosEvalUnits.getNote());
	 					evalprocRec.setQtykey(datosEvalUnits.getQtykey());
	 					evalprocRec.setQtytotal(datosEvalUnits.getQtytotal());
	 					evalprocRec.setQtyrange1(datosEvalUnits.getRange01());
	 					evalprocRec.setQtyrange2(datosEvalUnits.getRange02());
	 					evalprocRec.setQtyrange3(datosEvalUnits.getRange03());
	 					evalprocRec.setQtyrange4(datosEvalUnits.getRange04());
	 					evalprocRec.setQtyrange5(datosEvalUnits.getRange05());
	 					evalprocRec.setQtyrange6(datosEvalUnits.getRange06());
	 					evalprocRec.setQtyrange7(datosEvalUnits.getRange07());
	 					evalprocRec.setQtyrange8(datosEvalUnits.getRange08());
	 					evalprocRec.setQtyrange9(datosEvalUnits.getRange09());
	 					evalprocRec.setQtyrange10(datosEvalUnits.getRange10());
	 					evalprocRec.setQtyrange11(datosEvalUnits.getRange11());
	 					evalprocRec.setCreatedat(fechaDate);
	 					evalprocRec.setModifiedat(fechaDate);
	 					
	 					evalunitposRepository.save(evalprocRec);
					
	 					//int maxiInsertado = evalprocappsRepository.getMaxRecord();
	 					idmensaje = maxiInsertado;
	 					//Connection conexion = null;
	 					Connection conexion2 = DriverManager.getConnection(conexion,userbd, passbd);
	 					//(PreparedStatement sentenciaPreparada = conexion2.prepareStatement(sql))
	 					Statement sentenciaPreparada = null;
	 					sentenciaPreparada = conexion2.createStatement();
	 					 					            
	 			
	 			    //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////
	 			     String module = "Evaluación por Unidad";
	 			     //String Descmodule = "Actualización de parametro del Sistema con id: " + parmid  ;
	 			     String Descmodule = "Se actualizó Cargo en Evaluación de Unidad con Id: " + idmensaje;
	 			    
	 		         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());			        
	 		         
	 		         String singo1 = "(";
	 		         String singo2 = ")";
	 		         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
	 		         auditDto.setUserref(usryemail);
	 		         auditDto.setModule(module);
	 		         auditDto.setDesc(Descmodule);
	 		         auditDto.setCreatedat(fechaDate);
	 		 		   usersService.registrarAuditSesion(auditDto); 
	 		 		  //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////	
	 		 		   // SE ENVIA LA RESPUESTA QUE PIDE EL SERVICIO
	 		 			//String Resp = idinsertado.toString();
	 					respuestaValueDto= new RespuestaValueDto(idmensaje);
	 					//int parmid = 2;
	 					//respuestaValueDto= new RespuestaValueDto(userid);
	 					estatus=HttpStatus.OK;
	 					return new ResponseEntity(respuestaValueDto, estatus);
	 					
	             
	                  
	                  
	 		   	 }  catch (DataIntegrityViolationException ex) {
			    	    Throwable rootCause = ex.getRootCause();
			    	    String mensajeError = "Error al guardar.";
			    	    HttpStatus estatusError = HttpStatus.CONFLICT;

			    	    if (rootCause instanceof SQLException) {
			    	        SQLException sqlEx = (SQLException) rootCause;
			    	        if (sqlEx.getSQLState() != null && sqlEx.getSQLState().equals("23505")) {
			    	            mensajeError = "Registro Duplicado.";
			    	        } else {
			    	           // mensajeError = "Error de base de datos: " + sqlEx.getMessage();
			    	            mensajeError = "Registro Duplicado: ";
			    	            estatusError = HttpStatus.CONFLICT; // O el estatus que consideres apropiado
			    	            ex.printStackTrace(); // Loguea la excepción para depuración
			    	        }
			    	    } else {
			    	     //   mensajeError = "Registro Duplicado: " + ex.getMessage();
			    	    	 mensajeError = "Registro Duplicado: ";
			    	        estatusError = HttpStatus.CONFLICT; // O el estatus que consideres apropiado
			    	        ex.printStackTrace(); // Loguea la excepción para depuración
			    	    }

			    		respuesta= new RespuestaMsgDto(mensajeError);
						estatus=estatusError;
						return new ResponseEntity(respuesta, estatus);

			} catch (Exception e) {
			    	    respuesta= new RespuestaMsgDto("Error interno del servidor: " + e.getMessage());
						estatus=HttpStatus.INTERNAL_SERVER_ERROR;
						e.printStackTrace(); // Loguea la excepción para depuración
						return new ResponseEntity(respuesta, estatus);
			}
	 		
	 	  }				
	        
	 		}catch (Exception e) {
	             // Manejo de excepciones
	 			respuesta= new RespuestaMsgDto("Error interno del servidor");
	 			estatus=HttpStatus.INTERNAL_SERVER_ERROR;            
	         }
	 		
	 		return new ResponseEntity(respuesta, estatus);
	 	
	 	}

  //evalunits/evalunitid/positions/evalunitposid
	  @DeleteMapping("/evalunits/{evalunitid}/positions/{evalunitposid}")
	     public ResponseEntity<?> deleteEvalUnitPos(HttpServletRequest request, @PathVariable("evalunitid") final Integer evalunitid,@PathVariable("evalunitposid") final Integer evalunitposid) throws ParseException {
	 		
	 		RespuestaValueDto respuestaValueDto;
	 		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
	 		HttpStatus estatus = HttpStatus.FORBIDDEN;
	 		ParamsResponseDto paramsResponseDto = new ParamsResponseDto();
	 		ParamsDto detalleParams;
	 		PrivilegesDto detallePrivilege;
	 	     List<ParamsDto> listasParams = new ArrayList<>();
	 	     List<PrivilegesDto> listasPrivelege = new ArrayList<>();
	 	         String queryInsertProcesses = "";
	 	         String queryInsertUnidades= "";
	 	         
	 		 int idparametroEval = evalunitid;
	 		 int idparametroEvalRec = evalunitposid;
	 		 
	 		 Optional<Users> encontreSessionUsuario;
	 		 Optional<Evalprocapps> encontreEvalProcessesApp;
	 		 Applications encontreApp;
	 		 
	 		 Evalprocesses encontreEvalProcesses;
	 		 
	 		 int valor = idparametroEval;
	 		 int valor2 = idparametroEvalRec;
	 		 int idmensaje=0; 
	 		 String sessionid = request.getHeader("Authorization");
	 		 String queryUpdate;
	 		  Date fecha = new Date();
	 		    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 	        String dataFormattata = formatter.format(fecha);
	 	        Date fechaDate = formatter.parse(dataFormattata);
	 	        AuditRequestDto  auditDto=new AuditRequestDto();
	 	        boolean existeApp = false;	       	       	  		
	 		   Date fecha2 = new Date();
	 		   Calendar calendar = Calendar.getInstance();
	 	
	 		 
	 			if (sessionid==null) {
	 				String var = "";
	 				boolean bloked = false;
	 				RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 				//respuestaDto.setBlocked(bloked);
	 				respuestaDto.setMsg("Llamada al servicio malformado");
	 				//Error 400
	 				return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
	 			} else   {
	 				
	 			//	int statusCampaigns =campaignsRepository.findStatusCampaignByProcessId(evalunitid);
	 				int statusCampaigns =campaignsRepository.findStatusCampaignByEvalUnitId(evalunitid);
	 				statusCampaigns = 3;
					 if (statusCampaigns==0) {
						 
						 String var = "";
							boolean bloked = false;
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							//respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("No tiene los privilegios");
							//Error 400
							return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
						 
					  } 
	 								 
	 				   sessionid = sessionid.substring(7);
	 				   encontreSessionUsuario =usersRepository.getBySessionid(sessionid);
	 			       String fechaComoCadena;
	 				   
	 				   if (encontreSessionUsuario.isPresent()) {
	 					   
	 					   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 
	   					   //Llamada a la funcion que validad el tiempo de Session, retorna la fecha sumandole el tiempo de session activa, y vacio si no esta activa
	   					   
	   					   fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
	   					    if (fechaComoCadena=="") {  						     						   
	   						   
	   						   String var = "";
	   							boolean bloked = false;
	   							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	   							//respuestaDto.setBlocked(bloked);
	   							respuestaDto.setMsg("Sesión expirada o inválida"); 
	   							return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
	   						   
	   					    }
	   					   
	 					 //Actualiza o Incluye un registro de un usuario. (Si el unitid es 0 se incluye). (priv 111 MOD Y 112 INC)
	   				    //		 int idparametroEval = evalprocessid;
	   					//	 int idparametroEvalApp = evalprocappid;
	   					    
	   					  boolean existeEvalidUni =  evalunitsRepository.existsById(idparametroEval);
	 					   if (!existeEvalidUni) {
	 				    	    String var = "";
	 							boolean bloked = false;
	 							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 							//respuestaDto.setBlocked(bloked);
	 							respuestaDto.setMsg("Registro no encontrado"); 
	 							return new ResponseEntity(respuestaDto, HttpStatus.NOT_FOUND);
	 				    	  
	 				       } 		
	 				   
	 					   
	 						   boolean existeEvalidPosi =  evalunitposRepository.existsById(idparametroEvalRec);
	 						   if (!existeEvalidPosi) {
	 					    	    String var = "";
	 								boolean bloked = false;
	 								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 								//respuestaDto.setBlocked(bloked);
	 								respuestaDto.setMsg("Registro no encontrado"); 
	 								return new ResponseEntity(respuestaDto, HttpStatus.NOT_FOUND);
	 					    	  
	 					       } 		
	 					   
	 					   Roles roles = encontreSessionUsuario.get().getRolid();
	 					   int idrol = roles.getId();
	 					   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol,213);
	 					  //  rolisvalid = 3;
	 					   if (rolisvalid==0) {
	 						   
	 						   String var = "";
	 							boolean bloked = false;
	 							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 							//respuestaDto.setBlocked(bloked);
	 							respuestaDto.setMsg("No tiene los Privilegios"); 
	 							return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
	 						   
	 					     }
	 					   					   					 											 
	 						 	
	 				   
	 				 } else {
	 						String var = "";
	 						boolean bloked = false;
	 						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
	 						//respuestaDto.setBlocked(bloked);
	 						respuestaDto.setMsg("Sesión expirada o inválida");
	 						//Error 400
	 						return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
	 				 }
	 			}
	 			
	 			
	 		
	 		try {
	 			

	 			         Evalunitpos evalprocRec;								
	 			         evalunitposRepository.deleteEvalunitPosibyid(evalunitposid);
	 			
	 			 
	 			        //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////
	 				     String module = "Evaluación por Unidad";
	 				     String Descmodule = "Se Elimino Cargo en Evaluación de Unidad con Id: " + evalunitposid;
	 				    
	 			         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());			        
	 			         
	 			         String singo1 = "(";
	 			         String singo2 = ")";
	 			         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
	 			         auditDto.setUserref(usryemail);
	 			         auditDto.setModule(module);
	 			         auditDto.setDesc(Descmodule);
	 			         auditDto.setCreatedat(fechaDate);
	 			 		   usersService.registrarAuditSesion(auditDto); 
	 			 		   
	 						respuestaValueDto= new RespuestaValueDto(evalunitposid);
	 					
	 						estatus=HttpStatus.OK;
	 						return new ResponseEntity(respuestaValueDto, estatus);                    					        	         

	 		
	        
	 		   } catch (Exception e) {
	             // Manejo de excepciones
	 			respuesta= new RespuestaMsgDto("Error interno del servidor");
	 			estatus=HttpStatus.INTERNAL_SERVER_ERROR;            
	         }
	 		
	 		return new ResponseEntity(respuesta, estatus);
	 	
	 	}
	  
	  public static boolean esEnteroPositivo(int numero) {
	        return numero >= 0;
	    }
	  
	  public static boolean esEnteroPositivo(double numero) {
	        return numero > 0 && numero == Math.floor(numero);
	    }
	
}
