MaketRandevu/application/models/Appointments_model.php

654 lines
22 KiB
PHP
Raw Normal View History

<?php defined('BASEPATH') or exit('No direct script access allowed');
/* ----------------------------------------------------------------------------
2022-01-18 15:05:42 +03:00
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
2021-12-18 19:43:45 +03:00
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
/**
* Appointments model.
*
* @package Models
*/
class Appointments_model extends EA_Model {
/**
* @var array
*/
2023-03-13 11:06:18 +03:00
protected array $casts = [
'id' => 'integer',
'is_unavailability' => 'boolean',
'id_users_provider' => 'integer',
'id_users_customer' => 'integer',
'id_services' => 'integer',
];
/**
* @var array
*/
2023-03-13 11:06:18 +03:00
protected array $api_resource = [
'id' => 'id',
'book' => 'book_datetime',
'start' => 'start_datetime',
'end' => 'end_datetime',
'location' => 'location',
'color' => 'color',
'status' => 'status',
'notes' => 'notes',
'hash' => 'hash',
'serviceId' => 'id_services',
'providerId' => 'id_users_provider',
'customerId' => 'id_users_customer',
'googleCalendarId' => 'id_google_calendar',
];
/**
2021-10-27 11:04:01 +03:00
* Save (insert or update) an appointment.
*
2021-10-27 11:04:01 +03:00
* @param array $appointment Associative array with the appointment data.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @return int Returns the appointment ID.
*
2021-10-27 11:04:01 +03:00
* @throws InvalidArgumentException
*/
2021-10-27 11:04:01 +03:00
public function save(array $appointment): int
{
$this->validate($appointment);
2021-10-27 11:04:01 +03:00
if (empty($appointment['id']))
{
2021-10-27 11:04:01 +03:00
return $this->insert($appointment);
2018-01-23 12:08:37 +03:00
}
else
{
2021-10-27 11:04:01 +03:00
return $this->update($appointment);
}
}
/**
2021-10-27 11:04:01 +03:00
* Validate the appointment data.
*
2021-10-27 11:04:01 +03:00
* @param array $appointment Associative array with the appointment data.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @throws InvalidArgumentException
*/
2021-10-27 11:49:42 +03:00
public function validate(array $appointment)
{
2021-10-27 11:04:01 +03:00
// If an appointment ID is provided then check whether the record really exists in the database.
if ( ! empty($appointment['id']))
{
2021-10-27 11:04:01 +03:00
$count = $this->db->get_where('appointments', ['id' => $appointment['id']])->num_rows();
2021-10-27 11:04:01 +03:00
if ( ! $count)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The provided appointment ID does not exist in the database: ' . $appointment['id']);
}
}
2021-10-27 11:04:01 +03:00
// Make sure all required fields are provided.
$require_notes = filter_var(setting('require_notes'), FILTER_VALIDATE_BOOLEAN);
2021-10-27 11:04:01 +03:00
if (
empty($appointment['start_datetime'])
|| empty($appointment['end_datetime'])
|| empty($appointment['id_services'])
|| empty($appointment['id_users_provider'])
|| empty($appointment['id_users_customer'])
|| (empty($appointment['notes']) && $require_notes)
2021-10-27 11:04:01 +03:00
)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($appointment, TRUE));
}
2021-10-27 11:04:01 +03:00
// Make sure that the provided appointment date time values are valid.
if ( ! validate_datetime($appointment['start_datetime']))
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The appointment start date time is invalid.');
}
2021-10-27 11:04:01 +03:00
if ( ! validate_datetime($appointment['end_datetime']))
{
throw new InvalidArgumentException('The appointment end date time is invalid.');
}
// Make the appointment lasts longer than the minimum duration (in minutes).
$diff = (strtotime($appointment['end_datetime']) - strtotime($appointment['start_datetime'])) / 60;
if ($diff < EVENT_MINIMUM_DURATION)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The appointment duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes.');
}
2021-10-27 11:04:01 +03:00
// Make sure the provider ID really exists in the database.
$count = $this
->db
->select()
->from('users')
->join('roles', 'roles.id = users.id_roles', 'inner')
->where('users.id', $appointment['id_users_provider'])
->where('roles.slug', DB_SLUG_PROVIDER)
2021-10-27 11:04:01 +03:00
->get()
->num_rows();
2020-12-05 12:38:57 +03:00
2021-10-27 11:04:01 +03:00
if ( ! $count)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The appointment provider ID was not found in the database: ' . $appointment['id_users_provider']);
}
if ( ! filter_var($appointment['is_unavailability'], FILTER_VALIDATE_BOOLEAN))
{
2021-10-27 11:04:01 +03:00
// Make sure the customer ID really exists in the database.
$count = $this
->db
->select()
->from('users')
->join('roles', 'roles.id = users.id_roles', 'inner')
->where('users.id', $appointment['id_users_customer'])
->where('roles.slug', DB_SLUG_CUSTOMER)
2021-10-28 14:27:47 +03:00
->get()
->num_rows();
2020-12-05 12:38:57 +03:00
2021-10-27 11:04:01 +03:00
if ( ! $count)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The appointment customer ID was not found in the database: ' . $appointment['id_users_customer']);
}
2021-10-27 11:04:01 +03:00
// Make sure the service ID really exists in the database.
$count = $this->db->get_where('services', ['id' => $appointment['id_services']])->num_rows();
2020-12-05 12:38:57 +03:00
2021-10-27 11:04:01 +03:00
if ( ! $count)
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('Appointment service id is invalid.');
}
}
}
/**
2021-10-27 11:04:01 +03:00
* Insert a new appointment into the database.
*
2021-10-27 11:04:01 +03:00
* @param array $appointment Associative array with the appointment data.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @return int Returns the appointment ID.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @throws RuntimeException
*/
2021-10-27 11:04:01 +03:00
protected function insert(array $appointment): int
{
$appointment['book_datetime'] = date('Y-m-d H:i:s');
$appointment['create_datetime'] = date('Y-m-d H:i:s');
$appointment['update_datetime'] = date('Y-m-d H:i:s');
$appointment['hash'] = random_string('alnum', 12);
if ( ! $this->db->insert('appointments', $appointment))
{
2021-10-27 11:04:01 +03:00
throw new RuntimeException('Could not insert appointment.');
}
2021-10-27 11:04:01 +03:00
return $this->db->insert_id();
}
/**
2021-10-27 11:04:01 +03:00
* Update an existing appointment.
*
2021-10-27 11:04:01 +03:00
* @param array $appointment Associative array with the appointment data.
*
2021-10-27 11:04:01 +03:00
* @return int Returns the appointment ID.
*
2021-10-27 11:04:01 +03:00
* @throws RuntimeException
*/
2021-10-27 11:04:01 +03:00
protected function update(array $appointment): int
{
$appointment['update_datetime'] = date('Y-m-d H:i:s');
2021-10-27 11:04:01 +03:00
if ( ! $this->db->update('appointments', $appointment, ['id' => $appointment['id']]))
{
2021-10-27 11:04:01 +03:00
throw new RuntimeException('Could not update appointment record.');
}
2021-10-27 11:04:01 +03:00
return $appointment['id'];
}
/**
2021-10-27 11:04:01 +03:00
* Remove an existing appointment from the database.
*
2021-10-27 11:04:01 +03:00
* @param int $appointment_id Appointment ID.
* @param bool $force_delete Override soft delete.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @throws RuntimeException
*/
public function delete(int $appointment_id, bool $force_delete = FALSE)
{
if ($force_delete)
{
$this->db->delete('appointments', ['id' => $appointment_id]);
}
else
{
$this->db->update('appointments', ['delete_datetime' => date('Y-m-d H:i:s')], ['id' => $appointment_id]);
}
}
/**
2021-10-27 11:04:01 +03:00
* Get a specific appointment from the database.
*
2021-10-27 11:04:01 +03:00
* @param int $appointment_id The ID of the record to be returned.
* @param bool $with_trashed
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @return array Returns an array with the appointment data.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @throws InvalidArgumentException
*/
public function find(int $appointment_id, bool $with_trashed = FALSE): array
{
if ( ! $with_trashed)
{
$this->db->where('delete_datetime IS NULL');
}
2017-09-08 15:03:45 +03:00
$appointment = $this->db->get_where('appointments', ['id' => $appointment_id])->row_array();
if ( ! $appointment)
{
throw new InvalidArgumentException('The provided appointment ID was not found in the database: ' . $appointment_id);
}
$this->cast($appointment);
return $appointment;
}
/**
* Get a specific field value from the database.
*
2021-10-27 11:04:01 +03:00
* @param int $appointment_id Appointment ID.
* @param string $field Name of the value to be returned.
2017-09-08 15:03:45 +03:00
*
2023-01-14 11:39:14 +03:00
* @return mixed Returns the selected appointment value from the database.
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @throws InvalidArgumentException
*/
2023-01-14 11:39:14 +03:00
public function value(int $appointment_id, string $field): mixed
{
2021-10-27 11:04:01 +03:00
if (empty($field))
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The field argument is cannot be empty.');
}
2021-10-27 11:04:01 +03:00
if (empty($appointment_id))
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The appointment ID argument cannot be empty.');
}
2021-10-27 11:04:01 +03:00
// Check whether the appointment exists.
$query = $this->db->get_where('appointments', ['id' => $appointment_id]);
if ( ! $query->num_rows())
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The provided appointment ID was not found in the database: ' . $appointment_id);
}
2021-10-27 11:04:01 +03:00
// Check if the required field is part of the appointment data.
$appointment = $query->row_array();
$this->cast($appointment);
2021-10-27 11:04:01 +03:00
if ( ! array_key_exists($field, $appointment))
{
2021-10-27 11:04:01 +03:00
throw new InvalidArgumentException('The requested field was not found in the appointment data: ' . $field);
}
2021-10-27 11:04:01 +03:00
return $appointment[$field];
}
/**
2021-10-27 11:04:01 +03:00
* Get all appointments that match the provided criteria.
*
2023-03-13 11:06:18 +03:00
* @param array|string|null $where Where conditions.
2021-10-27 11:04:01 +03:00
* @param int|null $limit Record limit.
* @param int|null $offset Record offset.
* @param string|null $order_by Order by.
* @param bool $with_trashed
2017-09-08 15:03:45 +03:00
*
2021-10-27 11:04:01 +03:00
* @return array Returns an array of appointments.
*/
2023-03-13 11:06:18 +03:00
public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL, bool $with_trashed = FALSE): array
{
if ($where !== NULL)
{
$this->db->where($where);
}
if ($order_by)
{
$this->db->order_by($order_by);
}
if ( ! $with_trashed)
{
$this->db->where('delete_datetime IS NULL');
}
$appointments = $this->db->get_where('appointments', ['is_unavailability' => FALSE], $limit, $offset)->result_array();
foreach ($appointments as &$appointment)
{
$this->cast($appointment);
}
return $appointments;
}
/**
2021-10-27 11:04:01 +03:00
* Remove all the Google Calendar event IDs from appointment records.
*
2021-10-27 11:04:01 +03:00
* @param int $provider_id Matching provider ID.
*/
2021-10-27 11:49:42 +03:00
public function clear_google_sync_ids(int $provider_id)
{
2021-10-27 11:04:01 +03:00
$this->db->update('appointments', ['id_google_calendar' => NULL], ['id_users_provider' => $provider_id]);
}
/**
2021-10-27 11:04:01 +03:00
* Get the attendants number for the requested period.
*
2021-10-27 11:04:01 +03:00
* @param DateTime $start Period start.
* @param DateTime $end Period end.
* @param int $service_id Service ID.
* @param int $provider_id Provider ID.
* @param int|null $exclude_appointment_id Exclude an appointment from the result set.
*
2021-10-27 11:04:01 +03:00
* @return int Returns the number of appointments that match the provided criteria.
*/
2021-10-27 11:04:01 +03:00
public function get_attendants_number_for_period(DateTime $start, DateTime $end, int $service_id, int $provider_id, int $exclude_appointment_id = NULL): int
2018-01-23 12:08:37 +03:00
{
if ($exclude_appointment_id)
{
$this->db->where('id !=', $exclude_appointment_id);
}
2021-10-27 11:04:01 +03:00
$result = $this
->db
->select('count(*) AS attendants_number')
->from('appointments')
->group_start()
->group_start()
2021-10-27 11:04:01 +03:00
->where('start_datetime <=', $start->format('Y-m-d H:i:s'))
->where('end_datetime >', $start->format('Y-m-d H:i:s'))
->group_end()
->or_group_start()
2021-10-27 11:04:01 +03:00
->where('start_datetime <', $end->format('Y-m-d H:i:s'))
->where('end_datetime >=', $end->format('Y-m-d H:i:s'))
->group_end()
->group_end()
->where('id_services', $service_id)
->where('id_users_provider', $provider_id)
->get()
2021-10-27 11:04:01 +03:00
->row_array();
return $result['attendants_number'];
}
/**
2021-10-27 11:04:01 +03:00
*
* Returns the number of the other service attendants number for the provided time slot.
*
2021-10-27 11:04:01 +03:00
* @param DateTime $start Period start.
* @param DateTime $end Period end.
* @param int $service_id Service ID.
* @param int $provider_id Provider ID.
* @param int|null $exclude_appointment_id Exclude an appointment from the result set.
*
2021-10-27 11:04:01 +03:00
* @return int Returns the number of appointments that match the provided criteria.
*/
public function get_other_service_attendants_number(DateTime $start, DateTime $end, int $service_id, int $provider_id, int $exclude_appointment_id = NULL): int
{
if ($exclude_appointment_id)
{
$this->db->where('id !=', $exclude_appointment_id);
}
2021-10-27 11:04:01 +03:00
$result = $this
->db
->select('count(*) AS attendants_number')
->from('appointments')
->group_start()
->group_start()
2021-10-27 11:04:01 +03:00
->where('start_datetime <=', $start->format('Y-m-d H:i:s'))
->where('end_datetime >', $start->format('Y-m-d H:i:s'))
->group_end()
->or_group_start()
2021-10-27 11:04:01 +03:00
->where('start_datetime <', $end->format('Y-m-d H:i:s'))
->where('end_datetime >=', $end->format('Y-m-d H:i:s'))
->group_end()
->group_end()
->where('id_services !=', $service_id)
->where('id_users_provider', $provider_id)
->get()
2021-10-27 11:04:01 +03:00
->row_array();
return $result['attendants_number'];
}
/**
* Get the query builder interface, configured for use with the appointments table.
*
* @return CI_DB_query_builder
*/
public function query(): CI_DB_query_builder
{
return $this->db->from('appointments');
}
/**
* Search appointments by the provided keyword.
*
* @param string $keyword Search keyword.
* @param int|null $limit Record limit.
* @param int|null $offset Record offset.
* @param string|null $order_by Order by.
* @param bool $with_trashed
2021-10-27 11:04:01 +03:00
*
* @return array Returns an array of appointments.
*/
public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL, bool $with_trashed = FALSE): array
2021-10-27 11:04:01 +03:00
{
if ( ! $with_trashed)
{
$this->db->where('appointments.delete_datetime IS NULL');
}
$appointments = $this
2021-10-27 11:04:01 +03:00
->db
->select('appointments.*')
2021-10-27 11:04:01 +03:00
->from('appointments')
->join('services', 'services.id = appointments.id_services', 'left')
->join('users AS providers', 'providers.id = appointments.id_users_provider', 'inner')
2023-09-13 17:27:19 +03:00
->join('users AS customers', 'customers.id = appointments.id_users_customer', 'left')
->where('is_unavailability', FALSE)
->group_start()
2021-10-27 11:04:01 +03:00
->like('appointments.start_datetime', $keyword)
->or_like('appointments.end_datetime', $keyword)
->or_like('appointments.location', $keyword)
->or_like('appointments.hash', $keyword)
->or_like('appointments.notes', $keyword)
2023-09-13 17:27:19 +03:00
->or_like('services.name', $keyword)
->or_like('services.description', $keyword)
2021-10-27 11:04:01 +03:00
->or_like('providers.first_name', $keyword)
->or_like('providers.last_name', $keyword)
->or_like('providers.email', $keyword)
->or_like('providers.phone_number', $keyword)
->or_like('customers.first_name', $keyword)
->or_like('customers.last_name', $keyword)
->or_like('customers.email', $keyword)
->or_like('customers.phone_number', $keyword)
->group_end()
2021-10-27 11:04:01 +03:00
->limit($limit)
->offset($offset)
->order_by($order_by)
->get()
->result_array();
foreach ($appointments as &$appointment)
{
$this->cast($appointment);
}
return $appointments;
2021-10-27 11:04:01 +03:00
}
/**
* Load related resources to an appointment.
2021-10-27 11:04:01 +03:00
*
* @param array $appointment Associative array with the appointment data.
* @param array $resources Resource names to be attached ("service", "provider", "customer" supported).
*
* @throws InvalidArgumentException
*/
public function load(array &$appointment, array $resources)
2021-10-27 11:04:01 +03:00
{
if (empty($appointment) || empty($resources))
{
return;
}
2021-10-27 11:04:01 +03:00
foreach ($resources as $resource)
{
switch ($resource)
{
case 'service':
$appointment['service'] = $this
->db
->get_where('services', [
'id' => $appointment['id_services'] ?? $appointment['serviceId'] ?? NULL
2021-10-27 11:04:01 +03:00
])
->row_array();
break;
case 'provider':
$appointment['provider'] = $this
->db
->get_where('users', [
'id' => $appointment['id_users_provider'] ?? $appointment['providerId'] ?? NULL
2021-10-27 11:04:01 +03:00
])
->row_array();
break;
case 'customer':
$appointment['customer'] = $this
->db
->get_where('users', [
'id' => $appointment['id_users_customer'] ?? $appointment['customerId'] ?? NULL
2021-10-27 11:04:01 +03:00
])
->row_array();
break;
default:
throw new InvalidArgumentException('The requested appointment relation is not supported: ' . $resource);
}
}
}
/**
* Convert the database appointment record to the equivalent API resource.
*
* @param array $appointment Appointment data.
*/
public function api_encode(array &$appointment)
{
$encoded_resource = [
'id' => array_key_exists('id', $appointment) ? (int)$appointment['id'] : NULL,
'book' => $appointment['book_datetime'],
'start' => $appointment['start_datetime'],
'end' => $appointment['end_datetime'],
'hash' => $appointment['hash'],
2023-05-04 12:32:40 +03:00
'color' => $appointment['color'],
'status' => $appointment['status'],
'location' => $appointment['location'],
'notes' => $appointment['notes'],
'customerId' => $appointment['id_users_customer'] !== NULL ? (int)$appointment['id_users_customer'] : NULL,
'providerId' => $appointment['id_users_provider'] !== NULL ? (int)$appointment['id_users_provider'] : NULL,
'serviceId' => $appointment['id_services'] !== NULL ? (int)$appointment['id_services'] : NULL,
'googleCalendarId' => $appointment['id_google_calendar'] !== NULL ? (int)$appointment['id_google_calendar'] : NULL
];
$appointment = $encoded_resource;
}
/**
* Convert the API resource to the equivalent database appointment record.
*
* @param array $appointment API resource.
* @param array|null $base Base appointment data to be overwritten with the provided values (useful for updates).
*/
public function api_decode(array &$appointment, array $base = NULL)
{
$decoded_request = $base ?: [];
if (array_key_exists('id', $appointment))
{
$decoded_request['id'] = $appointment['id'];
}
if (array_key_exists('book', $appointment))
{
$decoded_request['book_datetime'] = $appointment['book'];
}
if (array_key_exists('start', $appointment))
{
$decoded_request['start_datetime'] = $appointment['start'];
}
if (array_key_exists('end', $appointment))
{
$decoded_request['end_datetime'] = $appointment['end'];
}
if (array_key_exists('hash', $appointment))
{
$decoded_request['hash'] = $appointment['hash'];
}
if (array_key_exists('location', $appointment))
{
$decoded_request['location'] = $appointment['location'];
}
if (array_key_exists('notes', $appointment))
{
$decoded_request['notes'] = $appointment['notes'];
}
if (array_key_exists('customerId', $appointment))
{
$decoded_request['id_users_customer'] = $appointment['customerId'];
}
if (array_key_exists('providerId', $appointment))
{
$decoded_request['id_users_provider'] = $appointment['providerId'];
}
if (array_key_exists('serviceId', $appointment))
{
$decoded_request['id_services'] = $appointment['serviceId'];
}
if (array_key_exists('googleCalendarId', $appointment))
{
$decoded_request['id_google_calendar'] = $appointment['googleCalendarId'];
}
$decoded_request['is_unavailability'] = FALSE;
$appointment = $decoded_request;
}
}