findAll(); } public function getProvinces() { $this->select('zoneid, zonename')->where('parentzoneid IS NULL', null, false); if (!empty($filters['zoneid'])) { $this->where('zoneid', $filters['zoneid']); } if (!empty($filters['zonename'])) { $this->like('zonename', $filters['zonename'], 'both'); } return $this->findAll(); } public function getCities($filter = []) { $rows = $this->select('zoneid, zonename')->where('parentzoneid IS NOT NULL', null, false); if (!empty($filter['zoneid'])) { $this->where('parentzoneid', $filter['zoneid']); } return $this->findAll(); } // synchronize with crm.zones public function synchronize($crmData) { $db = \Config\Database::connect(); $db->transBegin(); try { // Ambil semua data zoneid di database lokal $localData = $this->findAll(); $localIds = array_column($localData, 'zoneid'); // Siapkan ID dari data CRM $crmIds = array_column($crmData, 'zoneid'); // Hitung statistik $record = [ 'inserted' => 0, 'updated' => 0, 'deleted' => 0, ]; // Insert atau Update data foreach ($crmData as $zone) { if (!isset($zone['zoneid'])) continue; $exists = $this->find($zone['zoneid']); if ($exists) { // Update jika sudah ada $this->update($zone['zoneid'], [ 'parentzoneid' => $zone['parentzoneid'], 'zonecode' => $zone['zonecode'], 'zoneclass' => $zone['zoneclass'], 'zonename' => $zone['zonename'] ]); $this->checkDbError($db, 'Update Zones'); $record['updated']++; } else { // Insert jika belum ada $this->insert($zone); $this->checkDbError($db, 'Insert Zones'); $record['inserted']++; } } // Hapus data yang sudah tidak ada di CRM foreach ($localIds as $localId) { if (!in_array($localId, $crmIds)) { $this->delete($localId); $this->checkDbError($db, 'Delete Zones'); $record['deleted']++;; } } $db->transCommit(); } catch (\Exception $e) { $db->transRollback(); throw $e; } $db->transComplete(); return $record; } // Check Error and Send Spesific Messages private function checkDbError($db, string $context) { $error = $db->error(); if (!empty($error['code'])) { throw new \Exception( "{$context} failed: {$error['code']} - {$error['message']}" ); } } }