Calculate assistances, faults, delays in PHP

3

I want to calculate the attendances, faults and delays of ALL the employees that return the function buscarEmpleados() from a date A and a date B which are received in $dates1 and $dates2

buscarEmpleados returns a list of NoEmpleados or idClaves

the idclave that I return, I want to send it as a parameter to other functions, for example: consultarFecha($empleado,$tdate); I have defined a foreach that runs buscarEmpleados() to bring the NoEmpleados , however it is not doing it correct way, since in my table only brings me a single NoEmpleado and does not make the corresponding calculations.

The code works when it is a single NoEmpleado , but I have not managed to do it with more than 1

Code to calculate with all employees:

public $idclave;
public $fktipo;


public function buscarEmpleados()
    {


    $res = array("idclave"=>"","FechaIng"=>"");
    $i = 0;

    $stmt = sqlsrv_query($this->conn,"select * FROM tblpersonal ");

    if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
    }



    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {


       //$res[$i] = $row['idClave'];


        $this->idclave = $row['idClave'];
        $this->tipo = $row['fkTipo'];

       $i++;


    }


    sqlsrv_free_stmt($stmt);

     return $res;

    }

Code for calculating delays, faults, etc.:

<?php

$dates1 = strtotime($_POST['date1']); 
$dates2 = strtotime($_POST['date2']);   
$turno = array();


$horas = 0;
$festivo = false;
$festlab = 0; 

$datediff = $dates2 - $dates1;
$datedifdays = ($datediff/(60*60*24));
$descanso = 0;
$asistencias = 0;
$faltas = 0;
$horasextra = 0;
$festivotrabajado = 0;
$retardos = 0;
$diff_in_min = 0;
$deslab = 0;
$tolerancia = 0;
$permisos = 0;





include("horarios.php");
$numemp = array();



$numemp = $emp->buscarEmpleados();


foreach ($numemp as $empleado) {


    switch($emp->tipo)
{

    case 8:
    $tolerancia = -10;
    break;

    case 9:
    $tolerancia = -6;
    break;

    case 10:
    $tolerancia = -10;
    break;
}




    $val1 = $emp->idclave; ///Me retorna el NoEmpleado
    $val2 = $emp->tipo; ///Me retorna el tipo

    echo "Soy clave1",$val1; //Impresión
    echo "Soy clave2",$val2; //Impresión

    for ($i=0;$i<=$datedifdays;$i++){

    $date = new DateTime($_POST['date1']);
    $date->modify('+'.$i.' day');
    $dia = $date->format('l');




    if (in_array($dia,$turno))
    {



        $tdate = date_format($date, 'd-m-Y') . ' '; 
        $tdate = trim($tdate);  

        $arr = $db->consultarFecha($empleado,$tdate);

        $entrada = $arr["fechaEntrada"];
        $salida =  $arr["fechaSalida"];     

        $fest = array();
        $fest = $db->consultarFestivo($tdate);

        if ($fest["observacion"] != "")
        {
            $festivo = true;

        }else{
            $festivo = false;
        }


        $entr = new DateTime($entrada); 

            //retardo

        if ($entrada  == "" )
        {


            $permiso = array();
            $permiso = $db->consultarPermiso($empleado,$tdate);

            if($permiso["razon"] != "")
            {

                $permiso++;

            }else
            {

                if($festivo == false) 
                {
                    $faltas++;
                }


            }

        }


        if ($entrada != "" )        

        {

            $entrada1 = $entrada;
            $horaentrada = $date->format('d-m-Y') . " " . $ent; 
            $diffe = strtotime($horaentrada) - strtotime($entrada1);
            $diff_in_min = $diffe/60;               

            if($festivo == true) 
            {
                $festlab++;
            }


            $diff = strtotime($salida) - strtotime($entrada);
            $diff_in_hrs = $diff/3600;


        // calculamos sumario           

            $asistencias++;

            if (round($diff_in_hrs)  > $horas)
            {
                $horasextra +=  (round($diff_in_hrs)  - $horas );
            }


            if (round($diff_in_min)  < $tolerancia)
            {
                $retardos++;
            }

        }else
        {

        $tdate = date_format($date, 'd-m-Y'); 
        $tdate = trim($tdate);  
        $arr = $db->consultarFecha($empleado,$tdate);
        $entrada = $arr["fechaEntrada"];
        $salida =  $arr["fechaSalida"];         
        $entr = new DateTime($entrada); 


        if ($entrada != "" )        

        {

            $deslab++;

            $entrada1 = $entrada;
            $horaentrada = $date->format('d-m-Y') . " " . $ent; 
            $diffe = strtotime($horaentrada) - strtotime($entrada1);
            $diff_in_min = $diffe/60;               


            $diff = strtotime($salida) - strtotime($entrada);
            $diff_in_hrs = $diff/3600;

            if (round($diff_in_hrs)  > $horas)
            {
                $horasextra +=  (round($diff_in_hrs)  - $horas );
            }


            if (round($diff_in_min)  < $tolerancia)
            {

         // $retardos++;

            }

        }
        //echo "Descanso <br />";
        $descanso++;

    }
}


} 

?>
<table id="example" class="table table-striped table-bordered" >
    <thead>

        <tr>
            <th>Empleado</th>
            <th>Nombre</th>
            <th>Puesto</th>
            <th>Tipo</th>
            <th>Turno</th>
            <th>Supervisor</th>
            <th>Asistencia</th>
            <td>Faltas</td>
            <td>Retardos </td>
            <!--
            <th>Información </th>
            -->
        </tr>
    </thead>
    <tbody>

        <tr class="success">
            <td><?php  echo $empleado; ?></td>
            <td><?php echo $asistencias; ?></td>
            <td><?php echo $faltas; ?></td>

            <td><?php echo $retardos; ?></td>

        </tr>

    </tbody>
</table>

<?php

}


?>  

Code to calculate with a single employee:

Function searching for a specific node

public function buscarId($empno)
{

    $res = array();


         $stmt = sqlsrv_query($this->conn,"select p.*,e.Descripcion as Tipo,de.* from tblpersonal  
        JOIN tbldescanso de on p.idClave = de.idclave WHERE p.idclave ='". $empno."'  ");

    if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
    }

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {

    //General information 

        $this->idclave = $row['idClave'];
        $this->fktipo = $row['fkTipo'];




    }

    sqlsrv_free_stmt($stmt);
}


<?php

$db = new database();
$emp = new empleado();

$dates1 = strtotime($_POST['date1']);  // Obtenemos las dos Fechas
$dates2 = strtotime($_POST['date2']);   
$turno = array();

$empl = $_REQUEST['empno'];// Dato desde un campo de texto
$horas = 0;
$festivo = false;
$festlab = 0; 

$datediff = $dates2 - $dates1;
$datedifdays = ($datediff/(60*60*24));
$descanso = 0;
$asistencias = 0;
$faltas = 0;
$horasextra = 0;
$festivotrabajado = 0;
$retardos = 0;
$diff_in_min = 0;
$deslab = 0;
$tolerancia = 0;
$permisos = 0;

//** Obtenemos los datos del empleado 
$emp->buscarId($empl);

$nombre = $emp->nombre;
$idturno = $emp->idturno;
$puesto = "";
$evento = "";




switch($emp->tipo)
{

    case 8:
    $tolerancia = -10;
    break;

    case 9:
    $tolerancia = -6;
    break;

    case 10:
    $tolerancia = -10;
    break;


}

//Configuramos detalles turno, horario y horas trabajadas
//Carga configuración de horarios 



include("horarios.php");


for ($i=0;$i<=$datedifdays;$i++)
{

    $date = new DateTime($_POST['date1']);
    $date->modify('+'.$i.' day');
    $dia = $date->format('l');



    if (in_array($dia,$turno))
    {

        $tdate = date_format($date, 'd-m-Y') . ' '; 
        $tdate = trim($tdate);  

        $arr = $db->consultarFecha($empl,$tdate);

        $entrada = $arr["fechaEntrada"];
        $salida =  $arr["fechaSalida"];     

        $fest = array();
        $fest = $db->consultarFestivo($tdate);

        if ($fest["observacion"] != "")
        {
            $festivo = true;

        }else{
            $festivo = false;
        }


        $entr = new DateTime($entrada); 

            //retardo

        if ($entrada  == "" )
        {


            $permiso = array();
            $permiso = $db->consultarPermiso($empl,$tdate);

            if($permiso["razon"] != "")
            {

                $permiso++;

            }else
            {

                if($festivo == false) 
                {
                    $faltas++;
                }


            }

        }


        if ($entrada != "" )        

        {

            $entrada1 = $entrada;
            $horaentrada = $date->format('d-m-Y') . " " . $ent; 
            $diffe = strtotime($horaentrada) - strtotime($entrada1);
            $diff_in_min = $diffe/60;               

            if($festivo == true) 
            {
                $festlab++;
            }


            $diff = strtotime($salida) - strtotime($entrada);
            $diff_in_hrs = $diff/3600;



            $asistencias++;

            if (round($diff_in_hrs)  > $horas)
            {
                $horasextra +=  (round($diff_in_hrs)  - $horas );
            }


            if (round($diff_in_min)  < $tolerancia)
            {
                $retardos++;
            }

        }else
        {

        $tdate = date_format($date, 'd-m-Y');
        $tdate = trim($tdate);  
        $arr = $db->consultarFecha($empl,$tdate);
        $entrada = $arr["fechaEntrada"];
        $salida =  $arr["fechaSalida"];         
        $entr = new DateTime($entrada); 


        if ($entrada != "" )        

        {

            $deslab++;

            $entrada1 = $entrada;
            $horaentrada = $date->format('d-m-Y') . " " . $ent; 
            $diffe = strtotime($horaentrada) - strtotime($entrada1);
            $diff_in_min = $diffe/60;               


            $diff = strtotime($salida) - strtotime($entrada);
            $diff_in_hrs = $diff/3600;

            if (round($diff_in_hrs)  > $horas)
            {
                $horasextra +=  (round($diff_in_hrs)  - $horas );
            }


            if (round($diff_in_min)  < $tolerancia)
            {


            }

        }
        $descanso++;

    }
}

}

?>              
<p>Fecha de Inicio: <?php echo $_POST['date1'];  ?>   </p>       
<p>Fecha final:  <?php echo $_POST['date2'];  ?>    </p>       



<table class="table">
    <thead>
        <tr>
            <th>Empleado</th>
            <th>asistencia</th>
            <th>faltas</th>
            <th>retardo </th>

        </tr>
    </thead>
    <tbody>

        <tr class="success">
            <td><?php echo $empleado; ?></td>
            <td><?php echo $asistencias; ?></td>

            <td><?php echo $faltas; ?></td>

            <td><?php echo $retardos; ?></td>

        </tr>

    </tbody>
</table>
    
asked by Noel L 06.04.2018 в 07:35
source

2 answers

1

Your problem is here:

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {

   //$res[$i] = $row['idClave'];

    $this->idclave = $row['idClave'];
    $this->tipo = $row['fkTipo'];

   $i++;

}

The variables idclave and type can only hold one value and each time the iterated loop overwrites them. The variables should be arrays to store multiple values.

    
answered by 06.04.2018 в 20:58
0

Given that, as your code seems to indicate, where the function buscarEmpleados is a Clase , the logical thing would be that this class had an attribute that is an array, and that it is in that array where you keep the different values organized.

Moreover, that class could handle an array of objects of type Empleado , where the results obtained from the database are mapped. That would be the most logical. But let's not get into that now. Let's try to solve the problem and if you are interested, read my last comment within the code ...

For now, we could solve it with something like this (I have commented the lines in your original code that I consider unnecessary):

//public $idclave;
//public $fktipo;
/*
    *Declaras un miembro en la clase que será el array final con los resultados
    *Lo declaras como private, para respetar la encapsulación, o sea, que el array
    *no pueda modificarse desde fuera de la clase
    *Esta misma función haría las veces de getter, en este caso concreto
    *retornando una representación completa del array
*/
private  $arrEmpleados=array();

public function buscarEmpleados()
    {


    //$res = array("idclave"=>"","FechaIng"=>""); Esto vendría a ser un miembro de la clase
    //$i = 0; Esto no es necesario

    $stmt = sqlsrv_query($this->conn,"select * FROM tblpersonal ");

    if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
    }

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {

       /*
            *Nótese que aquí, las claves del array serán los nombres de cada columna
            *en tu código dabas otro nombre a las claves... no sé por qué
            *de todos modos, puedes hacerlo, modificando la línea de más abajo
            *pero sería algo ilógico...
            *Nótese que esto tiene MUCHA IMPORTANCIA, A LA HORA DE LEER EL ARRAY
        */
        $this->arrEmpleados[]=$row;
    }

    sqlsrv_free_stmt($stmt);

     /*Aquí estarías retornando un array con cada resultado encontrado*/
     return $this->arrEmpleados;

    }

THEN , the code where you use the method, should be modified slightly:

include("horarios.php");
//$numemp = array(); No hace falta... me permitiré también usar un nombre más descriptivo

$arrEmpleados = $emp->buscarEmpleados();
foreach ($arrEmpleados as $empleado) {

    /*
        *Aquí supongo que en tblpersonal hay un columna llamada tipo
        *dado que la función retornó un array propiamente dicho
        *lo leemos como tal $empleado["tipo"], 
        *y no como una propiedad de la clase usando $emp["tipo"]
        *esto demuestra un claro error de diseño en tu código
    */

    /*
        *Más abajo, volvías a recuperar este valor en la variable $val2
        *así que la definimos aquí una sola vez y listo...
    */

    $tipo=$empleado["tipo"];
    switch($tipo)
    {

        case 8:
        $tolerancia = -10;
        break;

        case 9:
        $tolerancia = -6;
        break;

        case 10:
        $tolerancia = -10;
        break;
    }   

    /*
        *Como ya comenté más arriba, aquí suponemos que también en tblpersonal
        *hay una columna llamada idclave y otra llamada tipo
        *En una futura evolución de tu código, si quieres tenerlo más organizado
        *quizá convenga tener una clase que represente a los empleados, y llenar 
        *un array de objetos Empleado con sus propiedades
        *en mi respuesta a esta pregunta: https://es.stackoverflow.com/q/134253/29967
        *puedes ver un ejemplo de lo que digo
    */

    $val1 = $empleado["idclave"]; ///Me retorna el NoEmpleado
    //$val2 = $empleado["tipo"]; ///Me retorna el tipo

    echo "Soy clave1 ",$val1; //Impresión
    echo "Soy clave2 ",$tipo; //Impresión

    for ($i=0;$i<=$datedifdays;$i++){

    $date = new DateTime($_POST['date1']);
    $date->modify('+'.$i.' day');
    $dia = $date->format('l');

//resto del código
//cierre del foreach
    
answered by 14.04.2018 в 21:00