/**
  * Get PL : person location
  *
  * @param CInteropReceiver $receiver    Receiver
  * @param CSejour          $sejour      Admit
  * @param CAffectation     $affectation Affectation
  *
  * @return array
  */
 function getPL(CInteropReceiver $receiver, CSejour $sejour, CAffectation $affectation = null)
 {
     $group = $sejour->loadRefEtablissement();
     $default_name = null;
     if ($receiver && $receiver->_id && isset($receiver->_configs)) {
         $default_name = $receiver->_configs["build_PV1_3_1_default"];
     }
     if (!$affectation) {
         // Chargement de l'affectation courante
         $affectation = $sejour->getCurrAffectation();
         // Si on n'a pas d'affectation on va essayer de chercher la première
         if (!$affectation->_id) {
             $affectation = $sejour->loadRefFirstAffectation();
         }
     }
     $affectation->loadRefLit()->loadRefChambre();
     $current_uf = $sejour->getUFs(null, $affectation->_id);
     $name = null;
     if ($receiver && $receiver->_id && isset($receiver->_configs)) {
         switch ($receiver->_configs["build_PV1_3_1"]) {
             case "UF":
                 $name = $current_uf["hebergement"]->code;
                 break;
             case "service":
                 if ($affectation->_id) {
                     $name = $affectation->loadRefService()->nom;
                 }
                 if (!$name) {
                     $name = $sejour->loadRefService()->nom;
                 }
                 break;
             default:
         }
     }
     $pl1 = $name ? $name : $default_name;
     return array(array($pl1, $this->getPL2($receiver, $affectation), $this->getPL3($receiver, $affectation), $this->getGroupAssigningAuthority($sejour->loadRefEtablissement()), $this->getPL5($receiver), null, CHL7v2TableEntry::mapTo("307", $group->_id)));
 }
 /**
  * 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;
 }
}
switch ($order_col) {
    case "_entree":
        $order = "entree {$order_way}, rpu.ccmu {$order_way}";
        break;
    case "ccmu":
        $order = "rpu.ccmu {$order_way}, entree {$order_way}";
        break;
    case "_patient_id":
        $order = "patients.nom {$order_way}, ccmu {$order_way}";
}
/** @var CSejour[] $listSejours */
$listSejours = $sejour->loadList($where, $order, null, "`sejour`.sejour_id", $ljoin);
if ($service_id) {
    foreach ($listSejours as $key => $sejour) {
        $curr_aff = $sejour->getCurrAffectation();
        if (!$curr_aff->_id && (!$sejour->service_id || $sejour->service_id != $service_id) || $curr_aff->service_id != $service_id) {
            unset($listSejours[$key]);
        }
    }
}
CMbObject::massLoadFwdRef($listSejours, "patient_id");
CMbObject::massLoadFwdRef($listSejours, "group_id");
$prats = CMbObject::massLoadFwdRef($listSejours, "praticien_id");
CMbObject::massLoadFwdRef($prats, "function_id");
CMbObject::massCountBackRefs($listSejours, "notes");
CMbObject::massCountBackRefs($listSejours, "rpu");
CMbObject::massCountBackRefs($listSejours, "consultations");
CMbObject::massCountBackRefs($listSejours, "prescriptions");
CMbObject::massCountBackRefs($listSejours, "documents");
CMbObject::massCountBackRefs($listSejours, "files");