From c3ef8a5bc2e2c6ec794bd853f749ae8ce3acb4b1 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Tue, 23 Sep 2025 13:47:00 +0700 Subject: [PATCH 1/8] update contact index --- app/Controllers/Contact.php | 8 ++++---- app/Controllers/PatVisit.php | 24 +++++++++++++++++------- app/Database/Seeds/CounterSeeder.php | 16 ++++++++++++++++ app/Database/Seeds/DBSeeder.php | 1 + 4 files changed, 38 insertions(+), 11 deletions(-) create mode 100644 app/Database/Seeds/CounterSeeder.php diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index 3a891e5..6c21553 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -16,10 +16,10 @@ class Contact extends Controller { } public function index() { - $sql = $this->db->table('contact'); - $sql->select("*") - ->join("contactdetail", "contact.ContactID=contactdetail.ContactID", "left") - ->join("occupation","contactdetail.OccupationID=occupation.OccupationID", "left"); + $sql = $this->db->table('contact c') + ->select("c.ContactID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") + ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") + ->join("occupation o","cd.OccupationID=o.OccupationID", "left"); $rows = $sql->get()->getResultArray(); if (empty($rows)) { diff --git a/app/Controllers/PatVisit.php b/app/Controllers/PatVisit.php index dd5d112..488661d 100644 --- a/app/Controllers/PatVisit.php +++ b/app/Controllers/PatVisit.php @@ -10,8 +10,23 @@ class PatVisit extends Controller { public function __construct() { $this->db = \Config\Database::connect(); + $this->visnum_prefix = "DV"; } + private function preparePVID($PVID) { + $row = $this->db->table('counter')->select('*')->where('CounterID','2')->get()->getResultArray(); + $cValue = $row[0]['CounterValue']; + $cStart = $row[0]['CounterStart']; + $cEnd = $row[0]['CounterEnd']; + $cReset = $row[0]['CounterReset']; + $cPad = strlen((string)$cEnd); + $cValue_next = $cValue++; + // next value > end, back to start + if($cValue_next > $cEnd) { $cValue_next = $cStart; } + $row = $this->db->table('counter')->set('CounterValue', $cValue_next)->where('CounterID','2'); + return $this->visnum_prefix.str_pad($cValue, $cPad, "0", STR_PAD_LEFT); + } + public function show($PVID = null) { try { $row = $this->db->table('patvisit pv') @@ -66,15 +81,9 @@ class PatVisit extends Controller { $this->db->transComplete(); - if (!empty($dbError['message'])) { - $this->db->transRollback(); - return $this->failServerError('Update failed: ' . $dbError['message']); - } - - if ($this->db->transStatus() === false) { $dbError = $this->db->error(); - return $this->failServerError('Failed to update patient data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown error')); + return $this->failServerError('Failed to create patient data (transaction rolled back): ' . ($dbError ?? 'Unknown error')); } return $this->respond([ @@ -94,6 +103,7 @@ class PatVisit extends Controller { $input = $this->request->getJSON(true); if (!$input) { return $this->respond(['status' => 'error', 'message' => 'Invalid JSON input'], 400); } + $input['PVID'] = $this->preparePVID($input['PVID']); $dataPatVisit = $this->preparePatVisitData($input); $dataPatDiag = $this->preparePatDiagData($input); $dataPatVisitAdt = $this->preparePatVisitAdtData($input); diff --git a/app/Database/Seeds/CounterSeeder.php b/app/Database/Seeds/CounterSeeder.php new file mode 100644 index 0000000..64f11be --- /dev/null +++ b/app/Database/Seeds/CounterSeeder.php @@ -0,0 +1,16 @@ +1, 'CounterValue'=>'1', 'CounterStart'=>'1', 'CounterEnd'=>'99999', 'CounterDesc'=>'Counter for Order#', 'CounterReset'=>'Y' ], + ['CounterID'=>2, 'CounterValue'=>'1', 'CounterStart'=>'1', 'CounterEnd'=>'9999', 'CounterDesc'=>'Counter for Visit#', 'CounterReset'=>'M' ], + ]; + $this->db->table('counter')->insertBatch($data); + } +} \ No newline at end of file diff --git a/app/Database/Seeds/DBSeeder.php b/app/Database/Seeds/DBSeeder.php index 2f14fff..226e79d 100644 --- a/app/Database/Seeds/DBSeeder.php +++ b/app/Database/Seeds/DBSeeder.php @@ -9,5 +9,6 @@ class DBSeeder extends Seeder { $this->call('MainSeeder'); $this->call('ValueSetSeeder'); $this->call('DummySeeder'); + $this->call('CounterSeeder'); } } From cfd791ddafb1f62a5a6f11437e0dd5137982f578 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Tue, 23 Sep 2025 14:20:09 +0700 Subject: [PATCH 2/8] PVID counter done --- app/Controllers/PatVisit.php | 19 +++++++++++-------- .../2025-09-09-155526_Pat_Visit.php | 1 + 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/Controllers/PatVisit.php b/app/Controllers/PatVisit.php index 488661d..3c1ecf6 100644 --- a/app/Controllers/PatVisit.php +++ b/app/Controllers/PatVisit.php @@ -13,18 +13,19 @@ class PatVisit extends Controller { $this->visnum_prefix = "DV"; } - private function preparePVID($PVID) { + private function preparePVID() { $row = $this->db->table('counter')->select('*')->where('CounterID','2')->get()->getResultArray(); $cValue = $row[0]['CounterValue']; $cStart = $row[0]['CounterStart']; $cEnd = $row[0]['CounterEnd']; $cReset = $row[0]['CounterReset']; - $cPad = strlen((string)$cEnd); - $cValue_next = $cValue++; + $cPad = strlen((string)$cEnd); + if($cValue > $cEnd) { $cValue = $cStart; } + $cnum = $this->visnum_prefix.str_pad($cValue, $cPad, "0", STR_PAD_LEFT); + $cValue_next = $cValue+1; // next value > end, back to start - if($cValue_next > $cEnd) { $cValue_next = $cStart; } - $row = $this->db->table('counter')->set('CounterValue', $cValue_next)->where('CounterID','2'); - return $this->visnum_prefix.str_pad($cValue, $cPad, "0", STR_PAD_LEFT); + $this->db->table('counter')->set('CounterValue', $cValue_next)->where('CounterID','2')->update(); + return $cnum; } public function show($PVID = null) { @@ -103,7 +104,10 @@ class PatVisit extends Controller { $input = $this->request->getJSON(true); if (!$input) { return $this->respond(['status' => 'error', 'message' => 'Invalid JSON input'], 400); } - $input['PVID'] = $this->preparePVID($input['PVID']); + if($input['PVID'] =='' || !isset($input['PVID'])) { + $input['PVID'] = $this->preparePVID(); + } + $dataPatVisit = $this->preparePatVisitData($input); $dataPatDiag = $this->preparePatDiagData($input); $dataPatVisitAdt = $this->preparePatVisitAdtData($input); @@ -140,7 +144,6 @@ class PatVisit extends Controller { 'message' => 'Data insert success', 'data' => $dataPatVisit ], 201); - } catch (\Exception $e) { $this->db->transRollback(); return $this->failServerError('Something went wrong: ' . $e->getMessage()); diff --git a/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php b/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php index 4ae0d88..2794ce5 100644 --- a/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php +++ b/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php @@ -19,6 +19,7 @@ class CreatePVTables extends Migration { ]); $this->forge->addField('CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); $this->forge->addKey('InternalPVID', true); + $this->forge->addUniqueKey('PVID', true); $this->forge->createTable('patvisit'); // patdiag From 5f317a7e38d3ebd1452aafb2c2433c54f4a99170 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Tue, 23 Sep 2025 15:57:19 +0700 Subject: [PATCH 3/8] add counter endpoint and move counter to model --- app/Config/Routes.php | 8 +- app/Controllers/Counter.php | 156 +++++++++++++++++++++++++++++++++++ app/Controllers/PatVisit.php | 21 ++--- app/Models/CounterModel.php | 27 ++++++ 4 files changed, 195 insertions(+), 17 deletions(-) create mode 100644 app/Controllers/Counter.php create mode 100644 app/Models/CounterModel.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 669cb56..6f6b622 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -75,4 +75,10 @@ $routes->get('/api/valuesetdef/', 'ValueSetDef::index'); $routes->get('/api/valuesetdef/(:num)', 'ValueSetDef::show/$1'); $routes->post('/api/valuesetdef', 'ValueSetDef::create'); $routes->patch('/api/valuesetdef', 'ValueSetDef::update'); -$routes->delete('/api/valuesetdef', 'ValueSetDef::delete'); \ No newline at end of file +$routes->delete('/api/valuesetdef', 'ValueSetDef::delete'); + +$routes->get('/api/counter/', 'Counter::index'); +$routes->get('/api/counter/(:num)', 'Counter::show/$1'); +$routes->post('/api/counter', 'Counter::create'); +$routes->patch('/api/counter', 'Counter::update'); +$routes->delete('/api/counter', 'Counter::delete'); \ No newline at end of file diff --git a/app/Controllers/Counter.php b/app/Controllers/Counter.php new file mode 100644 index 0000000..e64995d --- /dev/null +++ b/app/Controllers/Counter.php @@ -0,0 +1,156 @@ +db = \Config\Database::connect(); + } + + public function index() { + $rows = $this->db->table('counter')->select("*")->get()->getResultArray(); + + if (empty($rows)) { + return $this->respond([ + 'status' => 'success', + 'message' => "No Data.", + 'data' => [], + ], 200); + } + + return $this->respond([ + 'status' => 'success', + 'message'=> "Data fetched successfully", + 'data' => $rows, + ], 200); + } + + public function show($CounterID = null) { + $rows = $this->db->table('counter')->select("*")->where('CounterID', (int) $CounterID)->get()->getResultArray(); + + if (empty($rows)) { + return $this->respond([ + 'status' => 'success', + 'message' => "Data not found.", + 'data' => [], + ], 200); + } + + return $this->respond([ + 'status' => 'success', + 'message'=> "Data fetched successfully", + 'data' => $rows, + ], 200); + } + + public function create() { + $input = $this->request->getJSON(true); + $dataCounter = $this->prepareCounterData($input); + + try { + $this->db->transStart(); + $this->db->table('counter')->insert($dataCounter); + $this->db->transComplete(); + + if ($this->db->transStatus() === false) { + $dbError = $this->db->error(); + return $this->failServerError( + 'Failed to create data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown database error') + ); + } + + return $this->respondCreated([ + 'status' => 'success', + 'message' => 'Data created successfully', + 'data' => $dataCounter, + ], 201); + + } catch (\Throwable $e) { + // Ensure rollback if something goes wrong + if ($this->db->transStatus() !== false) { + $this->db->transRollback(); + } + return $this->failServerError('Something went wrong: ' . $e->getMessage()); + } + } + + public function update() { + try { + $input = $this->request->getJSON(true); + $dataCounter = $this->prepareCounterData($input); + + $this->db->transStart(); + $this->db->table('counter')->where('CounterID', $dataCounter["CounterID"])->update($dataCounterID); + $this->db->transComplete(); + + if ($this->db->transStatus() === false) { + $dbError = $this->db->error(); + return $this->failServerError( + 'Failed to update data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown database error') + ); + } + + return $this->respondCreated([ + 'status' => 'success', + 'message' => 'Data updated successfully', + 'data' => $dataCounter, + ], 201); + + } catch (\Throwable $e) { + // Ensure rollback if something goes wrong + if ($this->db->transStatus() !== false) { + $this->db->transRollback(); + } + return $this->failServerError('Something went wrong: ' . $e->getMessage()); + } + } + + public function delete() { + try { + $input = $this->request->getJSON(true); + $CounterID = $input["CounterID"]; + if (!$CounterID) { + return $this->failValidationError('CounterID is required.'); + } + + + $location = $this->db->table('counter')->where('CounterID', $CounterID)->get()->getRow(); + if (!$location) { + return $this->failNotFound("Data not found."); + } + + $this->db->table('counter')->where('CounterID', $CounterID)->update(['EndDate' => NOW()]); + + return $this->respondDeleted([ + 'status' => 'success', + 'message' => "Counter deleted successfully." + ]); + + } catch (\Throwable $e) { + // Ensure rollback if something goes wrong + if ($this->db->transStatus() !== false) { + $this->db->transRollback(); + } + return $this->failServerError('Something went wrong: ' . $e->getMessage()); + } + } + + private function prepareCounterData(array $input): array { + $data = [ + "CounterValue" => $input['CounterValue'] ?? null, + "CounterStart" => $input['CounterStart'] ?? null, + "CounterEnd" => $input['CounterEnd'] ?? null, + "CounterDesc" => $input['CounterDesc'] ?? null, + "CounterReset" => $input['CounterReset'] ?? null, + ]; + + if(!empty($input["CounterID"])) { $data["CounterID"] = $input["CounterID"]; } + + return $data; + } +} \ No newline at end of file diff --git a/app/Controllers/PatVisit.php b/app/Controllers/PatVisit.php index 3c1ecf6..c4f3573 100644 --- a/app/Controllers/PatVisit.php +++ b/app/Controllers/PatVisit.php @@ -5,6 +5,8 @@ use CodeIgniter\API\ResponseTrait; use CodeIgniter\Controller; use CodeIgniter\Database\RawSql; +use App\Models\CounterModel; + class PatVisit extends Controller { use ResponseTrait; @@ -13,21 +15,6 @@ class PatVisit extends Controller { $this->visnum_prefix = "DV"; } - private function preparePVID() { - $row = $this->db->table('counter')->select('*')->where('CounterID','2')->get()->getResultArray(); - $cValue = $row[0]['CounterValue']; - $cStart = $row[0]['CounterStart']; - $cEnd = $row[0]['CounterEnd']; - $cReset = $row[0]['CounterReset']; - $cPad = strlen((string)$cEnd); - if($cValue > $cEnd) { $cValue = $cStart; } - $cnum = $this->visnum_prefix.str_pad($cValue, $cPad, "0", STR_PAD_LEFT); - $cValue_next = $cValue+1; - // next value > end, back to start - $this->db->table('counter')->set('CounterValue', $cValue_next)->where('CounterID','2')->update(); - return $cnum; - } - public function show($PVID = null) { try { $row = $this->db->table('patvisit pv') @@ -105,7 +92,9 @@ class PatVisit extends Controller { if (!$input) { return $this->respond(['status' => 'error', 'message' => 'Invalid JSON input'], 400); } if($input['PVID'] =='' || !isset($input['PVID'])) { - $input['PVID'] = $this->preparePVID(); + $model = new CounterModel(); + $input['PVID'] = $this->visnum_prefix .$model->use(2); + //$input['PVID'] = $this->preparePVID(); } $dataPatVisit = $this->preparePatVisitData($input); diff --git a/app/Models/CounterModel.php b/app/Models/CounterModel.php new file mode 100644 index 0000000..7260137 --- /dev/null +++ b/app/Models/CounterModel.php @@ -0,0 +1,27 @@ +where('CounterID',$CounterID)->get()->getResultArray(); + $cValue = $row[0]['CounterValue']; + $cStart = $row[0]['CounterStart']; + $cEnd = $row[0]['CounterEnd']; + $cReset = $row[0]['CounterReset']; + $cPad = strlen((string)$cEnd); + // next value > end, back to start + if($cValue > $cEnd) { $cValue = $cStart; } + $cnum = str_pad($cValue, $cPad, "0", STR_PAD_LEFT); + $cValue_next = $cValue+1; + $this->set('CounterValue', $cValue_next)->where('CounterID',$CounterID)->update(); + return $cnum; + } + +} From 783018f2f21d6e3d2c980202fc841860c0831b57 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Tue, 23 Sep 2025 16:55:28 +0700 Subject: [PATCH 4/8] fix contactdetail --- app/Controllers/Contact.php | 43 ++++++++++++++++++++++++++---- app/Database/Seeds/DummySeeder.php | 16 ++++++----- 2 files changed, 47 insertions(+), 12 deletions(-) diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index 6c21553..3ce9c9c 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -38,11 +38,11 @@ class Contact extends Controller { } public function show($ContactID = null) { - $rows=$this->db->table('contact') + $rows=$this->db->table('contact c') ->select("*") - ->join("contactdetail", "contact.ContactID=contactdetail.ContactID", "left") - ->join("occupation","occupation.OccupationID=contactdetail.OccupationID", "left") - ->where('contact.ContactID', (int) $ContactID) + ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") + ->join("occupation o","o.OccupationID=cd.OccupationID", "left") + ->where('c.ContactID', (int) $ContactID) ->get()->getResultArray(); if (empty($rows)) { @@ -53,10 +53,43 @@ class Contact extends Controller { ], 200); } + // Rebuild into nested structure + $contact = [ + 'ContactID' => $rows[0]['ContactID'], + 'NameFirst' => $rows[0]['NameFirst'] ?? null, + 'NameLast' => $rows[0]['NameLast'] ?? null, + 'Title' => $rows[0]['Title'] ?? null, + 'Initial' => $rows[0]['Initial'] ?? null, + 'Birthdate' => $rows[0]['Birthdate'] ?? null, + 'EmailAddress1' => $rows[0]['EmailAddress1'] ?? null, + 'EmailAddress2' => $rows[0]['EmailAddress2'] ?? null, + 'Phone' => $rows[0]['Phone'] ?? null, + 'MobilePhone1' => $rows[0]['MobilePhone1'] ?? null, + 'MobilePhone2' => $rows[0]['MobilePhone2'] ?? null, + 'Specialty' => $rows[0]['Specialty'] ?? null, + 'SubSpecialty' => $rows[0]['SubSpecialty'] ?? null, + 'Details' => [] + ]; + + foreach ($rows as $row) { + if (!empty($row['ContactDetID'])) { + $contact['Details'][] = [ + 'ContactDetID' => $row['ContactDetID'], + 'ContactCode' => $row['ContactCode'] ?? null, + 'ContactEmail' => $row['DetailPhone'] ?? null, + 'OccupationID' => $row['OccupationID'] ?? null, + 'JobTitle' => $row['JobTitle'] ?? null, + 'Department' => $row['Department'] ?? null, + 'ContactStartDate' => $row['ContactStartDate'] ?? null, + 'ContactEndDate' => $row['ContactEndDate'] ?? null + ]; + } + } + return $this->respond([ 'status' => 'success', 'message'=> "Data fetched successfully", - 'data' => $rows, + 'data' => $contact, ], 200); } diff --git a/app/Database/Seeds/DummySeeder.php b/app/Database/Seeds/DummySeeder.php index d32da3b..2274d05 100644 --- a/app/Database/Seeds/DummySeeder.php +++ b/app/Database/Seeds/DummySeeder.php @@ -8,27 +8,29 @@ class DummySeeder extends Seeder { public function run() { // location $data = [ - ['LocationID'=>1, 'LocCode'=>'QLOC', 'LocFull'=>'Dummy Location', 'LocType'=>'ROOM', 'Description'=>'Location made for dummy testing' ] + ['LocationID'=>1, 'LocCode'=>'QLOC', 'LocFull'=>'Dummy Location', 'LocType'=>'ROOM', 'Description'=>'Location made for dummy testing' ], + ['LocationID'=>2, 'LocCode'=>'DEFLOC', 'LocFull'=>'Default Location', 'LocType'=>'ROOM', 'Description'=>'Default location' ] ]; $this->db->table('location')->insertBatch($data); $data = [ - ['LocationID'=>1, 'Street1'=>'Jalan Nginden', 'Street2'=>'Intan Raya', 'City'=>'Surabaya', 'Province'=>'East Java', 'PostCode'=>'60222'] + ['LocationID'=>1, 'Street1'=>'Jalan Nginden', 'Street2'=>'Intan Raya', 'City'=>'Surabaya', 'Province'=>'East Java', 'PostCode'=>'60222'], + ['LocationID'=>2, 'Street1'=>'Jalan ', 'Street2'=>'Jalan jalan', 'City'=>'Depok', 'Province'=>'DKI Jakarta', 'PostCode'=>'10123'] ]; $this->db->table('locationaddress')->insertBatch($data); // contact $data = [ - ['ContactID'=>1, 'NameFirst'=>'Default', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'DEFDOC', 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', - 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ] + ['ContactID'=>1, 'NameFirst'=>'Default', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'DEFDOC', 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ], + ['ContactID'=>2, 'NameFirst'=>'Dummy', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'QDOC' ] ]; $this->db->table('contact')->insertBatch($data); $data = [ - ['ContactID'=>1, 'ContactCode'=>'QDOC', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', - 'JobTitle'=>'', 'Department'=>'', 'ContactStartDate'=>'', 'ContactEndDate'=>'' ] + ['ContactID'=>1, 'ContactCode'=>'DEFDOC', 'ContactEmail'=>'defdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Jantung Sehat', 'ContactStartDate'=>'2020-01-05', 'ContactEndDate'=>'2023-01-05' ], + ['ContactID'=>1, 'ContactCode'=>'QDOC', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Hati Sehat', 'ContactStartDate'=>'2023-01-05', 'ContactEndDate'=>'' ] ]; $this->db->table('contactdetail')->insertBatch($data); - // patient + // patient $data = [ [ 'InternalPID'=>1, 'PatientID'=>'SMAJ1', 'NameFirst'=>'Dummy', 'NameLast' => 'Patient M', 'Gender'=>'1', 'BirthDate'=>'1991-09-09', 'Street_1'=>'Makati', 'IntCountryID'=>'105', 'EmailAddress1'=>'smaj1@5panda.id', 'RaceID'=>'1', 'ReligionID'=>'1', 'EthnicID'=>'1', 'DeathIndicator' => '0'], From dd999aaf7b8259898fb52be4430951827c0fd473 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Wed, 24 Sep 2025 16:15:55 +0700 Subject: [PATCH 5/8] contactdetail wow --- app/Controllers/Contact.php | 211 ++++++------------ .../2025-09-09-155526_Pat_Visit.php | 2 +- .../Migrations/2025-09-12-011643_Contact.php | 35 +-- app/Database/Seeds/DummySeeder.php | 13 +- app/Models/ContactDetailModel.php | 11 + app/Models/ContactModel.php | 110 +++++++++ 6 files changed, 197 insertions(+), 185 deletions(-) create mode 100644 app/Models/ContactDetailModel.php create mode 100644 app/Models/ContactModel.php diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index 3ce9c9c..be634cd 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -3,24 +3,23 @@ namespace App\Controllers; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Controller; -use CodeIgniter\Database\RawSql; + +use App\Models\ContactModel; class Contact extends Controller { use ResponseTrait; + protected $contactModel; + protected $contactRule; + public function __construct() { - $this->db = \Config\Database::connect(); - $this->rulesContact = [ - 'NameFirst' => 'required' - ]; + $this->contactModel = new ContactModel(); + $this->contactRule = [ 'NameFirst' => 'required' ]; } public function index() { - $sql = $this->db->table('contact c') - ->select("c.ContactID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") - ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") - ->join("occupation o","cd.OccupationID=o.OccupationID", "left"); - $rows = $sql->get()->getResultArray(); + $model = new ContactModel(); + $rows = $model->getContactsWithDetail(); if (empty($rows)) { return $this->respond([ @@ -38,13 +37,9 @@ class Contact extends Controller { } public function show($ContactID = null) { - $rows=$this->db->table('contact c') - ->select("*") - ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") - ->join("occupation o","o.OccupationID=cd.OccupationID", "left") - ->where('c.ContactID', (int) $ContactID) - ->get()->getResultArray(); - + $model = new ContactModel(); + $rows = $model->getContactWithDetail($ContactID); + if (empty($rows)) { return $this->respond([ 'status' => 'success', @@ -53,140 +48,63 @@ class Contact extends Controller { ], 200); } - // Rebuild into nested structure - $contact = [ - 'ContactID' => $rows[0]['ContactID'], - 'NameFirst' => $rows[0]['NameFirst'] ?? null, - 'NameLast' => $rows[0]['NameLast'] ?? null, - 'Title' => $rows[0]['Title'] ?? null, - 'Initial' => $rows[0]['Initial'] ?? null, - 'Birthdate' => $rows[0]['Birthdate'] ?? null, - 'EmailAddress1' => $rows[0]['EmailAddress1'] ?? null, - 'EmailAddress2' => $rows[0]['EmailAddress2'] ?? null, - 'Phone' => $rows[0]['Phone'] ?? null, - 'MobilePhone1' => $rows[0]['MobilePhone1'] ?? null, - 'MobilePhone2' => $rows[0]['MobilePhone2'] ?? null, - 'Specialty' => $rows[0]['Specialty'] ?? null, - 'SubSpecialty' => $rows[0]['SubSpecialty'] ?? null, - 'Details' => [] - ]; - - foreach ($rows as $row) { - if (!empty($row['ContactDetID'])) { - $contact['Details'][] = [ - 'ContactDetID' => $row['ContactDetID'], - 'ContactCode' => $row['ContactCode'] ?? null, - 'ContactEmail' => $row['DetailPhone'] ?? null, - 'OccupationID' => $row['OccupationID'] ?? null, - 'JobTitle' => $row['JobTitle'] ?? null, - 'Department' => $row['Department'] ?? null, - 'ContactStartDate' => $row['ContactStartDate'] ?? null, - 'ContactEndDate' => $row['ContactEndDate'] ?? null - ]; - } - } - return $this->respond([ - 'status' => 'success', + 'status' => 'success', 'message'=> "Data fetched successfully", - 'data' => $contact, + 'data' => $rows, ], 200); } public function create() { - try { - $input = $this->request->getJSON(true); + $input = $this->request->getJSON(true); + $dataContact = $this->prepareContactData($input); + $dataContactDetail = $this->prepareContactDetailData($input); - // Prepare data - $dataContact = $this->prepareContactData($input); - $dataContactDetail = $this->prepareContactDetailData($input); + if (!$this->validateData($dataContact, $this->contactRule)) { + return $this->failValidationErrors($this->validator->getErrors()); + } - if (!$this->validateData($dataContact, $this->rulesContact)) { - return $this->failValidationErrors($this->validator->getErrors()); + try{ + $result = $this->contactModel->create($dataContact, $dataContactDetail); + if ($result) { + return $this->respondCreated([ + 'status' => 'success', + 'message' => 'Contact created successfully', + 'data' => $dataContact, + ]); + } else { + return $this->failServerError('Failed to create contact'); } - - // Start transaction - $this->db->transStart(); - $this->db->table('contact')->insert($dataContact); - $newContactID = $this->db->insertID(); - - - if (!empty($dataContactDetail)) { - $dataContactDetail['ContactID'] = $newContactID; - $this->db->table('contactdetail')->insert($dataContactDetail); - } - - if ($this->db->transStatus() === false) { - $dbError = $this->db->error(); - return $this->failServerError( - 'Failed to create data (transaction rolled back): ' . ( $dbError['message'] ?? 'Unknown database error') - ); - } - - // Complete transaction - $this->db->transComplete(); - - return $this->respondCreated([ - 'status' => 'success', - 'message' => 'Contact created successfully', - 'data' => $dataContact, - ], 201); - } catch (\Throwable $e) { - // Ensure rollback if something goes wrong - if ($this->db->transStatus() !== false) { - $this->db->transRollback(); - } - return $this->failServerError('Something went wrong: ' . $e->getMessage()); + return $this->failServerError('Error: ' . $e->getMessage()); } } - public function update() { - try { - $input = $this->request->getJSON(true); + public function update() { + $input = $this->request->getJSON(true); + $ContactID = $input['ContactID']; + $dataContact = $this->prepareContactData($input); + $dataContactDetail = $this->prepareContactDetailData($input); - // Prepare data - $dataContact = $this->prepareContactData($input); - $dataContactDetail = $this->prepareContactDetailData($input); - - if (!$this->validateData($dataContact, $this->rulesContact)) { - return $this->failValidationErrors( $this->validator->getErrors()); - } - - // Start transaction - $this->db->transStart(); - - $this->db->table('contact')->where('ContactID', $dataContact["ContactID"])->update($dataContact); - - // Insert address if available - if (!empty($dataContactDetail)) { - $dataContactDetail['ContactID'] = $input["ContactID"]; - $this->db->table('contactdetail')->upsert($dataContactDetail); - } - - // Complete transaction - $this->db->transComplete(); - - if ($this->db->transStatus() === false) { - $dbError = $this->db->error(); - return $this->failServerError( - 'Failed to update contact data (transaction rolled back): ' . ($dbError['message'] ?? 'Unknown database error') - ); - } - - return $this->respondCreated([ - 'status' => 'success', - 'message' => 'Contact updated successfully', - 'data' => $dataContact, - ], 201); - - } catch (\Throwable $e) { - // Ensure rollback if something goes wrong - if ($this->db->transStatus() !== false) { - $this->db->transRollback(); - } - return $this->failServerError('Something went wrong: ' . $e->getMessage()); + if (!$this->validateData($dataContact, $this->contactRule)) { + return $this->failValidationErrors( $this->validator->getErrors()); } + + try{ + $result = $this->contactModel->update($ContactID, $dataContact, $dataContactDetail); + if ($result) { + return $this->respondCreated([ + 'status' => 'success', + 'message' => 'Contact created successfully', + 'data' => $dataContact, + ]); + } else { + return $this->failServerError('Failed to create contact'); + } + } catch (\Throwable $e) { + return $this->failServerError('Error: ' . $e->getMessage()); + } + } public function delete() { @@ -240,16 +158,17 @@ class Contact extends Controller { } private function prepareContactDetailData(array $input): array { - $data = [ - "ContactCode" => $input['ContactCode'] ?? null, - "ContactEmail" => $input['ContactEmail'] ?? null, - "OccupationID" => $input['OccupationID'] ?? null, - "JobTitle" => $input['JobTitle'] ?? null, - "Department" => $input['Department'] ?? null, - "ContactStartDate" => $input['ContactStartDate'] ?? null, - "ContactEndDate" => $input['ContactEndDate'] ?? null, - ]; - + foreach($input['ContactDetail'] as $detail) { + $data[] = [ + "ContactCode" => $detail['ContactCode'] ?? null, + "ContactEmail" => $detail['ContactEmail'] ?? null, + "OccupationID" => $detail['OccupationID'] ?? null, + "JobTitle" => $detail['JobTitle'] ?? null, + "Department" => $detail['Department'] ?? null, + "ContactStartDate" => $detail['ContactStartDate'] ?? null, + "ContactEndDate" => $detail['ContactEndDate'] ?? null, + ]; + } return $data; } } \ No newline at end of file diff --git a/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php b/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php index 2794ce5..51df1d9 100644 --- a/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php +++ b/app/Database/Migrations/2025-09-09-155526_Pat_Visit.php @@ -19,7 +19,7 @@ class CreatePVTables extends Migration { ]); $this->forge->addField('CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); $this->forge->addKey('InternalPVID', true); - $this->forge->addUniqueKey('PVID', true); + $this->forge->addUniqueKey('PVID'); $this->forge->createTable('patvisit'); // patdiag diff --git a/app/Database/Migrations/2025-09-12-011643_Contact.php b/app/Database/Migrations/2025-09-12-011643_Contact.php index 7799dde..89746ff 100644 --- a/app/Database/Migrations/2025-09-12-011643_Contact.php +++ b/app/Database/Migrations/2025-09-12-011643_Contact.php @@ -41,6 +41,7 @@ class CreateContactTable extends Migration { 'ContactEndDate' => [ 'type' => 'DATE', 'null' => true ], ]); $this->forge->addKey('ContactDetID', true); + $this->forge->addUniqueKey(['SiteID','ContactID']); $this->forge->createTable('contactdetail'); // Occupation @@ -53,45 +54,11 @@ class CreateContactTable extends Migration { $this->forge->addField('CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); $this->forge->addKey('OccupationID', true); $this->forge->createTable('occupation'); - - /* - - // ContactTraining - $this->forge->addField([ - 'ContactID' => [ 'type' => 'INT', 'constraint' => 11 ], - 'TrainingType' => [ 'type' => 'VARCHAR', 'constraint' => 50, 'null' => true ], - 'TrainingTitle' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => true ], - 'StartDate' => [ 'type' => 'DATETIME', 'null' => true ], - 'EndDate' => [ 'type' => 'DATETIME', 'null' => true ], - 'Facilitator' => [ 'type' => 'VARCHAR', 'constraint' => 150, 'null' => true ], - 'CertificateLocation'=> [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => true ], - ]); - $this->forge->addField('CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); - // $this->forge->addKey('ContactID', true); - $this->forge->createTable('ContactTraining'); - - // MedicalSpecialty - $this->forge->addField([ - 'SpecialtyID' => [ 'type' => 'INT', 'constraint' => 11 ], - 'SpecialtyText' => [ 'type' => 'VARCHAR', 'constraint' => 255, 'null' => true ], - 'Parent' => [ 'type' => 'VARCHAR', 'constraint' => 50, 'null' => true ], - 'Title' => [ 'type' => 'VARCHAR', 'constraint' => 50, 'null' => true ], - 'EndDate' => [ 'type' => 'DATETIME', 'null' => true ], - ]); - $this->forge->addField('CreateDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); - $this->forge->addKey('SpecialtyID', true); - $this->forge->createTable('MedicalSpecialty'); - - */ } public function down() { $this->forge->dropTable('Contact'); $this->forge->dropTable('ContactDetail'); $this->forge->dropTable('Occupation'); - /* - $this->forge->dropTable('ContactTraining'); - $this->forge->dropTable('MedicalSpecialty'); - */ } } diff --git a/app/Database/Seeds/DummySeeder.php b/app/Database/Seeds/DummySeeder.php index 2274d05..ea6fede 100644 --- a/app/Database/Seeds/DummySeeder.php +++ b/app/Database/Seeds/DummySeeder.php @@ -20,13 +20,18 @@ class DummySeeder extends Seeder { // contact $data = [ - ['ContactID'=>1, 'NameFirst'=>'Default', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'DEFDOC', 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ], - ['ContactID'=>2, 'NameFirst'=>'Dummy', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'QDOC' ] + ['ContactID'=>1, 'NameFirst'=>'Default', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'DEFDOC', + 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ], + ['ContactID'=>2, 'NameFirst'=>'Dummy', 'NameLast'=>'Doctor', 'Title'=>'', 'Initial'=>'QDOC', + 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ] ]; $this->db->table('contact')->insertBatch($data); $data = [ - ['ContactID'=>1, 'ContactCode'=>'DEFDOC', 'ContactEmail'=>'defdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Jantung Sehat', 'ContactStartDate'=>'2020-01-05', 'ContactEndDate'=>'2023-01-05' ], - ['ContactID'=>1, 'ContactCode'=>'QDOC', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Hati Sehat', 'ContactStartDate'=>'2023-01-05', 'ContactEndDate'=>'' ] + ['SiteID'=>1,'ContactID'=>1, 'ContactCode'=>'DEFDOC', 'ContactEmail'=>'defdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Jantung Sehat' ], + ['SiteID'=>2,'ContactID'=>1, 'ContactCode'=>'QDOC', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Hati Sehat' ], + ['SiteID'=>1,'ContactID'=>2, 'ContactCode'=>'S923', 'ContactEmail'=>'defdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Jantung Sehat' ], + ['SiteID'=>2,'ContactID'=>2, 'ContactCode'=>'B231', 'ContactEmail'=>'defdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Ginjal Sehat' ], + ['SiteID'=>3,'ContactID'=>2, 'ContactCode'=>'C342', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', 'JobTitle'=>'', 'Department'=>'Hati Sehat' ] ]; $this->db->table('contactdetail')->insertBatch($data); diff --git a/app/Models/ContactDetailModel.php b/app/Models/ContactDetailModel.php new file mode 100644 index 0000000..9ca3d8b --- /dev/null +++ b/app/Models/ContactDetailModel.php @@ -0,0 +1,11 @@ +select("c.ContactID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") + ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") + ->join("occupation o","cd.OccupationID=o.OccupationID", "left") + ->get()->getResultArray(); + + return $rows; + } + + public function getContactWithDetail($ContactID) { + $rows = $this->where('c.ContactID', $ContactID)->join('contactdetail cd', 'c.ContactID=cd.ContactID','left')->get()->getResultArray(); + $contact = [ + 'ContactID' => $rows[0]['ContactID'], + 'NameFirst' => $rows[0]['NameFirst'] ?? null, + 'NameLast' => $rows[0]['NameLast'] ?? null, + 'Title' => $rows[0]['Title'] ?? null, + 'Initial' => $rows[0]['Initial'] ?? null, + 'Birthdate' => $rows[0]['Birthdate'] ?? null, + 'EmailAddress1' => $rows[0]['EmailAddress1'] ?? null, + 'EmailAddress2' => $rows[0]['EmailAddress2'] ?? null, + 'Phone' => $rows[0]['Phone'] ?? null, + 'MobilePhone1' => $rows[0]['MobilePhone1'] ?? null, + 'MobilePhone2' => $rows[0]['MobilePhone2'] ?? null, + 'Specialty' => $rows[0]['Specialty'] ?? null, + 'SubSpecialty' => $rows[0]['SubSpecialty'] ?? null, + 'Details' => [] + ]; + + foreach ($rows as $row) { + if (!empty($row['ContactDetID'])) { + $contact['Details'][] = [ + 'SiteID' => $row['SiteID'] ?? null, + 'ContactDetID' => $row['ContactDetID'], + 'ContactCode' => $row['ContactCode'] ?? null, + 'ContactEmail' => $row['DetailPhone'] ?? null, + 'OccupationID' => $row['OccupationID'] ?? null, + 'JobTitle' => $row['JobTitle'] ?? null, + 'Department' => $row['Department'] ?? null, + 'ContactStartDate' => $row['ContactStartDate'] ?? null, + 'ContactEndDate' => $row['ContactEndDate'] ?? null + ]; + } + } + + return $contact; + } + + public function createContact(array $contactData, array $contactDetails) { + $db = \Config\Database::connect(); + $db->transStart(); + + try { + if (!$this->insert($contactData)) { + throw new \Exception('Failed to insert contact'); + } + $ContactID = $this->getInsertID(); + + $detailModel = new \App\Models\ContactDetailModel(); + foreach ($contactDetails as $detail) { + $detail['ContactID'] = $ContactID; + if (!$detailModel->insert($detail)) { + throw new \Exception('Failed to insert contact details'); + } + } + + $db->transComplete(); + return $db->transStatus(); + } catch (\Exception $e) { + $db->transRollback(); + throw $e; + } + } + + public function updateContact(array $contactData, array $contactDetails) { + $db = \Config\Database::connect(); + $db->transStart(); + + try { + if (!$this->update($contactData)) { + throw new \Exception('Failed to insert contact'); + } + $ContactID = $this->getInsertID(); + + $detailModel = new \App\Models\ContactDetailModel(); + foreach ($contactDetails as $detail) { + $detail['ContactID'] = $ContactID; + if (!$detailModel->insert($detail)) { + throw new \Exception('Failed to insert contact details'); + } + } + + $db->transComplete(); + return $db->transStatus(); + } catch (\Exception $e) { + $db->transRollback(); + throw $e; + } + } +} From 98acaff93b88dfb2593efa1fdb72cc29ce988e2c Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Thu, 25 Sep 2025 09:42:17 +0700 Subject: [PATCH 6/8] add siteid to contact index --- app/Controllers/Contact.php | 3 ++- app/Models/ContactDetailModel.php | 26 ++++++++++++++++++++++++++ app/Models/ContactModel.php | 18 ++++++------------ 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index be634cd..54db284 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -95,7 +95,7 @@ class Contact extends Controller { if ($result) { return $this->respondCreated([ 'status' => 'success', - 'message' => 'Contact created successfully', + 'message' => 'Contact updated successfully', 'data' => $dataContact, ]); } else { @@ -160,6 +160,7 @@ class Contact extends Controller { private function prepareContactDetailData(array $input): array { foreach($input['ContactDetail'] as $detail) { $data[] = [ + "SiteID" => $detail['SiteID'] ?? null, "ContactCode" => $detail['ContactCode'] ?? null, "ContactEmail" => $detail['ContactEmail'] ?? null, "OccupationID" => $detail['OccupationID'] ?? null, diff --git a/app/Models/ContactDetailModel.php b/app/Models/ContactDetailModel.php index 9ca3d8b..2059c93 100644 --- a/app/Models/ContactDetailModel.php +++ b/app/Models/ContactDetailModel.php @@ -8,4 +8,30 @@ class ContactDetailModel extends Model { protected $table = 'contactdetail'; protected $primaryKey = 'ContactDetID'; protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate']; + + public function syncDetails(int $contactId, array $details) { + $kept = []; + + foreach ($details as $detail) { + $detail['ContactID'] = $contactId; + + $existing = $this->where('SiteID', $detail['SiteID']) + ->where('ContactID', $contactId) + ->first(); + + if ($existing) { + $this->update($existing[$this->primaryKey], $detail); + $kept[] = $existing[$this->primaryKey]; + } else { + $newId = $this->insert($detail); + $kept[] = $newId; + } + } + + if (!empty($kept)) { + $this->where('ContactID', $contactId) + ->whereNotIn($this->primaryKey, $kept) + ->delete(); + } else { $this->where('ContactID', $contactId)->delete(); } + } } diff --git a/app/Models/ContactModel.php b/app/Models/ContactModel.php index 85b4c22..fcba800 100644 --- a/app/Models/ContactModel.php +++ b/app/Models/ContactModel.php @@ -10,7 +10,7 @@ class ContactModel extends Model { protected $allowedFields = ['NameFirst', 'NameLast', 'Title', 'Initial', 'Birthdate', 'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone1', 'MobilePhone2', 'Specialty', 'SubSpecialty']; public function getContactsWithDetail() { - $rows = $this->select("c.ContactID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") + $rows = $this->select("c.ContactID, cd.SiteID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") ->join("occupation o","cd.OccupationID=o.OccupationID", "left") ->get()->getResultArray(); @@ -40,7 +40,7 @@ class ContactModel extends Model { foreach ($rows as $row) { if (!empty($row['ContactDetID'])) { $contact['Details'][] = [ - 'SiteID' => $row['SiteID'] ?? null, + 'SiteID' => $row['SiteID'] ?? null, 'ContactDetID' => $row['ContactDetID'], 'ContactCode' => $row['ContactCode'] ?? null, 'ContactEmail' => $row['DetailPhone'] ?? null, @@ -82,23 +82,17 @@ class ContactModel extends Model { } } - public function updateContact(array $contactData, array $contactDetails) { + public function updateContact(int $ContactID, array $contactData, array $contactDetails) { $db = \Config\Database::connect(); $db->transStart(); try { - if (!$this->update($contactData)) { - throw new \Exception('Failed to insert contact'); + if (!$this->update($ContactID, $contactData)) { + throw new \Exception('Failed to update contact'); } - $ContactID = $this->getInsertID(); $detailModel = new \App\Models\ContactDetailModel(); - foreach ($contactDetails as $detail) { - $detail['ContactID'] = $ContactID; - if (!$detailModel->insert($detail)) { - throw new \Exception('Failed to insert contact details'); - } - } + $detailModel->syncDetails($ContactID, $contactDetails); $db->transComplete(); return $db->transStatus(); From 501ef06592704b916f6b9cec41caf5f1a18428f7 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Thu, 25 Sep 2025 13:30:15 +0700 Subject: [PATCH 7/8] fixing contactdetail --- app/Config/Routes.php | 4 +- app/Controllers/Contact.php | 131 ++++++++++-------------------- app/Models/ContactDetailModel.php | 62 +++++++++----- app/Models/ContactModel.php | 76 +++++++++-------- 4 files changed, 125 insertions(+), 148 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 6f6b622..4809e12 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -54,8 +54,8 @@ $routes->delete('/api/location', 'Location::delete'); $routes->get('/api/contact', 'Contact::index'); $routes->get('/api/contact/(:num)', 'Contact::show/$1'); -$routes->post('/api/contact', 'Contact::create'); -$routes->patch('/api/contact', 'Contact::update'); +$routes->post('/api/contact', 'Contact::save'); +$routes->patch('/api/contact', 'Contact::save'); $routes->delete('/api/contact', 'Contact::delete'); $routes->get('/api/occupation', 'Occupation::index'); diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index 54db284..2ea7e95 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -5,15 +5,16 @@ use CodeIgniter\API\ResponseTrait; use CodeIgniter\Controller; use App\Models\ContactModel; +use App\Models\ContactDetailModel; class Contact extends Controller { use ResponseTrait; - protected $contactModel; + protected $db; protected $contactRule; public function __construct() { - $this->contactModel = new ContactModel(); + $this->db = \Config\Database::connect(); $this->contactRule = [ 'NameFirst' => 'required' ]; } @@ -55,66 +56,14 @@ class Contact extends Controller { ], 200); } - public function create() { - $input = $this->request->getJSON(true); - $dataContact = $this->prepareContactData($input); - $dataContactDetail = $this->prepareContactDetailData($input); - - if (!$this->validateData($dataContact, $this->contactRule)) { - return $this->failValidationErrors($this->validator->getErrors()); - } - - try{ - $result = $this->contactModel->create($dataContact, $dataContactDetail); - if ($result) { - return $this->respondCreated([ - 'status' => 'success', - 'message' => 'Contact created successfully', - 'data' => $dataContact, - ]); - } else { - return $this->failServerError('Failed to create contact'); - } - } catch (\Throwable $e) { - return $this->failServerError('Error: ' . $e->getMessage()); - } - } - - public function update() { - $input = $this->request->getJSON(true); - $ContactID = $input['ContactID']; - $dataContact = $this->prepareContactData($input); - $dataContactDetail = $this->prepareContactDetailData($input); - - if (!$this->validateData($dataContact, $this->contactRule)) { - return $this->failValidationErrors( $this->validator->getErrors()); - } - - try{ - $result = $this->contactModel->update($ContactID, $dataContact, $dataContactDetail); - if ($result) { - return $this->respondCreated([ - 'status' => 'success', - 'message' => 'Contact updated successfully', - 'data' => $dataContact, - ]); - } else { - return $this->failServerError('Failed to create contact'); - } - } catch (\Throwable $e) { - return $this->failServerError('Error: ' . $e->getMessage()); - } - - } - public function delete() { try { $input = $this->request->getJSON(true); $ContactID = $input["ContactID"]; if (!$ContactID) { - return $this->failValidationError('ContactID is required.'); + return $this->failValidationErrors('ContactID is required.'); } - + $contact = $this->db->table('contact')->where('ContactID', $ContactID)->get()->getRow(); if (!$contact) { return $this->failNotFound("data with {$ContactID} not found."); @@ -136,40 +85,48 @@ class Contact extends Controller { } } - private function prepareContactData(array $input): array { - $data = [ - "NameFirst" => $input['NameFirst'] ?? null, - "NameLast" => $input['NameLast'] ?? null, - "Title" => $input['Title'] ?? null, - "Initial" => $input['Initial'] ?? null, - "Birthdate" => $input['Birthdate'] ?? null, - "EmailAddress1" => $input['EmailAddress1'] ?? null, - "EmailAddress2" => $input['EmailAddress2'] ?? null, - "Phone" => $input["Phone"] ?? null, - "MobilePhone1" => $input["MobilePhone1"] ?? null, - "MobilePhone2" => $input["MobilePhone2"] ?? null, - "Specialty" => $input["Specialty"] ?? null, - "SubSpecialty" => $input["SubSpecialty"] ?? null, - ]; + public function save() { + $input = $this->request->getJSON(true); + $contactModel = new ContactModel(); + $detailModel = new ContactDetailModel(); + $db = \Config\Database::connect(); - if(!empty($input["ContactID"])) { $data["ContactID"] = $input["ContactID"]; } + $db->transStart(); - return $data; - } + try { - private function prepareContactDetailData(array $input): array { - foreach($input['ContactDetail'] as $detail) { - $data[] = [ - "SiteID" => $detail['SiteID'] ?? null, - "ContactCode" => $detail['ContactCode'] ?? null, - "ContactEmail" => $detail['ContactEmail'] ?? null, - "OccupationID" => $detail['OccupationID'] ?? null, - "JobTitle" => $detail['JobTitle'] ?? null, - "Department" => $detail['Department'] ?? null, - "ContactStartDate" => $detail['ContactStartDate'] ?? null, - "ContactEndDate" => $detail['ContactEndDate'] ?? null, - ]; + if (!empty($input['ContactID'])) { + $ContactID = $input['ContactID']; + if (!$contactModel->update($ContactID, $input)) { throw new \RuntimeException('Failed to update contact'); } + } else { + $ContactID = $contactModel->insert($input, true); + if (!$ContactID) { throw new \RuntimeException('Failed to insert contact'); } + } + + if (!empty($input['Details'])) { + $result = $detailModel->syncDetails($ContactID, $input['Details']); + if ($result['status'] !== 'success') { + throw new \RuntimeException('Failed to sync details: ' . $result['message']); + } + } + + $db->transComplete(); + + if ($db->transStatus() === false) { + throw new \RuntimeException('Transaction failed'); + } + + return $this->respondCreated([ + 'status' => 'success', + 'ContactID' => $ContactID, + ]); + } catch (\Throwable $e) { + $db->transRollback(); + log_message('error', 'saveContact error: ' . $e->getMessage()); + return $this->fail([ + 'status' => 'error', + 'message' => $e->getMessage(), + ], 500); } - return $data; } } \ No newline at end of file diff --git a/app/Models/ContactDetailModel.php b/app/Models/ContactDetailModel.php index 2059c93..9925594 100644 --- a/app/Models/ContactDetailModel.php +++ b/app/Models/ContactDetailModel.php @@ -9,29 +9,51 @@ class ContactDetailModel extends Model { protected $primaryKey = 'ContactDetID'; protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate']; - public function syncDetails(int $contactId, array $details) { - $kept = []; + public function syncDetails(int $ContactID, array $contactDetails) { + try { + $keptSiteIDs = []; - foreach ($details as $detail) { - $detail['ContactID'] = $contactId; + foreach ($contactDetails as $detail) { + if (empty($detail['SiteID'])) { + continue; + } - $existing = $this->where('SiteID', $detail['SiteID']) - ->where('ContactID', $contactId) - ->first(); + $detail['ContactID'] = $ContactID; - if ($existing) { - $this->update($existing[$this->primaryKey], $detail); - $kept[] = $existing[$this->primaryKey]; - } else { - $newId = $this->insert($detail); - $kept[] = $newId; + $existing = $this->where('ContactID', $ContactID) + ->where('SiteID', $detail['SiteID']) + ->first(); + + if ($existing) { + $this->update($existing[$this->primaryKey], $detail); + } else { + $this->insert($detail); + } + + $keptSiteIDs[] = $detail['SiteID']; } - } - if (!empty($kept)) { - $this->where('ContactID', $contactId) - ->whereNotIn($this->primaryKey, $kept) - ->delete(); - } else { $this->where('ContactID', $contactId)->delete(); } - } + // Delete missing rows + if (!empty($keptSiteIDs)) { + $this->where('ContactID', $ContactID) + ->whereNotIn('SiteID', $keptSiteIDs) + ->delete(); + } else { + $this->where('ContactID', $ContactID)->delete(); + } + + return [ + 'status' => 'success', + 'inserted' => count($contactDetails) - count($keptSiteIDs), + 'kept' => count($keptSiteIDs), + ]; + } catch (\Throwable $e) { + log_message('error', 'syncDetails error: ' . $e->getMessage()); + + return [ + 'status' => 'error', + 'message' => $e->getMessage(), + ]; + } +} } diff --git a/app/Models/ContactModel.php b/app/Models/ContactModel.php index fcba800..1dd712d 100644 --- a/app/Models/ContactModel.php +++ b/app/Models/ContactModel.php @@ -5,13 +5,13 @@ namespace App\Models; use CodeIgniter\Model; class ContactModel extends Model { - protected $table = 'contact c'; + protected $table = 'contact'; protected $primaryKey = 'ContactID'; protected $allowedFields = ['NameFirst', 'NameLast', 'Title', 'Initial', 'Birthdate', 'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone1', 'MobilePhone2', 'Specialty', 'SubSpecialty']; public function getContactsWithDetail() { - $rows = $this->select("c.ContactID, cd.SiteID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") - ->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") + $rows = $this->select("contact.ContactID, cd.SiteID, cd.ContactCode, NameFirst, NameLast, Specialty") + ->join("contactdetail cd", "contact.ContactID=cd.ContactID", "left") ->join("occupation o","cd.OccupationID=o.OccupationID", "left") ->get()->getResultArray(); @@ -19,7 +19,7 @@ class ContactModel extends Model { } public function getContactWithDetail($ContactID) { - $rows = $this->where('c.ContactID', $ContactID)->join('contactdetail cd', 'c.ContactID=cd.ContactID','left')->get()->getResultArray(); + $rows = $this->where('contact.ContactID', $ContactID)->join('contactdetail cd', 'contact.ContactID=cd.ContactID','left')->get()->getResultArray(); $contact = [ 'ContactID' => $rows[0]['ContactID'], 'NameFirst' => $rows[0]['NameFirst'] ?? null, @@ -56,49 +56,47 @@ class ContactModel extends Model { return $contact; } - public function createContact(array $contactData, array $contactDetails) { - $db = \Config\Database::connect(); - $db->transStart(); + public function saveWithDetails(array $data): array { + $db = \Config\Database::connect(); + $db->transStart(); - try { - if (!$this->insert($contactData)) { - throw new \Exception('Failed to insert contact'); + try { + if (!empty($data['ContactID'])) { + $contactId = $data['ContactID']; + $this->update($contactId, $data); + } else { + $contactId = $this->insert($data, true); } - $ContactID = $this->getInsertID(); - $detailModel = new \App\Models\ContactDetailModel(); - foreach ($contactDetails as $detail) { - $detail['ContactID'] = $ContactID; - if (!$detailModel->insert($detail)) { - throw new \Exception('Failed to insert contact details'); + if (!$contactId) { + throw new \RuntimeException('Failed to save contact'); + } + + if (!empty($data['Details'])) { + $detailModel = new \App\Models\ContactDetailModel(); + $result = $detailModel->syncDetails($contactId, $data['Details']); + + if ($result['status'] !== 'success') { + throw new \RuntimeException('SyncDetails failed: ' . $result['message']); } } $db->transComplete(); - return $db->transStatus(); - } catch (\Exception $e) { + + return [ + 'status' => 'success', + 'ContactID' => $contactId, + ]; + } catch (\Throwable $e) { $db->transRollback(); - throw $e; - } + + log_message('error', 'saveWithDetails error: ' . $e->getMessage()); + + return [ + 'status' => 'error', + 'message' => $e->getMessage(), + ]; + } } - public function updateContact(int $ContactID, array $contactData, array $contactDetails) { - $db = \Config\Database::connect(); - $db->transStart(); - - try { - if (!$this->update($ContactID, $contactData)) { - throw new \Exception('Failed to update contact'); - } - - $detailModel = new \App\Models\ContactDetailModel(); - $detailModel->syncDetails($ContactID, $contactDetails); - - $db->transComplete(); - return $db->transStatus(); - } catch (\Exception $e) { - $db->transRollback(); - throw $e; - } - } } From e5d51dff866c0df79bdda42cfd655f11ce349709 Mon Sep 17 00:00:00 2001 From: mahdahar <89adham@gmail.com> Date: Thu, 25 Sep 2025 13:42:37 +0700 Subject: [PATCH 8/8] fixing contactdetail empty not delete --- app/Controllers/Contact.php | 12 +++--- app/Models/ContactDetailModel.php | 64 +++++++++++++++---------------- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/app/Controllers/Contact.php b/app/Controllers/Contact.php index 2ea7e95..65bd62a 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -63,7 +63,7 @@ class Contact extends Controller { if (!$ContactID) { return $this->failValidationErrors('ContactID is required.'); } - + $contact = $this->db->table('contact')->where('ContactID', $ContactID)->get()->getRow(); if (!$contact) { return $this->failNotFound("data with {$ContactID} not found."); @@ -103,12 +103,12 @@ class Contact extends Controller { if (!$ContactID) { throw new \RuntimeException('Failed to insert contact'); } } - if (!empty($input['Details'])) { - $result = $detailModel->syncDetails($ContactID, $input['Details']); - if ($result['status'] !== 'success') { - throw new \RuntimeException('Failed to sync details: ' . $result['message']); - } + + $result = $detailModel->syncDetails($ContactID, $input['Details']); + if ($result['status'] !== 'success') { + throw new \RuntimeException('Failed to sync details: ' . $result['message']); } + $db->transComplete(); diff --git a/app/Models/ContactDetailModel.php b/app/Models/ContactDetailModel.php index 9925594..e5e2488 100644 --- a/app/Models/ContactDetailModel.php +++ b/app/Models/ContactDetailModel.php @@ -11,48 +11,48 @@ class ContactDetailModel extends Model { public function syncDetails(int $ContactID, array $contactDetails) { try { - $keptSiteIDs = []; + $keptSiteIDs = []; - foreach ($contactDetails as $detail) { - if (empty($detail['SiteID'])) { - continue; - } - - $detail['ContactID'] = $ContactID; - - $existing = $this->where('ContactID', $ContactID) - ->where('SiteID', $detail['SiteID']) - ->first(); - - if ($existing) { - $this->update($existing[$this->primaryKey], $detail); - } else { - $this->insert($detail); - } - - $keptSiteIDs[] = $detail['SiteID']; + foreach ($contactDetails as $detail) { + if (empty($detail['SiteID'])) { + continue; } - // Delete missing rows - if (!empty($keptSiteIDs)) { - $this->where('ContactID', $ContactID) - ->whereNotIn('SiteID', $keptSiteIDs) - ->delete(); + $detail['ContactID'] = $ContactID; + + $existing = $this->where('ContactID', $ContactID) + ->where('SiteID', $detail['SiteID']) + ->first(); + + if ($existing) { + $this->update($existing[$this->primaryKey], $detail); } else { - $this->where('ContactID', $ContactID)->delete(); + $this->insert($detail); } - return [ - 'status' => 'success', - 'inserted' => count($contactDetails) - count($keptSiteIDs), - 'kept' => count($keptSiteIDs), - ]; + $keptSiteIDs[] = $detail['SiteID']; + } + + // Delete missing rows + if (!empty($keptSiteIDs)) { + $this->where('ContactID', $ContactID) + ->whereNotIn('SiteID', $keptSiteIDs) + ->delete(); + } else { + $this->where('ContactID', $ContactID)->delete(); + } + + return [ + 'status' => 'success', + 'inserted' => count($contactDetails) - count($keptSiteIDs), + 'kept' => count($keptSiteIDs), + ]; } catch (\Throwable $e) { log_message('error', 'syncDetails error: ' . $e->getMessage()); return [ - 'status' => 'error', - 'message' => $e->getMessage(), + 'status' => 'error', + 'message' => $e->getMessage(), ]; } }