clqms-be/app/Controllers/Patient.php
2025-08-08 13:59:24 +07:00

394 lines
18 KiB
PHP

<?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();
}
// OK - Done
public function index() {
try {
$InternalPID = $this->request->getVar('InternalPID');
$PatientID = $this->request->getVar('PatientID');
$Name = $this->request->getVar('Name');
$Birthdate = $this->request->getVar('Birthdate');
$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");
if ($Name !== null) {
$sql = $qname;
$rawSql = new RawSql($sql);
$builder->like($rawSql, $Name, 'both');
}
if ($InternalPID !== null) { $builder->where('InternalPID', $InternalPID); }
if ($PatientID !== null) { $builder->like('PatientID', $PatientID, 'both'); }
if ($Birthdate !== null) { $builder->where('Birthdate', $Birthdate); }
$filteredPatients = $builder->get()->getResultArray();
// Data pasien tidak ada mengembalikan - success 200
if (empty($filteredPatients)) {
return $this->respond([
'status' => 'success',
'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());
}
}
// OK - Done
public function show($InternalPID = null) {
try {
$builder = $this->db->table('patient');
$patient = $builder->where('InternalPID', ((int) $InternalPID))->get()->getRowArray();
// Data pasien tidak ada mengembalikan - success 200
if (empty($patient)) {
return $this->respond([
'status' => 'success',
'message' => 'Patient with ID ' . $InternalPID . ' not found.',
'data' => [],
], 200);
}
// 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());
}
}
// OK - Done
public function create() {
try {
$input = $this->request->getJSON(true);
// =========================
// 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
// 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'
];
// =========================
// 2. Data untuk tabel patidt
// =========================
$dataPatidt = [
"IdentifierType" => $input['IdentifierType'] ?? null,
"Identifier" => $input['Identifier'] ?? null
];
$rulesDataPatidt = [
'Identifier' => 'required|is_unique[patidt.Identifier]',
];
// =========================
// Validasi semua sebelum insert
// =========================
if (!$this->validateData($dataPatient, $rulesDataPatient)) {
return $this->respond([
'status' => 'error',
'message' => 'Validation failed (patient)',
'errors' => $this->validator->getErrors()
], 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();
$dataPatidt['InternalPID'] = $newInternalPatientId;
$this->db->table('patidt')->insert($dataPatidt);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
$dbError = $this->db->error(); // ambil error terakhir
return $this->failServerError(
'Failed to create patient data (transaction rolled back): ' .
($dbError['message'] ?? 'Unknown database error')
);
}
return $this->respondCreated([
'status' => 'success',
'message' => 'Patient created successfully',
'data' => $newInternalPatientId
], 201);
} catch (\Exception $e) {
$this->db->transRollback();
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
// OK - Done
public function update($InternalPID = null) {
try {
$InternalPID = (int) $InternalPID;
$input = $this->request->getJSON(true);
$data = [
"InternalPID" => $input['InternalPID'] ?? null,
"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" => 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" => null,
"City" => $input['City'] ?? null,
"Province" => $input['Province'] ?? null,
"ZIP" => $input['ZIP'] ?? null,
"CountryID" => isset($input['CountryID']) ? (int) $input['CountryID'] : null,
"EmailAddress1" => $input['EmailAddress1'] ?? null,
"EmailAddress2" => $input['EmailAddress2'] ?? null,
"Phone" => $input['Phone'] ?? null,
"MobilePhone" => $input['MobilePhone'] ?? null,
"Mother" => $input['Mother'] ?? null,
"AccountNumber" => isset($input['AccountNumber']) ? (int) $input['AccountNumber'] : null,
"RaceID" => isset($input['RaceID']) ? (int) $input['RaceID'] : 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,
// "LinkTo" => $input['LinkTo'] ?? null,
"CreateDate" => date('Y-m-d H:i:s'),
"DelDate" => null,
// Field tambahan dari struktur sebelumnya (bisa dihapus jika tidak dipakai)
// "PatientComment" => $input['PatientComment'] ?? null,
// "IdentityIDType" => $input['IdentityIDType'] ?? null,
// "IdentityID" => $input['IdentityID'] ?? null
];
// $data = [
// "PatientID" => $input['PatientID'] ?? null,
// "AlternatePID" => $input['AlternateID'] ?? null,
// "Prefix" => $input['Title'] ?? null,
// "NameFirst" => $input['NameFirst'] ?? null,
// "NameMiddle" => $input['NameMiddle'] ?? null,
// "NameMaiden" => $input['NameMaiden'] ?? null,
// "NameLast" => $input['NameLast'] ?? null,
// "Suffix" => $input['Suffix'] ?? null,
// "NameAlias" => null,
// "Gender" => ((int) $input['Gender']) ?? null, //int
// "PlaceOfBirth" => $input['PlaceOfBirthdate'] ?? null,
// "Birthdate" => $input['Birthdate'] ?? null,
// "Street1" => $input['Street1'] ?? null,
// "Street2" => $input['Street2'] ?? null,
// "Street3" => null,
// "City" => $input['City'] ?? null,
// "Province" => $input['Province'] ?? null,
// "ZIP" => null,
// "CountryID" => null, // int
// "EmailAddress1" => $input['Email1'] ?? null,
// "EmailAddress2" => $input['Email2'] ?? null,
// "Phone" => $input['Phone'] ?? null,
// "MobilePhone" => $input['Mobile'] ?? null,
// "Mother" => ((int) $input['Mother']) ?? null, //int
// "AccountNumber" => null, //int
// "RaceID" => ((int) $input['Race']) ?? null, //int
// "MaritalStatus" => $input['MaritalStatus'] ?? null,
// "ReligionID" => ((int) $input['Religion']) ?? null, //int
// "EthnicID" => ((int) $input['Ethnic']) ?? null, //int
// "Citizenship" => null,
// "DeathIndicator" => ((int) $input['Death']) ?? null, //int
// "DeathDateTime" => $input['DeathTime'] ?? null,
// "CreateDate" => date('Y-m-d H:i:s'),
// "LinkTo" => $input['LinkTo'] ?? null,
// "PatientComment" => $input['PatientComment'] ?? null,
// "IdentityIDType" => $input['IdentityIDType'] ?? null,
// "IdentityID" => $input['IdentityID'] ?? null
// ];
$rules = [
'NameFirst' => 'required|min_length[3]|max_length[255]',
'NameMiddle' => 'permit_empty',
'NameMaiden' => 'permit_empty',
'NameLast' => 'permit_empty',
// 'birth_date' => 'permit_empty|valid_date[Y-m-d]|not_in_list[0000-00-00]',
'AlternatePID' => 'permit_empty|max_length[50]',
'Street_1' => 'permit_empty',
'Street_2' => 'permit_empty',
'Street_3' => 'permit_empty',
'City' => 'permit_empty',
];
$existingPatient = $this->db->table('patient')->where('InternalPID', $InternalPID)->get()->getRowArray();
// Mengembalikan 404
if (empty($existingPatient)) {
return $this->failNotFound('Patient with ID ' . $InternalPID . ' not found.');
}
// Request dari client tidak valid atau tidak bisa diproses oleh server - 400
if (!$this->validateData($data, $rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$allowedUpdateFields = [
'NameFirst', 'NameLast', 'NameMiddle',
'PatientID', 'AlternatePID', 'Birthdate', 'PlaceOfBirth',
'Street_1', 'Street_2', 'Street_3', 'City', 'Province', 'ZIP',
'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone', 'Mother', 'AccountNumber'
];
$datas = [];
foreach ($allowedUpdateFields as $field) {
if (isset($data[$field])) {
$datas[$field] = $data[$field];
}
}
if (empty($data)) {
return $this->failValidationError('No data provided for update.');
}
$this->db->table('patient')->where('InternalPID', $InternalPID)->update($data);
// Sukses & Insert = 201 - Kirim data patient ID
return $this->respondCreated([
'status' => 'success',
'message' => 'Patient updated successfully',
'data' => $data
], 201);
} catch (\Exception $e) {
// Error Server = 500
return $this->failServerError('Something went wrong '.$e->getMessage());
}
}
// OK - Done
public function delete($InternalPID = null) {
try {
$InternalPID = (int) $InternalPID;
if (!$InternalPID) {
return $this->failValidationError('Patient ID is required.');
}
// Cari data pasien
$patient = $this->db->table('patient')->where('InternalPID', $InternalPID)->get()->getRow();
if (!$patient) {
return $this->failNotFound("Patient ID with {$InternalPID} not found.");
}
// Update kolom DelDate sebagai soft delete
$this->db->table('patient')->where('InternalPID', $InternalPID)->update(['DelDate' => date('Y-m-d H:i:s')]);
// Mengembalikan 200
return $this->respondDeleted([
'status' => 'success',
'message' => "Patient ID with {$InternalPID} deleted successfully."
]);
} catch (\Exception $e) {
return $this->failServerError("Internal server error: " . $e->getMessage());
}
}
}