/** * Delete customer appointment. */ public function executeDeleteCustomerAppointment() { $customer_appointment = new AB_CustomerAppointment(); $customer_appointment->load($this->getParameter('id')); $appointment = new AB_Appointment(); $appointment->load($customer_appointment->get('appointment_id')); $customer_appointment->delete(); // Delete appointment, if there aren't customers. $count = AB_CustomerAppointment::query()->where('appointment_id', $customer_appointment->get('appointment_id'))->count(); if (!$count) { $appointment->delete(); } else { $appointment->handleGoogleCalendar(); } wp_send_json_success(); }
/** * Set array of customers associated with this appointment. * * @param array $data Array of customer IDs, custom_fields and number_of_persons */ public function setCustomers(array $data) { // Prepare array of customers. $customers = array(); foreach ($data as $customer) { $customers[$customer['id']] = $customer; } // Retrieve customer IDs currently associated with this appointment. $current_ids = array_map(function ($ca) { return $ca->customer->get('id'); }, $this->getCustomerAppointments()); // Remove redundant customers. $customer_appointment = new AB_CustomerAppointment(); foreach (array_diff($current_ids, array_keys($customers)) as $id) { if ($customer_appointment->loadBy(array('appointment_id' => $this->get('id'), 'customer_id' => $id))) { $customer_appointment->delete(); } } // Add new customers. foreach (array_diff(array_keys($customers), $current_ids) as $id) { $customer_appointment = new AB_CustomerAppointment(); $customer_appointment->set('appointment_id', $this->get('id')); $customer_appointment->set('customer_id', $id); $customer_appointment->set('custom_fields', json_encode($customers[$id]['custom_fields'])); $customer_appointment->set('number_of_persons', $customers[$id]['number_of_persons']); $customer_appointment->save(); } // Update existing customers. foreach (array_intersect($current_ids, array_keys($customers)) as $id) { $customer_appointment = new AB_CustomerAppointment(); $customer_appointment->loadBy(array('appointment_id' => $this->get('id'), 'customer_id' => $id)); $customer_appointment->set('custom_fields', json_encode($customers[$id]['custom_fields'])); $customer_appointment->set('number_of_persons', $customers[$id]['number_of_persons']); $customer_appointment->save(); } }