MaterielsTable.php 10 KB
<?php
namespace App\Model\Table;

use App\Model\Entity\Materiel;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;

/**
 * Materiels Model
 *
 * @property \Cake\ORM\Association\BelongsTo $SurCategories
 * @property \Cake\ORM\Association\BelongsTo $Categories
 * @property \Cake\ORM\Association\BelongsTo $SousCategories
 * @property \Cake\ORM\Association\BelongsTo $GroupesThematiques
 * @property \Cake\ORM\Association\BelongsTo $GroupesMetiers
 * @property \Cake\ORM\Association\BelongsTo $Organismes
 * @property \Cake\ORM\Association\BelongsTo $Sites
 * @property \Cake\ORM\Association\HasMany $Documents
 * @property \Cake\ORM\Association\HasMany $Emprunts
 * @property \Cake\ORM\Association\HasMany $Suivis
 */
class MaterielsTable extends AppTable
{

	public $ALL_STATUS = array('CREATED', 'VALIDATED', 'TOBEARCHIVED', 'ARCHIVED');
	
	
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('materiels');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('SurCategories', [
            'foreignKey' => 'sur_categorie_id'
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'categorie_id'
        ]);
        $this->belongsTo('SousCategories', [
            'foreignKey' => 'sous_categorie_id'
        ]);
        $this->belongsTo('GroupesThematiques', [
            'foreignKey' => 'groupes_thematique_id'
        ]);
        $this->belongsTo('GroupesMetiers', [
            'foreignKey' => 'groupes_metier_id'
        ]);
        $this->belongsTo('Organismes', [
            'foreignKey' => 'organisme_id'
        ]);
        $this->belongsTo('Sites', [
            'foreignKey' => 'site_id'
        ]);
        $this->hasMany('Documents', [
            'foreignKey' => 'materiel_id'
        ]);
        $this->hasMany('Emprunts', [
            'foreignKey' => 'materiel_id'
        ]);
        $this->hasMany('Suivis', [
            'foreignKey' => 'materiel_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->notEmpty('designation' ,'Ce champ doit être rempli') 
           	->add('designation', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);

        $validator
        	->notEmpty('sur_categorie_id', 'Vous devez sélectionner une valeur');
        
        $validator
        	->notEmpty('categorie_id', 'Vous devez sélectionner une valeur');
        	
        $validator
            ->allowEmpty('numero_laboratoire')
            ->add('numero_laboratoire', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->allowEmpty('description')
            ->add('description', 'valid', ['rule' => 'check_string_with_some_special_cars', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);

        $validator
            ->boolean('materiel_administratif')
            ->allowEmpty('materiel_administratif');
        
        $validator
            ->boolean('materiel_technique')
            ->allowEmpty('materiel_technique');

        $validator
            ->add('status', 'valid', ['rule' => 'checkStatus', 'message' => 'Le statut doit prendre une des 4 valeurs CREATED, VALIDATED, TOBEARCHIVED, ou ARCHIVED', 'provider' => 'table']);
            
        $validator
            ->notEmpty('date_acquisition', 'Ce champ doit être rempli');
        
        $validator
            ->allowEmpty('fournisseur')
            ->add('fournisseur', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);

        $validator
            ->numeric('prix_ht')
            ->allowEmpty('prix_ht')
            ->add('prix_ht', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);

        $validator
            ->allowEmpty('eotp')
            ->add('eotp', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);

        $validator
            ->allowEmpty('numero_commande')
            ->add('numero_commande', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
            
        $validator
            ->allowEmpty('code_comptable')
            ->add('code_comptable', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('numero_serie')
            ->add('numero_serie', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('numero_inventaire_organisme')
            ->add('numero_inventaire_organisme', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('numero_inventaire_old')
            ->add('numero_inventaire_old', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('date_archivage');

        $validator
            ->boolean('etiquette')
            ->allowEmpty('etiquette');

        $validator
            ->allowEmpty('lieu_stockage');

        $validator
            ->allowEmpty('lieu_detail')
            ->add('lieu_detail', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('nom_responsable')
            ->add('nom_responsable', 'valid', ['rule' => 'check_string', 'message' => 'Ce champ contient des caractères interdits', 'provider' => 'table']);
             
        $validator
            ->allowEmpty('email_responsable')
            ->email('email_responsable');
 
        $validator
            ->allowEmpty('nom_createur');

        $validator
            ->allowEmpty('nom_modificateur');

        $validator
            ->allowEmpty('date_reception');
        return $validator;
    }

    
    
    public function checkStatus($check) {
    	return ( isset($check) && in_array($check, $this->ALL_STATUS) );
    }
    
    
    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
    	
    	
    	$checkAtLeastOneChecked = function($entity) {
    		return ( $entity->materiel_administratif || $entity->materiel_technique);
    	};
    
    	// return if price >=800€ then must be checked as "administratif"
   		$checkIfIsAdministratifWhenShouldBe = function ($entity) {
    		return ! ( isset($entity->prix_ht) && $entity->prix_ht >= 800 && !$entity->materiel_administratif );
   		};
    
    	// return if price <800€ then must NOT be checked as "administratif"
    	$checkIfIsNotAdministratifWhenShouldNotBe = function ($entity) {
    		return ! ( isset($entity->prix_ht) && $entity->prix_ht < 800 && $entity->materiel_administratif );
    	};
    	
    	
    	$rules->add($checkAtLeastOneChecked, [
    			'errorField' => 'materiel_administratif',
    			'message' => 'Le matériel est obligatoirement inventoriable ou technique.'
    	]);
    	$rules->add($checkIfIsAdministratifWhenShouldBe, [
    			'errorField' => 'materiel_administratif',
    			'message' => 'Le matériel vaut plus de 800€ HT, il est donc obligatoirement inventoriable.'
    	]);
    	$rules->add($checkIfIsNotAdministratifWhenShouldNotBe, [
    			'errorField' => 'materiel_administratif',
    			'message' => 'Le matériel vaut moins de 800€ HT, il n\'est donc pas inventoriable.'
    	]);

    	
    	
        $rules->add($rules->isUnique(['numero_laboratoire']));
        $rules->add($rules->existsIn(['sur_categorie_id'], 'SurCategories'));
        $rules->add($rules->existsIn(['categorie_id'], 'Categories'));
        $rules->add($rules->existsIn(['sous_categorie_id'], 'SousCategories'));
        $rules->add($rules->existsIn(['groupes_thematique_id'], 'GroupesThematiques'));
        $rules->add($rules->existsIn(['groupes_metier_id'], 'GroupesMetiers'));
        $rules->add($rules->existsIn(['organisme_id'], 'Organismes'));
        $rules->add($rules->existsIn(['site_id'], 'Sites'));
        return $rules;
    }
    
    
    public function beforeSave($event, $entity, $options)
    {
    	if(!empty($entity->get('nom_responsable')) && empty($entity->get('nom_responsable'))){
    		$entity->set('nom_responsable', $entity->get('nom_ancien_responsable'));
    	}
    	
    	// numero_laboratoire generator (QC changed this in Jan 2015)
    	if (empty($entity->get('numero_laboratoire')) && !empty($entity->get('date_acquisition'))) {
    		$year = substr($entity->get('date_acquisition'), 6, 4);
    		$labName = 'IRAP';
    		
    		$num = TableRegistry::get('Materiels')->find('all', [
    				'fields' => ['numero_laboratoire'],
    				'conditions' => ['Materiels.numero_laboratoire LIKE' => $labName.'-'.$year.'%'],
    				'order' => ['Materiels.numero_laboratoire DESC']
    		])->first()['numero_laboratoire'];
    		
    		$newId = substr($num, -4)+1;
    		$labNumber = $labName.'-'.$year.'-'.sprintf("%04d", $newId);
    		
    		$entity->set('numero_laboratoire', $labNumber);
    	}
    	
    	return true;
    }
    
    
}