diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 669cb56..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'); @@ -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/Contact.php b/app/Controllers/Contact.php index 3a891e5..65bd62a 100644 --- a/app/Controllers/Contact.php +++ b/app/Controllers/Contact.php @@ -3,24 +3,24 @@ namespace App\Controllers; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Controller; -use CodeIgniter\Database\RawSql; + +use App\Models\ContactModel; +use App\Models\ContactDetailModel; class Contact extends Controller { use ResponseTrait; + protected $db; + protected $contactRule; + public function __construct() { $this->db = \Config\Database::connect(); - $this->rulesContact = [ - 'NameFirst' => 'required' - ]; + $this->contactRule = [ 'NameFirst' => 'required' ]; } public function index() { - $sql = $this->db->table('contact'); - $sql->select("*") - ->join("contactdetail", "contact.ContactID=contactdetail.ContactID", "left") - ->join("occupation","contactdetail.OccupationID=occupation.OccupationID", "left"); - $rows = $sql->get()->getResultArray(); + $model = new ContactModel(); + $rows = $model->getContactsWithDetail(); if (empty($rows)) { return $this->respond([ @@ -38,13 +38,9 @@ class Contact extends Controller { } public function show($ContactID = null) { - $rows=$this->db->table('contact') - ->select("*") - ->join("contactdetail", "contact.ContactID=contactdetail.ContactID", "left") - ->join("occupation","occupation.OccupationID=contactdetail.OccupationID", "left") - ->where('contact.ContactID', (int) $ContactID) - ->get()->getResultArray(); - + $model = new ContactModel(); + $rows = $model->getContactWithDetail($ContactID); + if (empty($rows)) { return $this->respond([ 'status' => 'success', @@ -54,114 +50,18 @@ class Contact extends Controller { } return $this->respond([ - 'status' => 'success', + 'status' => 'success', 'message'=> "Data fetched successfully", 'data' => $rows, ], 200); } - public function create() { - try { - $input = $this->request->getJSON(true); - - // 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')->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()); - } - } - - public function update() { - try { - $input = $this->request->getJSON(true); - - // 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()); - } - } - 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(); @@ -185,38 +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 { - $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, - ]; - - return $data; + 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'); } + } + + + $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); + } } } \ 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 dd5d112..c4f3573 100644 --- a/app/Controllers/PatVisit.php +++ b/app/Controllers/PatVisit.php @@ -5,11 +5,14 @@ use CodeIgniter\API\ResponseTrait; use CodeIgniter\Controller; use CodeIgniter\Database\RawSql; +use App\Models\CounterModel; + class PatVisit extends Controller { use ResponseTrait; public function __construct() { $this->db = \Config\Database::connect(); + $this->visnum_prefix = "DV"; } public function show($PVID = null) { @@ -66,15 +69,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 +91,12 @@ class PatVisit extends Controller { $input = $this->request->getJSON(true); if (!$input) { return $this->respond(['status' => 'error', 'message' => 'Invalid JSON input'], 400); } + if($input['PVID'] =='' || !isset($input['PVID'])) { + $model = new CounterModel(); + $input['PVID'] = $this->visnum_prefix .$model->use(2); + //$input['PVID'] = $this->preparePVID(); + } + $dataPatVisit = $this->preparePatVisitData($input); $dataPatDiag = $this->preparePatDiagData($input); $dataPatVisitAdt = $this->preparePatVisitAdtData($input); @@ -130,7 +133,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..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,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'); $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/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'); } } diff --git a/app/Database/Seeds/DummySeeder.php b/app/Database/Seeds/DummySeeder.php index d32da3b..ea6fede 100644 --- a/app/Database/Seeds/DummySeeder.php +++ b/app/Database/Seeds/DummySeeder.php @@ -8,27 +8,34 @@ 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', + 'Birthdate'=>'', 'EmailAddress1'=>'', 'EmailAddress2'=>'', 'Phone'=>'', 'MobilePhone1'=>'', 'MobilePhone2'=>'', 'Specialty'=>'', 'SubSpecialty'=>'' ] ]; $this->db->table('contact')->insertBatch($data); $data = [ - ['ContactID'=>1, 'ContactCode'=>'QDOC', 'ContactEmail'=>'qdoc@email.com', 'OccupationID'=>'', - 'JobTitle'=>'', 'Department'=>'', 'ContactStartDate'=>'', '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); - // 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'], diff --git a/app/Models/ContactDetailModel.php b/app/Models/ContactDetailModel.php new file mode 100644 index 0000000..e5e2488 --- /dev/null +++ b/app/Models/ContactDetailModel.php @@ -0,0 +1,59 @@ +where('ContactID', $ContactID) + ->where('SiteID', $detail['SiteID']) + ->first(); + + if ($existing) { + $this->update($existing[$this->primaryKey], $detail); + } else { + $this->insert($detail); + } + + $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(), + ]; + } +} +} diff --git a/app/Models/ContactModel.php b/app/Models/ContactModel.php new file mode 100644 index 0000000..1dd712d --- /dev/null +++ b/app/Models/ContactModel.php @@ -0,0 +1,102 @@ +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(); + + return $rows; + } + + public function getContactWithDetail($ContactID) { + $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, + '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 saveWithDetails(array $data): array { + $db = \Config\Database::connect(); + $db->transStart(); + + try { + if (!empty($data['ContactID'])) { + $contactId = $data['ContactID']; + $this->update($contactId, $data); + } else { + $contactId = $this->insert($data, true); + } + + 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 [ + 'status' => 'success', + 'ContactID' => $contactId, + ]; + } catch (\Throwable $e) { + $db->transRollback(); + + log_message('error', 'saveWithDetails error: ' . $e->getMessage()); + + return [ + 'status' => 'error', + 'message' => $e->getMessage(), + ]; + } + } + +} 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; + } + +}