· 6 years ago · Mar 01, 2020, 05:12 PM
1<?php
2
3/**
4 * ------------------------------------------------------------------
5 * Heartbeat - Registration
6 * ------------------------------------------------------------------
7 *
8 * Creates and handles user registrations to IQVIA CRM.
9 *
10 * @package Heartbeat
11 * @author Sam Ayres <sam.ayres@weareheartbeat.com>
12 * @since 02/10/2020
13 *
14 */
15
16
17namespace Drupal\signup\Entity;
18
19require(__DIR__ . "/../../vendor/autoload.php");
20require_once(__DIR__ . "/../../helpers/Validation.php");
21use Symfony\Component\Dotenv\Dotenv;
22use GuzzleHttp\Client;
23use GuzzleHttp\Psr7\Request;
24use Drupal\Core\Site\Settings;
25use \Datetime;
26
27// Load our environment variables
28$dotenv = new Dotenv();
29$dotenv->load(__DIR__ . "/../../.env");
30
31class signUpNewContact {
32 private $_accessToken;
33 private $_errors;
34 private $_contactKey;
35 private $_firstName;
36 private $_lastName;
37 private $_email;
38 private $_onNuplazid;
39 private $_patient;
40 private $_caregiver;
41 private $_vendor;
42 private $_mcbu;
43 private $_updatedBy;
44 public $_updatedDate;
45
46 // GC
47 private $_gcConsentEmailChannel;
48 private $_gcConsentEmailTopic;
49 private $_gcConsentEmailValue;
50 private $_gcConsentEmailSetting;
51 private $_gcConsentEmailSource;
52 private $_gcConsentEmailDate;
53
54 // NU
55 private $_nuplazidEmailChannel;
56 private $_nuplazidEmailTopic;
57 private $_nuplazidEmailValue;
58 private $_nuplazidEmailSetting;
59 private $_nuplazidEmailSource;
60 private $_nuplazidEmailDate;
61
62 // NC
63 private $_ncEmailChannel;
64 private $_ncEmailTopic;
65 private $_ncEmailValue;
66 private $_ncEmailSetting;
67 private $_ncEmailSource;
68 private $_ncConsentEmailDate;
69
70 // M2P
71 private $_moreToPdRegistrationDate;
72 private $_moreToPdRegistration;
73 private $_moreToPdURL;
74 private $_moreToPdURLMLRCODE;
75
76 /**
77 * Sets the standard information we need from the request.
78 * We are expecting to have an access token and object with an array of info inside.
79 *
80 * @param string $accessToken
81 * @param array $items
82 * @return void
83 */
84 public function __construct($firstName=NULL, $lastName=NULL, $email, $patient=NULL, $caregiver=NULL) {
85 // To make requests to CRM server we need an access token.
86 // @TODO: Ask user if they are on nuplazid?
87 $this->_currentDate = date("y-m-d h:m:s");
88 $this->_accessToken = $this->getAccessToken();
89 $this->_contactKey = false;
90 $this->_firstName = $firstName;
91 $this->_lastName = $lastName;
92 $this->_email = $email;
93 $this->_onNupazid = "No";
94 $this->_patient = $patient;
95 $this->_caregiver = $caregiver;
96 $this->_vendor = "Heartbeat";
97 $this->_mcbu = "515002193";
98 $this->_updatedBy = "moretoparkinsons.com";
99 $this->_updatedDate = $this->_currentDate;
100
101 // GC
102 $this->$_gcConsentEmailChannel = "Email";
103 $this->$_gcConsentEmailTopic = "General Communications";
104 $this->$_gcConsentEmailValue = "Email";
105 $this->$_gcConsentEmailSetting = "True";
106 $this->$_gcConsentEmailSource = "moretoparkinsons.com";
107 $this->$_gcConsentEmailDate = $this->_currentDate;
108
109 // NU
110 $this->_nuplazidEmailChannel = "Email";
111 $this->_nuplazidEmailTopic = "General Communications";
112 $this->_nuplazidEmailValue = "Email";
113 $this->_nuplazidEmailSetting = "True";
114 $this->_nuplazidEmailSource = "moretoparkinsons.com";
115 $this->_nuplazidEmailDate = $this->_currentDate;
116
117 // NC
118 $this->_ncEmailChannel = "Email";
119 $this->_ncEmailTopic = "Nuplazid Connect";
120 $this->_ncEmailValue = "Email";
121 $this->_ncEmailSetting = "True";
122 $this->_ncEmailSource = "moretoparkinsons.com";
123 $this->_ncConsentEmailDate = $this->_currentDate;
124
125 // M2P
126 $this->_moreToPdRegistrationDate = $this->_currentDate;
127 $this->_moreToPdRegistration = "True";
128 $this->_moreToPdURL = "";
129 $this->_moreToPdURLMLRCODE = "";
130 }
131
132 /**
133 * Inits the sign up process
134 * @return bool
135 */
136 public function handleSignUp() {
137 $this->validateRequest();
138 $this->checkDuplicate();
139 $this->sendRegistration();
140 $this->sendRegistrationAttributeData();
141 $this->sendRegistrationOpts();
142 }
143
144 /** Inits the unsubscribe process
145 * @return bool
146 */
147 public function handleUnsubscribe() {
148 // $this->validateRequest();
149 // $this->checkDuplicate("unsubscribe");
150 // $this->sendUnsubscribeData();
151 // $this->sendUnsubscribeAttributeData();
152 // $this->sendUnsubscribeOpts();
153 }
154
155 /** Checks if an email is valid
156 * @return bool
157 */
158 public function checkEmail($str) {
159 return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
160 }
161
162 /** Generates a GUID for new users
163 * @return string
164 */
165 public function getGUID(){
166 if (function_exists('com_create_guid')){
167 return com_create_guid();
168 }
169 else {
170 mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
171 $charid = strtoupper(md5(uniqid(rand(), true)));
172 $hyphen = chr(45);// "-"
173 $uuid = chr(123)// "{"
174 .substr($charid, 0, 8).$hyphen
175 .substr($charid, 8, 4).$hyphen
176 .substr($charid,12, 4).$hyphen
177 .substr($charid,16, 4).$hyphen
178 .substr($charid,20,12)
179 .chr(125);// "}"
180 return $uuid;
181 }
182 }
183
184 /**
185 * Generate a request token to be used for the session.
186 *
187 * @return string
188 */
189 private function getAccessToken() {
190 try {
191 $client = new Client();
192
193 $options = [
194 "headers" => [
195 "Accept" => 'application/json',
196 ],
197 "form_params" => [
198 "grant_type" => "client_credentials",
199 "client_id" => $_ENV["CLIENT_ID"],
200 "client_secret" => $_ENV["CLIENT_SECRET"]
201 ]
202 ];
203 $result = $client->post($_ENV["AUTH_API_URL"], $options);
204
205 return (string) $result->getBody();
206 }
207 catch(Exception $error) {
208 \Drupal::logger('signup')->error("error " . $error-getMessage());
209 }
210 }
211
212
213 /**
214 * Validate that the request meets the requirements of the client.
215 *
216 * @return array
217 */
218 private function validateRequest() {
219 $emailCheck = $this->checkEmail($this->_email);
220
221 if($emailCheck && isset($this->_firstName) && isset($this->_lastName)) {
222 return true;
223 }
224 else {
225 $this->_errors = "Params failed to validate";
226 \Drupal::logger('signup')->error("Error " . print_r($this->_errors, TRUE));
227 return $this->_errors;
228 }
229 }
230
231 /**
232 * Check if user is dupicate
233 *
234 * @return bool
235 */
236 private function checkDuplicate($type=null) {
237 // If no errors we can submit the registrant
238 \Drupal::logger('signup')->notice("access token" . print_r($this->_accessToken, TRUE));
239 if(!$this->_errors) {
240 $checkNewUser = new Client();
241 try {
242 $options = [
243 'headers' => [
244 'Accept' => 'application/json',
245 'Content-Type' => 'application/x-www-form-urlencoded',
246 'Authorization' => "Bearer " . $this->_accessToken
247 ],
248 'debug' => true,
249 "query" => '$filter=email%20eq%20"' .$this->_email . '"&$fields=Contact Key,First Name,Last Name'
250 ];
251
252 $result = $checkNewUser->get($_ENV['REST_API_URL'], $options);
253 if($type === "unsubscribe") {
254 $this->_firstName = $result["items"]["values"]["first name"];
255 $this->_lastName = $result["items"]["values"]["last name"];
256 }
257 } catch (RequestException $e) {
258 \Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
259 if ($e->hasResponse()) {
260 \Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
261 echo $e->getRequest() . "\n";
262 \Drupal::logger('signup')->error("error " . print_r($e->getResponse(), TRUE));
263 }
264 }
265 }
266 else {
267 return $this->_errors;
268 }
269 }
270
271 /**
272 * Send the user registration details to CRM (IQVIA).
273 *
274 * @return string
275 */
276 private function sendRegistration() {
277 $checkFormResult = $this->validateRequest();
278 // If no errors we can submit the registrant
279 if(!$this->_errors && $checkFormResult) {
280 try {
281 // Generate new guid for new user
282 $sendNewUser = new Client();
283 $this->_contactKey = $this->getGUID();
284 $options = [
285 "headers" => [
286 "Accept" => "application/json",
287 "Authorization" => "Bearer " . $this->_accessToken,
288 "Content-type' => 'application/json"
289 ],
290 'debug' => true,
291 "body" => [
292 "items" => [
293 "Contact Key" => $this->_contactKey,
294 "First Name" => $this->_firstName,
295 "Last Name" => $this->_firstName,
296 "Email" => $this->_email,
297 "Patient" => $this->_patient,
298 "Caregiver" => $this->_caregiver,
299 "On Nuplazid" => $this->_onNuplazid,
300 "Vendor" => $this->_vendor,
301 "MC BU" => $this->_mcbu,
302 "GC Consent Email Channel" => $this->_gcConsentEmailChannel,
303 "GC Consent Email Topic" => $this->_gcConsentEmailTopic,
304 "GC Consent Email Value" => $this->_gcConsentEmailValue,
305 "GC Consent Email Setting" => $this->_gcConsentEmailSetting,
306 "GC Consent Email Source" => $this->_gcConsentEmailSource,
307 "GC Consent Email Date" => $this->_gcConsentEmailDate,
308 "Nuplazid Consent Email Channel" => $this->_nuplazidEmailChannel,
309 "Nuplazid Consent Email Topic" => $this->_nuplazidEmailTopic,
310 "Nuplazid Consent Email Value" => $this->_nuplazidEmailValue,
311 "Nuplazid Consent Email Setting" => $this->_nuplazidEmailSetting,
312 "Nuplazid Consent Email Source" => $this->_nuplazidEmailSource,
313 "Nuplazid Consent Email Date" => $this->_nuplazidEmailDate,
314 "NC Consent Email Channel" => $this->_ncEmailChannel,
315 "NC Consent Email Topic" => $this->_ncEmailTopic,
316 "NC Consent Email Value" => $this->_ncEmailValue,
317 "NC Consent Email Setting" => $this->_ncEmailSetting,
318 "NC Consent Email Source" => $this->_ncEmailSource,
319 "NC Consent Email Date" => $this->_ncConsentEmailDate,
320 "Updated By" => $this->_updatedBy,
321 "Updated Date" => $this->_updatedDate,
322 "MoretoPD Registration Date" => $this->_moreToPdRegistrationDate,
323 "MoretoPD Registration" => $this->_moreToPdRegistration,
324 "MoretoPD URL" => $this->_moreToPdURL,
325 "MoretoPD URL MLR CODE" => $this->_moreToPdURLMLRCODE
326 ]
327 ]
328 ];
329 // $result = $sendNewUser->put($_ENV["AUTH_API_URL"], $options);
330 $result = $sendNewUser->put($_ENV["AUTH_API_URL"], $options);
331 $result->getStatusCode();
332 \Drupal::logger('signup')->notice("registration " . print_r((string) $result->getBody(), TRUE));
333 return true;
334 }
335 catch (RequestException $e) {
336 \Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
337 if ($e->hasResponse()) {
338 \Drupal::logger('signup')->error("error " . print_r($e->getRequest(), TRUE));
339 echo $e->getRequest() . "\n";
340 \Drupal::logger('signup')->error("error " . print_r($e->getResponse(), TRUE));
341 }
342 return false;
343 }
344 }
345 else {
346 return $this->_errors;
347 }
348 }
349
350 /**
351 * Send the user registration attributes data to CRM (IQVIA).
352 *
353 * @return string
354 */
355 private function sendRegistrationAttributeData() {
356 $sendNewRegistrationAttrData = new Client();
357 // Large array of mainly static info
358 $itemsAttr = [
359 "items" => [
360 [
361 "Contact Key" => $this->_guid,
362 "AttributeCode" => "MCBU",
363 "AttributeType" => "Consumer",
364 "AttributeName" => "OCEMarketing",
365 "AttributeValue" => $this->_mcbu ,
366 "VendorName" => $this->_vendor,
367 "Updated" => $this->_currentDate,
368 "Status" => "Active"
369 ],
370 [
371 "Contact Key" => $this->_guid,
372 "AttributeCode" =>"API",
373 "AttributeType" => "Contact Registration",
374 "AttributeName" => "Vendor",
375 "AttributeValue" => $this->_vendor,
376 "VendorName" => $this->_vendor,
377 "Updated" => $this->_currentDate,
378 "Status" => "Active"
379 ],
380 [
381 "Contact Key" => $this->_guid,
382 "AttributeCode" =>"API",
383 "AttributeType" => "Contact Registration",
384 "AttributeName" => "Patient",
385 "AttributeValue" => $this->_patient,
386 "VendorName" => $this->_vendor,
387 "Updated" => $this->_currentDate,
388 "Status" => "Active"
389 ],
390 [
391 "Contact Key" => $this->_guid,
392 "AttributeCode" =>"API",
393 "AttributeType" => "Contact Registration",
394 "AttributeName" => "Caregiver",
395 "AttributeValue" => $this->_caregiver,
396 "VendorName" => $this->_vendor,
397 "Updated" => $this->_currentDate,
398 "Status" => "Active"
399 ],
400 [
401 "Contact Key" => $this->_guid,
402 "AttributeCode" =>"API",
403 "AttributeType" => "Contact Registration",
404 "AttributeName" => "Registration",
405 "AttributeValue" => "Registration from MoretoPD",
406 "VendorName" => $this->_vendor,
407 "Updated" => $this->_currentDate,
408 "Status" => "Active"
409 ],
410 [
411 "Contact Key" => $this->_guid,
412 "AttributeCode" =>"API",
413 "AttributeType" => "Contact Registration",
414 "AttributeName" => "On Nuplazid",
415 "AttributeValue" => $this->_onNuplazid,
416 "VendorName" => $this->_vendor,
417 "Updated" => $this->_currentDate,
418 "Status" => "Active"
419 ],
420 [
421 "Contact Key" => $this->_guid,
422 "AttributeCode" =>"API",
423 "AttributeType" => "Contact Registration",
424 "AttributeName" => "MoretoPD Registration Date",
425 "AttributeValue" => $this->_currentDate,
426 "VendorName" => $this->_vendor,
427 "Updated" => $this->_currentDate,
428 "Status" => "Active"
429 ],
430 [
431 "Contact Key" => $this->_guid,
432 "AttributeCode" =>"API",
433 "AttributeType" => "Contact Registration",
434 "AttributeName" => "MoretoPD URL",
435 "AttributeValue" => $this->_moreToPdURL,
436 "VendorName" => $this->_vendor,
437 "Updated" => $this->_currentDate,
438 "Status" => "Active"
439 ],
440 [
441 "Contact Key" => $this->_guid,
442 "AttributeCode" =>"API",
443 "AttributeType" => "Contact Registration",
444 "AttributeName" => "MoretoPD MLR CODE",
445 "AttributeValue" => $this->_moreToPdURLMLRCODE,
446 "VendorName" => $this->_vendor,
447 "Updated" => $this->_currentDate,
448 "Status" => "Active"
449 ]
450 ]
451 ];
452
453 $options = [
454 "headers" => [
455 "Accept" => "application/json",
456 "Authorization" => "Bearer " . $this->_accessToken,
457 "Content-type' => 'application/json"
458 ],
459 'debug' => true,
460 "body" => [
461 $itemsAttr
462 ]
463 ];
464
465 echo json_encode($itemsAttr);
466 exit;
467 $result = $sendNewUser->put($_ENV["REST_API_REGISTRANT_URL"], $options);
468 }
469
470
471 /**
472 * Send the user registration OPTS data to CRM (IQVIA).
473 *
474 * @return string
475 */
476 private function sendRegistrationOpts() {
477 $sendNewRegistrationOpts = new Client();
478
479 // Large array of mainly static info
480 $itemsOpts =
481 [
482 "items" => [
483 "Contact Key" => $this->_guid,
484 "Topic" => $this->$_gcConsentEmailTopic,
485 "Channel" => $this->$_gcConsentEmailChannel,
486 "Status" => "In",
487 "Date" => $this->updateDate,
488 "Updated" => $this->_updatedDate,
489 "VendorName" => $this->_vendor
490 ],
491 [
492 "Contact Key" => $this->_guid,
493 "Topic" => $this->$_nuplazidEmailTopic,
494 "Channel" => $this->$_nuplazidEmailChannel,
495 "Status" => "In",
496 "Date" => $this->updateDate,
497 "Updated" => $this->_updatedDate,
498 "VendorName" => $this->_vendor
499 ],
500 [
501 "Contact Key" => $this->_guid,
502 "Topic" => $this->_ncEmailTopic,
503 "Channel" => $this->_ncEmailChannel,
504 "Status" => "In",
505 "Date" => $this->updateDate,
506 "Updated" => $this->_updatedDate,
507 "VendorName" => $this->_vendor
508 ]
509 ];
510
511 $options = [
512 "headers" => [
513 "Accept" => "application/json",
514 "Authorization" => "Bearer " . $this->_accessToken,
515 "Content-type' => 'application/json"
516 ],
517 'debug' => true,
518 "body" => [
519 $itemsAttr
520 ]
521 ];
522
523 $result = $sendNewRegistrationOpts->put($_ENV["REST_API_REGISTRANT_URL"], $options);
524 \Drupal::logger('signup')->notice("json check " . print_r(json_encode($items), TRUE));
525 }
526
527 /**
528 * Send the user unsub attributes data to CRM (IQVIA).
529 *
530 * @return string
531 */
532 private function sendUnsubscribeAttributeData() {
533 $sendNewUnsubscribeAttrData = new Client();
534 // Large array of mainly static info
535 $itemsAttr = [
536 [
537 "items" => [
538 "Contact Key" => $this->_guid,
539 "AttributeCode" => "API",
540 "AttributeType" => "Contact Registration",
541 "AttributeName" => "MoretoPD Unsubscribe Date",
542 "AttributeValue" => $this->updatedDate,
543 "VendorName" => $this->_vendor,
544 "Updated" => $this->updatedDate,
545 "Status" => "Active"
546 ]
547 ]
548 ];
549
550 $options = [
551 "headers" => [
552 "Accept" => "application/json",
553 "Authorization" => "Bearer " . $this->_accessToken,
554 "Content-type' => 'application/json"
555 ],
556 'debug' => true,
557 "body" => [
558 $itemsAttr
559 ]
560 ];
561 $result = $sendNewUnsubscribeAttrData->put($_ENV["REST_API_REGISTRANT_URL"], $options);
562 }
563
564
565 /**
566 * Send the user registration OPTS data to CRM (IQVIA).
567 *
568 * @return string
569 */
570 private function sendUnsubscribeOpts() {
571 $sendNewUnsubscribeOpts = new Client();
572
573 // Large array of mainly static info
574 $itemsOpts = [
575 "items" => [
576 [
577 "Contact Key" => $this->_guid,
578 "Topic" => $this->$_gcConsentEmailTopic,
579 "Channel" => $this->$_gcConsentEmailChannel,
580 "Status" => "Out",
581 "Date" => $this->updateDate,
582 "Updated" => $this->_updatedDate,
583 "VendorName" => $this->_vendor
584 ],
585 [
586 "Contact Key" => $this->_guid,
587 "Topic" => $this->$_nuplazidEmailTopic,
588 "Channel" => $this->$_nuplazidEmailChannel,
589 "Status" => "Out",
590 "Date" => $this->updateDate,
591 "Updated" => $this->_updatedDate,
592 "VendorName" => $this->_vendor
593 ],
594 [
595 "Contact Key" => $this->_guid,
596 "Topic" => $this->_ncEmailTopic,
597 "Channel" => $this->_ncEmailChannel,
598 "Status" => "Out",
599 "Date" => $this->updateDate,
600 "Updated" => $this->_updatedDate,
601 "VendorName" => $this->_vendor
602 ]
603 ]];
604
605 $options = [
606 "headers" => [
607 "Accept" => "application/json",
608 "Authorization" => "Bearer " . $this->_accessToken,
609 "Content-type' => 'application/json"
610 ],
611 'debug' => true,
612 "body" => [
613 $itemsAttr
614 ]
615 ];
616
617 $result = $sendNewUnsubscribeOpts->put($_ENV["REST_API_REGISTRANT_URL"], $options);
618 \Drupal::logger('signup')->notice("json check " . print_r(json_encode($items), TRUE));
619 }
620}