70 lines
1.9 KiB
PHP
70 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Contact;
|
|
|
|
use App\Models\BaseModel;
|
|
|
|
class ContactDetailModel extends BaseModel {
|
|
protected $table = 'contactdetail';
|
|
protected $primaryKey = 'ContactDetID';
|
|
protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate'];
|
|
|
|
protected $useTimestamps = true;
|
|
protected $createdField = 'ContactStartDate';
|
|
protected $updatedField = '';
|
|
|
|
protected $beforeInsert = ['normalizeDatesToUTC'];
|
|
protected $beforeUpdate = ['normalizeDatesToUTC'];
|
|
protected $afterFind = ['convertDatesToUTCISO'];
|
|
protected $afterInsert = ['convertDatesToUTCISO'];
|
|
protected $afterUpdate = ['convertDatesToUTCISO'];
|
|
|
|
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(),
|
|
];
|
|
}
|
|
}
|
|
}
|