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

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;
use Cake\I18n\Time;
use Cake\I18n\Date;
use Cake\ORM\Association\BelongsTo;

/**
 * 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
 * @property \Cake\ORM\Association\BelongsTo $Fournisseurs
 * @property \Cake\ORM\Association\BelongsTo $Users
 */
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'
        ]);
        $this->belongsTo('Fournisseurs', [
            'foreignKey' => 'fournisseur_id'
        ]);
        
        // EP 9/6/17 added :
        $this->belongsTo('Users', [
            'foreignKey' => 'gestionnaire_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator
     *            Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $dateValide = function ($entity) {
            $time = Time::now(); // On récupère la date et l'heure actuelles
            $today = (new date("$time->year-$time->month-$time->day"))->format('Ymd'); // On extrait la date on la formatte en un format comparable de type 20171231
            $timeEntity = new time($entity);
            $dateEntity = (new date("$timeEntity->year-$timeEntity->month-$timeEntity->day"))->format('Ymd');
            return ($today >= $dateEntity);
        };
        
        $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'
        ]);
        $configuration = TableRegistry::get('Configurations')->find()
            ->where([
            'id =' => 1
        ])
            ->first();
        if ($configuration->date_commande_facultative) {
            $validator->allowEmpty('date_acquisition')->add('date_acquisition', 'custom', [
                'rule' => $dateValide,
                'message' => 'La date n\'est pas valide'
            ]);
        } else {
            $validator->notEmpty('date_acquisition', 'Ce champ doit être rempli')->add('date_acquisition', 'custom', [
                'rule' => $dateValide,
                'message' => 'La date n\'est pas valide'
            ]);
        }
        // Attention, configuration désactivée, cela ne génère pas ne num de labo, voir dans config/edit.ctp
        $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->allowEmpty('photo_id');
        $validator->boolean('etiquette')->allowEmpty('etiquette');
        $validator->boolean('hors_service')->allowEmpty('hors_service');
        $validator->
        // ->notEmpty('site_id', 'Ce champ doit être rempli');
        allowEmpty('site_id');
        $validator->allowEmpty('lieu_detail')->add('lieu_detail', 'valid', [
            'rule' => 'check_string',
            'message' => 'Ce champ contient des caractères interdits',
            'provider' => 'table'
        ]);
        $validator->notEmpty('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('gestionnaire_id');
        // ->notEmpty('gestionnaire_id', 'Ce champ doit être rempli');
        $validator->allowEmpty('nom_createur');
        $validator->allowEmpty('nom_modificateur');
        $validator->allowEmpty('date_reception');
        $validator->allowEmpty('date_fin_garantie');
        $validator->allowEmpty('duree_garantie');
        $validator->allowEmpty('unite_duree_garantie');
        return $validator;
    }

    public function checkStatus($check)
    {
        return ($check !== null && 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)
    {
        $configuration = TableRegistry::get('Configurations')->find()
            ->where([
            'id =' => 1
        ])
            ->first();
        $checkAtLeastOneChecked = function ($entity) {
            return ($entity->materiel_administratif || $entity->materiel_technique);
        };
        // return if price >= $configuration->prix_inventaire_administratif € then must be checked as "administratif"
        $checkIfIsAdministratifWhenShouldBe = function ($entity) {
            $configuration = TableRegistry::get('Configurations')->find()
                ->where([
                'id =' => 1
            ])
                ->first();
            return ! ($entity->prix_ht !== null && $entity->prix_ht >= $configuration->prix_inventaire_administratif && ! $entity->materiel_administratif);
        };
        // return if price <800€ then must NOT be checked as "administratif"
        $checkIfIsNotAdministratifWhenShouldNotBe = function ($entity) {
            $configuration = TableRegistry::get('Configurations')->find()
                ->where([
                'id =' => 1
            ])
                ->first();
            return ! ($entity->prix_ht !== null && $entity->prix_ht < $configuration->prix_inventaire_administratif && $entity->materiel_administratif);
        };
        // return if checked as "administratif" price MUST be set
        $checkPriceIfIsAdministratif = function ($entity) {
            if ($entity->materiel_administratif)
                return ($entity->prix_ht !== null);
            return true;
        };
        $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 ' . $configuration->prix_inventaire_administratif . '€ HT, il est donc obligatoirement inventoriable.'
        ]);
        $rules->add($checkIfIsNotAdministratifWhenShouldNotBe, [
            'errorField' => 'materiel_administratif',
            'message' => 'Le matériel vaut moins de ' . $configuration->prix_inventaire_administratif . '€ HT, il n\'est donc pas inventoriable.'
        ]);
        $rules->add($checkPriceIfIsAdministratif, [
            'errorField' => 'prix_ht',
            'message' => 'Le matériel ne peut pas être inventoriable et ne pas avoir de prix'
        ]);
        $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 (! $entity->get('administrer')) {
            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)
            $configuration = TableRegistry::get('Configurations')->find()
                ->where([
                'id =' => 1
            ])
                ->first();
            if ($configuration->numero_labo_sans_annee) {
                if (empty($entity->get('numero_laboratoire'))) {
                    $labShortName = $configuration->labNameShort;
                    $num = TableRegistry::get('Materiels')->find('all', [
                        'fields' => [
                            'numero_laboratoire'
                        ],
                        'conditions' => [
                            'Materiels.numero_laboratoire LIKE' => $labShortName . '%'
                        ],
                        'order' => [
                            'Materiels.numero_laboratoire DESC'
                        ]
                    ])->first()['numero_laboratoire'];
                    error_log($num);
                    $newId = substr($num, - 4) + 1;
                    error_log($newId);
                    $labNumber = $labShortName . '-' . sprintf("%04d", $newId);
                    $entity->set('numero_laboratoire', $labNumber);
                }
            } else {
                if (empty($entity->get('numero_laboratoire')) && ! empty($entity->get('date_acquisition'))) {
                    $year = substr($entity->get('date_acquisition'), 6, 4);
                    if (strlen($year) == 2) {
                        $year = '20' . $year;
                    }
                    $labShortName = $configuration->labNameShort;
                    $num = TableRegistry::get('Materiels')->find('all', [
                        'fields' => [
                            'numero_laboratoire'
                        ],
                        'conditions' => [
                            'Materiels.numero_laboratoire LIKE' => $labShortName . '-' . $year . '%'
                        ],
                        'order' => [
                            'Materiels.numero_laboratoire DESC'
                        ]
                    ])->first()['numero_laboratoire'];
                    $newId = substr($num, - 4) + 1;
                    $labNumber = $labShortName . '-' . $year . '-' . sprintf("%04d", $newId);
                    $entity->set('numero_laboratoire', $labNumber);
                }
            }
        }
        if (empty($entity->get('date_acquisition'))) {
            $entity->set('date_acquisition', null);
        }
        if (empty($entity->get('date_reception'))) {
            $entity->set('date_reception', null);
        }
        return true;
    }
}