This commit is contained in:
mikael-zakaria 2025-09-25 14:01:41 +07:00
commit 133ef55fac
12 changed files with 450 additions and 196 deletions

View File

@ -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');
$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');

View File

@ -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);
}
}
}

156
app/Controllers/Counter.php Normal file
View File

@ -0,0 +1,156 @@
<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use CodeIgniter\Database\RawSql;
class Counter extends Controller {
use ResponseTrait;
public function __construct() {
$this->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;
}
}

View File

@ -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());

View File

@ -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

View File

@ -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');
*/
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class CounterSeeder extends Seeder {
public function run() {
// counter
$data = [
['CounterID'=>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);
}
}

View File

@ -9,5 +9,6 @@ class DBSeeder extends Seeder {
$this->call('MainSeeder');
$this->call('ValueSetSeeder');
$this->call('DummySeeder');
$this->call('CounterSeeder');
}
}

View File

@ -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'],

View File

@ -0,0 +1,59 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
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 $contactDetails) {
try {
$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'];
}
// 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(),
];
}
}
}

102
app/Models/ContactModel.php Normal file
View File

@ -0,0 +1,102 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ContactModel extends Model {
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("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(),
];
}
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class CounterModel extends Model {
protected $table = 'counter';
protected $primaryKey = 'CounterID';
protected $allowedFields = ['CounterValue', 'CounterStart', 'CounterEnd', 'CounterReset'];
public function use($CounterID) {
$row = $this->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;
}
}