clqms-be/app/Controllers/Patient.php

415 lines
17 KiB
PHP
Raw Normal View History

<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use CodeIgniter\Database\RawSql;
class Patient extends Controller {
use ResponseTrait;
public function __construct() {
$this->db = \Config\Database::connect();
}
2025-08-01 22:18:45 +07:00
// OK - Done
public function index() {
2025-07-23 11:03:46 +07:00
try {
2025-08-04 13:21:13 +07:00
$InternalPID = $this->request->getVar('InternalPID');
2025-08-01 13:37:13 +07:00
$PatientID = $this->request->getVar('PatientID');
2025-08-04 13:21:13 +07:00
$Name = $this->request->getVar('Name');
$Birthdate = $this->request->getVar('Birthdate');
2025-08-05 10:34:58 +07:00
$qname = "LOWER(CONCAT_WS(' ', IFNULL(Prefix,''), IFNULL(NameFirst,''), IFNULL(NameMiddle,''), IFNULL(NameLast,''), IFNULL(NameMaiden,''), IFNULL(Suffix,'')))";
$builder = $this->db->table('patient');
$builder->select("InternalPID, PatientID, $qname as FullName, Gender, Birthdate, EmailAddress1 as Email, MobilePhone");
2025-08-04 13:21:13 +07:00
if ($Name !== null) {
2025-08-05 10:34:58 +07:00
$sql = $qname;
2025-07-23 11:03:46 +07:00
$rawSql = new RawSql($sql);
2025-08-04 13:21:13 +07:00
$builder->like($rawSql, $Name, 'both');
2025-07-23 11:03:46 +07:00
}
2025-08-04 13:21:13 +07:00
if ($InternalPID !== null) { $builder->where('InternalPID', $InternalPID); }
2025-08-05 11:38:11 +07:00
if ($PatientID !== null) { $builder->like('PatientID', $PatientID, 'both'); }
if ($Birthdate !== null) { $builder->where('Birthdate', $Birthdate); }
2025-07-23 11:03:46 +07:00
$filteredPatients = $builder->get()->getResultArray();
2025-07-23 11:03:46 +07:00
// Data pasien tidak ada mengembalikan - success 200
if (empty($filteredPatients)) {
return $this->respond([
2025-07-16 09:19:47 +07:00
'status' => 'success',
2025-07-23 11:03:46 +07:00
'message' => 'No patient records found matching the criteria.',
'data' => []
], 200);
}
// Data pasien ditemukan dan mengembalikan - success 200
return $this->respond([
'status' => 'success',
'message'=> "Patients fetched successfully",
'data' => $filteredPatients,
], 200);
} catch (\Exception $e) {
// Error Server Mengembalikan 500
return $this->failServerError('Something went wrong.'.$e->getMessage());
2025-07-23 11:03:46 +07:00
}
}
2025-08-01 22:18:45 +07:00
// OK - Done
public function show($InternalPID = null) {
2025-07-23 11:03:46 +07:00
try {
2025-08-11 12:50:57 +07:00
// $builder = $this->db->table('patient');
// $patient = $builder->join('patidt', 'patidt.InternalPID = patient.InternalPID', 'left')
// ->where('patient.InternalPID', ((int) $InternalPID))
// ->get()->getRowArray();
$patient = $this->db->table('patient')
->where('InternalPID', (int) $InternalPID)
->get()
->getRowArray();
2025-07-23 11:03:46 +07:00
// Data pasien tidak ada mengembalikan - success 200
if (empty($patient)) {
return $this->respond([
2025-07-16 09:19:47 +07:00
'status' => 'success',
2025-08-01 22:34:33 +07:00
'message' => 'Patient with ID ' . $InternalPID . ' not found.',
2025-07-23 11:03:46 +07:00
'data' => [],
], 200);
2025-08-11 12:50:57 +07:00
} else {
$patient["Age"] = $this->calculateAgeFromBirthdate($patient["Birthdate"]);
$patient["Birthdate"] = date("d-m-Y", strtotime($patient["Birthdate"]));
if ($patient['LinkTo'] != null) {
$ids = explode(',', $patient['LinkTo']); // dari string jadi array
$patientLinkTo = $this->db->table('patient')
->select('InternalPID, PatientID')
->whereIn('InternalPID', $ids)
->get()
->getResultArray();
$patient["LinkTo"] = $patientLinkTo == [] ? null : $patientLinkTo[0];
}
2025-08-11 12:50:57 +07:00
$patidt = $this->db->table('patidt')
->select('IdentifierType, Identifier')
2025-08-11 12:50:57 +07:00
->where('InternalPID', (int) $InternalPID)
->get()
->getResultArray();
$patient['Identity'] = $patidt == [] ? null : $patidt;
2025-07-23 11:03:46 +07:00
}
// Data pasien ditemukan dan mengembalikan - success 200
return $this->respond([
'status' => 'success',
'message'=> "Patient Show Successfully",
'data' => $patient,
], 200);
} catch (\Exception $e) {
// Error Server Mengembalikan 500
return $this->failServerError('Something went wrong'.$e->getMessage());
2025-07-23 11:03:46 +07:00
}
2025-07-16 09:19:47 +07:00
}
2025-08-01 22:18:45 +07:00
// OK - Done
public function create() {
2025-07-23 11:03:46 +07:00
try {
$input = $this->request->getJSON(true);
$LinkTo = null;
if (!empty($input['LinkTo'])) {
$ids = []; // Temporary
foreach ($input['LinkTo'] as $row) {
$ids[] = $row['InternalPID'];
}
$LinkTo = implode(',', $ids);
}
// =========================
// 1. Data untuk tabel patient
// =========================
$dataPatient = [
"PatientID" => $input['PatientID'] ?? null,
"AlternatePID" => $input['AlternatePID'] ?? null,
"Prefix" => $input['Prefix'] ?? null,
"NameFirst" => $input['NameFirst'] ?? null,
"NameMiddle" => $input['NameMiddle'] ?? null,
"NameMaiden" => $input['NameMaiden'] ?? null,
"NameLast" => $input['NameLast'] ?? null,
"Suffix" => $input['Suffix'] ?? null,
"NameAlias" => $input['NameAlias'] ?? null,
"Gender" => isset($input['Gender']) ? (int) $input['Gender'] : null,
"PlaceOfBirth" => $input['PlaceOfBirth'] ?? null,
"Birthdate" => $input['Birthdate'] ?: null,
"Street_1" => $input['Street_1'] ?? null,
"Street_2" => $input['Street_2'] ?? null,
"Street_3" => $input['Street_3'] ?? null,
"City" => $input['City'] ?? null,
"Province" => $input['Province'] ?? null,
"ZIP" => $input['ZIP'] ?? null,
"EmailAddress1" => $input['EmailAddress1'] ?? null,
"EmailAddress2" => $input['EmailAddress2'] ?? null,
"Phone" => $input['Phone'] ?? null,
"MobilePhone" => $input['MobilePhone'] ?? null,
"RaceID" => isset($input['RaceID']) ? (int) $input['RaceID'] : null,
"IntCountryID" => isset($input['IntCountryID']) ? (int) $input['IntCountryID'] : null,
"MaritalStatus" => $input['MaritalStatus'] ?? null,
"ReligionID" => isset($input['ReligionID']) ? (int) $input['ReligionID'] : null,
"EthnicID" => isset($input['EthnicID']) ? (int) $input['EthnicID'] : null,
"Citizenship" => $input['Citizenship'] ?? null,
"DeathIndicator" => isset($input['DeathIndicator']) ? (int) $input['DeathIndicator'] : null,
'DeathDateTime' => $input['DeathDateTime'] ?: null,
"CreateDate" => date('Y-m-d H:i:s'),
"DelDate" => null,
"LinkTo" => $LinkTo
2025-08-08 13:59:24 +07:00
// Mother
// AccountNumber
];
$rulesDataPatient = [
'PatientID' => 'required|is_unique[patient.PatientID]|max_length[50]',
'AlternatePID' => 'permit_empty|max_length[50]',
'NameFirst' => 'required|min_length[1]|max_length[255]',
'EmailAddress1' => 'required|is_unique[patient.EmailAddress1]',
'DeathIndicator' => 'required',
'Gender' => 'required'
2025-07-23 11:03:46 +07:00
];
$dataPatidt = [
"IdentifierType" => $input['IdentifierType'] ?? null,
"Identifier" => $input['Identifier'] ?? null,
"CreateDate" => date('Y-m-d H:i:s'),
2025-07-23 11:03:46 +07:00
];
$rulesDataPatidt = [
'Identifier' => 'required|is_unique[patidt.Identifier]',
];
// =========================
// Validasi semua sebelum insert
// =========================
if (!$this->validateData($dataPatient, $rulesDataPatient)) {
2025-07-23 11:03:46 +07:00
return $this->respond([
'status' => 'error',
'message' => 'Validation failed (patient)',
'errors' => $this->validator->getErrors()
2025-07-23 11:03:46 +07:00
], 400);
}
if (!$this->validateData($dataPatidt, $rulesDataPatidt)) {
return $this->respond([
'status' => 'error',
'message' => 'Validation failed (patidt)',
'errors' => $this->validator->getErrors()
], 400);
}
// =========================
// Mulai transaksi
// =========================
$this->db->transStart();
$this->db->table('patient')->insert($dataPatient);
$newInternalPatientId = $this->db->insertID();
2025-08-08 14:02:56 +07:00
$dbError = $this->db->error();
if (!empty($dbError['message'])) {
$this->db->transRollback();
return $this->failServerError('Insert patient failed: ' . $dbError['message']);
}
$dataPatidt['InternalPID'] = $newInternalPatientId;
$this->db->table('patidt')->insert($dataPatidt);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
$dbError = $this->db->error();
2025-08-08 13:59:24 +07:00
return $this->failServerError(
2025-08-08 14:02:56 +07:00
'Failed to create patient data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown database error')
2025-08-08 13:59:24 +07:00
);
}
2025-07-23 11:03:46 +07:00
return $this->respondCreated([
'status' => 'success',
2025-07-23 11:03:46 +07:00
'message' => 'Patient created successfully',
'data' => $newInternalPatientId
2025-07-23 11:03:46 +07:00
], 201);
} catch (\Exception $e) {
$this->db->transRollback();
return $this->failServerError('Something went wrong: ' . $e->getMessage());
2025-07-23 11:03:46 +07:00
}
}
// OK - Done
2025-08-01 22:18:45 +07:00
public function update($InternalPID = null) {
2025-07-23 11:03:46 +07:00
try {
$InternalPID = (int) $InternalPID;
2025-07-23 11:03:46 +07:00
$input = $this->request->getJSON(true);
$dataPatient = [
"PatientID" => $input['PatientID'] ?? null,
"AlternatePID" => $input['AlternatePID'] ?? null,
"Prefix" => $input['Prefix'] ?? null,
"NameFirst" => $input['NameFirst'] ?? null,
"NameMiddle" => $input['NameMiddle'] ?? null,
"NameMaiden" => $input['NameMaiden'] ?? null,
"NameLast" => $input['NameLast'] ?? null,
"Suffix" => $input['Suffix'] ?? null,
"NameAlias" => $input['NameAlias'] ?? null,
"Gender" => isset($input['Gender']) ? (int) $input['Gender'] : null,
"PlaceOfBirth" => $input['PlaceOfBirth'] ?? null,
"Birthdate" => $input['Birthdate'] ?: null,
"Street_1" => $input['Street_1'] ?? null,
"Street_2" => $input['Street_2'] ?? null,
"Street_3" => $input['Street_3'] ?? null,
"City" => $input['City'] ?? null,
"Province" => $input['Province'] ?? null,
"ZIP" => $input['ZIP'] ?? null,
"EmailAddress1" => $input['EmailAddress1'] ?? null,
"EmailAddress2" => $input['EmailAddress2'] ?? null,
"Phone" => $input['Phone'] ?? null,
"MobilePhone" => $input['MobilePhone'] ?? null,
"RaceID" => isset($input['RaceID']) ? (int) $input['RaceID'] : null,
"IntCountryID" => isset($input['IntCountryID']) ? (int) $input['IntCountryID'] : null,
"MaritalStatus" => $input['MaritalStatus'] ?? null,
"ReligionID" => isset($input['ReligionID']) ? (int) $input['ReligionID'] : null,
"EthnicID" => isset($input['EthnicID']) ? (int) $input['EthnicID'] : null,
"Citizenship" => $input['Citizenship'] ?? null,
"DeathIndicator" => isset($input['DeathIndicator']) ? (int) $input['DeathIndicator'] : null,
'DeathDateTime' => $input['DeathDateTime'] ?: null,
"CreateDate" => date('Y-m-d H:i:s'),
"DelDate" => null,
// Linkto
// Mother
// AccountNumber
];
$rulesDataPatient = [
'PatientID' => 'required|is_unique[patient.PatientID]|max_length[50]',
'AlternatePID' => 'permit_empty|max_length[50]',
'NameFirst' => 'required|min_length[1]|max_length[255]',
'EmailAddress1' => 'required|is_unique[patient.EmailAddress1]',
'DeathIndicator' => 'required',
'Gender' => 'required'
];
$dataPatidt = [
"IdentifierType" => $input['IdentifierType'] ?? null,
"Identifier" => $input['Identifier'] ?? null,
"CreateDate" => date('Y-m-d H:i:s'),
2025-07-23 11:03:46 +07:00
];
$rulesDataPatidt = [
'Identifier' => 'required|is_unique[patidt.Identifier]',
2025-08-01 13:37:13 +07:00
];
$existingPatient = $this->db->table('patient')->where('InternalPID', $InternalPID)->get()->getRowArray();
2025-07-23 11:03:46 +07:00
// Mengembalikan 404
if (empty($existingPatient)) {
2025-08-01 22:18:45 +07:00
return $this->failNotFound('Patient with ID ' . $InternalPID . ' not found.');
}
2025-07-23 11:03:46 +07:00
// Request dari client tidak valid atau tidak bisa diproses oleh server - 400
if (!$this->validateData($dataPatient, $rules)) {
2025-07-23 11:03:46 +07:00
return $this->failValidationErrors($this->validator->getErrors());
}
$allowedUpdateFields = [
2025-08-01 13:37:13 +07:00
'NameFirst', 'NameLast', 'NameMiddle',
'PatientID', 'AlternatePID', 'Birthdate', 'PlaceOfBirth',
2025-08-01 13:37:13 +07:00
'Street_1', 'Street_2', 'Street_3', 'City', 'Province', 'ZIP',
'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone', 'Mother', 'AccountNumber'
2025-07-23 11:03:46 +07:00
];
$datas = [];
foreach ($allowedUpdateFields as $field) {
if (isset($dataPatient[$field])) {
$datas[$field] = $dataPatient[$field];
2025-07-23 11:03:46 +07:00
}
}
if (empty($dataPatient)) {
2025-07-23 11:03:46 +07:00
return $this->failValidationError('No data provided for update.');
}
$this->db->table('patient')->where('InternalPID', $InternalPID)->update($dataPatient);
2025-07-23 11:03:46 +07:00
// Sukses & Insert = 201 - Kirim data patient ID
return $this->respondCreated([
'status' => 'success',
'message' => 'Patient updated successfully',
'data' => $dataPatient
2025-07-23 11:03:46 +07:00
], 201);
2025-07-23 11:03:46 +07:00
} catch (\Exception $e) {
// Error Server = 500
return $this->failServerError('Something went wrong '.$e->getMessage());
2025-07-23 11:03:46 +07:00
}
}
2025-07-23 11:03:46 +07:00
// OK - Done
2025-08-01 22:18:45 +07:00
public function delete($InternalPID = null) {
2025-07-23 11:03:46 +07:00
try {
$InternalPID = (int) $InternalPID;
2025-07-23 11:03:46 +07:00
2025-08-01 22:18:45 +07:00
if (!$InternalPID) {
2025-07-23 11:03:46 +07:00
return $this->failValidationError('Patient ID is required.');
}
// Cari data pasien
$patient = $this->db->table('patient')->where('InternalPID', $InternalPID)->get()->getRow();
2025-07-23 11:03:46 +07:00
if (!$patient) {
2025-08-01 22:18:45 +07:00
return $this->failNotFound("Patient ID with {$InternalPID} not found.");
2025-07-23 11:03:46 +07:00
}
2025-08-05 10:03:33 +07:00
// Update kolom DelDate sebagai soft delete
$this->db->table('patient')->where('InternalPID', $InternalPID)->update(['DelDate' => date('Y-m-d H:i:s')]);
2025-07-23 11:03:46 +07:00
// Mengembalikan 200
return $this->respondDeleted([
'status' => 'success',
2025-08-01 22:18:45 +07:00
'message' => "Patient ID with {$InternalPID} deleted successfully."
2025-07-23 11:03:46 +07:00
]);
} catch (\Exception $e) {
return $this->failServerError("Internal server error: " . $e->getMessage());
}
}
private function calculateAgeFromBirthdate($birthdate) {
$dob = new \DateTime($birthdate);
$today = new \DateTime();
$diff = $today->diff($dob);
$formattedAge = "";
if ($diff->y > 0){
$formattedAge .= "{$diff->y} Tahun ";
}
if ($diff->m > 0){
$formattedAge .= "{$diff->m} Bulan ";
}
if ($diff->d > 0){
$formattedAge .= "{$diff->d} Hari ";
}
return $formattedAge;
}
}