forked from openemr/openemr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eRxSOAP.php
741 lines (619 loc) · 22.6 KB
/
eRxSOAP.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
<?php
/**
* interface/eRxSOAP.php Functions for interacting with NewCrop SOAP calls.
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Sam Likins <[email protected]>
* @copyright Copyright (c) 2015 Sam Likins <[email protected]>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
class eRxSOAP
{
const ACTION_ALLERGIES = 'allergies';
const ACTION_MEDICATIONS = 'medications';
const FLAG_PRESCRIPTION_PRESS = '1';
const FLAG_PRESCRIPTION_IMPORT = '2';
const FLAG_ALLERGY_PRESS = '3';
const FLAG_ALLERGY_IMPORT = '4';
private $globals;
private $store;
private $authUserId;
private $authUserDetails;
private $patientId;
private $soapClient;
private $soapSettings = array();
private $siteId;
protected static function fixHtmlEntities($array, $xmltoarray)
{
$encoded = json_encode($array);
$fixed = $xmltoarray->fix_html_entities($encoded);
return json_decode($fixed, true);
}
/**
* Repair HTML/XML and return array
* @param string $xml XML for processing
* @return array|boolean Array on success, false on failure
*/
public static function htmlFixXmlToArray($xml)
{
$xmltoarray = new xmltoarray_parser_htmlfix(); //create instance of class
$xmltoarray->xmlparser_setoption(XML_OPTION_SKIP_WHITE, 1); //set options same as xml_parser_set_option
$xmltoarray->xmlparser_setoption(XML_OPTION_CASE_FOLDING, 0);
$xmltoarray->xmlparser_fix_into_struct(base64_decode($xml)); //fixes html values for XML
$array = $xmltoarray->createArray(); //creates an array with fixed html values
$array = self::fixHtmlEntities($array, $xmltoarray);
if (array_key_exists('NewDataSet', $array) && array_key_exists('Table', $array['NewDataSet'])) {
$array = $array['NewDataSet']['Table'];
} else {
$array = false;
}
return $array;
}
/**
* Set Globals for retrieving eRx global configurations
* @param object $globals The eRx Globals object to use for processing
* @return eRxPage This object is returned for method chaining
*/
public function setGlobals($globals)
{
$this->globals = $globals;
return $this;
}
/**
* Get Globals for retrieving eRx global configurations
* @return object The eRx Globals object to use for processing
*/
public function getGlobals()
{
return $this->globals;
}
/**
* Set Store to handle eRx cashed data
* @param object $store The eRx Store object to use for processing
* @return eRxSOAP This object is returned for method chaining
*/
public function setStore($store)
{
$this->store = $store;
return $this;
}
/**
* Get Store for handling eRx cashed data
* @return object The eRx Store object to use for processing
*/
public function getStore()
{
return $this->store;
}
/**
* Get Account Id set for SOAP communications with NewCrop
* @return string The Account Id sent with SOAP requests to NewCrop
*/
public function getAccountId()
{
return $this->getGlobals()->getAccountId();
}
/**
* Set SiteId for SOAP communications with NewCrop
* @param string $id The Site Id to send with SOAP requests to NewCrop
* @return eRxSOAP This object is returned for method chaining
*/
public function setSiteId($id)
{
$this->siteId = $id;
return $this;
}
/**
* Get Site Id set for SOAP communications with NewCrop
* @return string The Site Id sent with SOAP requests to NewCrop
*/
public function getSiteId()
{
if (null === $this->siteId) {
$this->siteId = $this->getStore()
->selectFederalEin();
}
return $this->siteId;
}
/**
* Get the authenticated users ID and NPI
* @return array The users ID and NPI
*/
public function getAuthUserDetails()
{
if (null === $this->authUserDetails) {
$this->authUserDetails = $this->getStore()
->getUserById($this->getAuthUserId());
}
return $this->authUserDetails;
}
/**
* Set the Id of the authenticated user
* @param integer $user The Id for the authenticated user
* @return eRxSOAP This object is returned for method chaining
*/
public function setAuthUserId($user)
{
$this->authUserId = $user;
return $this;
}
/**
* Get the Id of the authenticated user
* @return integer The Id of the authenticated user
*/
public function getAuthUserId()
{
return $this->authUserId;
}
/**
* Set the Id of the current patient
* @param integer $id The Id of the current patient
* @return eRxSOAP This object is returned for method chaining
*/
public function setPatientId($id)
{
$this->patientId = (int) $id;
return $this;
}
/**
* Get the Id of the current patient
* @return integer The Id of the current patient
*/
public function getPatientId()
{
return $this->patientId;
}
/**
* Generate and set a new SOAP client with provided Path Id
* @param integer $pathId Id for NewCrop eRx SOAP path: index [0 = Update, 1 = Patient]
* @return SoapClient Soap Client
*/
public function initializeSoapClient($pathId)
{
$paths = $this->getGlobals()->getSoapPaths();
return $this->setSoapClient(new SoapClient($paths[(int) $pathId]));
}
/**
* Set SOAP client for communication with NewCrop
* @param SoapClient $client SOAP client for communication with NewCrop
* @return eRxSOAP This object is returned for method chaining
*/
public function setSoapClient(SoapClient $client)
{
$this->soapClient = $client;
return $this;
}
/**
* Get SOAP client for communication with NewCrop
* @return SoapClient SOAP client for communication with NewCrop
*/
public function getSoapClient()
{
return $this->soapClient;
}
/**
* Set SOAP call settings for calls to NewCrop
* @param array $settings [optional] Setting to send with SOAP call to NewCrop
* @return eRxSOAP This object is returned for method chaining
*/
public function setSoapSettings($settings = array())
{
$this->soapSettings = (array) $settings;
return $this;
}
/**
* Get SOAP call settings for calls to NewCrop
* @return array Settings to send with SOAP call to NewCrop
*/
public function &getSoapSettings()
{
return $this->soapSettings;
}
/**
* Get TTL for provided SOAP process
* @param string $process SOAP process to retrieve TTL for
* @return number|boolean Number on success, false on failure
*/
public function getTTL($process)
{
switch ($process) {
case self::ACTION_ALLERGIES:
$return = $this->getGlobals()->getTTLSoapAllergies();
break;
case self::ACTION_MEDICATIONS:
$return = $this->getGlobals()->getTTLSoapMedications();
break;
default:
$return = false;
}
return $return;
}
/**
* Check if TTL of current patient has elapsed for provided SOAP process
* @param string $process SOAP process to check against for elapsed TTL of current patient
* @return boolean True if TTL of current patient has elapsed for provided SOAP process, otherwise false
*/
public function elapsedTTL($process)
{
$ttl = $this->getTTL($process);
if (false === $ttl || 0 == $ttl) {
return true;
}
$soap = $this->getStore()->getLastSOAP($process, $this->getPatientId());
if (false === $soap) {
return true;
}
return strtotime('-' . $ttl . ' seconds') >= strtotime($soap);
}
/**
* Update provided SOAP process TTL timestamp of current patient
* @param string $process SOAP process to update TTL of current patient
* @return eRxSOAP This object is returned for method chaining
*/
public function updateTTL($process)
{
$this->getStore()->setLastSOAP($process, $this->getPatientId());
return $this;
}
/**
* Check if import status of current patient is set to provided SOAP process(es)
* @param string|array $status SOAP process to check against import status of current patient, optionally an array of SOAP processes can be substituted
* @return boolean True if import status of current patient is set to provided SOAP process(es), otherwise false
*/
public function checkPatientImportStatus($status)
{
$currentStatus = $this->getStore()
->getPatientImportStatusByPatientId(
$this->getPatientId()
);
if (is_array($status)) {
$return = in_array($currentStatus, $status);
} else {
$return = ($currentStatus == $status);
}
return $return;
}
/**
* [updatePatientImportStatus description]
* @param string $status SOAP process to update import status of current patient
* @return eRxSOAP This object is returned for method chaining
*/
public function updatePatientImportStatus($status)
{
$this->getStore()
->updatePatientImportStatusByPatientId(
$this->getPatientId(),
$status
);
return $this;
}
/**
* Initialize SOAP settings with the credentials currently set
* @return eRxSOAP This object is returned for method chaining
*/
public function initializeCredentials()
{
$credentials = $this->getGlobals()->getCredentials();
$this->soapSettings['credentials'] = array(
'PartnerName' => $credentials['0'],
'Name' => $credentials['1'],
'Password' => $credentials['2'],
);
return $this;
}
/**
* Initialize SOAP settings with the NewCrop account and site Ids
* @return eRxSOAP This object is returned for method chaining
*/
public function initializeAccountRequest()
{
$this->soapSettings['accountRequest'] = array(
'AccountId' => $this->getGlobals()->getAccountId(),
'SiteId' => $this->getSiteId(),
);
return $this;
}
/**
* Initialize SOAP settings with patient information
* @return eRxSOAP This object is returned for method chaining
*/
public function initializePatientInformationRequester()
{
$userDetails = $this->getAuthUserDetails();
$this->soapSettings['patientInformationRequester'] = array(
'UserId' => $userDetails['id'],
'UserType' => 'D',
);
return $this;
}
/**
* Get account status information for current patient
* @return object SOAP client response from NewCrop call
*/
public function getAccountStatus()
{
$this->setSoapSettings()
->initializeCredentials()
->initializeAccountRequest();
$userDetails = $this->getAuthUserDetails();
$this->soapSettings['locationId'] = $this->getPatientId();
$this->soapSettings['userId'] = $userDetails['npi'];
$this->soapSettings['userType'] = 'P';
$this->initializeSoapClient(1);
return $this->getSoapClient()
->GetAccountStatus($this->soapSettings);
}
/**
* Get allergy history for current patient
* @return object SOAP client response from NewCrop call
*/
public function getPatientAllergyHistoryV3()
{
$this->setSoapSettings()
->initializeCredentials()
->initializeAccountRequest()
->initializePatientInformationRequester();
$this->soapSettings['patientRequest']['PatientId'] = $this->getPatientId();
$this->initializeSoapClient(0);
return $this->getSoapClient()
->GetPatientAllergyHistoryV3($this->soapSettings);
}
/**
* Get full medication history for current patient
* @return object SOAP client response from NewCrop call
*/
public function getPatientFullMedicationHistory6()
{
$this->setSoapSettings()
->initializeCredentials()
->initializeAccountRequest()
->initializePatientInformationRequester();
$this->soapSettings['patientRequest']['PatientId'] = $this->getPatientId();
$this->soapSettings['prescriptionHistoryRequest'] = array(
'StartHistory' => '2011-01-01T00:00:00.000',
'EndHistory' => date('Y-m-d') . 'T23:59:59.000',
'PrescriptionStatus' => 'C',
'PrescriptionSubStatus' => '%',
'PrescriptionArchiveStatus' => 'N',
);
$this->soapSettings['patientIdType'] = '';
$this->soapSettings['includeSchema'] = '';
$this->initializeSoapClient(0);
return $this->getSoapClient()
->GetPatientFullMedicationHistory6($this->soapSettings);
}
/**
* Get free form allergy history for current patient
* @return object SOAP client response from NewCrop call
*/
public function getPatientFreeFormAllergyHistory()
{
$this->setSoapSettings()
->initializeCredentials()
->initializeAccountRequest()
->initializePatientInformationRequester();
$this->soapSettings['patientRequest']['PatientId'] = $this->getPatientId();
$client = $this->initializeSoapClient(0);
return $this->getSoapClient()
->GetPatientFreeFormAllergyHistory($this->soapSettings);
}
/**
* Insert list option if missing and return the associated option Id
* @param string $listId Id of list to reference
* @param string $title Title text to find
* @return string Option Id of selected list item
*/
public function insertMissingListOptions($listId, $title)
{
$store = $this->getStore();
$optionId = $store->selectOptionIdByTitle($listId, $title);
if (false === $optionId) {
$optionId = 1 + $store->selectOptionIdsByListId($listId);
$store->insertListOptions($listId, $optionId, $title);
}
return $optionId;
}
/**
* Trigger Allergy History SOAP call to NewCrop for current patient and update local cached data
* @return integer Count of newly cached records
*/
public function insertUpdateAllergies()
{
$store = $this->getStore();
$insertedRows = 0;
$allergyArray = self::htmlFixXmlToArray(
$this->getPatientAllergyHistoryV3()
->GetPatientAllergyHistoryV3Result
->XmlResponse
);
if (is_array($allergyArray)) {
foreach ($allergyArray as $allergy) {
$optionId = $this->insertMissingListOptions(
'outcome',
$allergy['AllergySeverityName']
);
$allergySource = $store->selectAllergyErxSourceByPatientIdName(
$this->getPatientId(),
$allergy['AllergyName']
);
if (false === $allergySource) {
$store->insertAllergy(
$allergy['AllergyName'],
$allergy['AllergyId'],
$this->getPatientId(),
$this->getAuthUserId(),
$optionId
);
++$insertedRows;
} elseif (0 == $allergySource) {
$store->updateAllergyOutcomeExternalIdByPatientIdName(
$optionId,
$allergy['AllergyId'],
$this->getPatientId(),
$allergy['AllergyName']
);
} else {
$store->updateAllergyOutcomeByPatientIdExternalIdName(
$optionId,
$this->getPatientId(),
$allergy['AllergyId'],
$allergy['AllergyName']
);
}
}
$this->updatePatientAllergyEndDate($allergyArray);
}
return $insertedRows;
}
/**
* Iterate through provided list of allergies and update records with end dates
* @param array $allergyArray List of allergies
* @return eRxSOAP This object is returned for method chaining
*/
public function updatePatientAllergyEndDate($allergyArray)
{
$store = $this->getStore();
$patientId = $this->getPatientId();
$resource = $store->selectActiveAllergiesByPatientId($patientId);
while ($row = sqlFetchArray($resource)) {
$noMatch = true;
foreach ($allergyArray as $allergy) {
if (array_key_exists('AllergyName', $allergy) && $allergy['AllergyName'] == $row['title']) {
$noMatch = false;
break;
}
}
if ($noMatch) {
$store->updateAllergyEndDateByPatientIdListId(
$patientId,
$row['id']
);
}
}
return $this;
}
/**
* Update eRx uploaded status for current patient allergies
* @return boolean True on success, false on failure
*/
public function updateUploadedErx()
{
$patientFreeFormAllergyHistory = $this
->getPatientFreeFormAllergyHistory()
->GetPatientFreeFormAllergyHistoryResult;
if (0 < $patientFreeFormAllergyHistory->result->RowCount) {
$response = $patientFreeFormAllergyHistory
->patientFreeFormAllergyExtendedDetail
->PatientFreeFormAllergyExtendedDetail;
if (!is_array($response)) {
$response = array($response);
}
foreach ($response as $response) {
$this->getStore()
->updateErxUploadedByListId($response->ExternalId);
}
}
return isset($response);
}
/**
* Insert or update medications for current patient
* @return integer Count of newly cached records
*/
public function insertUpdateMedications()
{
$store = $this->getStore();
$insertedRows = 0;
$medArray = self::htmlFixXmlToArray(
$this->getPatientFullMedicationHistory6()
->GetPatientFullMedicationHistory6Result
->XmlResponse
);
$store->updatePrescriptionsActiveByPatientId($this->getPatientId());
if (is_array($medArray)) {
foreach ($medArray as $med) {
if ($med['DosageForm']) {
$optionIdDosageForm = $this->insertMissingListOptions(
'drug_form',
$med['DosageForm']
);
} else {
$optionIdDosageForm = null;
}
if ($med['Route']) {
$optionIdRoute = $this->insertMissingListOptions(
'drug_route',
$med['Route']
);
} else {
$optionIdRoute = null;
}
if ($med['StrengthUOM']) {
$optionIdStrengthUOM = $this->insertMissingListOptions(
'drug_units',
$med['StrengthUOM']
);
} else {
$optionIdStrengthUOM = null;
}
if ($med['DosageFrequencyDescription']) {
$optionIdFrequencyDescription = $this->insertMissingListOptions(
'drug_interval',
$med['DosageFrequencyDescription']
);
} else {
$optionIdFrequencyDescription = null;
}
$providerId = $store->selectUserIdByUserName($med['ExternalPhysicianID']);
$check = $store->selectPrescriptionIdByGuidPatientId(
$med['PrescriptionGuid'],
$med['ExternalPatientID']
);
$prescriptionId = '';
if (0 == sqlNumRows($check)) {
$prescriptionId = $store->insertPrescriptions(
$med,
$encounter,
$providerId,
$this->getAuthUserId(),
$optionIdDosageForm,
$optionIdRoute,
$optionIdStrengthUOM,
$optionIdFrequencyDescription
);
++$insertedRows;
setListTouch($this->getPatientId(), 'prescription_erx');
} else {
$store->updatePrescriptions(
$med,
$providerId,
$this->getAuthUserId(),
$optionIdDosageForm,
$optionIdRoute,
$optionIdStrengthUOM,
$optionIdFrequencyDescription
);
}
$result = sqlFetchArray($check);
if ($result['id']) {
$prescriptionId = $result['id'];
}
// Making sure only transmitted prescriptions entry added into amc_misc_data for eRx Numerator
if (!empty($med['PharmacyNCPDP'])) {
processAmcCall(
'e_prescribe_amc',
true,
'add',
$med['ExternalPatientID'],
'prescriptions',
$prescriptionId
);
}
if ($med['FormularyChecked'] === 'true') {
processAmcCall('e_prescribe_chk_formulary_amc', true, 'add', $med['ExternalPatientID'], 'prescriptions', $prescriptionId);
}
}
}
return $insertedRows;
}
}