-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathServices_model.php
More file actions
554 lines (472 loc) · 17 KB
/
Copy pathServices_model.php
File metadata and controls
554 lines (472 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
<?php defined('BASEPATH') or exit('No direct script access allowed');
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
/**
* Services model.
*
* Handles all the database operations of the service resource.
*
* @package Models
*/
class Services_model extends EA_Model
{
/**
* @var array
*/
protected array $casts = [
'id' => 'integer',
'price' => 'float',
'attendants_number' => 'integer',
'is_private' => 'boolean',
'id_service_categories' => 'integer',
];
/**
* @var array
*/
protected array $api_resource = [
'id' => 'id',
'name' => 'name',
'duration' => 'duration',
'price' => 'price',
'currency' => 'currency',
'description' => 'description',
'location' => 'location',
'color' => 'color',
'slotInterval' => 'slot_interval',
'attendantsNumber' => 'attendants_number',
'isPrivate' => 'is_private',
'serviceCategoryId' => 'id_service_categories',
'bufferBefore' => 'buffer_before',
'bufferAfter' => 'buffer_after',
];
/**
* Save (insert or update) a service.
*
* @param array $service Associative array with the service data.
*
* @return int Returns the service ID.
*
* @throws InvalidArgumentException
*/
public function save(array $service): int
{
$this->validate($service);
if (empty($service['id'])) {
return $this->insert($service);
} else {
return $this->update($service);
}
}
/**
* Validate the service data.
*
* @param array $service Associative array with the service data.
*
* @throws InvalidArgumentException
*/
public function validate(array $service): void
{
// If a service ID is provided then check whether the record really exists in the database.
if (!empty($service['id'])) {
$count = $this->db->get_where('services', ['id' => $service['id']])->num_rows();
if (!$count) {
throw new InvalidArgumentException(
'The provided service ID does not exist in the database: ' . $service['id'],
);
}
}
// Make sure all required fields are provided.
if (empty($service['name'])) {
throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($service, true));
}
// If a category was provided then make sure it really exists in the database.
if (!empty($service['id_service_categories'])) {
$count = $this->db
->get_where('service_categories', ['id' => $service['id_service_categories']])
->num_rows();
if (!$count) {
throw new InvalidArgumentException(
'The provided category ID was not found in the database: ' . $service['id_service_categories'],
);
}
}
// Make sure the duration value is valid.
if (!empty($service['duration'])) {
if ((int) $service['duration'] < EVENT_MINIMUM_DURATION) {
throw new InvalidArgumentException(
'The service duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes long.',
);
}
}
// Make sure the slot_interval value is valid.
if (!empty($service['slot_interval']) && (int) $service['slot_interval'] < 1) {
throw new InvalidArgumentException('The service slot interval must be at least 1 minute.');
}
// Validate the attendants number value.
if (empty($service['attendants_number']) || (int) $service['attendants_number'] < 1) {
throw new InvalidArgumentException(
'The provided attendants number is invalid: ' . $service['attendants_number'],
);
}
}
/**
* Insert a new service into the database.
*
* @param array $service Associative array with the service data.
*
* @return int Returns the service ID.
*
* @throws RuntimeException
*/
protected function insert(array $service): int
{
$service['create_datetime'] = date('Y-m-d H:i:s');
$service['update_datetime'] = date('Y-m-d H:i:s');
$provider_ids = $service['providers'] ?? [];
unset($service['providers']);
if (!$this->db->insert('services', $service)) {
throw new RuntimeException('Could not insert service.');
}
$service_id = $this->db->insert_id();
$this->set_provider_ids($service_id, $provider_ids);
return $service_id;
}
/**
* Update an existing service.
*
* @param array $service Associative array with the service data.
*
* @return int Returns the service ID.
*
* @throws RuntimeException
*/
protected function update(array $service): int
{
$service['update_datetime'] = date('Y-m-d H:i:s');
$provider_ids = $service['providers'] ?? null;
unset($service['providers']);
if (!$this->db->update('services', $service, ['id' => $service['id']])) {
throw new RuntimeException('Could not update service.');
}
if ($provider_ids !== null) {
$this->set_provider_ids($service['id'], $provider_ids);
}
return $service['id'];
}
/**
* Get the service provider IDs.
*
* @param int $service_id Service ID.
*
* @return array Returns an array of provider IDs.
*/
public function get_provider_ids(int $service_id): array
{
$service_provider_connections = $this->db
->get_where('services_providers', ['id_services' => $service_id])
->result_array();
$provider_ids = [];
foreach ($service_provider_connections as $service_provider_connection) {
$provider_ids[] = (int) $service_provider_connection['id_users'];
}
return $provider_ids;
}
/**
* Save the service provider IDs.
*
* @param int $service_id Service ID.
* @param array $provider_ids Provider IDs.
*/
public function set_provider_ids(int $service_id, array $provider_ids): void
{
// Re-insert the service-provider connections.
$this->db->delete('services_providers', ['id_services' => $service_id]);
foreach ($provider_ids as $provider_id) {
$service_provider_connection = [
'id_services' => $service_id,
'id_users' => $provider_id,
];
$this->db->insert('services_providers', $service_provider_connection);
}
}
/**
* Remove an existing service from the database.
*
* @param int $service_id Service ID.
*
* @throws RuntimeException
*/
public function delete(int $service_id): void
{
$this->db->delete('services', ['id' => $service_id]);
}
/**
* Get a specific service from the database.
*
* @param int $service_id The ID of the record to be returned.
*
* @return array Returns an array with the service data.
*
* @throws InvalidArgumentException
*/
public function find(int $service_id): array
{
$service = $this->db->get_where('services', ['id' => $service_id])->row_array();
if (!$service) {
throw new InvalidArgumentException('The provided service ID was not found in the database: ' . $service_id);
}
$this->cast($service);
return $service;
}
/**
* Get a specific field value from the database.
*
* @param int $service_id Service ID.
* @param string $field Name of the value to be returned.
*
* @return mixed Returns the selected service value from the database.
*
* @throws InvalidArgumentException
*/
public function value(int $service_id, string $field): mixed
{
if (empty($field)) {
throw new InvalidArgumentException('The field argument is cannot be empty.');
}
if (empty($service_id)) {
throw new InvalidArgumentException('The service ID argument cannot be empty.');
}
// Check whether the service exists.
$query = $this->db->get_where('services', ['id' => $service_id]);
if (!$query->num_rows()) {
throw new InvalidArgumentException('The provided service ID was not found in the database: ' . $service_id);
}
// Check if the required field is part of the service data.
$service = $query->row_array();
$this->cast($service);
if (!array_key_exists($field, $service)) {
throw new InvalidArgumentException('The requested field was not found in the service data: ' . $field);
}
return $service[$field];
}
/**
* Get all the service records that are assigned to at least one provider.
*
* @param bool $without_private Only include the public services.
*
* @return array Returns an array of services.
*/
public function get_available_services(bool $without_private = false): array
{
if ($without_private) {
$this->db->where('services.is_private', false);
}
$services = $this->db
->distinct()
->select(
'services.*, service_categories.name AS service_category_name, service_categories.id AS service_category_id',
)
->from('services')
->join('services_providers', 'services_providers.id_services = services.id', 'inner')
->join('service_categories', 'service_categories.id = services.id_service_categories', 'left')
->order_by('name ASC')
->get()
->result_array();
foreach ($services as &$service) {
$this->cast($service);
}
return $services;
}
/**
* Get all services that match the provided criteria.
*
* @param array|string|null $where Where conditions
* @param int|null $limit Record limit.
* @param int|null $offset Record offset.
* @param string|null $order_by Order by.
*
* @return array Returns an array of services.
*/
public function get(
array|string|null $where = null,
?int $limit = null,
?int $offset = null,
?string $order_by = null,
): array {
if ($where !== null) {
$this->db->where($where);
}
if ($order_by !== null) {
$this->db->order_by($this->quote_order_by($order_by));
}
$services = $this->db->get('services', $limit, $offset)->result_array();
foreach ($services as &$service) {
$this->cast($service);
}
return $services;
}
/**
* Get the query builder interface, configured for use with the services table.
*
* @return CI_DB_query_builder
*/
public function query(): CI_DB_query_builder
{
return $this->db->from('services');
}
/**
* Search services 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.
*
* @return array Returns an array of services.
*/
public function search(string $keyword, ?int $limit = null, ?int $offset = null, ?string $order_by = null): array
{
$services = $this->db
->select()
->from('services')
->group_start()
->like('name', $keyword)
->or_like('description', $keyword)
->group_end()
->limit($limit)
->offset($offset)
->order_by($this->quote_order_by($order_by))
->get()
->result_array();
foreach ($services as &$service) {
$this->cast($service);
}
return $services;
}
/**
* Get services as options for dropdowns.
*
* @param array|string|null $where Where conditions.
*
* @return array Returns an array of options with 'value' and 'label' keys.
*/
public function to_options(array|string|null $where = null): array
{
if ($where !== null) {
$this->db->where($where);
}
$services = $this->db->select('id, name')->from('services')->order_by('name')->get()->result_array();
$options = [];
foreach ($services as $service) {
$options[] = [
'value' => (int) $service['id'],
'label' => $service['name'],
];
}
return $options;
}
/**
* Load related resources to a service.
*
* @param array $service Associative array with the service data.
* @param array $resources Resource names to be attached ("category" supported).
*
* @throws InvalidArgumentException
*/
public function load(array &$service, array $resources): void
{
if (empty($service) || empty($resources)) {
return;
}
foreach ($resources as $resource) {
$service['category'] = match ($resource) {
'category' => $this->db
->get_where('service_categories', [
'id' => $service['id_service_categories'] ?? ($service['serviceCategoryId'] ?? null),
])
->row_array(),
default => throw new InvalidArgumentException(
'The requested appointment relation is not supported: ' . $resource,
),
};
}
}
/**
* Convert the database service record to the equivalent API resource.
*
* @param array $service Service data.
*/
public function api_encode(array &$service): void
{
$encoded_resource = [
'id' => array_key_exists('id', $service) ? (int) $service['id'] : null,
'name' => $service['name'],
'duration' => (int) $service['duration'],
'price' => (float) $service['price'],
'currency' => $service['currency'],
'description' => $service['description'],
'location' => $service['location'],
'slotInterval' => (int) $service['slot_interval'],
'attendantsNumber' => (int) $service['attendants_number'],
'isPrivate' => (bool) $service['is_private'],
'serviceCategoryId' =>
$service['id_service_categories'] !== null ? (int) $service['id_service_categories'] : null,
];
$service = $encoded_resource;
}
/**
* Convert the API resource to the equivalent database service record.
*
* @param array $service API resource.
* @param array|null $base Base service data to be overwritten with the provided values (useful for updates).
*/
public function api_decode(array &$service, ?array $base = null): void
{
$decoded_resource = $base ?: [];
if (array_key_exists('id', $service)) {
$decoded_resource['id'] = $service['id'];
}
if (array_key_exists('name', $service)) {
$decoded_resource['name'] = $service['name'];
}
if (array_key_exists('duration', $service)) {
$decoded_resource['duration'] = $service['duration'];
}
if (array_key_exists('price', $service)) {
$decoded_resource['price'] = $service['price'];
}
if (array_key_exists('color', $service)) {
$decoded_resource['color'] = $service['color'];
}
if (array_key_exists('currency', $service)) {
$decoded_resource['currency'] = $service['currency'];
}
if (array_key_exists('description', $service)) {
$decoded_resource['description'] = $service['description'];
}
if (array_key_exists('location', $service)) {
$decoded_resource['location'] = $service['location'];
}
if (array_key_exists('slotInterval', $service)) {
$decoded_resource['slot_interval'] = $service['slotInterval'];
}
if (array_key_exists('attendantsNumber', $service)) {
$decoded_resource['attendants_number'] = $service['attendantsNumber'];
}
if (array_key_exists('serviceCategoryId', $service)) {
$decoded_resource['id_service_categories'] = $service['serviceCategoryId'];
}
if (array_key_exists('isPrivate', $service)) {
$decoded_resource['is_private'] = (bool) $service['isPrivate'];
}
$service = $decoded_resource;
}
}