SuivisController.php 15.1 KB
<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;

/**
 * Suivis Controller
 *
 * @property \App\Model\Table\SuivisTable $Suivis
 */
class SuivisController extends AppController
{

	/**
	 * @param $user
	 *
	 * Give authorization for suivis
	 *
	 * @return boolean
	 */
	public function isAuthorized($user)
	{
		$configuration = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
		$role = TableRegistry::get('Users')->find()->where(['username' => $user[$configuration->authentificationType_ldap][0]])->first()['role'];
		 
		$action = $this->request->params['action'];
		 
		if($this->userHasRole('Administration')) return true;
		
		//Pour un "utilisateur"
		if (in_array($action, ['edit', 'delete'])) {
			$id = (int)$this->request->params['pass'][0];
			if($this->isOwnedBy($id, $user['sn'][0].' '.$user['givenname'][0])) return true;
			if($role == 'Responsable' && $this->isRespGroup($id, $user[$configuration->authentificationType_ldap][0])) return true;
		}
		 
		return parent::isAuthorized($user);
	}
	
	
	public function isOwnedBy($id, $nomCreateur)
	{
		return $this->Suivis->exists(['id' => $id, 'nom_createur' => $nomCreateur]);
	}

	public function isRespGroup($id, $loginResponsable)
	{
		$u = TableRegistry::get('Users')->find()->where(['username' => $loginResponsable])->first();
	
		if(isset($u['groupes_metier_id']) && $u['groupes_metier_id'] != TableRegistry::get('GroupesMetiers')->find()->where(['nom =' => 'N/A'])->first()['id']) {
			return ($this->Suivis->exists(['id' => $id, 'groupes_metier_id' => $u['groupes_metier_id']]));
		}
		else if (isset($u['groupe_thematique_id']) && $u['groupe_thematique_id'] != TableRegistry::get('GroupesThematiques')->find()->where(['nom =' => 'N/A'])->first()['id']) {
			return ($this->Suivis->exists(['id' => $id, 'groupes_thematique_id' => $u['groupe_thematique_id']]));
		}
		else {
			return false;
		}
	}
	
    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
    	$condition = '';
    
    	$GM = $this->request->query('GM');
    	$GT = $this->request->query('GT');
    	
    	if(isset($GM) || isset($GT)) {
    		if(isset($GM) && $GM != TableRegistry::get('GroupesMetiers')->find()->where(['nom =' => 'N/A'])->first()['id']) {
    			$condition = ['Suivis.groupes_metier_id =' => $GM];
    		}
    		else if (isset($GT) && $GT != TableRegistry::get('GroupesThematiques')->find()->where(['nom =' => 'N/A'])->first()['id']) {
    			$condition = ['Suivis.groupes_thematique_id =' => $GT];
    		}
    		else {
    			$condition = ['Suivis.id =' => 0];
    		}
    	}
    	
        $this->paginate = [
            'contain' => ['Materiels', 'TypeSuivis']
        ];
        $suivis = $this->paginate($this->Suivis->find('all', ['conditions' => $condition]));

        $this->set('nbSuivis', $this->Suivis->find('all', ['conditions' => $condition])->count());
        
        $this->set(compact('suivis'));
        $this->set('_serialize', ['suivis']);
    }

    /**
     * View method
     *
     * @param string|null $id Suivi id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $suivi = $this->Suivis->get($id, [
            'contain' => ['Materiels', 'Documents', 'TypeSuivis', 'GroupesThematiques', 'GroupesMetiers','Unites','Fichemetrologiques']
        ]);
		$typeDocuments = TableRegistry::get('TypeDocuments');
		$fichemet= TableRegistry::get('Fichemetrologiques')->find('all',['conditions' => [ 'suivi_id' => $this->passedArgs[0] ] ,'order' =>  ('id DESC')]);
		
		if($fichemet == null)
			$fiche = null;
		else
			$fiche = $fichemet->first();
		
		$this->set('typeDocuments', $typeDocuments);
		$this->set('suivi', $suivi);
		$this->set('fiche', $fiche);
        $this->set('_serialize', ['suivi']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $suivi = $this->Suivis->newEntity();
        if ($this->request->is('post')) {
            $suivi = $this->Suivis->patchEntity($suivi, $this->request->data);
			if($this->request->data['typemesure']=="1")
				$suivi->typemesure="Indirect";
            $suivi->panne_resolu = false;
            if ($this->Suivis->save($suivi)) {
                $this->Flash->success(__('Le suivi a bien été ajouté.'));
                return $this->redirect(['controller' => 'Materiels', 'action' => 'view', $this->passedArgs[0]]);
            } else {
                $this->Flash->error(__('Le suivi n\'a pas pu être ajouté.'));
				return $this->redirect(['controller' => 'Materiels', 'action' => 'view', $this->passedArgs[0]]);
            }
        }
        $materiels = $this->Suivis->Materiels->find('list');
        $unite = TableRegistry::get('Unites')->find('list', [ 'keyfield' => 'id', 'valueField' =>'nom']);
		$formule = TableRegistry::get('Formules')->find('list', [ 'keyfield' => 'id', 'valueField' =>'formule']);
		$formules = TableRegistry::get('Formules')->find('all');
        $metro = TableRegistry::get('Materiels')->find()->select('metrologie')->where(['id =' => $this->passedArgs[0]])->first()['metrologie'];
        $variables = TableRegistry::get('Variables')->find('list')->toArray();
		
		$materiel = $this->Suivis->Materiels->find()->where(['id =' => $this->passedArgs[0]])->first();
        //$domaineresp= TableRegistry::get('Users')->find()->select('sur_categorie_id')->where(['username =' => $this->LdapAuth->user($this->request->session()->read('authType'))[0]])->first()['sur_categorie_id'];
		if($metro ==1){
        $typeSuivis = $this->Suivis->TypeSuivis->find('list', [ 'keyField' => 'id', 'valueField' => 'nom']);
		}else{
		$typeSuivis = $this->Suivis->TypeSuivis->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'conditions' => [ 'AND' => [['id !=' => '4'] , ['id !=' => '5'], ['id !=' => '6']]]]);
        }
		$dom= TableRegistry::get('Materiels')->find()->select('sur_categorie_id')->where(['id =' => $materiel->id])->first()['sur_categorie_id'];
		$domaines= TableRegistry::get('Users')->find()->select('sur_categorie_id')->where(['username =' => $this->LdapAuth->user($this->request->session()->read('authType'))[0]])->first()['sur_categorie_id'];
		if($dom == $domaines)
			$domaineresp=true;
		else
			$domaineresp=false;
		
		
        $groupesThematiques = $this->Suivis->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
        $groupesMetiers = $this->Suivis->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
       
        $this->set(compact('variables','formule','formules','unite','domaineresp','suivi', 'materiels', 'typeSuivis', 'materiel', 'groupesThematiques', 'groupesMetiers'));
        $this->set('_serialize', ['suivi']);
    }

	
    /**
     * Edit method
     *
     * @param string|null $id Suivi id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $suivi = $this->Suivis->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $suivi = $this->Suivis->patchEntity($suivi, $this->request->data);
            if ($this->Suivis->save($suivi)) {
                $this->Flash->success(__('Le suivi a bien été édité.'));
                return $this->redirect(['action' => 'view', $id]);
            } else {
                $this->Flash->error(__('Le suivi n\'a pas pu être édité.'));
            }
        }
        $materiels = $this->Suivis->Materiels->find('list');
		$materiel = $this->Suivis->Materiels->find()->where(['id =' => $suivi->materiel_id])->first();
        $unite = TableRegistry::get('Unites')->find('list', [ 'keyfield' => 'id', 'valueField' =>'nom']);
        
        $numMateriel = $this->Suivis->Materiels->find()->select('numero_laboratoire')->where(['id =' => $suivi->get('materiel_id')])->first()['numero_laboratoire'];
        $metro = TableRegistry::get('Materiels')->find()->select('metrologie')->where(['id =' => $suivi->materiel_id])->first()['metrologie'];
       
        $typeSuivis = $this->Suivis->TypeSuivis->find('list', [ 'keyField' => 'id', 'valueField' => 'nom']);
        
		$groupesThematiques = $this->Suivis->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
        $groupesMetiers = $this->Suivis->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
        
		if($metro == 1){
        $typeSuivis = $this->Suivis->TypeSuivis->find('list', [ 'keyField' => 'id', 'valueField' => 'nom']);
		}else{
		$typeSuivis = $this->Suivis->TypeSuivis->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'conditions' => [ 'AND' => [['id !=' => '4'] , ['id !=' => '5'], ['id !=' => '6']]]]);
        }
		$dom= TableRegistry::get('Materiels')->find()->select('sur_categorie_id')->where(['id =' => $suivi->materiel_id])->first()['sur_categorie_id'];
		$domaines= TableRegistry::get('Users')->find()->select('sur_categorie_id')->where(['username =' => $this->LdapAuth->user($this->request->session()->read('authType'))[0]])->first()['sur_categorie_id'];
		if($dom == $domaines)
			$domaineresp=true;
		else
			$domaineresp=false;

        $this->set(compact('unite','metro','domaineresp','suivi','materiel', 'materiels', 'typeSuivis', 'numMateriel', 'groupesThematiques', 'groupesMetiers'));
        $this->set('_serialize', ['suivi']);
		
		
    }

    /**
     * Delete method
     *
     * @param string|null $id Suivi id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $suivi = $this->Suivis->get($id);
        if ($this->Suivis->delete($suivi)) {
            $this->Flash->success(__('Le suivi a bien été supprimé.'));
        } else {
            $this->Flash->error(__('Le suivi n\'a pas pu être supprimé.'));
        }
        return $this->redirect(['action' => 'index']);
    }
    
		
	
    /**
     * GetConditionForField method
     *
     * @param unknown $fieldName
     * @return string[]|NULL
     */
    private function getConditionForField($fieldName) {
    	$searchFieldName = 's_' . $fieldName;
    	if ( isset($this->request->data[$searchFieldName]) && ($this->request->data[$searchFieldName] != '')) return ["Suivis.$fieldName LIKE" => '%'.$this->request->data[$searchFieldName].'%'];
    	return NULL;
    }
    
    
    /**
     * GetConditionForFieldNumber method
     *
     * @param unknown $fieldName
     * @return $string[]|NULL
     */
    private function getConditionForFieldNumber($fieldName) {
    	$searchFieldName = 's_' . $fieldName;
    	if ( isset($this->request->data[$searchFieldName]) && ($this->request->data[$searchFieldName] != '')) return ["Suivis.$fieldName =" => $this->request->data[$searchFieldName]];
    	return NULL;
    }
    
    
    /**
     * Find method
     */
    public function find() {
    
    	$s_groupes_thematiques = $this->Suivis->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
    	$s_groupes_metiers = $this->Suivis->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
    	$s_type_suivis = $this->Suivis->TypeSuivis;
    	$materiels = $this->Suivis->Materiels;
    	
    	$this->set(compact('s_groupes_thematiques', 's_groupes_metiers', 's_type_suivis', 'materiels'));
    	 
    	$resultTri = $this->request->session()->read("resultTri");
    	 
    	if ($this->request->is('post')) {
    		$specificFieldsConditions = NULL;
			
			$periode_interventionRequest = NULL;
    		$date_intervention = NULL;
    		if ($this->request->data['s_periode_controle1'] != '') $periode_interventionRequest['Suivis.date_controle >='] = date('Y-m-d', strtotime(str_replace('/', '-', $this->request->data['s_periode_controle1'])));
    		if ($this->request->data['s_periode_controle2'] != '') $periode_interventionRequest['Suivis.date_controle <='] = date('Y-m-d', strtotime(str_replace('/', '-', $this->request->data['s_periode_controle2'])));
	 		if ($this->request->data['s_date_controle'] != '') $date_intervention['Suivis.date_controle ='] = date('Y-m-d', strtotime(str_replace('/', '-', $this->request->data['s_date_controle'])));
    		
    		$specificFieldsConditions = [
				$date_intervention,
				$periode_interventionRequest,
    			$this->getConditionForFieldNumber('type_suivi_id'),
    			$this->getConditionForField('organisme'),
    			$this->getConditionForField('statut'),
   				$this->getConditionForFieldNumber('groupes_metier_id'),
    			$this->getConditionForFieldNumber('groupes_thematique_id'),					
    		];
    
    		// CONSTRUCTION DE LA REQUETE SQL COMPLETE = $specificFieldsConditions
    		// by default, no sort
    		$lastResults = $this->Suivis->find('all', ['conditions' => $specificFieldsConditions]);
    
    		$this->paginate = ['limit' => 1000];
    		$_results = $this->paginate($lastResults);
    		$this->set(compact('_results'));
    
    	} // end if()
    	else if (isset($resultTri) && strstr($this->request->here(), 'sort') != false && strstr($this->request->here(), 'direction') != false) {
    		$findedSuivis = [];
    
    		foreach($resultTri as $r) {
    			array_push($findedSuivis, $r->id);
    		}
    		$res = $this->Suivis->find('all', ['limit' => 1000]);
    		for($i = 0; $i < sizeof($findedSuivis); $i++) {
    			$res->orWhere(['id =' => $findedSuivis[$i]]);
    		}
    
    		$this->paginate = ['limit' => 1000];
    		$_results = $this->paginate($res);
    		$this->set(compact('_results'));

    	}
    }
    
    // called from Javascript (Ajax)
    public function getNextDate($dateORjour, $frequenceORmois, $typeFrequenceORannee, $frequence = null, $typeFrequence = null) {

    	if($frequence != null && $typeFrequence != null) {
    		$date = $dateORjour.'-'.$frequenceORmois.'-'.$typeFrequenceORannee;
    	} else {
    		$date = $dateORjour;
    		$frequence = $frequenceORmois;
    		$typeFrequence = $typeFrequenceORannee;
    	}
    	
    	$date_next = date_create_from_format('d-m-Y', $date);
    	
    	switch($typeFrequence) {
    		case "Jours":
    			date_add($date_next, date_interval_create_from_date_string($frequence.' days'));
    			break;
    		case "Semaines":
    			date_add($date_next, date_interval_create_from_date_string((7*$frequence).' days'));
    			break;
    		case "Mois":
    			date_add($date_next, date_interval_create_from_date_string($frequence.' months'));
    			break;
    		case "Ans":
    			date_add($date_next, date_interval_create_from_date_string($frequence.' years'));
    			break;
    	}
    	
    	$this->set ('date', date_format($date_next, 'd-m-Y'));

    
    	$this->viewBuilder()->layout = 'ajax';
    }
    
}