<?php
namespace App\Service;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Doctrine\Persistence\ManagerRegistry;
use App\Repository\{PatientRepository};
class Abha
{
private $flash;
private $patientRepo;
public function __construct(FlashBagInterface $flash, private ManagerRegistry $doctrine, PatientRepository $patientRepo)
{
$this->flash = $flash;
$this->patientRepo = $patientRepo;
}
public function GUID()
{
if (function_exists('com_create_guid') === true) {
return trim(com_create_guid(), '{}');
}
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}
// public function getAccessToken()
// {
// $now = new \DateTime('now', new \DateTimeZone('UTC'));
// $isoTimestamp = $now->format('Y-m-d\TH:i:s.v\Z');
// $reqId = self::GUID();
// try {
// $client = HttpClient::create();
// // $sessionUrl = env('ABDM_URL') . '/v0.5/sessions';
// $sessionUrl = 'https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions';
// $tokenReq = $client->post($sessionUrl, [
// 'headers' => [
// 'Content-Type' => 'application/json',
// 'X-CM-ID' => 'sbx',
// 'REQUEST-ID' => $reqId,
// 'TIMESTAMP' => $isoTimestamp],
// 'json' => [
// 'clientId' => 'SBX_002132',
// 'clientSecret' => 'dd468fe5-74f5-44f1-9fb5-47542de0f60b',
// 'grantType' => 'client_credentials'
// ]
// ]);
// // Log::debug($tokenReq->getBody());
// $res = json_decode($tokenReq->getBody(), true);
// return 'Bearer ' . $res['accessToken'];
// } catch (\Exception $ex) {
// info('Error in fetching access token');
// info($ex->getMessage());
// }
// }
public function getAccessToken()
{
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$isoTimestamp = $now->format('Y-m-d\TH:i:s.v\Z');
$reqId = self::GUID();
$client = HttpClient::create();
$response = $client->request('POST', 'https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions', [
'headers' => [
'Content-Type' => 'application/json',
'X-CM-ID' => 'sbx',
'REQUEST-ID' => $reqId,
'TIMESTAMP' => $isoTimestamp
],
'json' => [
'clientId' => 'SBX_002132',
'clientSecret' => 'dd468fe5-74f5-44f1-9fb5-47542de0f60b',
'grantType' => 'client_credentials'
]
]);
$decodedPayload = $response->toArray();
return 'Bearer ' . $decodedPayload['accessToken'];
}
public function getUserDetails($content)
{
$contentArr['token'] = $content['token'];
$contentArr['firstName'] = $content['first_name'];
$contentArr['middleName'] = $content['middle_name'];
$contentArr['lastName'] = $content['last_name'];
$contentArr['yearOfBirth'] = date('Y', strtotime($content['dob']));
$contentArr['monthOfBirth'] = date('m', strtotime($content['dob']));
$contentArr['dayOfBirth'] = date('d', strtotime($content['dob']));
$contentArr['dob'] = date('Y-m-d', strtotime($content['dob']));
$contentArr['gender'] = $content['gender'];
$contentArr['mobile'] = isset($content['identifiers']['mobile']) ? $content['identifiers']['mobile'] : '';
$contentArr['healthIdNumber'] = isset($content['identifiers']['health_number']) ? $content['identifiers']['health_number'] : '';
$contentArr['healthIdAddress'] = $content['id'];
$contentArr['refresh_token'] = isset($content['refreshToken']) ? $content['refreshToken'] : '';
return $contentArr;
}
/* M3 Part Start here*/
public function getConsentList()
{
$conn = $this->doctrine->getConnection('cnmgts');
$sql = "SELECT * FROM cnmgts_abha_consent_request ORDER BY id DESC";
return $conn->fetchAllAssociative($sql);
}
public function requestInt($data)
{
$expiry = $data['expiry'];
$purpose = $data['purpose'];
$fromTo = $data['fromTo'];
$ArrDate = explode('-', $fromTo);
$currentDate = date('d-m-Y');
$from = str_replace('/', '-', trim($ArrDate[0]));
$to = str_replace('/', '-', trim($ArrDate[1]));
$current = str_replace('/', '-', $currentDate);
$expiryDate = str_replace('/', '-', $expiry);
$type = $data['type'];
$healthAddress = $data['health_id']; //TODO :: health address store in session
if ($_ENV['ABHA_ENV'] == 'sandbox') {
$suffix = $_ENV['ABHA_SBX_SUFFIX'];
} else {
$suffix = $_ENV['ABHA_PROD_SUFFIX'];
}
if (!strpos($healthAddress, $suffix) !== false) {
$healthAddress = $healthAddress . $suffix;
}
$past = $future = $lt = false;
if ($healthAddress != '' && $purpose != '' && $fromTo != '' && $expiryDate != '' && $type != '') {
if (strtotime($currentDate) < strtotime($from) || strtotime($currentDate) < strtotime($to)) { // TODO future date are not allowed
$future = true;
$this->flash->add(
'danger',
'Future date not allowed.'
);
}
if (strtotime($from) > strtotime($to)) {
$lt = true;
$this->flash->add(
'danger',
'From date should be less than to date.'
);
}
if (strtotime($current) > strtotime($expiryDate)) { // TODO past date are not allowed
$past = true;
$this->flash->add(
'danger',
'Past date not allowed.'
);
}
if ($lt || $future || $past) {
return false;
}
} else {
$this->flash->add(
'danger',
'Please enter valid details.'
);
return false;
}
try {
$payload = [
'healthAddress' => $healthAddress,
'purpose' => $purpose,
'from' => $from,
'to' => $to,
'expiry' => $expiryDate,
'type' => $type,
'hiu_name' => 'Rani Unchegaon',
'hiu_id' => 'HIURANI'
];
$url = $_ENV['ABDM_BASE_URL'] . 'm3/request-init';
$this->patientRepo->insertPayload($payload, $url);
$client = HttpClient::create();
$client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json'
],
'json' => $payload
]);
return true;
} catch (\Throwable $th) {
$this->flash->add(
'danger',
'Something went wrong. please try again.'
);
return false;
}
}
public function getDataRequest($id)
{
$conn = $this->doctrine->getConnection('cnmgts');
$sql = "SELECT artefact_id, request_from, request_to, expiry_date, key_material FROM cnmgts_abha_consent_request WHERE id = ? ORDER BY id DESC LIMIT 1";
$arrData = $conn->fetchAllAssociative($sql, [$id]);
// dd($arrData);
if ($arrData[0]) {
try {
$payload = [
'artefactId' => $arrData[0]['artefact_id'],
'from' => $arrData[0]['request_from'],
'to' => $arrData[0]['request_to'],
'expiry' => $arrData[0]['expiry_date'],
'keyMaterial' => $arrData[0]['key_material'],
];
$url = $_ENV['ABDM_BASE_URL'] .'m3/cm-request';
$this->patientRepo->insertPayload($payload, $url);
$client = HttpClient::create();
$client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json'
],
'json' => $payload
]);
// return true;
// $contentData = json_decode($response->getContent(), true);
$this->flash->add(
'success',
'Your request sent successfully.'
);
$flag = true;
} catch (\Throwable $th) {
$this->flash->add(
'danger',
'Something went wrong please try again.'
);
$flag = true;
}
} else {
$flag = true;
}
return $flag;
}
public function getViewData($id)
{
$htmlFinalArr = [];
try {
$conn = $this->doctrine->getConnection('cnmgts');
$sql = "SELECT artefact_id, key_material FROM cnmgts_abha_consent_request WHERE id = ? ORDER BY id DESC LIMIT 1";
$arrData = $conn->fetchAllAssociative($sql, [$id]);
if ($arrData[0]) {
$payload = [
'artefactId' => $arrData[0]['artefact_id'],
'keyMaterial' => $arrData[0]['key_material']
];
$url = $_ENV['ABDM_BASE_URL'] .'m3/data-decryption';
$this->patientRepo->insertPayload($payload, $url);
$client = HttpClient::create();
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json'
],
'json' => $payload
]);
$contentData = json_decode($response->getContent(), true);
if (!empty($contentData)) {
foreach ($contentData as $cKey => $cData) {
$htmlStr = '';
$htmlArr = $htmlPatient = $contentVal = [];
foreach ($cData['entry'] as $data) {
if ($data['resource']) {
if ($data['resource']['resourceType'] == "Patient") {
$htmlPatient[$data['resource']['resourceType']] = $data['resource']['text']['div'];
} else {
$htmlArr[$data['resource']['resourceType']] = $data['resource']['text']['div'];
if (isset($data['resource']['content'])) {
foreach ($data['resource']['content'] as $cVal) {
if ($cVal['attachment']['contentType'] == "application/pdf") {
$contentVal[$cVal['attachment']['contentType']] = $cVal['attachment']['data'];
} else {
$contentVal[$cVal['attachment']['contentType']] = $cVal['attachment']['data'];
}
$htmlFinalArr[$cKey]['content'] = $contentVal;
}
}
}
}
}
$htmlPatient = array_merge($htmlPatient, $htmlArr);
$htmlStr = implode('<div style="border-bottom: 1px solid #EBEDF3;" class="my-2"></div>', $htmlPatient);
$htmlFinalArr[$cKey]['str'] = $htmlStr; // TODO: Care context wise string
}
$flag = true;
} else {
$this->flash->add(
'danger',
'Something went wrong please try again. else'
);
$flag = false;
}
} else {
$flag = false;
}
} catch (\Throwable $th) {
$this->flash->add(
'danger',
'Something went wrong please try again. catch'
);
$flag = false;
}
return array($flag, $htmlFinalArr);
}
public function patientFind($healthId)
{
$requestId = self::GUID();
$accessToken = self::getAccessToken();
$name = '';
// if ($_ENV['ABHA_ENV'] == 'sandbox') {
// $suffix = $_ENV['ABHA_SBX_SUFFIX'];
// } else {
// $suffix = $_ENV['ABHA_PROD_SUFFIX'];
// }
// $hiuId = $this->getUser()->getProfile()->getHospital()->getHIUCode();
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$suffix = '@sbx';
$isoTimestamp = $now->format('Y-m-d\TH:i:s.v\Z');
$client = HttpClient::create();
$response = $client->request('POST', 'https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/search', [
'headers' => [
"REQUEST-ID" => $requestId,
"TIMESTAMP" => $isoTimestamp,
'Authorization' => $accessToken,
'Content-Type' => 'application/json',
'X-CM-ID' => 'sbx'
],
'json' => [
"abhaAddress" => $healthId . $suffix
]
]);
$decodedPayload = $response->toArray();
return $decodedPayload['abhaAddress'];
// $response->getStatusCode();
// var_dump($response);
// return $response;
}
/* End of m3 Part Here*/
}