fixing contactdetail

This commit is contained in:
mahdahar 2025-09-25 13:30:15 +07:00
parent 98acaff93b
commit 501ef06592
4 changed files with 125 additions and 148 deletions

View File

@ -54,8 +54,8 @@ $routes->delete('/api/location', 'Location::delete');
$routes->get('/api/contact', 'Contact::index'); $routes->get('/api/contact', 'Contact::index');
$routes->get('/api/contact/(:num)', 'Contact::show/$1'); $routes->get('/api/contact/(:num)', 'Contact::show/$1');
$routes->post('/api/contact', 'Contact::create'); $routes->post('/api/contact', 'Contact::save');
$routes->patch('/api/contact', 'Contact::update'); $routes->patch('/api/contact', 'Contact::save');
$routes->delete('/api/contact', 'Contact::delete'); $routes->delete('/api/contact', 'Contact::delete');
$routes->get('/api/occupation', 'Occupation::index'); $routes->get('/api/occupation', 'Occupation::index');

View File

@ -5,15 +5,16 @@ use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller; use CodeIgniter\Controller;
use App\Models\ContactModel; use App\Models\ContactModel;
use App\Models\ContactDetailModel;
class Contact extends Controller { class Contact extends Controller {
use ResponseTrait; use ResponseTrait;
protected $contactModel; protected $db;
protected $contactRule; protected $contactRule;
public function __construct() { public function __construct() {
$this->contactModel = new ContactModel(); $this->db = \Config\Database::connect();
$this->contactRule = [ 'NameFirst' => 'required' ]; $this->contactRule = [ 'NameFirst' => 'required' ];
} }
@ -55,64 +56,12 @@ class Contact extends Controller {
], 200); ], 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() { public function delete() {
try { try {
$input = $this->request->getJSON(true); $input = $this->request->getJSON(true);
$ContactID = $input["ContactID"]; $ContactID = $input["ContactID"];
if (!$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(); $contact = $this->db->table('contact')->where('ContactID', $ContactID)->get()->getRow();
@ -136,40 +85,48 @@ class Contact extends Controller {
} }
} }
private function prepareContactData(array $input): array { public function save() {
$data = [ $input = $this->request->getJSON(true);
"NameFirst" => $input['NameFirst'] ?? null, $contactModel = new ContactModel();
"NameLast" => $input['NameLast'] ?? null, $detailModel = new ContactDetailModel();
"Title" => $input['Title'] ?? null, $db = \Config\Database::connect();
"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,
];
if(!empty($input["ContactID"])) { $data["ContactID"] = $input["ContactID"]; } $db->transStart();
return $data; try {
}
private function prepareContactDetailData(array $input): array { if (!empty($input['ContactID'])) {
foreach($input['ContactDetail'] as $detail) { $ContactID = $input['ContactID'];
$data[] = [ if (!$contactModel->update($ContactID, $input)) { throw new \RuntimeException('Failed to update contact'); }
"SiteID" => $detail['SiteID'] ?? null, } else {
"ContactCode" => $detail['ContactCode'] ?? null, $ContactID = $contactModel->insert($input, true);
"ContactEmail" => $detail['ContactEmail'] ?? null, if (!$ContactID) { throw new \RuntimeException('Failed to insert contact'); }
"OccupationID" => $detail['OccupationID'] ?? null, }
"JobTitle" => $detail['JobTitle'] ?? null,
"Department" => $detail['Department'] ?? null, if (!empty($input['Details'])) {
"ContactStartDate" => $detail['ContactStartDate'] ?? null, $result = $detailModel->syncDetails($ContactID, $input['Details']);
"ContactEndDate" => $detail['ContactEndDate'] ?? null, 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;
} }
} }

View File

@ -9,29 +9,51 @@ class ContactDetailModel extends Model {
protected $primaryKey = 'ContactDetID'; protected $primaryKey = 'ContactDetID';
protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate']; protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate'];
public function syncDetails(int $contactId, array $details) { public function syncDetails(int $ContactID, array $contactDetails) {
$kept = []; try {
$keptSiteIDs = [];
foreach ($details as $detail) { foreach ($contactDetails as $detail) {
$detail['ContactID'] = $contactId; if (empty($detail['SiteID'])) {
continue;
}
$existing = $this->where('SiteID', $detail['SiteID']) $detail['ContactID'] = $ContactID;
->where('ContactID', $contactId)
->first();
if ($existing) { $existing = $this->where('ContactID', $ContactID)
$this->update($existing[$this->primaryKey], $detail); ->where('SiteID', $detail['SiteID'])
$kept[] = $existing[$this->primaryKey]; ->first();
} else {
$newId = $this->insert($detail); if ($existing) {
$kept[] = $newId; $this->update($existing[$this->primaryKey], $detail);
} else {
$this->insert($detail);
}
$keptSiteIDs[] = $detail['SiteID'];
} }
}
if (!empty($kept)) { // Delete missing rows
$this->where('ContactID', $contactId) if (!empty($keptSiteIDs)) {
->whereNotIn($this->primaryKey, $kept) $this->where('ContactID', $ContactID)
->delete(); ->whereNotIn('SiteID', $keptSiteIDs)
} else { $this->where('ContactID', $contactId)->delete(); } ->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(),
];
}
}
} }

View File

@ -5,13 +5,13 @@ namespace App\Models;
use CodeIgniter\Model; use CodeIgniter\Model;
class ContactModel extends Model { class ContactModel extends Model {
protected $table = 'contact c'; protected $table = 'contact';
protected $primaryKey = 'ContactID'; protected $primaryKey = 'ContactID';
protected $allowedFields = ['NameFirst', 'NameLast', 'Title', 'Initial', 'Birthdate', 'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone1', 'MobilePhone2', 'Specialty', 'SubSpecialty']; protected $allowedFields = ['NameFirst', 'NameLast', 'Title', 'Initial', 'Birthdate', 'EmailAddress1', 'EmailAddress2', 'Phone', 'MobilePhone1', 'MobilePhone2', 'Specialty', 'SubSpecialty'];
public function getContactsWithDetail() { public function getContactsWithDetail() {
$rows = $this->select("c.ContactID, cd.SiteID, cd.ContactCode, c.NameFirst, c.NameLast, c.Specialty") $rows = $this->select("contact.ContactID, cd.SiteID, cd.ContactCode, NameFirst, NameLast, Specialty")
->join("contactdetail cd", "c.ContactID=cd.ContactID", "left") ->join("contactdetail cd", "contact.ContactID=cd.ContactID", "left")
->join("occupation o","cd.OccupationID=o.OccupationID", "left") ->join("occupation o","cd.OccupationID=o.OccupationID", "left")
->get()->getResultArray(); ->get()->getResultArray();
@ -19,7 +19,7 @@ class ContactModel extends Model {
} }
public function getContactWithDetail($ContactID) { 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 = [ $contact = [
'ContactID' => $rows[0]['ContactID'], 'ContactID' => $rows[0]['ContactID'],
'NameFirst' => $rows[0]['NameFirst'] ?? null, 'NameFirst' => $rows[0]['NameFirst'] ?? null,
@ -56,49 +56,47 @@ class ContactModel extends Model {
return $contact; return $contact;
} }
public function createContact(array $contactData, array $contactDetails) { public function saveWithDetails(array $data): array {
$db = \Config\Database::connect(); $db = \Config\Database::connect();
$db->transStart(); $db->transStart();
try { try {
if (!$this->insert($contactData)) { if (!empty($data['ContactID'])) {
throw new \Exception('Failed to insert contact'); $contactId = $data['ContactID'];
$this->update($contactId, $data);
} else {
$contactId = $this->insert($data, true);
} }
$ContactID = $this->getInsertID();
$detailModel = new \App\Models\ContactDetailModel(); if (!$contactId) {
foreach ($contactDetails as $detail) { throw new \RuntimeException('Failed to save contact');
$detail['ContactID'] = $ContactID; }
if (!$detailModel->insert($detail)) {
throw new \Exception('Failed to insert contact details'); 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(); $db->transComplete();
return $db->transStatus();
} catch (\Exception $e) { return [
'status' => 'success',
'ContactID' => $contactId,
];
} catch (\Throwable $e) {
$db->transRollback(); $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;
}
}
} }