Ejemplo n.º 1
0
 /**
  * Get the patient merge by date
  *
  * @param Date $before before date
  * @param Date $now    now date
  *
  * @return array
  */
 static function getPatientMergeByDate($before, $now)
 {
     $where = array("date >= '{$before} 00:00:00'", "date <= '{$now} 23:59:59'", "type = 'merge'", "object_class = 'CPatient'");
     $ds = CSQLDataSource::get("std");
     $ds->exec("SET SESSION group_concat_max_len = 100000;");
     $request = new CRequest();
     $request->addSelect("DATE(date) AS 'date', COUNT(*) AS 'total', GROUP_CONCAT( object_id  SEPARATOR '-') as ids");
     $request->addTable("user_log");
     $request->addWhere($where);
     $request->addGroup("DATE(date)");
     return $ds->loadList($request->makeSelect());
 }
Ejemplo n.º 2
0
 /**
  * @return string[]
  */
 function getItemNames()
 {
     $item = new CExListItem();
     $where = array($this->getBackRefField() => "= '{$this->_id}'");
     $request = new CRequest();
     $request->addWhere($where);
     $request->addTable($item->_spec->table);
     $request->addOrder("LPAD(code, 20, '0'), name");
     $request->addSelect(array($item->_spec->key, "name"));
     $ds = $item->_spec->ds;
     return $ds->loadHashList($request->makeSelect());
 }
Ejemplo n.º 3
0
 /**
  * Ajout des codes pour les Groups
  *
  * @return bool
  */
 protected function addCodeToGroups()
 {
     $ds = CSQLDataSource::get("std");
     $request = new CRequest();
     $request->addSelect(array("group_id", "code", "text"));
     $request->addTable("groups_mediboard");
     $query = $request->makeSelect();
     $groups = $ds->loadList($query);
     foreach ($groups as $_group) {
         $group_id = $_group["group_id"];
         $code = CMbString::makeInitials($_group["text"]);
         $query = $ds->prepare("UPDATE `groups_mediboard` SET `code`=?1 WHERE `group_id`= ?2", $code, $group_id);
         $ds->exec($query);
     }
     return true;
 }
Ejemplo n.º 4
0
 function check()
 {
     $msg = parent::check();
     if (!$msg) {
         $where = array();
         $where["date"] = $this->_spec->ds->prepare("= %", $this->date);
         $where["affectation_id"] = $this->_spec->ds->prepare("= %", $this->affectation_id);
         $where["typerepas_id"] = $this->_spec->ds->prepare("= %", $this->typerepas_id);
         if ($this->repas_id) {
             $where["repas_id"] = $this->_spec->ds->prepare("!= %", $this->repas_id);
         }
         $select = "count(`" . $this->_spec->key . "`) AS `total`";
         $sql = new CRequest();
         $sql->addTable($this->_spec->table);
         $sql->addSelect($select);
         $sql->addWhere($where);
         $nbRepas = $this->_spec->ds->loadResult($sql->makeSelect());
         if ($nbRepas) {
             $msg .= "Un repas a déjà été créé, vous ne pouvez pas en créer un nouveau.";
         }
     }
     return $msg;
 }
Ejemplo n.º 5
0
 /**
  * Nettoie les operation_id
  *
  * @return bool
  */
 protected function cleanOperationIdError()
 {
     $ds = $this->ds;
     $where = array();
     $where["consultation_anesth.operation_id"] = "!= 0";
     $where[] = "consultation_anesth.operation_id IS NOT NULL";
     $where[] = "(SELECT COUNT(operations.operation_id) FROM operations WHERE operation_id=consultation_anesth.operation_id)=0";
     $query = new CRequest();
     $query->addSelect("consultation_anesth_id");
     $query->addTable("consultation_anesth");
     $query->addWhere($where);
     $aKeyxAnesth = $ds->loadColumn($query->makeSelect());
     if ($aKeyxAnesth === false) {
         return false;
     }
     if (count($aKeyxAnesth)) {
         $query = "UPDATE consultation_anesth SET operation_id = NULL WHERE (consultation_anesth_id " . CSQLDataSource::prepareIn($aKeyxAnesth) . ")";
         if (!$ds->exec($query)) {
             return false;
         }
         return true;
     }
     return true;
 }
Ejemplo n.º 6
0
// filtre sur le praticien
if ($prat_id) {
    $where["sejour.praticien_id"] = "= '{$prat_id}'";
}
$where["sejour.entree"] = " BETWEEN '{$month_min}' AND '{$nextmonth}'";
$where["sejour.group_id"] = " = '{$group->_id}'";
$where["sejour.annule"] = " = '0'";
// Liste des admissions par jour
$request = new CRequest();
$request->addSelect(array("DATE_FORMAT(sejour.entree, '%Y-%m-%d') AS 'date'", "COUNT(sejour.sejour_id) AS 'num'"));
$request->addTable("sejour");
$request->addWhere($where);
$request->addLJoin($leftjoin);
$request->addGroup("date");
$request->addOrder("date");
foreach ($ds->loadHashList($request->makeSelect()) as $day => $num1) {
    $days[$day]["admissions"] = $num1;
}
// Liste des admissions non préparées
$where["sejour.entree_preparee"] = " = '0'";
$request->addWhere($where);
foreach ($ds->loadHashList($request->makeSelect()) as $day => $num3) {
    $days[$day]["admissions_non_preparee"] = $num3;
}
// Liste des admissions non effectuées par jour
unset($where['sejour.entree']);
unset($where['sejour.entree_preparee']);
$request->where = array();
$where["sejour.entree_prevue"] = " BETWEEN '{$month_min}' AND '{$nextmonth}'";
$where["sejour.entree_reelle"] = " IS NULL";
$request->addWhere($where);
Ejemplo n.º 7
0
<?php

/**
 * $Id$
 *
 * @package    Mediboard
 * @subpackage SSR
 * @author     SARL OpenXtrem <*****@*****.**>
 * @license    GNU General Public License, see http://www.gnu.org/licenses/gpl.html
 * @version    $Revision$
 */
CCanDo::checkEdit();
// Liste des RHSs
$rhs = new CRHS();
$req = new CRequest();
$req->addTable("rhs");
$req->addLJoinClause("sejour", "sejour.sejour_id = rhs.sejour_id");
$req->addColumn("date_monday", "mondate");
$req->addColumn("COUNT(*)", "count");
$req->addWhereClause("rhs.facture", " = '0'");
$req->addWhereClause("sejour.annule", " = '0'");
$req->addGroup("date_monday");
$ds = $rhs->_spec->ds;
$rhs_counts = $ds->loadList($req->makeSelect());
foreach ($rhs_counts as &$_rhs_count) {
    $_rhs_count["sundate"] = CMbDT::date("+6 DAYS", $_rhs_count["mondate"]);
}
// Création du template
$smarty = new CSmartyDP();
$smarty->assign("rhs_counts", $rhs_counts);
$smarty->display("vw_facturation_rhs.tpl");
Ejemplo n.º 8
0
        $where["prescription.type"] = "= 'sejour'";
        $where["prescription.object_class"] = "= 'CSejour'";
        $where["prescription.object_id"] = $ds->prepareIn($sejour_ids);
        $line_ids = $line->loadIds($where, null, null, null, $join);
        // Prescriptions exécutables
        $query = new CRequest();
        $query->addSelect("DISTINCT prescription_id");
        $query->addTable("prescription_line_element");
        $query->addWhereClause("prescription_line_element_id", $ds->prepareIn($line_ids));
        $prescription_ids = $ds->loadColumn($query->makeSelect());
        // Séjours planifiables
        $query = new CRequest();
        $query->addSelect("DISTINCT object_id");
        $query->addTable("prescription");
        $query->addWhereClause("prescription_id", $ds->prepareIn($prescription_ids));
        $sejour_ids = $ds->loadColumn($query->makeSelect());
        $where = array();
        $where["sejour_id"] = $ds->prepareIn($sejour_ids);
        $join = array();
        $join["patients"] = "patients.patient_id = sejour.patient_id";
        $order = "nom, prenom";
        if ($mode == "count") {
            $counts["plannable"] = $sejour->countList($where, null, $join);
        } else {
            $sejours = $sejour->loadList($where, $order, null, null, $join);
        }
    }
}
// Mode count
if ($mode == "count") {
    $smarty = new CSmartyDP();
         $request_b->addSelect("operations.operation_id, patients.patient_id" . $other_fields);
         $request_b->addTable("operations");
         $request_b->addOrder("patients.nom ASC, operations.date ASC");
     } else {
         $request_b->addSelect("patients.patient_id");
         $request_b->addTable("patients");
         $request_b->addOrder("patients.nom ASC");
     }
     $request_b->addLJoin($ljoin);
     $request_b->addRJoin($rjoinMix);
     $request_b->addWhere($where);
     $request_b->addWhere($whereMix);
     if (!$export) {
         $request_b->setLimit("{$start},30");
     }
     $results = array_merge($results, $ds->loadList($request_b->makeSelect()));
 }
 foreach ($results as $_result) {
     $_patient_id = $_result["patient_id"];
     $pat = new CPatient();
     $pat->load($_patient_id);
     // Recherche sur un antécédent
     if (isset($_result["antecedent_id"])) {
         $_atcd = new CAntecedent();
         $_atcd->load($_result["antecedent_id"]);
         $pat->_ref_antecedent = $_atcd;
     } else {
         // On affiche tous les antécédents du patient
         $dossier_medical = $pat->loadRefDossierMedical(false);
         $pat->_refs_antecedents = $dossier_medical->loadRefsAntecedents();
         $pat->_refs_allergies = $dossier_medical->loadRefsAllergies();
Ejemplo n.º 10
0
<?php

/**
 * Add domain with idex EAI
 *
 * @category EAI
 * @package  Mediboard
 * @author   SARL OpenXtrem <*****@*****.**>
 * @license  GNU General Public License, see http://www.gnu.org/licenses/gpl.html
 * @version  SVN: $Id:$
 * @link     http://www.mediboard.org
 */
CCanDo::checkAdmin();
$domain = new CDomain();
// Récupération des objet_class
$req = new CRequest();
$req->addTable("id_sante400");
$req->addColumn("object_class");
$req->addGroup("object_class");
$ds = CSQLDataSource::get("std");
$idexs_class = CMbArray::pluck($ds->loadList($req->makeSelect()), "object_class");
// Création du template
$smarty = new CSmartyDP();
$smarty->assign("domain", $domain);
$smarty->assign("idexs_class", $idexs_class);
$smarty->display("inc_add_domain_with_idex.tpl");
Ejemplo n.º 11
0
/* $Id$ */
/**
 * @package Mediboard
 * @subpackage sante400
 * @version $Revision$
 * @author SARL OpenXtrem
 * @license GNU General Public License, see http://www.gnu.org/licenses/gpl.html 
 */
CCanDo::checkEdit();
CView::enforceSlave();
// Statistiques sur les id400
$req = new CRequest();
$req->addTable("id_sante400");
$req->addColumn("COUNT(DISTINCT object_id)", "nbObjects");
$req->addColumn("COUNT(id_sante400_id)", "nbID400s");
$ds = CSQLDataSource::get("std");
$statTotal = $ds->loadList($req->makeSelect());
$statTotal = $statTotal[0];
$req->addSelect("object_class");
$req->addGroup("object_class");
$stats = $ds->loadList($req->makeSelect());
// Computes average ID400 count per object
foreach ($stats as &$stat) {
    $stat["average"] = $stat["nbID400s"] / $stat["nbObjects"];
}
$statTotal["average"] = @($statTotal["nbID400s"] / $statTotal["nbObjects"]);
// Création du template
$smarty = new CSmartyDP();
$smarty->assign("stats", $stats);
$smarty->assign("statTotal", $statTotal);
$smarty->display("stats_identifiants.tpl");
Ejemplo n.º 12
0
        }
        $orderby = "{$order_column} {$order_way}";
    }
}
$request = new CRequest();
$request->addTable($table);
$request->addSelect("*");
$request->setLimit("{$start},{$count}");
if ($orderby) {
    $request->addOrder($orderby);
}
if ($where_column) {
    $where = array($where_column => $ds->prepare("=?", $where_value));
    $request->addWhere($where);
}
$rows = $ds->loadList($request->makeSelect());
$request->setLimit(null);
$request->order = null;
$total = $ds->loadResult($request->makeSelectCount());
$counts = array(10, 50, 100, 200, 500, 1000, 5000);
$smarty = new CSmartyDP();
$smarty->assign("rows", $rows);
$smarty->assign("columns", $columns);
$smarty->assign("tooltip", $tooltip);
$smarty->assign("dsn", $dsn);
$smarty->assign("table", $table);
$smarty->assign("total", $total);
$smarty->assign("start", $start);
$smarty->assign("count", $count);
$smarty->assign("counts", $counts);
$smarty->assign("order_column", $order_column);
}
$select = $fields;
$select["TOTAL"] = "COUNT(*)";
$select["IDS"] = "GROUP_CONCAT(CAST({$spec->key} AS CHAR))";
$orderby = "TOTAL DESC";
$count_min = max(1, $count_min);
$having = array("TOTAL" => $spec->ds->prepare("> ?", $count_min));
$where = array("patient_id" => "IS NOT NULL");
$request = new CRequest();
$request->addSelect($select);
$request->addTable($spec->table);
$request->addGroup($fields);
$request->addWhere($where);
$request->addOrder($orderby);
$request->addHaving($having);
$list = $spec->ds->loadList($request->makeSelect());
$count_total = 0;
foreach ($list as $_corresp) {
    $ids = explode(",", $_corresp["IDS"]);
    if (empty($ids)) {
        continue;
    }
    array_unique($ids);
    sort($ids);
    array_pop($ids);
    // Only keep last
    CAppUI::stepAjax(" -- Patient #" . $_corresp["patient_id"], UI_MSG_OK);
    $count = 0;
    foreach ($ids as $_id) {
        if ($dry_run) {
            $count++;
 /**
  * MassCount des allergies
  *
  * @param array $dossiers Dossier médicaux
  *
  * @return array
  */
 static function massCountAllergies($dossiers = array())
 {
     $antecedent = new CAntecedent();
     $where["type"] = "= 'alle'";
     $where["annule"] = " ='0'";
     $where["dossier_medical_id"] = CSQLDataSource::prepareIn($dossiers);
     $where["rques"] = 'NOT IN ("' . str_replace('|', '","', CAppUI::conf("soins Other ignore_allergies", CGroups::loadCurrent()->_guid)) . '")';
     $request = new CRequest();
     $request->addColumn("dossier_medical_id");
     $request->addColumn("count(*)", "c");
     $request->addWhere($where);
     $request->addGroup("dossier_medical_id");
     $request->addTable("antecedent");
     return $antecedent->getDS()->loadHashList($request->makeSelect());
 }
    $where["sejour.praticien_id"] = " = '{$prat_id}'";
}
$month_min = CMbDT::dateTime(null, $month_min);
$nextmonth = CMbDT::dateTime(null, $nextmonth);
// Liste des sorties par jour
$request = new CRequest();
$request->addSelect(array("DATE_FORMAT(sejour.sortie_reelle, '%Y-%m-%d') AS 'date'", "COUNT(sejour.sejour_id) AS 'num'"));
$request->addTable("sejour");
$where["sejour.sortie_reelle"] = "BETWEEN '{$month_min}' AND '{$nextmonth}'";
$where["sejour.group_id"] = " = '{$group->_id}'";
$where["sejour.annule"] = " = '0'";
$request->addWhere($where);
$request->addLJoin($leftjoin);
$request->addGroup("date");
$request->addOrder("date");
foreach ($ds->loadHashList($request->makeSelect()) as $day => $_sortie) {
    $days[$day]["sortie"] = $_sortie;
}
// Liste des sorties dont le dossier n'a pas été reçu
$leftjoin["traitement_dossier"] = "traitement_dossier.sejour_id = sejour.sejour_id";
$where["traitement_dossier.traitement"] = " IS NOT NULL";
$request->addWhere($where);
$request->addLJoin($leftjoin);
foreach ($ds->loadHashList($request->makeSelect()) as $day => $_traitement) {
    $days[$day]["traitement"] = $_traitement;
}
// Liste des sorties dont le dossier est traité
unset($where['traitement_dossier.traitement']);
$request->where = array();
$where["traitement_dossier.validate"] = " IS NOT NULL";
$request->addWhere($where);
 /**
  * Transform the mb locales with the overwrite system
  *
  * @param array       $locales  locales from mediboard
  * @param string|null $language language chosen, if not defined, use the preference.
  *
  * @return array $locales locales transformed
  */
 function transformLocales($locales, $language = null)
 {
     $ds = $this->_spec->ds;
     $where = array("language" => $ds->prepare("=%", $language ? $language : CAppUI::pref("LOCALE")));
     $query = new CRequest();
     $query->addSelect("source, translation");
     $query->addTable("translation");
     $query->addWhere($where);
     $overwrites = $ds->loadList($query->makeSelect());
     foreach ($overwrites as $_overwrite) {
         $locales[$_overwrite["source"]] = $_overwrite["translation"];
     }
     return $locales;
 }
Ejemplo n.º 17
0
 /**
  * Vérifie l'unicité d'une aide à la saisie
  * 
  * @return string
  */
 function check()
 {
     $msg = "";
     $ds = $this->_spec->ds;
     $where = array();
     if ($this->user_id) {
         $where["user_id"] = $ds->prepare("= %", $this->user_id);
     } else {
         if ($this->function_id) {
             $where["function_id"] = $ds->prepare("= %", $this->function_id);
         } else {
             $where["group_id"] = $ds->prepare("= %", $this->group_id);
         }
     }
     $where["class"] = $ds->prepare("= %", $this->class);
     $where["field"] = $ds->prepare("= %", $this->field);
     $where["depend_value_1"] = $ds->prepare("= %", $this->depend_value_1);
     $where["depend_value_2"] = $ds->prepare("= %", $this->depend_value_2);
     $where["text"] = $ds->prepare("= %", $this->text);
     $where["aide_id"] = $ds->prepare("!= %", $this->aide_id);
     $sql = new CRequest();
     $sql->addSelect("count(aide_id)");
     $sql->addTable("aide_saisie");
     $sql->addWhere($where);
     $nb_result = $ds->loadResult($sql->makeSelect());
     if ($nb_result) {
         $msg .= "Cette aide existe déjà<br />";
     }
     return $msg . parent::check();
 }
Ejemplo n.º 18
0
 * @subpackage Stock
 * @author     SARL OpenXtrem <*****@*****.**>
 * @license    GNU General Public License, see http://www.gnu.org/licenses/gpl.html
 * @version    $Revision$
 */
CCanDo::checkEdit();
$ratio = (double) CValue::get("ratio", 2);
CApp::setMemoryLimit('512M');
CApp::setTimeLimit(120);
$sql = new CRequest();
$sql->addTable("product_order_item");
$sql->addSelect("\r\n  product_order_item.order_item_id,\r\n  product_order_item.reference_id, \r\n  product_reference.price AS RP, \r\n  product_order_item.unit_price AS OP, \r\n  product_order_item.quantity AS OQ, \r\n  product_order.order_id, \r\n  product_order.order_number, \r\n  product_order.date_ordered");
$sql->addLJoin(array("product_reference" => "product_reference.reference_id = product_order_item.reference_id", "product_order" => "product_order.order_id = product_order_item.order_id"));
$sql->addWhere("\r\n  product_order.cancelled = '0' \r\n  AND (product_reference.cancelled = '0' OR product_reference.cancelled IS NULL)\r\n  AND product_reference.price != product_order_item.unit_price\r\n  AND (\r\n    product_order_item.unit_price > product_reference.price*{$ratio} OR \r\n    product_reference.price > product_order_item.unit_price*{$ratio}\r\n  )");
$sql->addOrder("product_reference.code");
$changes = $this->_spec->ds->loadList($sql->makeSelect());
$changes_struct = array();
$references = array();
$references_cahpp = array();
foreach ($changes as $_change) {
    if (!isset($references[$_change["reference_id"]])) {
        $_reference = new CProductReference();
        $_reference->load($_change["reference_id"]);
        $references[$_reference->_id] = $_reference;
        $article = new CCAHPPArticle();
        $where = array("reference_fournisseur" => $article->_spec->ds->prepare("=%", $_reference->supplier_code));
        if (!$article->loadObject($where)) {
            $where = array("cip" => $article->_spec->ds->prepare("=%", $_reference->loadRefProduct()->code));
            $article->loadObject($where);
        }
        $references_cahpp[$_reference->_id] = $article;
 /**
  * Object list by a request object
  *
  * @param CRequest $request Request
  *
  * @return self[] List of found objects, null if module is not installed
  */
 function loadListByReq(CRequest $request)
 {
     if (!$this->_ref_module) {
         return null;
     }
     return $this->loadQueryList($request->makeSelect($this));
 }
Ejemplo n.º 20
0
 /**
  * Get random value
  *
  * @param string $field       Field name
  * @param bool   $is_not_null Search field not null
  *
  * @return mixed
  */
 function getRandomValue($field, $is_not_null = false)
 {
     $ds = $this->getDS();
     $query = new CRequest();
     $query->addSelect($field);
     $query->addTable($this->_spec->table);
     if ($is_not_null) {
         $query->addWhereClause($field, "IS NOT NULL");
     }
     $query->addOrder("RAND()");
     $query->setLimit(1);
     return $ds->loadResult($query->makeSelect());
 }
// Comptage des événements hors-séjours
$group = "sejour.sejour_id";
$query = new CRequest();
$query->addTable("evenement_ssr");
$query->addColumn("COUNT(evenement_ssr_id)", "evenements_count");
$query->addWhereClause("debut", "BETWEEN '{$date_min}' AND '{$date_max}'");
$query->addWhereClause("type", "= 'ssr'");
$query->addLJoinClause("sejour", "sejour.sejour_id = evenement_ssr.sejour_id");
$query->addColumn("sejour.sejour_id");
$query->addWhereClause(null, "debut NOT BETWEEN DATE(entree) AND DATE(ADDDATE(sortie, 1))");
$query->addWhereClause("sejour.annule", "!= '1'");
$query->addGroup("sejour.sejour_id");
$sejour = new CSejour();
$ds = $sejour->_spec->ds;
$evenements_counts = array();
foreach ($ds->loadList($query->makeSelect()) as $row) {
    $evenements_counts[$row["sejour_id"]] = $row["evenements_count"];
}
// Chargement des séjours concernés
/** @var CSejour[] $sejours */
$sejours = $sejour->loadAll(array_keys($evenements_counts));
$sejours_count = count($sejours);
// Détails sur les séjours concernés
foreach ($sejours as $_sejour) {
    $_sejour->checkDaysRelative($date);
    $_sejour->loadRefPatient()->loadIPP();
}
// Création du template
$smarty = new CSmartyDP();
$smarty->assign("sejours", $sejours);
$smarty->assign("sejours_count", $sejours_count);
Ejemplo n.º 22
0
 function getDbIds($min_id = null)
 {
     $ds = CSQLDataSource::get("std");
     $request = new CRequest();
     $request->addColumn("DISTINCT id400");
     $request->addTable("id_sante400");
     $tag = $this->getImportTag();
     $where = array("object_class" => "= '{$this->_class}'", "tag" => "= '{$tag}'");
     if ($min_id) {
         $where["id400"] = $ds->prepare("> ?", $min_id);
     }
     $request->addWhere($where);
     return $ds->loadColumn($request->makeSelect());
 }
Ejemplo n.º 23
0
 /**
  * Get the latest constantes values
  *
  * @param int|CPatient $patient   The patient to load the constantes for
  * @param string       $datetime  The reference datetime
  * @param array        $selection A selection of constantes to load
  * @param CMbObject    $context   The context
  * @param boolean      $use_cache Force the function to return the latest_values is already set
  *
  * @return array The constantes values and dates
  */
 static function getLatestFor($patient, $datetime = null, $selection = array(), $context = null, $use_cache = true)
 {
     $patient_id = $patient instanceof CPatient ? $patient->_id : $patient;
     if (isset(self::$_latest_values[$patient_id][$datetime]) && $use_cache === true) {
         return self::$_latest_values[$patient_id][$datetime];
     }
     if (empty($selection)) {
         $list_constantes = CConstantesMedicales::$list_constantes;
     } else {
         $list_constantes = array_intersect_key(CConstantesMedicales::$list_constantes, array_flip($selection));
     }
     // Constante que l'on va construire
     $constante = new CConstantesMedicales();
     if (!$patient_id) {
         return array($constante, array());
     }
     $constante->patient_id = $patient_id;
     $constante->datetime = CMbDT::dateTime();
     $constante->loadRefPatient();
     $where = array("patient_id" => "= '{$patient_id}'");
     if ($context) {
         $where["context_class"] = " = '{$context->_class}'";
         $where["context_id"] = " = '{$context->_id}'";
     }
     if ($datetime) {
         $where["datetime"] = "<= '{$datetime}'";
     }
     if (count($selection)) {
         $ors = array();
         foreach ($selection as $_item) {
             $ors[] = "{$_item} IS NOT NULL";
         }
         $where[] = implode(" OR ", $ors);
     }
     $count = $constante->countList($where);
     // Load all constants instead of checking every type to reduce number of SQL queries
     /** @var self[] $all_list */
     $all_list = array();
     if ($count <= 30) {
         $all_list = $constante->loadList($where, "datetime DESC");
     }
     $list_datetimes = array();
     foreach ($list_constantes as $type => $params) {
         $list_datetimes[$type] = null;
         if ($type[0] == "_") {
             continue;
         }
         // Load them, if any ...
         if ($count > 0) {
             // Load them all and dispatch
             if ($count <= 30) {
                 foreach ($all_list as $_const) {
                     $_value = $_const->{$type};
                     if ($_value != null) {
                         $constante->{$type} = $_value;
                         $list_datetimes[$type] = $_const->datetime;
                         break;
                     }
                 }
             } else {
                 $_where = $where;
                 $_where[$type] = "IS NOT NULL";
                 $_list = $constante->loadList($_where, "datetime DESC", 1);
                 if (count($_list)) {
                     $_const = reset($_list);
                     $constante->{$type} = $_const->{$type};
                     $list_datetimes[$type] = $_const->datetime;
                 }
             }
         }
     }
     // Cumul de la diurese
     if ($datetime) {
         foreach ($list_constantes as $_name => $_params) {
             if (isset($_params["cumul_reset_config"]) || isset($_params["formula"])) {
                 $day_defore = CMbDT::dateTime("-24 hours", $datetime);
                 if (isset($_params["cumul_reset_config"]) && !isset($_params['formula'])) {
                     $cumul_field = '_' . $_name . '_cumul';
                     $reset_hour = str_pad(self::getHostConfig($_params["cumul_reset_config"], $context), 2, '0', STR_PAD_LEFT);
                     $cumul_begin = '';
                     $cumul_end = '';
                     if ($datetime >= CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00")) {
                         $cumul_begin = CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00");
                         $cumul_end = CMbDT::format(CMbDT::date('+1 DAY', $datetime), "%Y-%m-%d {$reset_hour}:00:00");
                     } else {
                         $cumul_begin = CMbDT::format(CMbDT::date('-1 DAY', $datetime), "%Y-%m-%d {$reset_hour}:00:00");
                         $cumul_end = CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00");
                     }
                     $query = new CRequest();
                     $query->addSelect("SUM(`{$_name}`)");
                     $query->addTable('constantes_medicales');
                     $query->addWhere(array("`datetime` >= '{$cumul_begin}'", "`datetime` <= '{$cumul_end}'", "`{$_name}` IS NOT NULL", "`patient_id` = {$patient_id}"));
                     $ds = CSQLDataSource::get('std');
                     $constante->{$cumul_field} = $ds->loadResult($query->makeSelect());
                 } else {
                     // cumul de plusieurs champs (avec formule)
                     $formula = $_params["formula"];
                     foreach ($formula as $_field => $_sign) {
                         $_where = $where;
                         $_where[$_field] = "IS NOT NULL";
                         $_where[] = "datetime >= '{$day_defore}'";
                         $_list = $constante->loadList($_where);
                         foreach ($_list as $_const) {
                             if ($_sign === "+") {
                                 $constante->{$_name} += $_const->{$_field};
                             } else {
                                 $constante->{$_name} -= $_const->{$_field};
                             }
                         }
                     }
                 }
             }
         }
     }
     $constante->updateFormFields();
     // Don't cache partial loadings
     if (empty($selection)) {
         self::$_latest_values[$patient_id][$datetime] = array($constante, $list_datetimes);
     }
     return array($constante, $list_datetimes);
 }
Ejemplo n.º 24
0
     }
     break;
     // Nombre de transferts
 // Nombre de transferts
 case "transfers_count":
     $data[$axe] = array("options" => array("title" => utf8_encode("Nombre de transferts")), "series" => array());
     $series =& $data[$axe]['series'];
     $sejour = new CSejour();
     $end = end($dates);
     $start = reset($dates);
     $query = new CRequest();
     $query->addSelect("sejour.etablissement_sortie_id");
     $query->addTable("sejour");
     $query->addGroup("sejour.etablissement_sortie_id");
     $query->addWhere(array("sejour.entree" => "BETWEEN '{$start}' AND '{$end}'", "sejour.etablissement_sortie_id" => "IS NOT NULL"));
     $etab_externe_ids = $sejour->_spec->ds->loadColumn($query->makeSelect());
     $etab_externe = new CEtabExterne();
     $etabs = $etab_externe->loadList(array($etab_externe->_spec->key => $etab_externe->_spec->ds->prepareIn($etab_externe_ids)));
     $etabs["none"] = $etab_externe;
     $etabs["none"]->_view = "Non renseigné";
     $where["sejour.mode_sortie"] = "= 'transfert'";
     $key = 0;
     foreach ($etabs as $_id => $_etab) {
         $series[$key] = array('data' => array(), 'label' => utf8_encode($_etab->_view));
         $sub_total = 0;
         foreach ($dates as $i => $_date) {
             $_date_next = CMbDT::date("+1 {$period}", $_date);
             $where['sejour.entree'] = "BETWEEN '{$_date}' AND '{$_date_next}'";
             $where['sejour.etablissement_sortie_id'] = $_id === "none" ? "IS NULL" : "= '{$_id}'";
             $count = $sejour->countList($where, null, $ljoin);
             $total += $count;
Ejemplo n.º 25
0
//</editor-fold>
//<editor-fold desc=" ----- Insert ----- ">
$request = new CRequest();
$request->addWhereClause("user_log_id", "BETWEEN {$min} AND {$max}");
$request->addForceIndex("PRIMARY");
// Insert clauses
$triplets = array();
foreach ($inserts as $_insert) {
    list($object_class, $type, $fields) = $_insert;
    $triplets[] = "{$object_class}-{$type}-{$fields}";
}
$where = "CONCAT_WS('-', `object_class`, `type`, `fields`) " . CSQLDataSource::prepareIn($triplets);
$request->addWhere($where);
// Actual query
if ($execute) {
    $query = $request->makeSelect($log);
    $list = $ds->loadList($query);
    $class_to_table = array();
    foreach ($list as $_row) {
        $_object_class = $_row["object_class"];
        $_type = $_row["type"];
        $_fields = $_row["fields"];
        if (!isset($class_to_table[$_object_class])) {
            $_obj = CModelObject::getInstance($_object_class);
            $_spec = $_obj->_spec;
            $class_to_table[$_object_class] = array("table" => $_spec->table, "key" => $_spec->key);
        }
        $_table_info = $class_to_table[$_object_class];
        $_table = $_table_info["table"];
        $_key = $_table_info["key"];
        foreach ($inserts as $_insert) {
 /**
  * Get the configuration values of an object, without inheritance
  *
  * @param string  $object_class Object class
  * @param integer $object_id    Object ID
  * @param array   $config_keys  The keys of the values to get
  *
  * @return array The configuration values
  */
 protected static function getSelfConfig($object_class = null, $object_id = null, $config_keys = null)
 {
     static $cache_data = null;
     static $cache = array();
     $key = "{$object_class}/{$object_id}/" . ($config_keys ? implode("-", $config_keys) : "");
     if (isset($cache[$key])) {
         return $cache[$key];
     }
     if ($cache_data === null) {
         $spec = self::_getSpec();
         $request = new CRequest();
         $request->addTable($spec->table);
         $request->addSelect(array("feature", "value", "object_class", "object_id"));
         $cache_data = $spec->ds->loadList($request->makeSelect());
     }
     if ($object_class && $object_id) {
         $data = array_filter($cache_data, function ($v) use($object_class, $object_id) {
             return $v["object_class"] === $object_class && $v["object_id"] === $object_id;
         });
     } else {
         $data = array_filter($cache_data, function ($v) {
             return $v["object_class"] === null && $v["object_id"] === null;
         });
     }
     if ($config_keys) {
         $data = array_filter($data, function ($v) use($config_keys) {
             return in_array($v["feature"], $config_keys);
         });
     }
     $final_data = array();
     foreach ($data as $_data) {
         $final_data[$_data["feature"]] = $_data["value"];
     }
     return $cache[$key] = $final_data;
 }
 * @author     SARL OpenXtrem <*****@*****.**>
 * @license    GNU General Public License, see http://www.gnu.org/licenses/gpl.html
 * @version    $Revision$
 */
CCanDo::checkAdmin();
$original_trigger_code = CValue::post("original_trigger_code");
$do_it = CValue::post("do_it");
$count = CValue::post("count", 10);
$auto = CValue::post("auto");
$request = new CRequest();
$request->addSelect(array("CAST(GROUP_CONCAT(movement_id) AS CHAR) AS ids", "original_trigger_code", "start_of_movement", "sejour_id"))->addTable("movement")->addWhere(array("original_trigger_code" => "= '{$original_trigger_code}'"))->addGroup(array("original_trigger_code", "start_of_movement", "sejour_id"))->addHaving("COUNT(movement_id) > 1");
if ($do_it) {
    $request->setLimit($count);
}
$mov = new CMovement();
$query = $request->makeSelect();
$list = $mov->_spec->ds->loadList($query);
if (!$do_it) {
    CAppUI::setMsg(count($list) . " doublons à traiter");
} else {
    foreach ($list as $_mvt) {
        $ids = explode(",", $_mvt["ids"]);
        sort($ids);
        // IMPORTANT, must use the first movement created as a reference
        $first = new CMovement();
        $first->load($ids[0]);
        $second = new CMovement();
        $second->load($ids[1]);
        $tag = CIdSante400::getMatch($second->_class, $second->getTagMovement(), null, $second->_id);
        if ($tag->_id) {
            $tag->tag = "trash_{$tag->tag}";
Ejemplo n.º 28
0
$query->addGroup("debut");
$query->addColumn("fin");
$query->addGroup("fin");
$query->addColumn("chir_id");
$query->addGroup("chir_id");
$query->addColumn("spec_id");
$query->addGroup("spec_id");
$query->addColumn("plagesop.salle_id");
$query->addGroup("plagesop.salle_id");
$query->addLJoinClause("sallesbloc", "sallesbloc.salle_id = plagesop.salle_id");
$query->addLJoinClause("bloc_operatoire", "bloc_operatoire.bloc_operatoire_id = sallesbloc.bloc_id");
$query->addWhereClause("bloc_operatoire.group_id", "= '{$group->_id}'");
$query->addOrder("plagesop.date");
$query->addHaving("plage_count > 1");
$ds = $plage->_spec->ds;
$duplicates = $ds->loadColumn($query->makeSelect($plage));
$count = count($duplicates);
$success_count = 0;
$failures = array();
$i = $max;
if ($merge) {
    foreach ($duplicates as $_plage_ids) {
        if (!$i--) {
            break;
        }
        $plage_ids = explode("-", $_plage_ids);
        $plages = $plage->loadAll($plage_ids);
        /** @var CPlageOp $first */
        $first = array_shift($plages);
        while ($next = array_shift($plages)) {
            if ($msg = $first->merge(array($next))) {
 /**
  * Get all the fields' names
  *
  * @param bool $name_as_key Put the names in the keys
  * @param bool $all_groups  Load all groups
  *
  * @return string[] List of field names
  */
 function getFieldNames($name_as_key = true, $all_groups = true)
 {
     $ds = $this->_spec->ds;
     $req = new CRequest();
     $req->addTable($this->_spec->table);
     $req->addSelect("ex_class_field.name, ex_class_field_translation.std AS locale");
     $ljoin = array("ex_class_field_translation" => "ex_class_field_translation.ex_class_field_id = ex_class_field.ex_class_field_id");
     $req->addLJoin($ljoin);
     $this->completeField("ex_group_id");
     $where = array();
     if ($all_groups) {
         $ex_group = $this->loadRefExGroup();
         $where_ids = array("ex_class_id" => $ds->prepare("= %", $ex_group->ex_class_id));
         $ids = $ex_group->loadIds($where_ids);
         $where["ex_group_id"] = $ds->prepareIn($ids);
     } else {
         $where["ex_group_id"] = $ds->prepare("= %", $this->ex_group_id);
     }
     $req->addWhere($where);
     $results = $ds->loadList($req->makeSelect());
     if ($name_as_key) {
         return array_combine(CMbArray::pluck($results, "name"), CMbArray::pluck($results, "locale"));
     }
     return array_combine(CMbArray::pluck($results, "locale"), CMbArray::pluck($results, "name"));
 }
Ejemplo n.º 30
0
 /**
  * Computes the weighted average price (PMP)
  *
  * @param string $since    [optional]
  * @param string $date_max [optional]
  * @param bool   $ttc      Include taxes
  *
  * @return float
  */
 function getWAP($since = "-1 MONTH", $date_max = null, $ttc = false)
 {
     $qty = $this->getSupply($since, $date_max);
     if (!$qty) {
         return null;
     }
     $where = array("product.product_id" => "= '{$this->_id}'", "product_order_item_reception.date > '" . CMbDT::date($since) . "'");
     if ($date_max) {
         $where[] = "product_order_item_reception.date <= '" . CMbDT::date($date_max) . "'";
     }
     $ljoin = array("product_order_item" => "product_order_item.order_item_id = product_order_item_reception.order_item_id", "product_reference" => "product_reference.reference_id = product_order_item.reference_id", "product" => "product.product_id = product_reference.product_id");
     $sql = new CRequest();
     $sql->addTable("product_order_item_reception");
     $select = "SUM(product_order_item_reception.quantity * product_order_item.unit_price)";
     if ($ttc) {
         $ttc_select = "product_order_item.unit_price + (product_order_item.unit_price * (product_order_item.tva / 100))";
         $select = "SUM(product_order_item_reception.quantity * ({$ttc_select}))";
     }
     $sql->addSelect($select);
     $sql->addLJoin($ljoin);
     $sql->addWhere($where);
     $total = $this->_spec->ds->loadResult($sql->makeSelect());
     return $total / $qty;
 }