MaterielsController.php 15.6 KB
<?php
namespace App\Controller;

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

/**
 * Materiels Controller
 *
 * @property \App\Model\Table\MaterielsTable $Materiels
 */
class MaterielsController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {   
    	$this->paginate = [
            'contain' => ['SurCategories', 'Categories', 'SousCategories', 'GroupesThematiques', 'GroupesMetiers', 'Organismes', 'Sites']
        ];
        $materiels = $this->paginate($this->Materiels);
        
        $this->set('nbMateriels', $this->Materiels->find('all')->count());
        
        $this->set(compact('materiels'));
        $this->set('_serialize', ['materiels']);
    }

    /**
     * View method
     *
     * @param string|null $id Materiel id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $materiel = $this->Materiels->get($id, [
            'contain' => ['SurCategories', 'Categories', 'SousCategories', 'GroupesThematiques', 'GroupesMetiers', 'Organismes', 'Sites', 'Documents', 'Emprunts', 'Suivis']
        ]);
        
        $this->set('materiel', $materiel);
        $this->set('_serialize', ['materiel']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $materiel = $this->Materiels->newEntity();
        if ($this->request->is('post')) {
            $materiel = $this->Materiels->patchEntity($materiel, $this->request->data);
            if ($this->Materiels->save($materiel)) {
                $this->Flash->success(__('Le matériel a bien été ajouté.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('Le matériel n\'a pas pu être ajouté.'));
            }
        }
        
        $surCategories = $this->Materiels->SurCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SurCategories.nom']);
        $categories = $this->Materiels->Categories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Categories.nom']);
        $sousCategories = $this->Materiels->SousCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SousCategories.nom']);
        $groupesThematiques = $this->Materiels->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
        $groupesMetiers = $this->Materiels->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
        $organismes = $this->Materiels->Organismes->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Organismes.nom']);
        $sites = $this->Materiels->Sites->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Sites.nom']);
        
        $utilisateurs = TableRegistry::get('Users')->find('list', [ 'keyField' => 'nom', 'valueField' => 'nom']);
        
        $mail_responsable = TableRegistry::get('Users')->find()->select('email')->where(['username =' => $this->Auth->user('username')])->first()['email'];
        
        $this->set(compact('materiel', 'surCategories', 'categories', 'sousCategories', 'groupesThematiques', 'groupesMetiers', 'organismes', 'sites', 'utilisateurs', 'mail_responsable'));
        $this->set('_serialize', ['materiel']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Materiel 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)
    {
        $materiel = $this->Materiels->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $materiel = $this->Materiels->patchEntity($materiel, $this->request->data);
            if ($this->Materiels->save($materiel)) {
                $this->Flash->success(__('Le matériel a bien été édité.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('Le matériel n\'a pas pu être édité.'));
            }
        }
        $surCategories = $this->Materiels->SurCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SurCategories.nom']);
        $categories = $this->Materiels->Categories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Categories.nom']);
        $sousCategories = $this->Materiels->SousCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SousCategories.nom']);
        $groupesThematiques = $this->Materiels->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
        $groupesMetiers = $this->Materiels->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
        $organismes = $this->Materiels->Organismes->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Organismes.nom']);
        $sites = $this->Materiels->Sites->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Sites.nom']);
        
        $utilisateurs = TableRegistry::get('Users')->find('list', [ 'keyField' => 'nom', 'valueField' => 'nom']);
        
        if(!empty($materiel->get('nom_responsable'))){
        	if(!in_array($materiel->get('nom_responsable'), $utilisateurs->toArray())){
        		$nom_ancien_responsable = $materiel->get('nom_responsable');
        		$this->set(compact('nom_ancien_responsable'));
        	}
        }
        $mail_responsable = TableRegistry::get('Users')->find()->select('email')->where(['username =' => $this->Auth->user('username')])->first()['email'];

        $this->set(compact('materiel', 'surCategories', 'categories', 'sousCategories', 'groupesThematiques', 'groupesMetiers', 'organismes', 'sites', 'utilisateurs', 'mail_responsable'));
        $this->set('_serialize', ['materiel']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Materiel 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']);
        $materiel = $this->Materiels->get($id);
        if ($this->Materiels->delete($materiel)) {
            $this->Flash->success(__('Le matériel a bien été supprimé.'));
        } else {
            $this->Flash->error(__('Le matériel n\'a pas pu être supprimé.'));
        }
        return $this->redirect(['action' => 'index']);
    }
    
    private function statusSetTo($newStatus, $message, $id = null, $from = 'index') {
    	$materiel = $this->Materiels->get($id)->set('status', $newStatus);
    	
    	if ($this->Materiels->save($materiel)) {
    		$this->Flash->success(__($message));
    	}
    	
    	return $this->redirect(['action'=>$from, $id]);
    }
    
    public function statusValidated($id = null, $from = 'index') {
    	$this->statusSetTo('VALIDATED', 'Le matériel a bien été validé', $id, $from);
    }
    public function statusToBeArchived($id = null, $from = 'index') {
    	$this->statusSetTo('TOBEARCHIVED', 'La sortie d\'inventaire a bien été demandée', $id, $from);
    }
    public function statusArchived($id = null, $from = 'index') {
    	$this->statusSetTo('ARCHIVED', 'Le matériel a bien été sorti de l\'inventaire', $id, $from);
    }
    
    private function getConditionForField($fieldName) {
    	$searchFieldName = 's_' . $fieldName;
    	if ( isset($this->request->data[$searchFieldName]) && ($this->request->data[$searchFieldName] != '')) return ["Materiels.$fieldName LIKE" => '%'.$this->request->data[$searchFieldName].'%'];
    	return NULL;
    }
    
    private function getConditionForFieldNumber($fieldName) {
    	$searchFieldName = 's_' . $fieldName;
    	if ( isset($this->request->data[$searchFieldName]) && ($this->request->data[$searchFieldName] != '')) return ["Materiels.$fieldName =" => $this->request->data[$searchFieldName]];
    	return NULL;
    }
    
    public function find() {

    	$s_sur_categories = $this->Materiels->SurCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SurCategories.nom']);
    	$s_categories = $this->Materiels->Categories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Categories.nom']);
    	$s_sous_categories = $this->Materiels->SousCategories->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'SousCategories.nom']);
    	$s_groupes_thematiques = $this->Materiels->GroupesThematiques->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesThematiques.nom']);
    	$s_groupes_metiers = $this->Materiels->GroupesMetiers->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'GroupesMetiers.nom']);
    	$s_organismes = $this->Materiels->Organismes->find('list', [ 'keyField' => 'id', 'valueField' => 'nom', 'order' => 'Organismes.nom']);
    	
    	$this->set(compact('s_sur_categories', 's_categories', 's_sous_categories', 's_groupes_thematiques', 's_groupes_metiers', 's_organismes'));
    	
    	// some data POSTED (au moins le champ de recherche generale) ?
    	if ( isset($this->request->data['s_all']) || isset($this->request->data['s_all_2']) || isset($this->request->data['designation'])) {
    		$generalFieldConditions = NULL;
    		// if general field set (s_all), then set general request for it
    		if (isset($this->request->data['s_all'])) {
    			$all = $this->request->data['s_all'];
    			$generalFieldConditions = ['OR' => [
    					'Materiels.designation LIKE' => '%'.$all.'%',
    					'Materiels.numero_laboratoire LIKE' => '%'.$all.'%',
    					'Materiels.numero_inventaire_organisme LIKE' => '%'.$all.'%',
    					'Materiels.numero_inventaire_old LIKE' => '%'.$all.'%',
    					'Materiels.numero_commande LIKE' => '%'.$all.'%',
    					'Materiels.description LIKE' => '%'.$all.'%',
    					'Materiels.fournisseur LIKE' => '%'.$all.'%',
    					'Materiels.nom_responsable LIKE' => '%'.$all.'%',
    					'Materiels.email_responsable LIKE' => '%'.$all.'%',
    					'Materiels.code_comptable LIKE' => '%'.$all.'%',
    					'Materiels.numero_serie LIKE' => '%'.$all.'%',
    					'Materiels.date_acquisition LIKE' => '%'.$all.'%',
    					'Materiels.date_reception LIKE' => '%'.$all.'%',
    			]];
    		}
    		if (isset($this->request->data['s_all_2'])) {
    			$all = $this->request->data['s_all_2'];
    			$generalFieldConditions = ['OR' => [
    					'Materiels.designation LIKE' => '%'.$all.'%',
    					'Materiels.numero_laboratoire LIKE' => '%'.$all.'%',
    					'Materiels.numero_inventaire_organisme LIKE' => '%'.$all.'%',
    					'Materiels.numero_inventaire_old LIKE' => '%'.$all.'%',
    					'Materiels.numero_commande LIKE' => '%'.$all.'%',
    					'Materiels.description LIKE' => '%'.$all.'%',
    					'Materiels.fournisseur LIKE' => '%'.$all.'%',
    					'Materiels.nom_responsable LIKE' => '%'.$all.'%',
    					'Materiels.email_responsable LIKE' => '%'.$all.'%',
    					'Materiels.code_comptable LIKE' => '%'.$all.'%',
    					'Materiels.numero_serie LIKE' => '%'.$all.'%',
    					'Materiels.date_acquisition LIKE' => '%'.$all.'%',
    					'Materiels.date_reception LIKE' => '%'.$all.'%',
    			]];
    		}
    		$specificFieldsConditions = NULL;
    		// au moins un champ specifique rempli ?
    		if ( isset($this->request->data['s_designation']) ) {
    			// Materiel type
    			$matostype = $this->request->data['s_matostype'];
    			$matostypeRequest = NULL;
    	
    			switch ($matostype) {
    				// Administratif
    				case 'A':
    					$matostypeRequest['Materiels.materiel_administratif ='] = '1';
    					break;
    					// Technique
    				case 'T':
    					$matostypeRequest['Materiels.materiel_technique ='] = '1';
    					break;
    					// Admin et Tech
    				case 'AT':
    					$matostypeRequest['Materiels.materiel_administratif ='] = '1';
    					$matostypeRequest['Materiels.materiel_technique ='] = '1';
    					break;
    					// Admin ONLY
    				case 'AO':
    					$matostypeRequest['Materiels.materiel_administratif ='] = '1';
    					$matostypeRequest['Materiels.materiel_technique ='] = '0';
    					break;
    					// Tech ONLY
    				case 'TO':
    					$matostypeRequest['Materiels.materiel_administratif ='] = '0';
    					$matostypeRequest['Materiels.materiel_technique ='] = '1';
    					break;
    			}
    	
    			$periode_acquisitionRequest = NULL;
    			if ($this->request->data['s_periode_acquisition1'] != '')
    				$periode_acquisitionRequest['Materiels.date_acquisition >='] = $this->request->data['s_periode_acquisition1'];
    				if ($this->request->data['s_periode_acquisition2'] != '')
    					$periode_acquisitionRequest['Materiels.date_acquisition <='] = $this->request->data['s_periode_acquisition2'];
    	
    					$montantRequest = [];
    					if ($this->request->data['s_prix_ht_inf'] != '')
    						$montantRequest['Materiels.prix_ht <='] = $this->request->data['s_prix_ht_inf'];
    						if ($this->request->data['s_prix_ht_sup'] != '')
    							$montantRequest['Materiels.prix_ht >='] = $this->request->data['s_prix_ht_sup'];

    							$specificFieldsConditions = [
    									'Materiels.designation LIKE' => '%'.$this->request->data['s_designation'].'%',
    									'Materiels.numero_laboratoire LIKE' => '%'.$this->request->data['s_numero_laboratoire'].'%',
    									$this->getConditionForField('numero_commande'),
    									'Materiels.date_acquisition LIKE' => '%'.$this->request->data['s_date_acquisition'].'%',
    									$periode_acquisitionRequest,
    									$this->getConditionForFieldNumber('prix_ht'),
    									$montantRequest,
    									$this->getConditionForFieldNumber('sur_categorie_id'),
    									$this->getConditionForFieldNumber('categorie_id'),
    									$this->getConditionForFieldNumber('sous_categorie_id'),
    									$this->getConditionForField('nom_responsable'),
    									$this->getConditionForField('numero_inventaire_organisme'),
    									$this->getConditionForField('numero_inventaire_old'),
    									$this->getConditionForFieldNumber('groupes_metier_id'),
    									$this->getConditionForFieldNumber('groupes_thematique_id'),
    									$this->getConditionForField('status'),
    									$this->getConditionForFieldNumber('organisme_id'),
    									$matostypeRequest,
    							];
    		}

    		// CONSTRUCTION DE LA REQUETE SQL COMPLETE = $specificFieldsConditions OR $generalFieldConditions  (mais entre chaque champ, c'est un AND)
    		// by default, no sort
    		$order = [];
    	
    		if (isset($this->passedArgs[0]) && isset($this->passedArgs[1])) {
    			$order = $this->passedArgs[0];
    			$order .= ' '.$this->passedArgs[1];
    		}
    		
    		if (isset($this->request->data['s_all_2']) && $this->request->data['s_all_2'] != '') {
    			$conditions = $generalFieldConditions;
    		}
    		else if (isset($this->request->data['s_all']) && $this->request->data['s_all'] != '') {
    			$conditions = $generalFieldConditions;
    		}
    		else {
    			$conditions = $specificFieldsConditions;
    		}
    						
    		$lastResults = $this->Materiels->find('all', ['limit' => 1000, 'order' => $order, 'conditions' => $conditions])->toArray();
    				
    		$this->set('_results', $lastResults);

    	} // end if()
    }
    
    public function export() {
    	
    }
    
    
    
    
}