forked from openemr/openemr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncounterService.php
760 lines (681 loc) · 28.5 KB
/
EncounterService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
<?php
/**
* EncounterService
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Matthew Vita <[email protected]>
* @author Jerry Padgett <[email protected]>
* @author Brady Miller <[email protected]>
* @copyright Copyright (c) 2018 Matthew Vita <[email protected]>
* @copyright Copyright (c) 2018 Jerry Padgett <[email protected]>
* @copyright Copyright (c) 2018 Brady Miller <[email protected]>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
namespace OpenEMR\Services;
use OpenEMR\Common\Acl\AclMain;
use OpenEMR\Common\Database\QueryUtils;
use OpenEMR\Common\Database\SqlQueryException;
use OpenEMR\Common\Logging\SystemLogger;
use OpenEMR\Common\Uuid\UuidRegistry;
use OpenEMR\Services\Search\{
DateSearchField,
FhirSearchWhereClauseBuilder,
SearchFieldException,
TokenSearchField,
TokenSearchValue
};
use OpenEMR\Validators\EncounterValidator;
use OpenEMR\Validators\ProcessingResult;
use Particle\Validator\Validator;
require_once dirname(__FILE__) . "/../../library/forms.inc.php";
require_once dirname(__FILE__) . "/../../library/encounter.inc.php";
class EncounterService extends BaseService
{
/**
* @var EncounterValidator
*/
private $encounterValidator;
public const ENCOUNTER_TABLE = "form_encounter";
private const PATIENT_TABLE = "patient_data";
private const PROVIDER_TABLE = "users";
private const FACILITY_TABLE = "facility";
/**
* Default class_code from list_options. Defaults to outpatient ambulatory care.
*/
const DEFAULT_CLASS_CODE = 'AMB';
/**
* Default constructor.
*/
public function __construct()
{
parent::__construct('form_encounter');
UuidRegistry::createMissingUuidsForTables([self::ENCOUNTER_TABLE, self::PATIENT_TABLE, self::PROVIDER_TABLE,
self::FACILITY_TABLE]);
$this->encounterValidator = new EncounterValidator();
}
/**
* Returns a list of encounters matching the encounter identifier.
*
* @param $eid The encounter identifier of particular encounter
* @param $puuidBind - Optional variable to only allow visibility of the patient with this puuid.
* @return ProcessingResult which contains validation messages, internal error messages, and the data
* payload.
*/
public function getEncounterById($eid, $puuidBind = null)
{
$search = ['eid' => new TokenSearchField('eid', [new TokenSearchValue($eid)])];
return $this->search($search, true, $puuidBind);
}
/**
* Returns a list of encounters matching the encounter identifier.
*
* @param $euuid The encounter identifier of particular encounter
* @param $puuidBind - Optional variable to only allow visibility of the patient with this puuid.
* @return ProcessingResult which contains validation messages, internal error messages, and the data
* payload.
*/
public function getEncounter($euuid, $puuidBind = null)
{
$search = ['euuid' => new TokenSearchField('euuid', [new TokenSearchValue($euuid, null, true)])];
return $this->search($search, true, $puuidBind);
}
/**
* Returns an encounter matching the patient and encounter identifier.
*
* @param $pid The legacy identifier of particular patient
* @param $encounter_id The identifier of a particular encounter
* @return array first row of encounter data
*/
public function getOneByPidEid($pid, $encounter_id)
{
$encounterResult = $this->search(['pid' => $pid, 'eid' => $encounter_id], $options = ['limit' => '1']);
if ($encounterResult->hasData()) {
return $encounterResult->getData()[0];
}
return [];
}
public function getUuidFields(): array
{
return ['provider_uuid', 'facility_uuid', 'euuid', 'puuid', 'billing_facility_uuid'
, 'facility_location_uuid', 'billing_location_uuid', 'referrer_uuid'];
}
/**
* Given a patient pid return the most recent patient encounter for that patient
* @param $pid The unique public id (pid) for the patient.
* @return array|null Returns the encounter if found, null otherwise
*/
public function getMostRecentEncounterForPatient($pid): ?array
{
$pid = new TokenSearchField('pid', [new TokenSearchValue($pid, null)]);
// we discovered that most queries were ordering by encounter id which may NOT be the most recent encounter as
// an older historical encounter may be entered after a more recent encounter, so ordering be encounter id screws
// this up.
$result = $this->search(['pid' => $pid], true, '', ['limit' => 1, 'order' => '`date` DESC']);
if ($result->hasData()) {
return array_pop($result->getData());
}
return null;
}
/**
* Returns a list of encounters matching optional search criteria.
* Search criteria is conveyed by array where key = field/column name, value = field value.
* If no search criteria is provided, all records are returned.
*
* @param array $search search array parameters
* @param bool $isAndCondition specifies if AND condition is used for multiple criteria. Defaults to true.
* @param string $puuidBindValue - Optional puuid to only allow visibility of the patient with this puuid.
* @param array $options - Optional array of sql clauses like LIMIT, ORDER, etc
* @return bool|ProcessingResult|true|null ProcessingResult which contains validation messages, internal error messages, and the data
* payload.
*/
public function search($search = array(), $isAndCondition = true, $puuidBindValue = '', $options = array())
{
$limit = $options['limit'] ?? null;
$sqlBindArray = array();
$processingResult = new ProcessingResult();
// Validating and Converting _id to UUID byte
if (isset($search['uuid'])) {
$isValidEncounter = $this->encounterValidator->validateId(
'uuid',
self::ENCOUNTER_TABLE,
$search['uuid'],
true
);
if ($isValidEncounter !== true) {
return $isValidEncounter;
}
$search['uuid'] = UuidRegistry::uuidToBytes($search['uuid']);
}
// passed in uuid string to bind patient via their uuid.
// confusing ...
if (!empty($puuidBindValue)) {
// code to support patient binding
$isValidPatient = $this->encounterValidator->validateId('uuid', self::PATIENT_TABLE, $puuidBindValue, true);
if ($isValidPatient !== true) {
return $isValidPatient;
}
$pid = $this->getIdByUuid(UuidRegistry::uuidToBytes($puuidBindValue), self::PATIENT_TABLE, "pid");
if (empty($pid)) {
$processingResult->setValidationMessages("Invalid pid");
return $processingResult;
}
$search['puuid'] = new TokenSearchField('puuid', [new TokenSearchValue($puuidBindValue, null, true)]);
}
$sql = "SELECT fe.eid,
fe.euuid,
fe.date,
fe.reason,
fe.onset_date,
fe.sensitivity,
fe.billing_note,
fe.pc_catid,
fe.last_level_billed,
fe.last_level_closed,
fe.last_stmt_date,
fe.stmt_count,
fe.supervisor_id,
fe.invoice_refno,
fe.referral_source,
fe.billing_facility,
fe.external_id,
fe.last_update,
fe.pos_code,
fe.class_code,
class.notes as class_title,
opc.pc_catname,
patient.pid,
patient.puuid,
facilities.facility_id,
facilities.facility_uuid,
facilities.facility_name,
facilities.facility_location_uuid,
fa.billing_facility_id,
fa.billing_facility_uuid,
fa.billing_facility_name,
fa.billing_location_uuid,
fe.provider_id,
fe.referring_provider_id,
fe.ordering_provider_id,
providers.provider_uuid,
providers.provider_username,
referrers.referrer_uuid,
referrers.referrer_username,
fe.discharge_disposition,
discharge_list.discharge_disposition_text
FROM (
select
encounter as eid,
uuid as euuid,
`date`,
reason,
onset_date,
sensitivity,
billing_note,
pc_catid,
last_level_billed,
last_level_closed,
last_stmt_date,
stmt_count,
provider_id,
supervisor_id,
invoice_refno,
referral_source,
billing_facility,
external_id,
pos_code,
class_code,
facility_id,
discharge_disposition,
pid as encounter_pid,
referring_provider_id,
ordering_provider_id,
last_update
FROM form_encounter
) fe
LEFT JOIN openemr_postcalendar_categories as opc
ON opc.pc_catid = fe.pc_catid
LEFT JOIN list_options as class ON class.option_id = fe.class_code
LEFT JOIN (
select
facility.id AS billing_facility_id
,facility.uuid AS billing_facility_uuid
,facility.`name` AS billing_facility_name
,locations.uuid AS billing_location_uuid
from facility
LEFT JOIN uuid_mapping AS locations
ON locations.target_uuid = facility.uuid AND locations.resource='Location'
) fa ON fa.billing_facility_id = fe.billing_facility
LEFT JOIN (
select
pid
,uuid AS puuid
FROM patient_data
) patient ON fe.encounter_pid = patient.pid
LEFT JOIN (
select
id AS provider_provider_id
,uuid AS provider_uuid
,`username` AS provider_username
FROM users
WHERE
npi IS NOT NULL and npi != ''
) providers ON fe.provider_id = providers.provider_provider_id
LEFT JOIN (
select
id AS referring_provider_id
,uuid AS referrer_uuid
,`username` AS referrer_username
FROM users
WHERE
npi IS NOT NULL and npi != ''
) referrers ON fe.referring_provider_id = referrers.referring_provider_id
LEFT JOIN (
select
facility.id AS facility_id
,facility.uuid AS facility_uuid
,facility.`name` AS facility_name
,`locations`.`uuid` AS facility_location_uuid
from facility
LEFT JOIN uuid_mapping AS locations
ON locations.target_uuid = facility.uuid AND locations.resource='Location'
) facilities ON facilities.facility_id = fe.facility_id
LEFT JOIN (
select option_id AS discharge_option_id
,title AS discharge_disposition_text
FROM list_options
WHERE list_id = 'discharge-disposition'
) discharge_list ON fe.discharge_disposition = discharge_list.discharge_option_id";
try {
$whereFragment = FhirSearchWhereClauseBuilder::build($search, $isAndCondition);
$sql .= $whereFragment->getFragment();
if (empty($options['order'])) {
$sql .= " ORDER BY fe.eid DESC";
} else {
$sql .= " ORDER BY " . $options['order'];
}
if (is_int($limit) && $limit > 0) {
$sql .= " LIMIT " . $limit;
}
$records = QueryUtils::fetchRecords($sql, $whereFragment->getBoundValues());
if (!empty($records)) {
foreach ($records as $row) {
$resultRecord = $this->createResultRecordFromDatabaseResult($row);
$processingResult->addData($resultRecord);
}
}
} catch (SqlQueryException $exception) {
// we shouldn't hit a query exception
(new SystemLogger())->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
$processingResult->addInternalError("Error selecting data from database");
} catch (SearchFieldException $exception) {
(new SystemLogger())->error($exception->getMessage(), ['trace' => $exception->getTraceAsString(), 'field' => $exception->getField()]);
$processingResult->setValidationMessages([$exception->getField() => $exception->getMessage()]);
}
return $processingResult;
}
/**
* Inserts a new Encounter record.
*
* @param $puuid The patient identifier of particular encounter
* @param $data The encounter fields (array) to insert.
* @return ProcessingResult which contains validation messages, internal error messages, and the data
* payload.
*/
public function insertEncounter($puuid, $data)
{
$processingResult = new ProcessingResult();
$processingResult = $this->encounterValidator->validate(
array_merge($data, ["puuid" => $puuid]),
EncounterValidator::DATABASE_INSERT_CONTEXT
);
if (!$processingResult->isValid()) {
return $processingResult;
}
$encounter = generate_id();
$data['encounter'] = $encounter;
$data['uuid'] = UuidRegistry::getRegistryForTable(self::ENCOUNTER_TABLE)->createUuid();
if (empty($data['date'])) {
$data['date'] = date("Y-m-d");
}
$puuidBytes = UuidRegistry::uuidToBytes($puuid);
$data['pid'] = $this->getIdByUuid($puuidBytes, self::PATIENT_TABLE, "pid");
$query = $this->buildInsertColumns($data);
$sql = " INSERT INTO form_encounter SET ";
$sql .= $query['set'];
$results = sqlInsert(
$sql,
$query['bind']
);
addForm(
$encounter,
"New Patient Encounter",
$results,
"newpatient",
$data['pid'],
$data["provider_id"],
$data["date"],
$data['user'],
$data['group']
);
if ($results) {
$processingResult->addData(array(
'encounter' => $encounter,
'uuid' => UuidRegistry::uuidToString($data['uuid']),
));
} else {
$processingResult->addProcessingError("error processing SQL Insert");
}
return $processingResult;
}
/**
* Updates an existing Encounter record.
*
* @param $puuid The patient identifier of particular encounter.
* @param $euuid - The Encounter identifier used for update.
* @param $data - The updated Encounter data fields
* @return ProcessingResult which contains validation messages, internal error messages, and the data
* payload.
*/
public function updateEncounter($puuid, $euuid, $data)
{
$processingResult = new ProcessingResult();
$processingResult = $this->encounterValidator->validate(
array_merge($data, ["puuid" => $puuid, "euuid" => $euuid]),
EncounterValidator::DATABASE_UPDATE_CONTEXT
);
if (!$processingResult->isValid()) {
return $processingResult;
}
$puuidBytes = UuidRegistry::uuidToBytes($puuid);
$euuidBytes = UuidRegistry::uuidToBytes($euuid);
$pid = $this->getIdByUuid($puuidBytes, self::PATIENT_TABLE, "pid");
$encounter = $this->getIdByUuid($euuidBytes, self::ENCOUNTER_TABLE, "encounter");
$facilityService = new FacilityService();
$facilityresult = $facilityService->getById($data["facility_id"]);
$facility = $facilityresult['name'];
$result = sqlQuery("SELECT sensitivity FROM form_encounter WHERE encounter = ?", array($encounter));
if ($result['sensitivity'] && !AclMain::aclCheckCore('sensitivities', $result['sensitivity'])) {
return "You are not authorized to see this encounter.";
}
// See view.php to allow or disallow updates of the encounter date.
if (!AclMain::aclCheckCore('encounters', 'date_a')) {
unset($data["date"]);
}
$data['facility'] = $facility;
$query = $this->buildUpdateColumns($data);
$sql = " UPDATE form_encounter SET ";
$sql .= $query['set'];
$sql .= " WHERE encounter = ?";
$sql .= " AND pid = ?";
array_push($query['bind'], $encounter);
array_push($query['bind'], $pid);
$results = sqlStatement(
$sql,
$query['bind']
);
if ($results) {
$processingResult = $this->getEncounter($euuid, $puuid);
} else {
$processingResult->addProcessingError("error processing SQL Update");
}
return $processingResult;
}
public function insertSoapNote($pid, $eid, $data)
{
$soapSql = " INSERT INTO form_soap SET";
$soapSql .= " date=NOW(),";
$soapSql .= " activity=1,";
$soapSql .= " pid=?,";
$soapSql .= " subjective=?,";
$soapSql .= " objective=?,";
$soapSql .= " assessment=?,";
$soapSql .= " plan=?";
$soapResults = sqlInsert(
$soapSql,
array(
$pid,
$data["subjective"],
$data["objective"],
$data["assessment"],
$data["plan"]
)
);
if (!$soapResults) {
return false;
}
$formSql = "INSERT INTO forms SET";
$formSql .= " date=NOW(),";
$formSql .= " encounter=?,";
$formSql .= " form_name='SOAP',";
$formSql .= " authorized='1',";
$formSql .= " form_id=?,";
$formSql .= " pid=?,";
$formSql .= " formdir='soap'";
$formResults = sqlInsert(
$formSql,
array(
$eid,
$soapResults,
$pid
)
);
return array($soapResults, $formResults);
}
public function updateSoapNote($pid, $eid, $sid, $data)
{
$sql = " UPDATE form_soap SET";
$sql .= " date=NOW(),";
$sql .= " activity=1,";
$sql .= " pid=?,";
$sql .= " subjective=?,";
$sql .= " objective=?,";
$sql .= " assessment=?,";
$sql .= " plan=?";
$sql .= " where id=?";
return sqlStatement(
$sql,
array(
$pid,
$data["subjective"],
$data["objective"],
$data["assessment"],
$data["plan"],
$sid
)
);
}
public function updateVital($pid, $eid, $vid, $data)
{
$data['date'] = date("Y-m-d H:i:s");
$data['activity'] = 1;
$data['id'] = $vid;
$data['pid'] = $pid;
$data['eid'] = $eid;
$vitalsService = new VitalsService();
$updatedRecords = $vitalsService->save($data);
return $updatedRecords;
}
public function insertVital($pid, $eid, $data)
{
$data['eid'] = $eid;
$data['authorized'] = '1';
$data['pid'] = $pid;
$vitalsService = new VitalsService();
$savedVitals = $vitalsService->save($data);
// need to grab the form record here, not sure why people need this but sure, why not, since the old method returned
// it we will keep the functionality.
$vitalsFormId = $savedVitals['id'];
$formId = intval(QueryUtils::fetchSingleValue('select id FROM forms WHERE form_id = ? ', 'id', [$vitalsFormId]));
return [$vitalsFormId, $formId];
}
public function getVitals($pid, $eid)
{
$vitalsService = new VitalsService();
$vitals = $vitalsService->getVitalsForPatientEncounter($pid, $eid) ?? [];
return $vitals;
}
public function getVital($pid, $eid, $vid)
{
$vitalsService = new VitalsService();
$vitals = $vitalsService->getVitalsForForm($vid);
if (!empty($vitals) && $vitals['eid'] == $eid && $vitals['pid'] == $pid) {
return $vitals;
}
return null;
}
public function getSoapNotes($pid, $eid)
{
$sql = " SELECT fs.*";
$sql .= " FROM forms fo";
$sql .= " JOIN form_soap fs on fs.id = fo.form_id";
$sql .= " WHERE fo.encounter = ?";
$sql .= " AND fs.pid = ?";
$statementResults = sqlStatement($sql, array($eid, $pid));
$results = array();
while ($row = sqlFetchArray($statementResults)) {
array_push($results, $row);
}
return $results;
}
public function getSoapNote($pid, $eid, $sid)
{
$sql = " SELECT fs.*";
$sql .= " FROM forms fo";
$sql .= " JOIN form_soap fs on fs.id = fo.form_id";
$sql .= " WHERE fo.encounter = ?";
$sql .= " AND fs.id = ?";
$sql .= " AND fs.pid = ?";
return sqlQuery($sql, array($eid, $sid, $pid));
}
public function validateSoapNote($soapNote)
{
$validator = new Validator();
$validator->optional('subjective')->lengthBetween(2, 65535);
$validator->optional('objective')->lengthBetween(2, 65535);
$validator->optional('assessment')->lengthBetween(2, 65535);
$validator->optional('plan')->lengthBetween(2, 65535);
return $validator->validate($soapNote);
}
public function validateVital($vital)
{
$validator = new Validator();
$validator->optional('temp_method')->lengthBetween(1, 255);
$validator->optional('note')->lengthBetween(1, 255);
$validator->optional('BMI_status')->lengthBetween(1, 255);
$validator->optional('bps')->numeric();
$validator->optional('bpd')->numeric();
$validator->optional('weight')->numeric();
$validator->optional('height')->numeric();
$validator->optional('temperature')->numeric();
$validator->optional('pulse')->numeric();
$validator->optional('respiration')->numeric();
$validator->optional('BMI')->numeric();
$validator->optional('waist_circ')->numeric();
$validator->optional('head_circ')->numeric();
$validator->optional('oxygen_saturation')->numeric();
return $validator->validate($vital);
}
public function getEncountersForPatientByPid($pid)
{
$encounterResult = $this->search(['pid' => $pid]);
if ($encounterResult->hasData()) {
return $encounterResult->getData();
}
return [];
}
/**
* The result of this function returns the format needed by the frontend with the window.left_nav.setPatientEncounter function
* @param $pid
* @return array
*/
public function getPatientEncounterListWithCategories($pid)
{
$encounters = $this->getEncountersForPatientByPid($pid);
$encounterList = [
'ids' => []
,'dates' => []
,'categories' => []
];
foreach ($encounters as $index => $encounter) {
$encounterList['ids'][$index] = $encounter['eid'];
$encounterList['dates'][$index] = date("Y-m-d", strtotime($encounter['date']));
$encounterList['categories'][$index] = $encounter['pc_catname'];
}
return $encounterList;
}
/**
* Returns the sensitivity level for the encounter matching the patient and encounter identifier.
*
* @param $pid The legacy identifier of particular patient
* @param $encounter_id The identifier of a particular encounter
* @return string sensitivity_level of first row of encounter data
*/
public function getSensitivity($pid, $encounter_id)
{
$encounterResult = $this->search(['pid' => $pid, 'eid' => $encounter_id], $options = ['limit' => '1']);
if ($encounterResult->hasData()) {
return $encounterResult->getData()[0]['sensitivity'];
}
return [];
}
/**
* Returns the referring provider for the encounter matching the patient and encounter identifier.
*
* @param $pid The legacy identifier of particular patient
* @param $encounter_id The identifier of a particular encounter
* @return string referring provider of first row of encounter data (it's an id from the users table)
*/
public function getReferringProviderID($pid, $encounter_id)
{
$encounterResult = $this->search(['pid' => $pid, 'eid' => $encounter_id], $options = ['limit' => '1']);
if ($encounterResult->hasData()) {
return $encounterResult->getData()[0]['referring_provider_id'] ?? '';
}
return [];
}
/**
* Returns the ordering provider for the encounter matching the patient and encounter identifier.
*
* @param $pid The legacy identifier of particular patient
* @param $encounter_id The identifier of a particular encounter
* @return string ordering provider of first row of encounter data (it's an id from the users table)
*/
public function getOrderingProviderID($pid, $encounter_id)
{
$encounterResult = $this->search(['pid' => $pid, 'eid' => $encounter_id], $options = ['limit' => '1']);
if ($encounterResult->hasData()) {
return $encounterResult->getData()[0]['ordering_provider_id'] ?? '';
}
return [];
}
/**
* Return an array of encounters within a date range
*
* @param $start_date Any encounter starting on this date
* @param $end_date Any encounter ending on this date
* @return Array Encounter data payload.
*/
public function getEncountersByDateRange($startDate, $endDate)
{
$dateField = new DateSearchField('date', ['ge' . $startDate, 'le' . $endDate], DateSearchField::DATE_TYPE_DATE, $isAnd = true);
$encounterResult = $this->search(['date' => $dateField]);
if ($encounterResult->hasData()) {
$result = $encounterResult->getData();
return $result;
}
return [];
}
/**
* Returns the default POS code that is set in the facility table.
*
* @param $facility_id
* @return mixed
*/
public function getPosCode($facility_id)
{
$sql = "SELECT pos_code FROM facility WHERE id = ?";
$result = sqlQuery($sql, [$facility_id]);
return $result['pos_code'];
}
}