/** * @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()); }
/** * 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()); }
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; }
/** * 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; }
/** * 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(); }
/** * 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; }
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()); }
* * @package Mediboard * @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);
function doIt() { $this->doBind(); if ($this->synchro) { if (!$this->_old->_id && $this->_obj->repas_id) { // Repas supprimé depuis la derniere synchro CAppUI::setMsg("Le repas a été supprimé depuis la dernière synchronisation.", UI_MSG_ERROR); $this->doRedirect(); } //Test suppression de ref $error_ref = null; $object = $this->_obj; $plats = new CPlat(); $object->loadRemplacements(); $object->loadRefAffectation(); $object->loadRefMenu(); if (!$object->_ref_affectation->affectation_id) { CAppUI::setMsg("L'affectation n'existe pas.", UI_MSG_ERROR); $error_ref = true; } if ($object->menu_id && !$object->_ref_menu->menu_id) { CAppUI::setMsg("Le menu n'existe pas.", UI_MSG_ERROR); $error_ref = true; } foreach ($plats->_specs["type"]->_list as $curr_typePlat) { if ($object->{$curr_typePlat} && !$object->{"_ref_" . $curr_typePlat}) { CAppUI::setMsg("Le Plat de remplacement " . $curr_typePlat . " n'existe pas.", UI_MSG_ERROR); $error_ref = true; } } if ($error_ref) { $this->doRedirect(); } if (!$this->synchroConfirm && $this->_old->_id) { $object = $this->_old; $select = "count(`user_log_id`) AS `total`"; $table = "user_log"; $where = array(); $where["object_id"] = "= '{$object->_id}'"; $where["object_class"] = "= '{$this->className}'"; $where["date"] = ">= '" . strftime("%Y-%m-%d %H:%M:%S", $this->synchroDatetime) . "'"; $sql = new CRequest(); $sql->addTable($table); $sql->addSelect($select); $sql->addWhere($where); $nbLogs = $this->ds->loadResult($sql->makeSelect()); if ($nbLogs) { CAppUI::setMsg("Le repas a été modifié depuis la dernière synchronisation. Voulez-vous tout de même l'enregistrer ?", UI_MSG_WARNING); $this->doRedirect(true); } } } if (intval(CValue::post('del'))) { $this->doDelete(); } else { $this->doStore(); } $this->doRedirect(); }
/** * Return the formated datas of a constant for making graphs with Flot * * @param string $constant_name The name of the constant * @param string $constant_type The type of the constant : line|cumul|formula|bandwidth * @param CConstantesMedicales[] $constant_values The CConstantesMedicales containing the values * * @return array */ function getDatasForConstant($constant_name, $constant_type, $constant_values) { $tick = 1; $datas = array('values' => array()); $values = array(); /* Initializing the period for the cumul */ if (($constant_type == 'cumul' || $constant_type == 'formula') && !empty($constant_values)) { $reset_hour = CConstantesMedicales::getResetHour($constant_name); $first_value = reset($constant_values); $start = strtotime(CMbDT::format($first_value->datetime, "%Y-%m-%d 0{$reset_hour}:00:00")); if (strtotime($first_value->datetime) < $start) { $start = $start - 24 * 3600; } $current_period = array('start' => $start, 'end' => $start + 24 * 3600); $current_value = null; $start_tick = 1; $periods = array(); } foreach ($constant_values as $_value) { /* Calculating the value for the cumul */ if ($constant_type == 'cumul' || $constant_type == 'formula') { if ($constant_type == 'formula') { $_value->{$constant_name} = $_value->applyFormula($constant_name); } $timestamp = strtotime($_value->datetime); /* If the current CConstantesMedicales's datetime is in the current period, we add the value to the cumuled value */ if ($timestamp > $current_period['start'] && $timestamp <= $current_period['end']) { $current_value += $_value->{$constant_name}; } else { /* If not, we add the cumuled value to the periods array, and initialize the current period */ $periods[] = array('start' => $start_tick, 'end' => $tick, 'start_time' => $current_period['start'], 'end_time' => $current_period['end'], 'value' => $current_value); $current_value = $_value->{$constant_name}; $start_tick = $tick; $start = $current_period['end']; if (strtotime($_value->datetime) - $start > 24 * 3600) { $start = strtotime(CMbDT::format($_value->datetime, '%Y-%m-%d' . sprintf('%02d', $reset_hour) . ':00:00')); if (strtotime($_value->datetime) < $start) { $start = $start - 24 * 3600; } } $current_period = array('start' => $start, 'end' => $start + 24 * 3600); } } if (!is_null($_value->{$constant_name}) && $constant_type != 'formula') { /* Get the last 5 user logs of the CConstantesMedicales object */ $users_logs = array(); if ($constant_name[0] !== "_") { $_value->loadRefUser(); if ($_value->_ref_user) { $users_logs[] = utf8_encode(CMbDT::format($_value->getCreationDate(), '%d/%m/%y %H:%M') . ' - ' . $_value->_ref_user->_view); } } if ($this->display['mode'] == 'time') { $entry = array(CMbDate::toUTCTimestamp($_value->datetime)); } else { $entry = array($tick); } if ($constant_type == 'bandwidth') { $field = CConstantesMedicales::$list_constantes[$constant_name]['formfields']; $entry[] = $_value->{$field}[0]; $entry[] = $_value->{$field}[1]; $values[] = $_value->{$field}[0]; $values[] = $_value->{$field}[1]; } else { if (isset(CConstantesMedicales::$list_constantes[$constant_name]['formfields'])) { $field = CConstantesMedicales::$list_constantes[$constant_name]['formfields']; $entry[] = $_value->{$field}[0]; $values[] = $_value->{$field}[0]; } else { $entry[] = $_value->{$constant_name}; $values[] = $_value->{$constant_name}; } } $entry['id'] = $_value->_id; $entry['date'] = utf8_encode(CMbDT::format($_value->datetime, '%d/%m/%y')); $entry['hour'] = utf8_encode(CMbDT::format($_value->datetime, '%Hh%M')); $entry['users'] = $users_logs; if ($_value->comment) { $entry['comment'] = utf8_encode($_value->comment); } if ("{$_value->context_class}-{$_value->context_id}" !== $this->context_guid) { $_value->loadRefContext(); if ($_value->_ref_context) { $_value->_ref_context->loadRefsFwd(); $entry['context'] = utf8_encode($_value->_ref_context->_view); $entry['context_guid'] = "{$_value->context_class}-{$_value->context_id}"; } } $datas['values'][] = $entry; } $tick++; } if ($constant_type == 'cumul' || $constant_type == 'formula') { $cumul_datas = array(); if (!empty($constant_values)) { $periods[] = array('start' => $start_tick, 'end' => $tick, 'start_time' => $current_period['start'], 'end_time' => $current_period['end'], 'value' => $current_value); $cumul_datas = array(); $dtz = new DateTimeZone('Europe/Paris'); $tz_ofsset = $dtz->getOffset(new DateTime('now', $dtz)); foreach ($periods as $_period) { if ($this->display['mode'] == 'time') { $x = ($_period['start_time'] + $tz_ofsset) * 1000; $bar_width = ($_period['end_time'] - $_period['start_time']) * 1000; } else { $x = $_period['start']; $bar_width = $_period['end'] - $_period['start']; } if ($this->widget) { $first_value = reset($constant_values); $start_date = strftime('%Y-%m-%d %H:%M:%S', $_period['start_time']); $end_date = strftime('%Y-%m-%d %H:%M:%S', $_period['end_time']); $query = new CRequest(); $query->addSelect("SUM(`{$constant_name}`)"); $query->addTable('constantes_medicales'); $query->addWhere(array("`patient_id` = {$first_value->patient_id}", "`context_class` = '{$first_value->context_class}'", "`context_id` = {$first_value->context_id}", "`datetime` >= '{$start_date}'", "`datetime` <= '{$end_date}'", "`{$constant_name}` IS NOT NULL")); $ds = CSQLDataSource::get('std'); $_period['value'] = $ds->loadResult($query->makeSelect()); } $cumul_datas[] = array($x, $_period['value'], 'date' => utf8_encode(strftime('%d/%m/%y %H:%M', $_period['start_time']) . ' au ' . strftime('%d/%m/%y %H:%M', $_period['end_time'])), 'barWidth' => $bar_width); $values[] = $_period['value']; } } $datas['cumul'] = $cumul_datas; } if (!empty($values)) { $datas['min'] = floor(min($values)); $datas['max'] = ceil(max($values)); } return $datas; }
} elseif ($sejour_filled) { $request_b->addSelect("sejour.sejour_id, patients.patient_id" . $other_fields); $request_b->addTable("sejour"); $request_b->addOrder("patients.nom ASC, sejour.entree_prevue ASC"); } elseif ($interv_filled) { $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;
* @license GNU General Public License, see http://www.gnu.org/licenses/gpl.html * @version $Revision$ */ CCanDo::checkAdmin(); $type = CValue::get("type", "CEvenementSSR"); $date = CValue::get("date"); $period = CValue::get("period", "month"); $stats = new CMediusersStats($date, $period, "DATE(debut)", 18); $consult = new CConsultation(); $ds = $consult->_spec->ds; $group = CGroups::loadCurrent(); $query = new CRequest(); $query->addColumn("COUNT(*) total"); $query->addColumn("therapeute_id", "user_id"); $query->addColumn($stats->sql_date, "refdate"); $query->addWhere("{$stats->sql_date} BETWEEN '{$stats->min_date}' AND '{$stats->max_date}'"); $query->addWhereClause("functions_mediboard.group_id", "= '{$group->_id}'"); $query->addGroup("therapeute_id, refdate"); $query->addOrder("refdate DESC"); $totals = array(); switch ($type) { case "CEvenementSSR": $query->addTable("`evenement_ssr`"); $query->addLJoinClause("sejour", "sejour.sejour_id = evenement_ssr.sejour_id"); $query->addLJoinClause("users_mediboard", "users_mediboard.user_id = evenement_ssr.therapeute_id"); $query->addLJoinClause("functions_mediboard", "functions_mediboard.function_id = users_mediboard.function_id"); // Réalisés $query1 = clone $query; $query1->addWhereClause("evenement_ssr.realise", "= '1'"); foreach ($ds->loadList($query1->makeSelect()) as $_row) { $stats->addTotal($_row["user_id"], $_row["refdate"], $_row["total"], "realises");
/** * Inits locale cache * * @return void */ static function initLocales() { if (self::$_locales_ready) { return; } $lang = CAppUI::pref("LOCALE"); $_all_locales = DSHM::get("exclass-locales-{$lang}"); if (!$_all_locales) { $undefined = CAppUI::tr("Undefined"); $ds = CSQLDataSource::get("std"); $_all_locales = array(); $request = new CRequest(); $request->addTable("ex_class_field_translation"); $request->addWhere(array("lang" => "= '{$lang}'")); $request->addLJoin(array("ex_class_field" => "ex_class_field.ex_class_field_id = ex_class_field_translation.ex_class_field_id", "ex_concept" => "ex_concept.ex_concept_id = ex_class_field.concept_id", "ex_class_field_group" => "ex_class_field_group.ex_class_field_group_id = ex_class_field.ex_group_id")); $request->addSelect(array("ex_class_field_translation.std", "IF(ex_class_field_translation.desc IS NOT NULL, ex_class_field_translation.desc, ex_class_field_translation.std) AS `desc`", "IF(ex_class_field_translation.court IS NOT NULL, ex_class_field_translation.court, ex_class_field_translation.std) AS `court`", "ex_class_field.ex_class_field_id AS field_id", "ex_class_field.name", "ex_class_field.prop", "ex_class_field.concept_id", "ex_class_field_group.ex_class_id", "ex_concept.ex_list_id")); $list = $ds->loadList($request->makeSelect()); // Chargement des list_items par concept, field ou list $request = new CRequest(); $request->addTable("ex_list_item"); $request->addSelect(array("ex_list_item_id", "list_id", "concept_id", "field_id", "name")); $list_items = $ds->loadList($request->makeSelect()); // Chargement en une seule requete de toutes les traductions de champs $enum_list_cache = array("list" => array(), "concept" => array(), "field" => array()); $mapper = array("list_id" => "list", "concept_id" => "concept", "field_id" => "field"); foreach ($list_items as $_item) { $_item_id = $_item["ex_list_item_id"]; $_item_name = $_item["name"]; foreach ($mapper as $_field_name => $_to) { if ($_field_value = $_item[$_field_name]) { $enum_list_cache[$_to][$_field_value][$_item_id] = $_item_name; } } } foreach ($list as $_item) { $_locales = array(); $key = "-{$_item['name']}"; $_locales[$key] = $_item["std"]; if ($_item["desc"]) { $_locales["{$key}-desc"] = $_item["desc"]; } if ($_item["court"]) { $_locales["{$key}-court"] = $_item["court"]; } $_ex_class_id = $_item['ex_class_id']; $_prefix = "CExObject_{$_ex_class_id}"; $prop = $_item["prop"]; if (strpos($prop, "enum") === false && strpos($prop, "set") === false) { if (!isset($_all_locales[$_prefix])) { $_all_locales[$_prefix] = array(); } $_all_locales[$_prefix] = array_merge($_all_locales[$_prefix], $_locales); continue; } $key = ".{$_item['name']}"; $_locales["{$key}."] = $undefined; $concept_id = $_item["concept_id"]; $ex_list_id = $_item["ex_list_id"]; $field_id = $_item["field_id"]; $enum_list = array(); if ($concept_id) { if ($ex_list_id) { if (isset($enum_list_cache["list"][$ex_list_id])) { $enum_list = $enum_list_cache["list"][$ex_list_id]; } } else { if (isset($enum_list_cache["concept"][$concept_id])) { $enum_list = $enum_list_cache["concept"][$concept_id]; } } } else { if (isset($enum_list_cache["field"][$field_id])) { $enum_list = $enum_list_cache["field"][$field_id]; } } foreach ($enum_list as $_value => $_locale) { $_locales["{$key}.{$_value}"] = $_locale; } if (!isset($_all_locales[$_prefix])) { $_all_locales[$_prefix] = array(); } $_all_locales[$_prefix] = array_merge($_all_locales[$_prefix], $_locales); } DSHM::put("exclass-locales-{$lang}", $_all_locales, true); } foreach ($_all_locales as $_prefix => $_locales) { CAppUI::addLocales($_prefix, $_locales); } self::$_locales_ready = true; }
<?php /* $Id $ */ /** * Show list tags 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(); $object_class = CValue::get("object_class"); $ds = CSQLDataSource::get("std"); $where = array("object_class" => "= '{$object_class}'"); // Liste des tags pour un object_class $req = new CRequest(); $req->addTable("id_sante400"); $req->addColumn("tag"); $req->addWhere($where); $req->addGroup("tag"); $tags = CMbArray::pluck($ds->loadList($req->makeSelect()), "tag"); // Création du template $smarty = new CSmartyDP(); $smarty->assign("tags", $tags); $smarty->display("inc_show_list_tags.tpl");
/** * Get the formula field * * @param string $field_name Field name * @param array $where The WHERE statement * * @return array|null */ function getFormulaResult($field_name, $where) { $ds = $this->getDS(); $table = $this->getTableName(); $where["ex_link.ex_class_id"] = "= '{$this->_id}'"; $ljoin = array("ex_link" => "ex_link.ex_object_id = {$table}.ex_object_id"); $request = new CRequest(); $request->addSelect($field_name); $request->addTable($table); $request->addWhere($where); $request->addLJoin($ljoin); $request->addOrder("ex_link.ex_object_id DESC"); return $ds->loadResult($request->makeSelect()); }
/** * Get the HL7v2 mapping table values * * @param string $table The table to get * @param boolean $from_mb Get the reversed table (MB => HL7) * @param bool $get_description Return the escriptions instead of the value * * @return array The table */ static function getTable($table, $from_mb = true, $get_description = false) { if (self::$ds === null) { return; } if (self::$ds === false) { self::$ds = CSQLDataSource::get("hl7v2"); } static $tables = array(); if (isset($tables[$table][$from_mb])) { return $tables[$table][$from_mb]; } $where = array("number" => self::$ds->prepare("=%", $table)); if ($from_mb) { $cols = array("code_mb_from", $get_description ? "description" : "code_hl7_to"); } else { $cols = array("code_hl7_from", $get_description ? "description" : "code_mb_to"); } $req = new CRequest(); $req->addSelect($cols); $req->addTable("table_entry"); $req->addWhere($where); $result = self::$ds->loadHashList($req->makeSelect()); if (!$get_description) { $tables[$table][$from_mb] = $result; } return $result; }
/** * Get all number patient by a state and the filter * * @param String $date_min Date minimum * @param String $date_max Date maximum * * @return array */ static function getAllNumberPatient($date_min = null, $date_max = null) { $patients_count = array(); $leftjoin = null; $where = array(); if ($date_min) { $where["entree"] = ">= '{$date_min}'"; $leftjoin["sejour"] = "patients.patient_id = sejour.patient_id"; } if ($date_max) { $where["entree"] = "<= '{$date_max}'"; $leftjoin["sejour"] = "patients.patient_id = sejour.patient_id"; } $ds = CSQLDataSource::get("std"); $request = new CRequest(); $request->addSelect("`status`, COUNT(DISTINCT(`patients`.`patient_id`)) as `total`"); $request->addTable("patients"); $request->addLJoin($leftjoin); $request->addWhere($where); $request->addGroup("`status`"); $result = $ds->loadList($request->makeSelect()); $state_count = array(); foreach ($result as $_result) { $state_count[$_result["status"]] = $_result["total"]; } foreach (self::$list_state as $_state) { $patients_count[CMbString::lower($_state)] = CMbArray::get($state_count, $_state, 0); if ($_state == "CACH") { $where = array("vip" => "= '1'", "status" => "!= 'VALI'"); $patient = new CPatient(); $patients_count[CMbString::lower($_state)] = $patient->countList($where, null, $leftjoin); } if ($_state == "DPOT") { $patient_link = new CPatientLink(); $patients_count[CMbString::lower($_state)] = $patient_link->countList($where, null, array("sejour" => "patient_link.patient_id1 = sejour.patient_id")); } } return $patients_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()); }
$context = null; } $patient->loadRefPhotoIdentite(); $where = array("patient_id" => " = '{$patient->_id}'"); // Construction d'une constante médicale $constantes->patient_id = $patient->_id; $constantes->loadRefPatient(); // Les constantes qui correspondent (dans le contexte ou non) $where_context = $where; $where_context["context_class"] = "IS NOT NULL"; $where_context["context_id"] = "IS NOT NULL"; $query = new CRequest(); $query->addTable($constantes->_spec->table); $query->addColumn("context_class"); $query->addColumn("context_id"); $query->addWhere($where_context); $query->addGroup(array("context_class", "context_id")); $query = $query->makeSelect(); $list = $constantes->_spec->ds->loadList($query); $list_contexts = array(); foreach ($list as $_context) { /** @var CMbObject $c */ $c = new $_context["context_class"](); $c = $c->getCached($_context["context_id"]); // Cas d'un RPU if ($c instanceof CConsultation && $c->sejour_id) { $c->loadRefSejour(); if ($c->_ref_sejour->type == 'urg') { continue; } }
} } 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);
$_key = $_table_info["key"]; foreach ($inserts as $_insert) { /** @var callable $callback */ list($object_class, $type, $fields, $callback) = $_insert; if ($fields === $_fields && $object_class === $_object_class && $type === $_type) { $_query = $callback($ds, $_row); $ds->exec($_query); $counts["insert"] += $ds->affectedRows(); } } } // Delete user logs entries $request = new CRequest(); $request->addWhereClause("user_log_id", "BETWEEN {$min} AND {$max}"); $request->addForceIndex("PRIMARY"); $request->addWhere($where); $query = $request->makeDelete($log); $ds->exec($query); $counts["insert"] = $ds->affectedRows(); } else { $query = $request->makeSelectCount($log); $counts["insert"] = $ds->loadResult($query); } //</editor-fold> $offset = $max + 1; // Stop auto if end is reached $log->loadMatchingObject("user_log_id DESC"); if ($log->_id < $offset) { $auto = 0; } // Création du template
/** * 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; }
function getModelesIds() { $ds = $this->getDS(); $request = new CRequest(); $request->addSelect("modele_id"); $request->addTable("modele_to_pack"); $request->addWhere("pack_id = '{$this->_id}'"); $this->_modeles_ids = $ds->loadColumn($request->makeSelect()); }
/** * Object count of a multiple list by an SQL request constructor using group-by statement * * @param array $where Array of where clauses * @param array|string $order Order statement * @param array|string $group Group by statement * @param array $ljoin Array of left join clauses * @param array $fields Append fields to the SELECT * @param array|string $index Force index * * @return self[] */ function countMultipleList($where = null, $order = null, $group = null, $ljoin = null, $fields = array(), $index = null) { if (!$this->_ref_module) { return null; } $request = new CRequest(); $request->addWhere($where); $request->addOrder($order); $request->addGroup($group); $request->addLJoin($ljoin); $request->addForceIndex($index); $ds = $this->_spec->ds; return $ds->loadList($request->makeSelectCount($this, $fields)); }
/** * Get observation results for this object * * @param CMbObject $object Reference object * @param bool $utf8 Encode data int UTF-8 * * @return array|CObservationResultSet[] */ static function getResultsFor(CMbObject $object, $utf8 = true) { $request = new CRequest(); $request->addTable("observation_result"); $request->addSelect("*"); $request->addLJoin(array("observation_result_set" => "observation_result_set.observation_result_set_id = observation_result.observation_result_set_id", "user_log" => "observation_result_set.observation_result_set_id = user_log.object_id AND\r\n user_log.object_class = 'CObservationResultSet' AND user_log.type = 'create'", "users" => "users.user_id = user_log.user_id")); $request->addWhere(array("observation_result_set.context_class" => "= '{$object->_class}'", "observation_result_set.context_id" => "= '{$object->_id}'")); $request->addOrder("observation_result_set.datetime"); $request->addOrder("observation_result.observation_result_id"); $results = $object->_spec->ds->loadList($request->makeSelect()); $times = array(); $data = array(); foreach ($results as $_result) { $_time = CMbDate::toUTCTimestamp($_result["datetime"]); $times[$_time] = $_result["datetime"]; $unit_id = $_result["unit_id"] ? $_result["unit_id"] : "none"; $label = null; if ($_result["label_id"]) { $label_obj = new CSupervisionGraphAxisValueLabel(); $label_obj->load($_result["label_id"]); $label = $label_obj->title; } $float_value = $_result["value"]; $float_value = CMbFieldSpec::checkNumeric($float_value, false); $_user_name = $_result["user_first_name"] . " " . $_result["user_last_name"]; $data[$_result["value_type_id"]][$unit_id][] = array(0 => $_time, 1 => $float_value, "ts" => $_time, "value" => $_result["value"], "datetime" => $_result["datetime"], "file_id" => $_result["file_id"], "set_id" => $_result["observation_result_set_id"], "result_id" => $_result["observation_result_id"], "label_id" => $_result["label_id"], "label" => $utf8 ? utf8_encode($label) : $label, "user_id" => $_result["user_id"], "user" => $utf8 ? utf8_encode($_user_name) : $_user_name); } return array($data, $times); }
/** * 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); }
/** * @see parent::check() */ function check() { $msg = null; $ds = $this->_spec->ds; if (!$this->perm_object_id) { $where = array(); $where["user_id"] = $ds->prepare("= %", $this->user_id); $where["object_class"] = $ds->prepare("= %", $this->object_class); if ($this->object_id) { $where["object_id"] = $ds->prepare("= %", $this->object_id); } else { $where["object_id"] = "IS NULL"; } $query = new CRequest(); $query->addSelect("count(perm_object_id)"); $query->addTable("perm_object"); $query->addWhere($where); $nb_result = $ds->loadResult($query->makeSelect()); if ($nb_result) { $msg .= "Une permission sur cet objet existe déjà.<br />"; } } return $msg . parent::check(); }
/** * 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")); }
/** * Récuparation du graphique du nombre d'interventions annulées le jour même * * @param string $date_min Date de début * @param string $date_max Date de fin * @param int $prat_id Identifiant du praticien * @param int $salle_id Identifiant de la salle * @param int $bloc_id Identifiant du bloc * @param string $code_ccam Code CCAM * @param string $type_sejour Type de séjour * @param bool $hors_plage Prise en charge des hors plage * * @return array */ function graphOpAnnulees($date_min = null, $date_max = null, $prat_id = null, $salle_id = null, $bloc_id = null, $code_ccam = null, $type_sejour = null, $hors_plage = false) { $miner = new COperationWorkflow(); $miner->warnUsage(); if (!$date_min) { $date_min = CMbDT::date("-1 YEAR"); } if (!$date_max) { $date_max = CMbDT::date(); } $date_min = CMbDT::format($date_min, "%Y-%m-01"); $date_max = CMbDT::transform("+1 MONTH", $date_max, "%Y-%m-01"); $prat = new CMediusers(); $prat->load($prat_id); $serie_total = array('label' => 'Total', 'data' => array(), 'markers' => array('show' => true), 'bars' => array('show' => false)); $salles = CSalle::getSallesStats($salle_id, $bloc_id); $query = new CRequest(); $query->addColumn("salle_id"); $query->addColumn("DATE_FORMAT(date_operation, '%Y-%m')", "mois"); $query->addColumn("COUNT(DISTINCT(operations.operation_id))", "total"); $query->addTable("operations"); $query->addLJoinClause("operation_workflow", "operation_workflow.operation_id = operations.operation_id"); $query->addWhere("DATE(date_cancellation) = DATE(date_operation)"); $query->addWhereClause("date_operation", "BETWEEN '{$date_min}' AND '{$date_max}'"); $query->addWhereClause("salle_id", CSQLDataSource::prepareIn(array_keys($salles))); $query->addGroup("mois, salle_id"); $query->addOrder("mois, salle_id"); // Filtre sur hors plage if (!$hors_plage) { $query->addWhereClause("plageop_id", "IS NOT NULL"); } // Filtre sur le praticien if ($prat_id) { $query->addWhereClause("operations.chir_id", "= '{$prat_id}'"); } // Filtre sur les codes CCAM if ($code_ccam) { $query->addWhereClause("operations.codes_ccam", "LIKE '%{$code_ccam}%'"); } // Filtre sur le type d'hospitalisation if ($type_sejour) { $query->addLJoinClause("sejour", "sejour.sejour_id = operations.sejour_id"); $query->addWhereClause("sejour.type", "= '{$type_sejour}'"); } // Query result $ds = CSQLDataSource::get("std"); $tree = $ds->loadTree($query->makeSelect()); // Build horizontal ticks $months = array(); $ticks = array(); for ($_date = $date_min; $_date < $date_max; $_date = CMbDT::date("+1 MONTH", $_date)) { $count_ticks = count($ticks); $ticks[] = array($count_ticks, CMbDT::format($_date, "%m/%Y")); $months[CMbDT::format($_date, "%Y-%m")] = $count_ticks; $serie_total['data'][] = array(count($serie_total['data']), 0); } // Build series $series = array(); $total = 0; foreach ($salles as $_salle) { $_serie = array("label" => utf8_encode($bloc_id ? $_salle->nom : $_salle->_view)); $data = array(); foreach ($months as $_month => $_tick) { $value = isset($tree[$_salle->_id][$_month]) ? $tree[$_salle->_id][$_month] : 0; $data[] = array($_tick, $value); $serie_total["data"][$_tick][1] += $value; $total += $value; } $_serie["data"] = $data; $series[] = $_serie; } $series[] = $serie_total; // Set up the title for the graph $title = "Interventions annulées le jour même"; $subtitle = "{$total} interventions"; if ($prat_id) { $subtitle .= " - Dr {$prat->_view}"; } if ($salle_id) { $salle = reset($salles); $subtitle .= " - {$salle->_view}"; } if ($code_ccam) { $subtitle .= " - CCAM : {$code_ccam}"; } if ($type_sejour) { $subtitle .= " - " . CAppUI::tr("CSejour.type.{$type_sejour}"); } $options = array('title' => utf8_encode($title), 'subtitle' => utf8_encode($subtitle), 'xaxis' => array('labelsAngle' => 45, 'ticks' => $ticks), 'yaxis' => array('autoscaleMargin' => 1), 'bars' => array('show' => true, 'stacked' => true, 'barWidth' => 0.8), 'HtmlText' => false, 'legend' => array('show' => true, 'position' => 'nw'), 'grid' => array('verticalLines' => false), 'spreadsheet' => array('show' => true, 'csvFileSeparator' => ';', 'decimalSeparator' => ',', 'tabGraphLabel' => utf8_encode('Graphique'), 'tabDataLabel' => utf8_encode('Données'), 'toolbarDownload' => utf8_encode('Fichier CSV'), 'toolbarSelectAll' => utf8_encode('Sélectionner tout le tableau'))); return array('series' => $series, 'options' => $options); }