/**
  * Mapping et enregistrement de l'affectation
  *
  * @param CSejour   $newVenue Admit
  * @param array     $data     Datas
  * @param CMovement $movement Movement
  *
  * @return CAffectation|string|null
  */
 function mapAndStoreAffectation(CSejour $newVenue, $data, CMovement $movement = null)
 {
     $sender = $this->_ref_sender;
     if ($newVenue->annule) {
         return null;
     }
     $PV1_3 = $this->queryNode("PV1.3", $data["PV1"]);
     $affectation = new CAffectation();
     $affectation->sejour_id = $newVenue->_id;
     $event_code = $this->_ref_exchange_hl7v2->code;
     // Récupération de la date de réalisation de l'évènement
     // Dans le cas spécifique de quelques évènements, on récupère le code sur le ZBE
     $datetime = $this->queryTextNode("EVN.6/TS.1", $data["EVN"]);
     if (array_key_exists("ZBE", $data) && $data["ZBE"] && CMbArray::in($event_code, array("A01", "A02", "A04", "A15", "Z80", "Z84"))) {
         $datetime = $this->queryTextNode("ZBE.2/TS.1", $data["ZBE"]);
     }
     switch ($event_code) {
         // Cas d'une suppression de mutation ou d'une permission d'absence
         case "A12":
         case "A52":
             // Quand on a un mouvement (provenant d'un ZBE)
             if (array_key_exists("ZBE", $data) && $data["ZBE"]) {
                 if (!$movement) {
                     return null;
                 }
                 $affectation->load($movement->affectation_id);
                 if (!$affectation->_id) {
                     return "Le mouvement '{$movement->_id}' n'est pas lié à une affectation dans Mediboard";
                 }
             } else {
                 $affectation->entree = $datetime;
                 $affectation->loadMatchingObject();
                 if (!$affectation->_id) {
                     return null;
                 }
             }
             // Pas de synchronisation
             $affectation->_no_synchro = true;
             if ($msgAffectation = $affectation->delete()) {
                 return $msgAffectation;
             }
             return null;
             // Annulation admission
         // Annulation admission
         case "A11":
             if (!$movement) {
                 return null;
             }
             $affectation = $newVenue->getCurrAffectation($datetime);
             // Si le mouvement n'a pas d'affectation associée, et que l'on a déjà une affectation dans MB
             if (!$movement->affectation_id && $affectation->_id) {
                 return "Le mouvement '{$movement->_id}' n'est pas lié à une affectation dans Mediboard";
             }
             // Si on a une affectation associée, alors on charge celle-ci
             if ($movement->affectation_id) {
                 $affectation = $movement->loadRefAffectation();
             }
             // Pas de synchronisation
             $affectation->_no_synchro = true;
             if ($msg = $affectation->delete()) {
                 return $msg;
             }
             return null;
             // Annuler le retour du patient
         // Annuler le retour du patient
         case "A53":
             if (!$movement) {
                 return null;
             }
             $affectation->load($movement->affectation_id);
             if (!$affectation->_id) {
                 return "Le mouvement '{$movement->_id}' n'est pas lié à une affectation dans Mediboard";
             }
             $affectation->effectue = 0;
             // Pas de synchronisation
             $affectation->_no_synchro = true;
             $affectation->_eai_sender_guid = $sender->_guid;
             if ($msg = $affectation->store()) {
                 return $msg;
             }
             return $affectation;
             // Cas d'un départ pour une permission d'absence
         // Cas d'un départ pour une permission d'absence
         case "A21":
             $affectation->entree = $datetime;
             $affectation->loadMatchingObject();
             // Si on ne retrouve pas une affectation
             // Création de l'affectation
             // et mettre à 'effectuee' la précédente si elle existe sinon création de celle-ci
             if (!$affectation->_id) {
                 $service_externe = CService::loadServiceExterne($sender->group_id);
                 if (!$service_externe->_id) {
                     return "CService-externe-none";
                 }
                 $affectation->service_id = $service_externe->_id;
                 $return_affectation = $newVenue->forceAffectation($affectation, true);
                 //$datetime, $affectation->lit_id, $affectation->service_id);
                 if (is_string($return_affectation)) {
                     return $return_affectation;
                 }
                 $affectation = $return_affectation;
             }
             return $affectation;
             // Cas d'un retour pour une permission d'absence
         // Cas d'un retour pour une permission d'absence
         case "A22":
             $service_externe = CService::loadServiceExterne($sender->group_id);
             if (!$service_externe->_id) {
                 return "CService-externe-none";
             }
             // Recherche de l'affectation correspondant à une permission d'absence
             $search = new CAffectation();
             $where = array();
             $where["sejour_id"] = "=  '{$newVenue->_id}'";
             $where["service_id"] = "=  '{$service_externe->_id}'";
             $where["effectue"] = "=  '0'";
             $where["entree"] = "<= '{$datetime}'";
             $where["sortie"] = ">= '{$datetime}'";
             $search->loadObject($where);
             // Si on ne la retrouve pas on prend la plus proche
             if (!$search->_id) {
                 $where = array();
                 $where["sejour_id"] = "=  '{$newVenue->_id}'";
                 $where["service_id"] = "=  '{$service_externe->_id}'";
                 $where["effectue"] = "=  '0'";
                 $search->loadObject($where);
             }
             $search->effectue = 1;
             $search->sortie = $datetime;
             $search->_eai_sender_guid = $sender->_guid;
             if ($msg = $search->store()) {
                 return $msg;
             }
             return $search;
             // Cas mutation
         // Cas mutation
         case "A02":
             $affectation->entree = $datetime;
             $affectation->loadMatchingObject();
             // Si on ne retrouve pas une affectation
             // Création de l'affectation
             // et mettre à 'effectuee' la précédente si elle existe sinon création de celle-ci
             if (!$affectation->_id) {
                 // Récupération du Lit et UFs
                 $this->getPL($PV1_3, $affectation, $newVenue);
                 $return_affectation = $newVenue->forceAffectation($affectation, true);
                 //$datetime, $affectation->lit_id, $affectation->service_id);
                 if (is_string($return_affectation)) {
                     return $return_affectation;
                 }
                 $affectation = $return_affectation;
             }
             break;
             // Cas modification
         // Cas modification
         case "Z99":
             if (!$movement) {
                 return null;
             }
             // Si on a une affectation associée, alors on charge celle-ci
             if ($movement->affectation_id) {
                 $affectation = $movement->loadRefAffectation();
             } else {
                 // On recherche l'affectation "courante"
                 // Si qu'une affectation sur le séjour
                 $newVenue->loadRefsAffectations();
                 if (count($newVenue->_ref_affectations) == 1) {
                     $affectation = reset($newVenue->_ref_affectations);
                 } else {
                     // On recherche l'affectation "courante"
                     $affectation = $newVenue->getCurrAffectation($datetime);
                 }
                 // Sinon on récupère et on met à jour la première affectation
                 if (!$affectation->_id) {
                     $affectation->sejour_id = $newVenue->_id;
                     $affectation->entree = $newVenue->entree;
                     $affectation->sortie = $newVenue->sortie;
                 }
             }
             break;
             // Tous les autres cas on récupère et on met à jour la première affectation
         // Tous les autres cas on récupère et on met à jour la première affectation
         default:
             $newVenue->loadRefsAffectations();
             $affectation = $newVenue->_ref_first_affectation;
             if (!$affectation->_id) {
                 $affectation->sejour_id = $newVenue->_id;
                 $affectation->entree = $newVenue->entree;
                 $affectation->sortie = $newVenue->sortie;
             }
     }
     // Si pas d'UF/service/chambre/lit on retourne une affectation vide
     if (!$PV1_3) {
         if ($msgVenue = self::storeUFMedicaleSoinsSejour($data, $newVenue)) {
             return $msgVenue;
         }
         return $affectation;
     }
     if ($this->queryTextNode("PL.1", $PV1_3) == $sender->_configs["handle_PV1_3_null"]) {
         if ($msgVenue = self::storeUFMedicaleSoinsSejour($data, $newVenue)) {
             return $msgVenue;
         }
         return $affectation;
     }
     // Si pas de lit on affecte le service sur le séjour
     if (!$this->queryTextNode("PL.3", $PV1_3)) {
         $affectation_uf = new CAffectationUniteFonctionnelle();
         // On essaye de récupérer le service dans ce cas depuis l'UF d'hébergement
         $date_deb = $affectation->_id ? CMbDT::date($affectation->sortie) : CMbDT::date($newVenue->sortie);
         $date_fin = $affectation->_id ? CMbDT::date($affectation->entree) : CMbDT::date($newVenue->entree);
         $uf = CUniteFonctionnelle::getUF($this->queryTextNode("PL.1", $PV1_3), "hebergement", $newVenue->group_id, $date_deb, $date_fin);
         if ($uf->code && $uf->_id) {
             $affectation_uf->uf_id = $uf->_id;
             $affectation_uf->object_class = "CService";
             $affectation_uf->loadMatchingObject();
         }
         // Dans le cas où l'on retrouve un service associé à l'UF d'hébergement
         if ($affectation_uf->_id) {
             $newVenue->service_id = $affectation_uf->object_id;
             $newVenue->uf_hebergement_id = $affectation_uf->uf_id;
         }
         $uf_med = $this->mappingUFMedicale($data, $newVenue, $affectation);
         $newVenue->uf_medicale_id = $uf_med ? $uf_med->_id : null;
         $uf_soins = $this->mappingUFSoins($data, $newVenue, $affectation);
         $newVenue->uf_soins_id = $uf_soins ? $uf_soins->_id : null;
         // On ne check pas la cohérence des dates des consults/intervs
         $newVenue->_skip_date_consistencies = true;
         $newVenue->_eai_sender_guid = $sender->_guid;
         if ($msgVenue = self::storeUFMedicaleSoinsSejour($data, $newVenue)) {
             return $msgVenue;
         }
         // Si on a pas d'UF on retourne une affectation vide
         if (!$uf->_id || !$affectation_uf->_id) {
             return $affectation;
         }
     }
     // Récupération du Lit et UFs
     $this->getPL($PV1_3, $affectation, $newVenue);
     $uf_med = $this->mappingUFMedicale($data, $newVenue, $affectation);
     $affectation->uf_medicale_id = $uf_med ? $uf_med->_id : null;
     $uf_soins = $this->mappingUFSoins($data, $newVenue, $affectation);
     $affectation->uf_soins_id = $uf_soins ? $uf_soins->_id : null;
     $affectation->_eai_sender_guid = $sender->_guid;
     if ($msg = $affectation->store()) {
         return $msg;
     }
     return $affectation;
 }
$type = CValue::post("type");
$entree_preparee_trigger = CValue::post("_entree_preparee_trigger");
$sejour_id = CValue::post("sejour_id");
$create_affectation = CAppUI::conf("urgences create_affectation");
$sejour = new CSejour();
$sejour->load($sejour_id);
$rpu = $sejour->loadRefRPU();
if ($rpu && $rpu->mutation_sejour_id) {
    $sejour_id = $sejour->_ref_rpu->mutation_sejour_id;
}
$sejour_hospit = new CSejour();
$sejour_hospit->load($sejour_id);
$curr_affectation_hospit = $sejour_hospit->loadRefCurrAffectation();
// Pour un séjour ayant comme mode de sortie urgence:
if ($create_affectation && $mode_sortie == "mutation" && $rpu && $rpu->_id && ($lit_id && $curr_affectation_hospit->lit_id != $lit_id || $service_sortie_id && $curr_affectation_hospit->service_id != $service_sortie_id)) {
    // Création de l'affectation d'hospitalisation
    $affectation_hospit = new CAffectation();
    $affectation_hospit->entree = CMbDT::dateTime();
    $affectation_hospit->lit_id = $lit_id;
    $affectation_hospit->service_id = $service_sortie_id;
    // Mutation en provenance des urgences
    $affectation_hospit->_mutation_urg = true;
    $sejour_hospit->forceAffectation($affectation_hospit);
}
// Lancement des formulaires automatiques sur le champ entrée préparée
if ($sejour->_id && $entree_preparee_trigger && CModule::getActive("forms")) {
    $ex_class_events = CExClassEvent::getForObject($sejour, "preparation_entree_auto", "required");
    echo CExClassEvent::getJStrigger($ex_class_events);
}
$do = new CDoObjectAddEdit("CSejour");
$do->doIt();