Passed
Branch develop (f6c1a1)
by
unknown
28:54
created

Holiday::updateSoldeCP()   C

Complexity

Conditions 14
Paths 19

Size

Total Lines 114
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 66
nc 19
nop 3
dl 0
loc 114
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2011		Dimitri Mouillard	<[email protected]>
3
 * Copyright (C) 2012-2014	Laurent Destailleur	<[email protected]>
4
 * Copyright (C) 2012-2016	Regis Houssin		<[email protected]>
5
 * Copyright (C) 2013		Florian Henry		<[email protected]>
6
 * Copyright (C) 2016       Juanjo Menent       <[email protected]>
7
 * Copyright (C) 2018       Frédéric France         <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
/**
24
 *    \file       holiday.class.php
25
 *    \ingroup    holiday
26
 *    \brief      Class file of the module paid holiday.
27
 */
28
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29
30
31
/**
32
 *	Class of the module paid holiday. Developed by Teclib ( http://www.teclib.com/ )
33
 */
34
class Holiday extends CommonObject
35
{
36
	/**
37
	 * @var string ID to identify managed object
38
	 */
39
	public $element = 'holiday';
40
41
	/**
42
	 * @var string Name of table without prefix where object is stored
43
	 */
44
	public $table_element = 'holiday';
45
46
	/**
47
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
48
	 * @var int
49
	 */
50
	public $ismultientitymanaged = 0;
51
52
	/**
53
	 * @var int Field with ID of parent key if this field has a parent
54
	 */
55
	public $fk_element = 'fk_holiday';
56
57
	/**
58
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
59
	 */
60
	public $picto = 'holiday';
61
62
	/**
63
	 * @deprecated
64
	 * @see $id
65
	 */
66
	public $rowid;
67
68
	/**
69
	 * @var int User ID
70
	 */
71
	public $fk_user;
72
73
	public $date_create = '';
74
75
	/**
76
	 * @var string description
77
	 */
78
	public $description;
79
80
	public $date_debut = ''; // Date start in PHP server TZ
81
	public $date_fin = ''; // Date end in PHP server TZ
82
	public $date_debut_gmt = ''; // Date start in GMT
83
	public $date_fin_gmt = ''; // Date end in GMT
84
	public $halfday = ''; // 0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
85
	public $statut = ''; // 1=draft, 2=validated, 3=approved
86
87
	/**
88
     * @var int ID
89
     */
90
	public $fk_validator;
91
92
	public $date_valid = '';
93
94
	/**
95
     * @var int ID
96
     */
97
	public $fk_user_valid;
98
99
	public $date_refuse = '';
100
101
	/**
102
     * @var int ID
103
     */
104
	public $fk_user_refuse;
105
106
	public $date_cancel = '';
107
108
	/**
109
     * @var int ID
110
     */
111
	public $fk_user_cancel;
112
113
	public $detail_refuse = '';
114
115
	/**
116
     * @var int ID
117
     */
118
	public $fk_type;
119
120
	public $holiday = array();
121
	public $events = array();
122
	public $logs = array();
123
124
	public $optName = '';
125
	public $optValue = '';
126
	public $optRowid = '';
127
128
	/**
129
	 * Draft status
130
	 */
131
	const STATUS_DRAFT = 1;
132
	/**
133
	 * Validated status
134
	 */
135
	const STATUS_VALIDATED = 2;
136
	/**
137
	 * Approved
138
	 */
139
	const STATUS_APPROVED = 3;
140
	/**
141
	 * Canceled
142
	 */
143
	const STATUS_CANCELED = 4;
144
	/**
145
	 * Refused
146
	 */
147
	const STATUS_REFUSED = 5;
148
149
150
	/**
151
	 *   Constructor
152
	 *
153
	 *   @param		DoliDB		$db      Database handler
154
	 */
155
	public function __construct($db)
156
	{
157
		$this->db = $db;
158
	}
159
160
161
	/**
162
	 *  Returns the reference to the following non used Order depending on the active numbering module
163
	 *  defined into HOLIDAY_ADDON
164
	 *
165
	 *	@param	Societe		$objsoc     third party object
166
	 *  @return string      			Holiday free reference
167
	 */
168
	public function getNextNumRef($objsoc)
169
	{
170
		global $langs, $conf;
171
		$langs->load("order");
172
173
		if (empty($conf->global->HOLIDAY_ADDON))
174
		{
175
			$conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
176
		}
177
178
		if (!empty($conf->global->HOLIDAY_ADDON))
179
		{
180
			$mybool = false;
181
182
			$file = $conf->global->HOLIDAY_ADDON.".php";
183
			$classname = $conf->global->HOLIDAY_ADDON;
184
185
			// Include file with class
186
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
187
			foreach ($dirmodels as $reldir)
188
			{
189
				$dir = dol_buildpath($reldir."core/modules/holiday/");
190
191
				// Load file with numbering class (if found)
192
				$mybool |= @include_once $dir.$file;
193
			}
194
195
			if ($mybool === false)
196
			{
197
				dol_print_error('', "Failed to include file ".$file);
198
				return '';
199
			}
200
201
			$obj = new $classname();
202
			$numref = $obj->getNextValue($objsoc, $this);
203
204
			if ($numref != "")
205
			{
206
				return $numref;
207
			} else {
208
				$this->error = $obj->error;
209
				//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
210
				return "";
211
			}
212
		} else {
213
			print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
214
			return "";
215
		}
216
	}
217
218
	/**
219
	 * Update balance of vacations and check table of users for holidays is complete. If not complete.
220
	 *
221
	 * @return	int			<0 if KO, >0 if OK
222
	 */
223
	public function updateBalance()
224
	{
225
		$this->db->begin();
226
227
		// Update sold of vocations
228
		$result = $this->updateSoldeCP();
229
230
		// Check nb of users into table llx_holiday_users and update with empty lines
231
		//if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
232
233
		if ($result >= 0)
234
		{
235
			$this->db->commit();
236
			return 1;
237
		} else {
238
			$this->db->rollback();
239
			return -1;
240
		}
241
	}
242
243
	/**
244
	 *   Créer un congés payés dans la base de données
245
	 *
246
	 *   @param		User	$user        	User that create
247
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
248
	 *   @return    int			         	<0 if KO, Id of created object if OK
249
	 */
250
	public function create($user, $notrigger = 0)
251
	{
252
		global $conf;
253
		$error = 0;
254
255
		$now = dol_now();
256
257
		// Check parameters
258
		if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error = "ErrorBadParameterFkUser"; return -1; }
259
		if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) { $this->error = "ErrorBadParameterFkValidator"; return -1; }
260
		if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error = "ErrorBadParameterFkType"; return -1; }
261
262
		// Insert request
263
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
264
		$sql .= "ref,";
265
		$sql .= "fk_user,";
266
		$sql .= "date_create,";
267
		$sql .= "description,";
268
		$sql .= "date_debut,";
269
		$sql .= "date_fin,";
270
		$sql .= "halfday,";
271
		$sql .= "statut,";
272
		$sql .= "fk_validator,";
273
		$sql .= "fk_type,";
274
		$sql .= "fk_user_create,";
275
		$sql .= "entity";
276
		$sql .= ") VALUES (";
277
		$sql .= "'(PROV)',";
278
		$sql .= "'".$this->db->escape($this->fk_user)."',";
279
		$sql .= " '".$this->db->idate($now)."',";
280
		$sql .= " '".$this->db->escape($this->description)."',";
281
		$sql .= " '".$this->db->idate($this->date_debut)."',";
282
		$sql .= " '".$this->db->idate($this->date_fin)."',";
283
		$sql .= " ".$this->halfday.",";
284
		$sql .= " '1',";
285
		$sql .= " '".$this->db->escape($this->fk_validator)."',";
286
		$sql .= " ".$this->fk_type.",";
287
		$sql .= " ".$user->id.",";
288
		$sql .= " ".$conf->entity;
289
		$sql .= ")";
290
291
		$this->db->begin();
292
293
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
294
		$resql = $this->db->query($sql);
295
		if (!$resql) {
296
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
297
		}
298
299
		if (!$error)
300
		{
301
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
302
303
			if ($this->id)
304
			{
305
				// update ref
306
				$initialref = '(PROV'.$this->id.')';
307
				if (!empty($this->ref)) $initialref = $this->ref;
308
309
				$sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
310
				if ($this->db->query($sql))
311
				{
312
					$this->ref = $initialref;
313
314
					if (!$error)
315
					{
316
						$result = $this->insertExtraFields();
317
						if ($result < 0) $error++;
318
					}
319
320
					if (!$error && !$notrigger)
321
					{
322
						// Call trigger
323
						$result = $this->call_trigger('HOLIDAY_CREATE', $user);
324
						if ($result < 0) { $error++; }
325
						// End call triggers
326
					}
327
				}
328
			}
329
		}
330
331
		// Commit or rollback
332
		if ($error)
333
		{
334
			foreach ($this->errors as $errmsg)
335
			{
336
				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
337
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
338
			}
339
			$this->db->rollback();
340
			return -1 * $error;
341
		} else {
342
			$this->db->commit();
343
			return $this->id;
344
		}
345
	}
346
347
348
	/**
349
	 *	Load object in memory from database
350
	 *
351
	 *  @param	int		$id         Id object
352
	 *  @param	string	$ref        Ref object
353
	 *  @return int         		<0 if KO, 0 if not found, >0 if OK
354
	 */
355
	public function fetch($id, $ref = '')
356
	{
357
		global $langs;
358
359
		$sql = "SELECT";
360
		$sql .= " cp.rowid,";
361
		$sql .= " cp.ref,";
362
		$sql .= " cp.fk_user,";
363
		$sql .= " cp.date_create,";
364
		$sql .= " cp.description,";
365
		$sql .= " cp.date_debut,";
366
		$sql .= " cp.date_fin,";
367
		$sql .= " cp.halfday,";
368
		$sql .= " cp.statut,";
369
		$sql .= " cp.fk_validator,";
370
		$sql .= " cp.date_valid,";
371
		$sql .= " cp.fk_user_valid,";
372
		$sql .= " cp.date_refuse,";
373
		$sql .= " cp.fk_user_refuse,";
374
		$sql .= " cp.date_cancel,";
375
		$sql .= " cp.fk_user_cancel,";
376
		$sql .= " cp.detail_refuse,";
377
		$sql .= " cp.note_private,";
378
		$sql .= " cp.note_public,";
379
		$sql .= " cp.fk_user_create,";
380
		$sql .= " cp.fk_type,";
381
		$sql .= " cp.entity";
382
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
383
		if ($id > 0) $sql .= " WHERE cp.rowid = ".$id;
384
		else $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'";
385
386
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
387
		$resql = $this->db->query($sql);
388
		if ($resql)
389
		{
390
			if ($this->db->num_rows($resql))
391
			{
392
				$obj = $this->db->fetch_object($resql);
393
394
				$this->id    = $obj->rowid;
395
				$this->ref   = ($obj->ref ? $obj->ref : $obj->rowid);
396
				$this->fk_user = $obj->fk_user;
397
				$this->date_create = $this->db->jdate($obj->date_create);
398
				$this->description = $obj->description;
399
				$this->date_debut = $this->db->jdate($obj->date_debut);
400
				$this->date_fin = $this->db->jdate($obj->date_fin);
401
				$this->date_debut_gmt = $this->db->jdate($obj->date_debut, 1);
402
				$this->date_fin_gmt = $this->db->jdate($obj->date_fin, 1);
403
				$this->halfday = $obj->halfday;
404
				$this->statut = $obj->statut;
405
				$this->fk_validator = $obj->fk_validator;
406
				$this->date_valid = $this->db->jdate($obj->date_valid);
407
				$this->fk_user_valid = $obj->fk_user_valid;
408
				$this->date_refuse = $this->db->jdate($obj->date_refuse);
409
				$this->fk_user_refuse = $obj->fk_user_refuse;
410
				$this->date_cancel = $this->db->jdate($obj->date_cancel);
411
				$this->fk_user_cancel = $obj->fk_user_cancel;
412
				$this->detail_refuse = $obj->detail_refuse;
413
				$this->note_private = $obj->note_private;
414
				$this->note_public = $obj->note_public;
415
				$this->fk_user_create = $obj->fk_user_create;
416
				$this->fk_type = $obj->fk_type;
417
				$this->entity = $obj->entity;
418
419
				$this->fetch_optionals();
420
421
				$result = 1;
422
			} else {
423
				$result = 0;
424
			}
425
			$this->db->free($resql);
426
427
			return $result;
428
		} else {
429
			$this->error = "Error ".$this->db->lasterror();
430
			return -1;
431
		}
432
	}
433
434
	/**
435
	 *	List holidays for a particular user or list of users
436
	 *
437
	 *  @param		int|string		$user_id    ID of user to list, or comma separated list of IDs of users to list
438
	 *  @param      string			$order      Sort order
439
	 *  @param      string			$filter     SQL Filter
440
	 *  @return     int      					-1 if KO, 1 if OK, 2 if no result
441
	 */
442
	public function fetchByUser($user_id, $order = '', $filter = '')
443
	{
444
		global $langs, $conf;
445
446
		$sql = "SELECT";
447
		$sql .= " cp.rowid,";
448
		$sql .= " cp.ref,";
449
450
		$sql .= " cp.fk_user,";
451
		$sql .= " cp.fk_type,";
452
		$sql .= " cp.date_create,";
453
		$sql .= " cp.description,";
454
		$sql .= " cp.date_debut,";
455
		$sql .= " cp.date_fin,";
456
		$sql .= " cp.halfday,";
457
		$sql .= " cp.statut,";
458
		$sql .= " cp.fk_validator,";
459
		$sql .= " cp.date_valid,";
460
		$sql .= " cp.fk_user_valid,";
461
		$sql .= " cp.date_refuse,";
462
		$sql .= " cp.fk_user_refuse,";
463
		$sql .= " cp.date_cancel,";
464
		$sql .= " cp.fk_user_cancel,";
465
		$sql .= " cp.detail_refuse,";
466
467
		$sql .= " uu.lastname as user_lastname,";
468
		$sql .= " uu.firstname as user_firstname,";
469
		$sql .= " uu.login as user_login,";
470
		$sql .= " uu.statut as user_statut,";
471
		$sql .= " uu.photo as user_photo,";
472
473
		$sql .= " ua.lastname as validator_lastname,";
474
		$sql .= " ua.firstname as validator_firstname,";
475
		$sql .= " ua.login as validator_login,";
476
		$sql .= " ua.statut as validator_statut,";
477
		$sql .= " ua.photo as validator_photo";
478
479
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
480
		$sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
481
		$sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack pour la recherche sur le tableau
482
		$sql .= " AND cp.fk_user IN (".$user_id.")";
483
484
		// Selection filter
485
		if (!empty($filter)) {
486
			$sql .= $filter;
487
		}
488
489
		// Order of display of the result
490
		if (!empty($order)) {
491
			$sql .= $order;
492
		}
493
494
		dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
495
		$resql = $this->db->query($sql);
496
497
		// If no SQL error
498
		if ($resql) {
499
			$i = 0;
500
			$tab_result = $this->holiday;
501
			$num = $this->db->num_rows($resql);
502
503
			// If no registration
504
			if (!$num) {
505
				return 2;
506
			}
507
508
			// List the records and add them to the table
509
			while ($i < $num) {
510
				$obj = $this->db->fetch_object($resql);
511
512
				$tab_result[$i]['rowid'] = $obj->rowid;
513
				$tab_result[$i]['ref'] = ($obj->ref ? $obj->ref : $obj->rowid);
514
515
				$tab_result[$i]['fk_user'] = $obj->fk_user;
516
				$tab_result[$i]['fk_type'] = $obj->fk_type;
517
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
518
				$tab_result[$i]['description'] = $obj->description;
519
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
520
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
521
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
522
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
523
				$tab_result[$i]['halfday'] = $obj->halfday;
524
				$tab_result[$i]['statut'] = $obj->statut;
525
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
526
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
527
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
528
				$tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
529
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
530
				$tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
531
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
532
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
533
534
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
535
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
536
				$tab_result[$i]['user_login'] = $obj->user_login;
537
				$tab_result[$i]['user_statut'] = $obj->user_statut;
538
				$tab_result[$i]['user_photo'] = $obj->user_photo;
539
540
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
541
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
542
				$tab_result[$i]['validator_login'] = $obj->validator_login;
543
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
544
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
545
546
				$i++;
547
			}
548
549
			// Returns 1 with the filled array
550
			$this->holiday = $tab_result;
551
			return 1;
552
		} else {
553
			// SQL Error
554
			$this->error = "Error ".$this->db->lasterror();
555
			return -1;
556
		}
557
	}
558
559
	/**
560
	 *	List all holidays of all users
561
	 *
562
	 *  @param      string	$order      Sort order
563
	 *  @param      string	$filter     SQL Filter
564
	 *  @return     int      			-1 if KO, 1 if OK, 2 if no result
565
	 */
566
	public function fetchAll($order, $filter)
567
	{
568
		global $langs;
569
570
		$sql = "SELECT";
571
		$sql .= " cp.rowid,";
572
		$sql .= " cp.ref,";
573
574
		$sql .= " cp.fk_user,";
575
		$sql .= " cp.fk_type,";
576
		$sql .= " cp.date_create,";
577
		$sql .= " cp.tms as date_update,";
578
		$sql .= " cp.description,";
579
		$sql .= " cp.date_debut,";
580
		$sql .= " cp.date_fin,";
581
		$sql .= " cp.halfday,";
582
		$sql .= " cp.statut,";
583
		$sql .= " cp.fk_validator,";
584
		$sql .= " cp.date_valid,";
585
		$sql .= " cp.fk_user_valid,";
586
		$sql .= " cp.date_refuse,";
587
		$sql .= " cp.fk_user_refuse,";
588
		$sql .= " cp.date_cancel,";
589
		$sql .= " cp.fk_user_cancel,";
590
		$sql .= " cp.detail_refuse,";
591
592
		$sql .= " uu.lastname as user_lastname,";
593
		$sql .= " uu.firstname as user_firstname,";
594
		$sql .= " uu.login as user_login,";
595
		$sql .= " uu.statut as user_statut,";
596
		$sql .= " uu.photo as user_photo,";
597
598
		$sql .= " ua.lastname as validator_lastname,";
599
		$sql .= " ua.firstname as validator_firstname,";
600
		$sql .= " ua.login as validator_login,";
601
		$sql .= " ua.statut as validator_statut,";
602
		$sql .= " ua.photo as validator_photo";
603
604
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
605
		$sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
606
		$sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau
607
608
		// Selection filtering
609
		if (!empty($filter)) {
610
			$sql .= $filter;
611
		}
612
613
		// order of display
614
		if (!empty($order)) {
615
			$sql .= $order;
616
		}
617
618
		dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
619
		$resql = $this->db->query($sql);
620
621
		// If no SQL error
622
		if ($resql) {
623
			$i = 0;
624
			$tab_result = $this->holiday;
625
			$num = $this->db->num_rows($resql);
626
627
			// If no registration
628
			if (!$num) {
629
				return 2;
630
			}
631
632
			// List the records and add them to the table
633
			while ($i < $num) {
634
				$obj = $this->db->fetch_object($resql);
635
636
				$tab_result[$i]['rowid'] = $obj->rowid;
637
				$tab_result[$i]['ref'] = ($obj->ref ? $obj->ref : $obj->rowid);
638
				$tab_result[$i]['fk_user'] = $obj->fk_user;
639
				$tab_result[$i]['fk_type'] = $obj->fk_type;
640
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
641
				$tab_result[$i]['date_update'] = $this->db->jdate($obj->date_update);
642
				$tab_result[$i]['description'] = $obj->description;
643
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
644
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
645
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
646
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
647
				$tab_result[$i]['halfday'] = $obj->halfday;
648
				$tab_result[$i]['statut'] = $obj->statut;
649
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
650
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
651
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
652
				$tab_result[$i]['date_refuse'] = $obj->date_refuse;
653
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
654
				$tab_result[$i]['date_cancel'] = $obj->date_cancel;
655
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
656
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
657
658
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
659
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
660
				$tab_result[$i]['user_login'] = $obj->user_login;
661
				$tab_result[$i]['user_statut'] = $obj->user_statut;
662
				$tab_result[$i]['user_photo'] = $obj->user_photo;
663
664
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
665
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
666
				$tab_result[$i]['validator_login'] = $obj->validator_login;
667
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
668
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
669
670
				$i++;
671
			}
672
			// Returns 1 and adds the array to the variable
673
			$this->holiday = $tab_result;
674
			return 1;
675
		} else {
676
			// SQL Error
677
			$this->error = "Error ".$this->db->lasterror();
678
			return -1;
679
		}
680
	}
681
682
683
	/**
684
	 *	Validate leave request
685
	 *
686
	 *  @param	User	$user        	User that validate
687
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
688
	 *  @return int         			<0 if KO, >0 if OK
689
	 */
690
	public function validate($user = null, $notrigger = 0)
691
	{
692
		global $conf, $langs;
693
		$error = 0;
694
695
		// Define new ref
696
		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id))
697
		{
698
			$num = $this->getNextNumRef(null);
699
		} else {
700
			$num = $this->ref;
701
		}
702
		$this->newref = dol_sanitizeFileName($num);
703
704
		// Update status
705
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
706
		if (!empty($this->statut) && is_numeric($this->statut)) {
707
			$sql .= " statut = ".$this->statut.",";
708
		} else {
709
			$error++;
710
		}
711
		$sql .= " ref = '".$this->db->escape($num)."'";
712
		$sql .= " WHERE rowid= ".$this->id;
713
714
		$this->db->begin();
715
716
		dol_syslog(get_class($this)."::validate", LOG_DEBUG);
717
		$resql = $this->db->query($sql);
718
		if (!$resql) {
719
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
720
		}
721
722
		if (!$error)
723
		{
724
			if (!$notrigger)
725
			{
726
				// Call trigger
727
				$result = $this->call_trigger('HOLIDAY_VALIDATE', $user);
728
				if ($result < 0) { $error++; }
729
				// End call triggers
730
			}
731
		}
732
733
		// Commit or rollback
734
		if ($error)
735
		{
736
			foreach ($this->errors as $errmsg)
737
			{
738
				dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
739
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
740
			}
741
			$this->db->rollback();
742
			return -1 * $error;
743
		} else {
744
			$this->db->commit();
745
			return 1;
746
		}
747
	}
748
749
750
	/**
751
	 *	Approve leave request
752
	 *
753
	 *  @param	User	$user        	User that approve
754
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
755
	 *  @return int         			<0 if KO, >0 if OK
756
	 */
757
	public function approve($user = null, $notrigger = 0)
758
	{
759
		global $conf, $langs;
760
		$error = 0;
761
762
		// Update request
763
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
764
765
		$sql .= " description= '".$this->db->escape($this->description)."',";
766
767
		if (!empty($this->date_debut)) {
768
			$sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
769
		} else {
770
			$error++;
771
		}
772
		if (!empty($this->date_fin)) {
773
			$sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
774
		} else {
775
			$error++;
776
		}
777
		$sql .= " halfday = ".$this->halfday.",";
778
		if (!empty($this->statut) && is_numeric($this->statut)) {
779
			$sql .= " statut = ".$this->statut.",";
780
		} else {
781
			$error++;
782
		}
783
		if (!empty($this->fk_validator)) {
784
			$sql .= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
785
		} else {
786
			$error++;
787
		}
788
		if (!empty($this->date_valid)) {
789
			$sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
790
		} else {
791
			$sql .= " date_valid = NULL,";
792
		}
793
		if (!empty($this->fk_user_valid)) {
794
			$sql .= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
795
		} else {
796
			$sql .= " fk_user_valid = NULL,";
797
		}
798
		if (!empty($this->date_refuse)) {
799
			$sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
800
		} else {
801
			$sql .= " date_refuse = NULL,";
802
		}
803
		if (!empty($this->fk_user_refuse)) {
804
			$sql .= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
805
		} else {
806
			$sql .= " fk_user_refuse = NULL,";
807
		}
808
		if (!empty($this->date_cancel)) {
809
			$sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
810
		} else {
811
			$sql .= " date_cancel = NULL,";
812
		}
813
		if (!empty($this->fk_user_cancel)) {
814
			$sql .= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
815
		} else {
816
			$sql .= " fk_user_cancel = NULL,";
817
		}
818
		if (!empty($this->detail_refuse)) {
819
			$sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
820
		} else {
821
			$sql .= " detail_refuse = NULL";
822
		}
823
824
		$sql .= " WHERE rowid= ".$this->id;
825
826
		$this->db->begin();
827
828
		dol_syslog(get_class($this)."::approve", LOG_DEBUG);
829
		$resql = $this->db->query($sql);
830
		if (!$resql) {
831
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
832
		}
833
834
		if (!$error)
835
		{
836
			if (!$notrigger)
837
			{
838
				// Call trigger
839
				$result = $this->call_trigger('HOLIDAY_APPROVE', $user);
840
				if ($result < 0) { $error++; }
841
				// End call triggers
842
			}
843
		}
844
845
		// Commit or rollback
846
		if ($error)
847
		{
848
			foreach ($this->errors as $errmsg)
849
			{
850
				dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
851
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
852
			}
853
			$this->db->rollback();
854
			return -1 * $error;
855
		} else {
856
			$this->db->commit();
857
			return 1;
858
		}
859
	}
860
861
	/**
862
	 *	Update database
863
	 *
864
	 *  @param	User	$user        	User that modify
865
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
866
	 *  @return int         			<0 if KO, >0 if OK
867
	 */
868
	public function update($user = null, $notrigger = 0)
869
	{
870
		global $conf, $langs;
871
		$error = 0;
872
873
		// Update request
874
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
875
876
		$sql .= " description= '".$this->db->escape($this->description)."',";
877
878
		if (!empty($this->date_debut)) {
879
			$sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
880
		} else {
881
			$error++;
882
		}
883
		if (!empty($this->date_fin)) {
884
			$sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
885
		} else {
886
			$error++;
887
		}
888
		$sql .= " halfday = ".$this->halfday.",";
889
		if (!empty($this->statut) && is_numeric($this->statut)) {
890
			$sql .= " statut = ".$this->statut.",";
891
		} else {
892
			$error++;
893
		}
894
		if (!empty($this->fk_validator)) {
895
			$sql .= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
896
		} else {
897
			$error++;
898
		}
899
		if (!empty($this->date_valid)) {
900
			$sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
901
		} else {
902
			$sql .= " date_valid = NULL,";
903
		}
904
		if (!empty($this->fk_user_valid)) {
905
			$sql .= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
906
		} else {
907
			$sql .= " fk_user_valid = NULL,";
908
		}
909
		if (!empty($this->date_refuse)) {
910
			$sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
911
		} else {
912
			$sql .= " date_refuse = NULL,";
913
		}
914
		if (!empty($this->fk_user_refuse)) {
915
			$sql .= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
916
		} else {
917
			$sql .= " fk_user_refuse = NULL,";
918
		}
919
		if (!empty($this->date_cancel)) {
920
			$sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
921
		} else {
922
			$sql .= " date_cancel = NULL,";
923
		}
924
		if (!empty($this->fk_user_cancel)) {
925
			$sql .= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
926
		} else {
927
			$sql .= " fk_user_cancel = NULL,";
928
		}
929
		if (!empty($this->detail_refuse)) {
930
			$sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
931
		} else {
932
			$sql .= " detail_refuse = NULL";
933
		}
934
935
		$sql .= " WHERE rowid= ".$this->id;
936
937
		$this->db->begin();
938
939
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
940
		$resql = $this->db->query($sql);
941
		if (!$resql) {
942
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
943
		}
944
945
		if (!$error)
946
		{
947
			if (!$notrigger)
948
			{
949
				// Call trigger
950
				$result = $this->call_trigger('HOLIDAY_MODIFY', $user);
951
				if ($result < 0) { $error++; }
952
				// End call triggers
953
			}
954
		}
955
956
		// Commit or rollback
957
		if ($error)
958
		{
959
			foreach ($this->errors as $errmsg)
960
			{
961
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
962
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
963
			}
964
			$this->db->rollback();
965
			return -1 * $error;
966
		} else {
967
			$this->db->commit();
968
			return 1;
969
		}
970
	}
971
972
973
	/**
974
	 *   Delete object in database
975
	 *
976
	 *	 @param		User	$user        	User that delete
977
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
978
	 *	 @return	int						<0 if KO, >0 if OK
979
	 */
980
	public function delete($user, $notrigger = 0)
981
	{
982
		global $conf, $langs;
983
		$error = 0;
984
985
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
986
		$sql .= " WHERE rowid=".$this->id;
987
988
		$this->db->begin();
989
990
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
991
		$resql = $this->db->query($sql);
992
		if (!$resql) {
993
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
994
		}
995
996
		if (!$error)
997
		{
998
			if (!$notrigger)
999
			{
1000
				// Call trigger
1001
				$result = $this->call_trigger('HOLIDAY_DELETE', $user);
1002
				if ($result < 0) { $error++; }
1003
				// End call triggers
1004
			}
1005
		}
1006
1007
		// Commit or rollback
1008
		if ($error)
1009
		{
1010
			foreach ($this->errors as $errmsg)
1011
			{
1012
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1013
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1014
			}
1015
			$this->db->rollback();
1016
			return -1 * $error;
1017
		} else {
1018
			$this->db->commit();
1019
			return 1;
1020
		}
1021
	}
1022
1023
	/**
1024
	 *	Check if a user is on holiday (partially or completely) into a period.
1025
	 *  This function can be used to avoid to have 2 leave requests on same period for example.
1026
	 *  Warning: It consumes a lot of memory because it load in ->holiday all holiday of a dedicated user at each call.
1027
	 *
1028
	 *  @param 	int		$fk_user		Id user
1029
	 *  @param 	integer	$dateStart		Start date of period to check
1030
	 *  @param 	integer	$dateEnd		End date of period to check
1031
	 *  @param  int     $halfday        Tag to define how start and end the period to check:
1032
	 *                                  0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
1033
	 * 	@return boolean					False = New range overlap an existing holiday, True = no overlapping (is never on holiday during checked period).
1034
	 *  @see verifDateHolidayForTimestamp()
1035
	 */
1036
	public function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday = 0)
1037
	{
1038
		$this->fetchByUser($fk_user, '', '');
1039
1040
		foreach ($this->holiday as $infos_CP)
1041
		{
1042
			if ($infos_CP['statut'] == 4) continue; // ignore not validated holidays
1043
			if ($infos_CP['statut'] == 5) continue; // ignore not validated holidays
1044
			/*
1045
			 var_dump("--");
1046
			 var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1047
			 var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1048
			 */
1049
1050
			if ($halfday == 0)
1051
			{
1052
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1053
				{
1054
					return false;
1055
				}
1056
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1057
				{
1058
					return false;
1059
				}
1060
			} elseif ($halfday == -1)
1061
			{
1062
				// new start afternoon, new end afternoon
1063
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1064
				{
1065
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1066
				}
1067
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1068
				{
1069
					if ($dateStart < $dateEnd) return false;
1070
					if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1071
				}
1072
			} elseif ($halfday == 1)
1073
			{
1074
				// new start morning, new end morning
1075
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1076
				{
1077
					if ($dateStart < $dateEnd) return false;
1078
					if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1079
				}
1080
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1081
				{
1082
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1083
				}
1084
			} elseif ($halfday == 2)
1085
			{
1086
				// new start afternoon, new end morning
1087
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
1088
				{
1089
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
1090
				}
1091
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
1092
				{
1093
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
1094
				}
1095
			} else {
1096
				dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1097
			}
1098
		}
1099
1100
		return true;
1101
	}
1102
1103
1104
	/**
1105
	 *	Check that a user is not on holiday for a particular timestamp
1106
	 *
1107
	 * 	@param 	int			$fk_user				Id user
1108
	 *  @param	integer	    $timestamp				Time stamp date for a day (YYYY-MM-DD) without hours  (= 12:00AM in english and not 12:00PM that is 12:00)
1109
	 *  @param	string		$status					Filter on holiday status. '-1' = no filter.
1110
	 * 	@return array								array('morning'=> ,'afternoon'=> ), Boolean is true if user is available for day timestamp.
1111
	 *  @see verifDateHolidayCP()
1112
	 */
1113
	public function verifDateHolidayForTimestamp($fk_user, $timestamp, $status = '-1')
1114
	{
1115
		global $langs, $conf;
1116
1117
		$isavailablemorning = true;
1118
		$isavailableafternoon = true;
1119
1120
		$sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut";
1121
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1122
		$sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
1123
		$sql .= " AND cp.fk_user = ".(int) $fk_user;
1124
		$sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1125
		if ($status != '-1') $sql .= " AND cp.statut IN (".$this->db->escape($status).")";
1126
1127
		$resql = $this->db->query($sql);
1128
		if ($resql)
1129
		{
1130
			$num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon
1131
			if ($num_rows > 0)
1132
			{
1133
				$arrayofrecord = array();
1134
				$i = 0;
1135
				while ($i < $num_rows)
1136
				{
1137
					$obj = $this->db->fetch_object($resql);
1138
1139
					// Note: $obj->halfday is  0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning
1140
					$arrayofrecord[$obj->rowid] = array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday);
1141
					$i++;
1142
				}
1143
1144
				// We found a record, user is on holiday by default, so is not available is true.
1145
				$isavailablemorning = true;
1146
				foreach ($arrayofrecord as $record)
1147
				{
1148
					if ($timestamp == $record['date_start'] && $record['halfday'] == 2)  continue;
1149
					if ($timestamp == $record['date_start'] && $record['halfday'] == -1) continue;
1150
					$isavailablemorning = false;
1151
					break;
1152
				}
1153
				$isavailableafternoon = true;
1154
				foreach ($arrayofrecord as $record)
1155
				{
1156
					if ($timestamp == $record['date_end'] && $record['halfday'] == 2) continue;
1157
					if ($timestamp == $record['date_end'] && $record['halfday'] == 1) continue;
1158
					$isavailableafternoon = false;
1159
					break;
1160
				}
1161
			}
1162
		} else dol_print_error($this->db);
1163
1164
		return array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon);
1165
	}
1166
1167
1168
	/**
1169
	 *	Return clicable name (with picto eventually)
1170
	 *
1171
	 *	@param	int			$withpicto					0=_No picto, 1=Includes the picto in the linkn, 2=Picto only
1172
	 *  @param  int     	$save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1173
	 *	@return	string									String with URL
1174
	 */
1175
	public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
1176
	{
1177
		global $langs;
1178
1179
		$result = '';
1180
1181
		$label = $langs->trans("Show").': '.$this->ref;
1182
1183
		$url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1184
1185
		//if ($option != 'nolink')
1186
		//{
1187
		// Add param to save lastsearch_values or not
1188
		$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1189
		if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1190
		if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1191
		//}
1192
1193
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1194
		$linkend = '</a>';
1195
1196
		$result .= $linkstart;
1197
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $notooltip seems to be never defined.
Loading history...
1198
		if ($withpicto != 2) $result .= $this->ref;
1199
		$result .= $linkend;
1200
1201
		return $result;
1202
	}
1203
1204
1205
	/**
1206
	 *	Returns the label status
1207
	 *
1208
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1209
	 *	@return     string      		Label
1210
	 */
1211
	public function getLibStatut($mode = 0)
1212
	{
1213
		return $this->LibStatut($this->statut, $mode, $this->date_debut);
1214
	}
1215
1216
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217
	/**
1218
	 *	Returns the label of a status
1219
	 *
1220
	 *	@param      int		$status     Id status
1221
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1222
	 *  @param		integer	$startdate	Date holiday should start
1223
	 *	@return     string      		Label
1224
	 */
1225
	public function LibStatut($status, $mode = 0, $startdate = '')
1226
	{
1227
		// phpcs:enable
1228
		if (empty($this->labelStatus) || empty($this->labelStatusShort))
1229
		{
1230
			global $langs;
1231
			//$langs->load("mymodule");
1232
			$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('DraftCP');
1233
			$this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ToReviewCP');
1234
			$this->labelStatus[self::STATUS_APPROVED] = $langs->trans('ApprovedCP');
1235
			$this->labelStatus[self::STATUS_CANCELED] = $langs->trans('CancelCP');
1236
			$this->labelStatus[self::STATUS_REFUSED] = $langs->trans('RefuseCP');
1237
			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('DraftCP');
1238
			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('ToReviewCP');
1239
			$this->labelStatusShort[self::STATUS_APPROVED] = $langs->trans('ApprovedCP');
1240
			$this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('CancelCP');
1241
			$this->labelStatusShort[self::STATUS_REFUSED] = $langs->trans('RefuseCP');
1242
		}
1243
1244
		$statusType = 'status6';
1245
		if (!empty($startdate) && $startdate > dol_now()) $statusType = 'status4';
1246
		if ($status == self::STATUS_DRAFT) $statusType = 'status0';
1247
		if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1248
		if ($status == self::STATUS_CANCELED) $statusType = 'status5';
1249
		if ($status == self::STATUS_REFUSED) $statusType = 'status5';
1250
1251
		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1252
	}
1253
1254
1255
	/**
1256
	 *   Affiche un select HTML des statuts de congés payés
1257
	 *
1258
	 *   @param 	int		$selected   	Id of preselected status
1259
	 *   @param		string	$htmlname		Name of HTML select field
1260
	 *   @return    string					Show select of status
1261
	 */
1262
    public function selectStatutCP($selected = '', $htmlname = 'select_statut')
1263
    {
1264
1265
		global $langs;
1266
1267
		// Liste des statuts
1268
		$name = array('DraftCP', 'ToReviewCP', 'ApprovedCP', 'CancelCP', 'RefuseCP');
1269
		$nb = count($name) + 1;
1270
1271
		// Select HTML
1272
		$statut = '<select name="'.$htmlname.'" class="flat">'."\n";
1273
		$statut .= '<option value="-1">&nbsp;</option>'."\n";
1274
1275
		// Boucle des statuts
1276
		for ($i = 1; $i < $nb; $i++) {
1277
			if ($i == $selected) {
1278
				$statut .= '<option value="'.$i.'" selected>'.$langs->trans($name[$i - 1]).'</option>'."\n";
1279
			} else {
1280
				$statut .= '<option value="'.$i.'">'.$langs->trans($name[$i - 1]).'</option>'."\n";
1281
			}
1282
		}
1283
1284
		$statut .= '</select>'."\n";
1285
		print $statut;
1286
	}
1287
1288
	/**
1289
	 *  Met à jour une option du module Holiday Payés
1290
	 *
1291
	 *  @param	string	$name       name du paramètre de configuration
1292
	 *  @param	string	$value      vrai si mise à jour OK sinon faux
1293
	 *  @return boolean				ok or ko
1294
	 */
1295
    public function updateConfCP($name, $value)
1296
    {
1297
1298
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1299
		$sql .= " value = '".$value."'";
1300
		$sql .= " WHERE name = '".$name."'";
1301
1302
		dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG);
1303
		$result = $this->db->query($sql);
1304
		if ($result) {
1305
			return true;
1306
		}
1307
1308
		return false;
1309
	}
1310
1311
	/**
1312
	 *  Return value of a conf parameterfor leave module
1313
	 *  TODO Move this into llx_const table
1314
	 *
1315
	 *  @param	string	$name                 Name of parameter
1316
	 *  @param  string  $createifnotfound     'stringvalue'=Create entry with string value if not found. For example 'YYYYMMDDHHMMSS'.
1317
	 *  @return string      		          Value of parameter. Example: 'YYYYMMDDHHMMSS' or < 0 if error
1318
	 */
1319
	public function getConfCP($name, $createifnotfound = '')
1320
	{
1321
		$sql = "SELECT value";
1322
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1323
		$sql .= " WHERE name = '".$this->db->escape($name)."'";
1324
1325
		dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1326
		$result = $this->db->query($sql);
1327
1328
		if ($result) {
1329
			$obj = $this->db->fetch_object($result);
1330
			// Return value
1331
			if (empty($obj))
1332
			{
1333
				if ($createifnotfound)
1334
				{
1335
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1336
					$sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1337
					$result = $this->db->query($sql);
1338
					if ($result)
1339
					{
1340
						return $createifnotfound;
1341
					} else {
1342
						$this->error = $this->db->lasterror();
1343
						return -2;
1344
					}
1345
				} else {
1346
					return '';
1347
				}
1348
			} else {
1349
				return $obj->value;
1350
			}
1351
		} else {
1352
			// Erreur SQL
1353
			$this->error = $this->db->lasterror();
1354
			return -1;
1355
		}
1356
	}
1357
1358
	/**
1359
	 *	Met à jour le timestamp de la dernière mise à jour du solde des CP
1360
	 *
1361
	 *	@param		int		$userID		Id of user
1362
	 *	@param		int		$nbHoliday	Nb of days
1363
	 *  @param		int		$fk_type	Type of vacation
1364
	 *  @return     int					0=Nothing done, 1=OK, -1=KO
1365
	 */
1366
	public function updateSoldeCP($userID = '', $nbHoliday = '', $fk_type = '')
1367
	{
1368
		global $user, $langs;
1369
1370
		$error = 0;
1371
1372
		if (empty($userID) && empty($nbHoliday) && empty($fk_type))
1373
		{
1374
			$langs->load("holiday");
1375
1376
			// Si mise à jour pour tout le monde en début de mois
1377
			$now = dol_now();
1378
1379
			$month = date('m', $now);
1380
			$newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S');
1381
1382
			// Get month of last update
1383
			$lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate);
1384
			$monthLastUpdate = $lastUpdate[4].$lastUpdate[5];
1385
			//print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit;
1386
1387
			// Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp
1388
			if ($month != $monthLastUpdate)
1389
			{
1390
				$this->db->begin();
1391
1392
				$users = $this->fetchUsers(false, false);
1393
				$nbUser = count($users);
1394
1395
				$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1396
				$sql .= " value = '".$this->db->escape($newdateforlastupdate)."'";
1397
				$sql .= " WHERE name = 'lastUpdate'";
1398
				$result = $this->db->query($sql);
1399
1400
				$typeleaves = $this->getTypes(1, 1);
1401
1402
				// Update each user counter
1403
				foreach ($users as $userCounter) {
0 ignored issues
show
Bug introduced by
The expression $users of type integer is not traversable.
Loading history...
1404
					$nbDaysToAdd = $typeleaves[$userCounter['type']]['newByMonth'];
1405
					if (empty($nbDaysToAdd)) continue;
1406
1407
					dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG);
1408
1409
					$nowHoliday = $userCounter['nb_holiday'];
1410
					$newSolde = $nowHoliday + $nbDaysToAdd;
1411
1412
					// We add a log for each user
1413
					$this->addLogCP($user->id, $userCounter['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $newSolde, $userCounter['type']);
1414
1415
					$result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type'], $langs->trans('HolidaysMonthlyUpdate'));
1416
1417
					if ($result < 0)
1418
					{
1419
						$error++;
1420
						break;
1421
					}
1422
				}
1423
1424
				if (!$error)
1425
				{
1426
					$this->db->commit();
1427
					return 1;
1428
				} else {
1429
					$this->db->rollback();
1430
					return -1;
1431
				}
1432
			}
1433
1434
			return 0;
1435
		} else {
1436
			// Mise à jour pour un utilisateur
1437
			$nbHoliday = price2num($nbHoliday, 5);
1438
1439
			$sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1440
			$sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1441
			$resql = $this->db->query($sql);
1442
			if ($resql)
1443
			{
1444
				$num = $this->db->num_rows($resql);
1445
1446
				if ($num > 0)
1447
				{
1448
					// Update for user
1449
					$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1450
					$sql .= " nb_holiday = ".$nbHoliday;
1451
					$sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1452
					$result = $this->db->query($sql);
1453
					if (!$result)
1454
					{
1455
						$error++;
1456
						$this->errors[] = $this->db->lasterror();
1457
					}
1458
				} else {
1459
					// Insert for user
1460
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1461
					$sql .= $nbHoliday;
1462
					$sql .= ", ".(int) $userID.", ".(int) $fk_type.")";
1463
					$result = $this->db->query($sql);
1464
					if (!$result)
1465
					{
1466
						$error++;
1467
						$this->errors[] = $this->db->lasterror();
1468
					}
1469
				}
1470
			} else {
1471
				$this->errors[] = $this->db->lasterror();
1472
				$error++;
1473
			}
1474
1475
			if (!$error)
1476
			{
1477
				return 1;
1478
			} else {
1479
				return -1;
1480
			}
1481
		}
1482
	}
1483
1484
	/**
1485
	 *	Retourne un checked si vrai
1486
	 *
1487
	 *  @param	string	$name       name du paramètre de configuration
1488
	 *  @return string      		retourne checked si > 0
1489
	 */
1490
    public function getCheckOption($name)
1491
    {
1492
1493
		$sql = "SELECT value";
1494
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1495
		$sql .= " WHERE name = '".$name."'";
1496
1497
		$result = $this->db->query($sql);
1498
1499
		if ($result) {
1500
			$obj = $this->db->fetch_object($result);
1501
1502
			// Si la valeur est 1 on retourne checked
1503
			if ($obj->value) {
1504
				return 'checked';
1505
			}
1506
		}
1507
	}
1508
1509
1510
	/**
1511
	 *  Créer les entrées pour chaque utilisateur au moment de la configuration
1512
	 *
1513
	 *  @param	boolean		$single		Single
1514
	 *  @param	int			$userid		Id user
1515
	 *  @return void
1516
	 */
1517
	public function createCPusers($single = false, $userid = '')
1518
	{
1519
		// Si c'est l'ensemble des utilisateurs à ajouter
1520
		if (!$single)
1521
		{
1522
			dol_syslog(get_class($this).'::createCPusers');
1523
			$arrayofusers = $this->fetchUsers(false, true);
1524
1525
			foreach ($arrayofusers as $users)
0 ignored issues
show
Bug introduced by
The expression $arrayofusers of type integer is not traversable.
Loading history...
1526
			{
1527
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1528
				$sql .= " (fk_user, nb_holiday)";
1529
				$sql .= " VALUES ('".$users['rowid']."','0')";
1530
1531
				$resql = $this->db->query($sql);
1532
				if (!$resql) dol_print_error($this->db);
1533
			}
1534
		} else {
1535
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1536
			$sql .= " (fk_user, nb_holiday)";
1537
			$sql .= " VALUES ('".$userid."','0')";
1538
1539
			$resql = $this->db->query($sql);
1540
			if (!$resql) dol_print_error($this->db);
1541
		}
1542
	}
1543
1544
	/**
1545
	 *  Supprime un utilisateur du module Congés Payés
1546
	 *
1547
	 *  @param	int		$user_id        ID de l'utilisateur à supprimer
1548
	 *  @return boolean      			Vrai si pas d'erreur, faut si Erreur
1549
	 */
1550
    public function deleteCPuser($user_id)
1551
    {
1552
1553
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users";
1554
		$sql .= " WHERE fk_user = '".$user_id."'";
1555
1556
		$this->db->query($sql);
1557
	}
1558
1559
1560
	/**
1561
	 *  Retourne le solde de congés payés pour un utilisateur
1562
	 *
1563
	 *  @param	int		$user_id    ID de l'utilisateur
1564
	 *  @param	int		$fk_type	Filter on type
1565
	 *  @return float        		Retourne le solde de congés payés de l'utilisateur
1566
	 */
1567
	public function getCPforUser($user_id, $fk_type = 0)
1568
	{
1569
		$sql = "SELECT nb_holiday";
1570
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday_users";
1571
		$sql .= " WHERE fk_user = ".(int) $user_id;
1572
		if ($fk_type > 0) $sql .= " AND fk_type = ".(int) $fk_type;
1573
1574
		dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG);
1575
		$result = $this->db->query($sql);
1576
		if ($result)
1577
		{
1578
			$obj = $this->db->fetch_object($result);
1579
			//return number_format($obj->nb_holiday,2);
1580
			if ($obj) return $obj->nb_holiday;
1581
			else return null;
1582
		} else {
1583
			return null;
1584
		}
1585
	}
1586
1587
	/**
1588
	 *    Get list of Users or list of vacation balance.
1589
	 *
1590
	 *    @param      boolean			$stringlist	    If true return a string list of id. If false, return an array with detail.
1591
	 *    @param      boolean   		$type			If true, read Dolibarr user list, if false, return vacation balance list.
1592
	 *    @param      string            $filters        Filters
1593
	 *    @return     array|string|int      			Return an array
1594
	 */
1595
	public function fetchUsers($stringlist = true, $type = true, $filters = '')
1596
	{
1597
		global $conf;
1598
1599
		dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1600
1601
		if ($stringlist)
1602
		{
1603
			if ($type)
1604
			{
1605
				// If user of Dolibarr
1606
				$sql = "SELECT";
1607
				if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1608
					$sql .= " DISTINCT";
1609
				}
1610
				$sql .= " u.rowid";
1611
				$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1612
1613
				if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1614
				{
1615
					$sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1616
					$sql .= " WHERE ((ug.fk_user = u.rowid";
1617
					$sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1618
					$sql .= " OR u.entity = 0)"; // Show always superadmin
1619
				} else {
1620
					$sql .= " WHERE u.entity IN (".getEntity('user').")";
1621
				}
1622
				$sql .= " AND u.statut > 0";
1623
				if ($filters) $sql .= $filters;
1624
1625
				$resql = $this->db->query($sql);
1626
1627
				// Si pas d'erreur SQL
1628
				if ($resql) {
1629
					$i = 0;
1630
					$num = $this->db->num_rows($resql);
1631
					$stringlist = '';
1632
1633
					// Boucles du listage des utilisateurs
1634
					while ($i < $num)
1635
					{
1636
						$obj = $this->db->fetch_object($resql);
1637
1638
						if ($i == 0) {
1639
							$stringlist .= $obj->rowid;
1640
						} else {
1641
							$stringlist .= ', '.$obj->rowid;
1642
						}
1643
1644
						$i++;
1645
					}
1646
					// Retoune le tableau des utilisateurs
1647
					return $stringlist;
1648
				} else {
1649
					// Erreur SQL
1650
					$this->error = "Error ".$this->db->lasterror();
1651
					return -1;
1652
				}
1653
			} else {
1654
				// We want only list of vacation balance for user ids
1655
				$sql = "SELECT DISTINCT cpu.fk_user";
1656
				$sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1657
				$sql .= " WHERE cpu.fk_user = u.rowid";
1658
				if ($filters) $sql .= $filters;
1659
1660
				$resql = $this->db->query($sql);
1661
1662
				// Si pas d'erreur SQL
1663
				if ($resql) {
1664
					$i = 0;
1665
					$num = $this->db->num_rows($resql);
1666
					$stringlist = '';
1667
1668
					// Boucles du listage des utilisateurs
1669
					while ($i < $num)
1670
					{
1671
						$obj = $this->db->fetch_object($resql);
1672
1673
						if ($i == 0) {
1674
							$stringlist .= $obj->fk_user;
1675
						} else {
1676
							$stringlist .= ', '.$obj->fk_user;
1677
						}
1678
1679
						$i++;
1680
					}
1681
					// Retoune le tableau des utilisateurs
1682
					return $stringlist;
1683
				} else {
1684
					// Erreur SQL
1685
					$this->error = "Error ".$this->db->lasterror();
1686
					return -1;
1687
				}
1688
			}
1689
		} else {
1690
			// Si faux donc return array
1691
			// List for Dolibarr users
1692
			if ($type)
1693
			{
1694
								// If user of Dolibarr
1695
				$sql = "SELECT";
1696
				if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1697
					$sql .= " DISTINCT";
1698
				}
1699
				$sql .= " u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1700
				$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1701
1702
				if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1703
				{
1704
					$sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1705
					$sql .= " WHERE ((ug.fk_user = u.rowid";
1706
					$sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1707
					$sql .= " OR u.entity = 0)"; // Show always superadmin
1708
				} else {
1709
					$sql .= " WHERE u.entity IN (".getEntity('user').")";
1710
				}
1711
1712
				$sql .= " AND u.statut > 0";
1713
				if ($filters) $sql .= $filters;
1714
1715
				$resql = $this->db->query($sql);
1716
1717
				// Si pas d'erreur SQL
1718
				if ($resql)
1719
				{
1720
					$i = 0;
1721
					$tab_result = $this->holiday;
1722
					$num = $this->db->num_rows($resql);
1723
1724
					// Boucles du listage des utilisateurs
1725
					while ($i < $num) {
1726
						$obj = $this->db->fetch_object($resql);
1727
1728
						$tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
1729
						$tab_result[$i]['name'] = $obj->lastname; // deprecated
1730
						$tab_result[$i]['lastname'] = $obj->lastname;
1731
						$tab_result[$i]['firstname'] = $obj->firstname;
1732
						$tab_result[$i]['gender'] = $obj->gender;
1733
						$tab_result[$i]['status'] = $obj->statut;
1734
						$tab_result[$i]['employee'] = $obj->employee;
1735
						$tab_result[$i]['photo'] = $obj->photo;
1736
						$tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
1737
						//$tab_result[$i]['type'] = $obj->type;
1738
						//$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1739
1740
						$i++;
1741
					}
1742
					// Retoune le tableau des utilisateurs
1743
					return $tab_result;
1744
				} else {
1745
					// Erreur SQL
1746
					$this->errors[] = "Error ".$this->db->lasterror();
1747
					return -1;
1748
				}
1749
			} else {
1750
				// List of vacation balance users
1751
				$sql = "SELECT cpu.fk_type, cpu.nb_holiday, u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1752
				$sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1753
				$sql .= " WHERE cpu.fk_user = u.rowid";
1754
				if ($filters) $sql .= $filters;
1755
1756
				$resql = $this->db->query($sql);
1757
1758
				// Si pas d'erreur SQL
1759
				if ($resql)
1760
				{
1761
					$i = 0;
1762
					$tab_result = $this->holiday;
1763
					$num = $this->db->num_rows($resql);
1764
1765
					// Boucles du listage des utilisateurs
1766
					while ($i < $num)
1767
					{
1768
						$obj = $this->db->fetch_object($resql);
1769
1770
						$tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
1771
						$tab_result[$i]['name'] = $obj->lastname; // deprecated
1772
						$tab_result[$i]['lastname'] = $obj->lastname;
1773
						$tab_result[$i]['firstname'] = $obj->firstname;
1774
						$tab_result[$i]['gender'] = $obj->gender;
1775
						$tab_result[$i]['status'] = $obj->statut;
1776
						$tab_result[$i]['employee'] = $obj->employee;
1777
						$tab_result[$i]['photo'] = $obj->photo;
1778
						$tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
1779
1780
						$tab_result[$i]['type'] = $obj->fk_type;
1781
						$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1782
1783
						$i++;
1784
					}
1785
					// Retoune le tableau des utilisateurs
1786
					return $tab_result;
1787
				} else {
1788
					// Erreur SQL
1789
					$this->error = "Error ".$this->db->lasterror();
1790
					return -1;
1791
				}
1792
			}
1793
		}
1794
	}
1795
1796
1797
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1798
	/**
1799
	 * Return list of people with permission to validate leave requests.
1800
	 * Search for permission "approve leave requests"
1801
	 *
1802
	 * @return  array       Array of user ids
1803
	 */
1804
	public function fetch_users_approver_holiday()
1805
	{
1806
        // phpcs:enable
1807
		$users_validator = array();
1808
1809
		$sql = "SELECT DISTINCT ur.fk_user";
1810
		$sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1811
		$sql .= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
1812
		$sql .= "UNION";
1813
		$sql .= " SELECT DISTINCT ugu.fk_user";
1814
		$sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1815
		$sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
1816
		//print $sql;
1817
1818
		dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
1819
		$result = $this->db->query($sql);
1820
		if ($result)
1821
		{
1822
			$num_rows = $this->db->num_rows($result); $i = 0;
1823
			while ($i < $num_rows)
1824
			{
1825
				$objp = $this->db->fetch_object($result);
1826
				array_push($users_validator, $objp->fk_user);
1827
				$i++;
1828
			}
1829
			return $users_validator;
1830
		} else {
1831
			$this->error = $this->db->lasterror();
1832
			dol_syslog(get_class($this)."::fetch_users_approver_holiday  Error ".$this->error, LOG_ERR);
1833
			return -1;
1834
		}
1835
	}
1836
1837
1838
	/**
1839
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr
1840
	 *
1841
	 *  @return     int      retourne le nombre d'utilisateur
1842
	 */
1843
	public function countActiveUsers()
1844
	{
1845
		$sql = "SELECT count(u.rowid) as compteur";
1846
		$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1847
		$sql .= " WHERE u.statut > 0";
1848
1849
		$result = $this->db->query($sql);
1850
		$objet = $this->db->fetch_object($result);
1851
1852
		return $objet->compteur;
1853
	}
1854
	/**
1855
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr sans CP
1856
	 *
1857
	 *  @return     int      retourne le nombre d'utilisateur
1858
	 */
1859
    public function countActiveUsersWithoutCP()
1860
    {
1861
1862
		$sql = "SELECT count(u.rowid) as compteur";
1863
		$sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
1864
		$sql .= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
1865
1866
		$result = $this->db->query($sql);
1867
		$objet = $this->db->fetch_object($result);
1868
1869
		return $objet->compteur;
1870
	}
1871
1872
	/**
1873
	 *  Compare le nombre d'utilisateur actif de Dolibarr à celui des utilisateurs des congés payés
1874
	 *
1875
	 *  @param    int	$userDolibarrWithoutCP	Number of active users in Dolibarr without holidays
1876
	 *  @param    int	$userCP    				Number of active users into table of holidays
1877
	 *  @return   int							<0 if KO, >0 if OK
1878
	 */
1879
	public function verifNbUsers($userDolibarrWithoutCP, $userCP)
1880
	{
1881
		if (empty($userCP)) $userCP = 0;
1882
		dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
1883
		return 1;
1884
	}
1885
1886
1887
	/**
1888
	 * addLogCP
1889
	 *
1890
	 * @param 	int		$fk_user_action		Id user creation
1891
	 * @param 	int		$fk_user_update		Id user update
1892
	 * @param 	string	$label				Label
1893
	 * @param 	int		$new_solde			New value
1894
	 * @param	int		$fk_type			Type of vacation
1895
	 * @return 	int							Id of record added, 0 if nothing done, < 0 if KO
1896
	 */
1897
	public function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
1898
	{
1899
		global $conf, $langs;
1900
1901
		$error = 0;
1902
1903
		$prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5);
1904
		$new_solde = price2num($new_solde, 5);
1905
		//print "$prev_solde == $new_solde";
1906
1907
		if ($prev_solde == $new_solde) return 0;
1908
1909
		$this->db->begin();
1910
1911
		// Insert request
1912
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
1913
		$sql .= "date_action,";
1914
		$sql .= "fk_user_action,";
1915
		$sql .= "fk_user_update,";
1916
		$sql .= "type_action,";
1917
		$sql .= "prev_solde,";
1918
		$sql .= "new_solde,";
1919
		$sql .= "fk_type";
1920
		$sql .= ") VALUES (";
1921
		$sql .= " '".$this->db->idate(dol_now())."',";
1922
		$sql .= " '".$fk_user_action."',";
1923
		$sql .= " '".$fk_user_update."',";
1924
		$sql .= " '".$this->db->escape($label)."',";
1925
		$sql .= " '".$prev_solde."',";
1926
		$sql .= " '".$new_solde."',";
1927
		$sql .= " ".$fk_type;
1928
		$sql .= ")";
1929
1930
		$resql = $this->db->query($sql);
1931
		if (!$resql)
1932
		{
1933
			$error++; $this->errors[] = "Error ".$this->db->lasterror();
1934
		}
1935
1936
		if (!$error)
1937
		{
1938
			$this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
1939
		}
1940
1941
		// Commit or rollback
1942
		if ($error)
1943
		{
1944
			foreach ($this->errors as $errmsg)
1945
			{
1946
				dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
1947
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1948
			}
1949
			$this->db->rollback();
1950
			return -1 * $error;
1951
		} else {
1952
			$this->db->commit();
1953
			return $this->optRowid;
1954
		}
1955
	}
1956
1957
	/**
1958
	 *  Liste le log des congés payés
1959
	 *
1960
	 *  @param	string	$order      Filtrage par ordre
1961
	 *  @param  string	$filter     Filtre de séléction
1962
	 *  @return int         		-1 si erreur, 1 si OK et 2 si pas de résultat
1963
	 */
1964
	public function fetchLog($order, $filter)
1965
	{
1966
		global $langs;
1967
1968
		$sql = "SELECT";
1969
		$sql .= " cpl.rowid,";
1970
		$sql .= " cpl.date_action,";
1971
		$sql .= " cpl.fk_user_action,";
1972
		$sql .= " cpl.fk_user_update,";
1973
		$sql .= " cpl.type_action,";
1974
		$sql .= " cpl.prev_solde,";
1975
		$sql .= " cpl.new_solde,";
1976
		$sql .= " cpl.fk_type";
1977
		$sql .= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
1978
		$sql .= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
1979
1980
		// Filtrage de séléction
1981
		if (!empty($filter)) {
1982
			$sql .= " ".$filter;
1983
		}
1984
1985
		// Ordre d'affichage
1986
		if (!empty($order)) {
1987
			$sql .= " ".$order;
1988
		}
1989
1990
		dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
1991
		$resql = $this->db->query($sql);
1992
1993
		// Si pas d'erreur SQL
1994
		if ($resql) {
1995
			$i = 0;
1996
			$tab_result = $this->logs;
1997
			$num = $this->db->num_rows($resql);
1998
1999
			// Si pas d'enregistrement
2000
			if (!$num) {
2001
				return 2;
2002
			}
2003
2004
			// On liste les résultats et on les ajoutent dans le tableau
2005
			while ($i < $num) {
2006
				$obj = $this->db->fetch_object($resql);
2007
2008
				$tab_result[$i]['rowid'] = $obj->rowid;
2009
				$tab_result[$i]['date_action'] = $obj->date_action;
2010
				$tab_result[$i]['fk_user_action'] = $obj->fk_user_action;
2011
				$tab_result[$i]['fk_user_update'] = $obj->fk_user_update;
2012
				$tab_result[$i]['type_action'] = $obj->type_action;
2013
				$tab_result[$i]['prev_solde'] = $obj->prev_solde;
2014
				$tab_result[$i]['new_solde'] = $obj->new_solde;
2015
				$tab_result[$i]['fk_type'] = $obj->fk_type;
2016
2017
				$i++;
2018
			}
2019
			// Retourne 1 et ajoute le tableau à la variable
2020
			$this->logs = $tab_result;
2021
			return 1;
2022
		} else {
2023
			// Erreur SQL
2024
			$this->error = "Error ".$this->db->lasterror();
2025
			return -1;
2026
		}
2027
	}
2028
2029
2030
	/**
2031
	 *  Return array with list of types
2032
	 *
2033
	 *  @param		int		$active		Status of type. -1 = Both
2034
	 *  @param		int		$affect		Filter on affect (a request will change sold or not). -1 = Both
2035
	 *  @return     array	    		Return array with list of types
2036
	 */
2037
	public function getTypes($active = -1, $affect = -1)
2038
	{
2039
		global $mysoc;
2040
2041
		$sql = "SELECT rowid, code, label, affect, delay, newByMonth";
2042
		$sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types";
2043
		$sql .= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')';
2044
		if ($active >= 0) $sql .= " AND active = ".((int) $active);
2045
		if ($affect >= 0) $sql .= " AND affect = ".((int) $affect);
2046
2047
		$result = $this->db->query($sql);
2048
		if ($result)
2049
		{
2050
			$num = $this->db->num_rows($result);
2051
			if ($num)
2052
			{
2053
				while ($obj = $this->db->fetch_object($result))
2054
				{
2055
					$types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth);
2056
				}
2057
2058
				return $types;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $types does not seem to be defined for all execution paths leading up to this point.
Loading history...
2059
			}
2060
		} else dol_print_error($this->db);
2061
2062
		return array();
2063
	}
2064
2065
2066
	/**
2067
	 *  Initialise an instance with random values.
2068
	 *  Used to build previews or test instances.
2069
	 *	id must be 0 if object instance is a specimen.
2070
	 *
2071
	 *  @return	void
2072
	 */
2073
	public function initAsSpecimen()
2074
	{
2075
		global $user, $langs;
2076
2077
		// Initialise parameters
2078
		$this->id = 0;
2079
		$this->specimen = 1;
2080
2081
		$this->fk_user = 1;
2082
		$this->description = 'SPECIMEN description';
2083
		$this->date_debut = dol_now();
2084
		$this->date_fin = dol_now() + (24 * 3600);
2085
		$this->date_valid = dol_now();
2086
		$this->fk_validator = 1;
2087
		$this->halfday = 0;
2088
		$this->fk_type = 1;
2089
		$this->statut = Holiday::STATUS_VALIDATED;
2090
	}
2091
2092
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2093
	/**
2094
     *      Load this->nb for dashboard
2095
     *
2096
     *      @return     int         <0 if KO, >0 if OK
2097
     */
2098
    public function load_state_board()
2099
    {
2100
        // phpcs:enable
2101
		global $user;
2102
2103
        $this->nb = array();
2104
2105
        $sql = "SELECT count(h.rowid) as nb";
2106
        $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2107
        $sql .= " WHERE h.statut > 1";
2108
        $sql .= " AND h.entity IN (".getEntity('holiday').")";
2109
		if (empty($user->rights->expensereport->read_all))
2110
		{
2111
			$userchildids = $user->getAllChildIds(1);
2112
			$sql.= " AND (h.fk_user IN (".join(',', $userchildids).")";
2113
			$sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))";
2114
		}
2115
2116
        $resql = $this->db->query($sql);
2117
        if ($resql) {
2118
            while ($obj = $this->db->fetch_object($resql)) {
2119
                $this->nb["holidays"] = $obj->nb;
2120
            }
2121
            $this->db->free($resql);
2122
            return 1;
2123
        } else {
2124
            dol_print_error($this->db);
2125
            $this->error = $this->db->error();
2126
            return -1;
2127
        }
2128
    }
2129
2130
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2131
    /**
2132
     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2133
     *
2134
     *      @param	User	$user   		Objet user
2135
     *      @return WorkboardResponse|int 	<0 if KO, WorkboardResponse if OK
2136
     */
2137
    public function load_board($user)
2138
    {
2139
        // phpcs:enable
2140
        global $conf, $langs;
2141
2142
        if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
2143
2144
        $now = dol_now();
2145
2146
        $sql = "SELECT h.rowid, h.date_debut";
2147
        $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2148
        $sql .= " WHERE h.statut = 2";
2149
        $sql .= " AND h.entity IN (".getEntity('holiday').")";
2150
		if (empty($user->rights->expensereport->read_all))
2151
		{
2152
			$userchildids = $user->getAllChildIds(1);
2153
			$sql.= " AND (h.fk_user IN (".join(',', $userchildids).")";
2154
			$sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))";
2155
		}
2156
2157
        $resql = $this->db->query($sql);
2158
        if ($resql)
2159
        {
2160
            $langs->load("members");
2161
2162
            $response = new WorkboardResponse();
2163
            $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
2164
            $response->label = $langs->trans("HolidaysToApprove");
2165
            $response->labelShort = $langs->trans("ToApprove");
2166
            $response->url = DOL_URL_ROOT.'/holiday/list.php?search_statut=2&amp;mainmenu=hrm&amp;leftmenu=holiday';
2167
            $response->img = img_object('', "holiday");
2168
2169
            while ($obj = $this->db->fetch_object($resql))
2170
            {
2171
                $response->nbtodo++;
2172
2173
                if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) {
2174
                    $response->nbtodolate++;
2175
                }
2176
            }
2177
2178
            return $response;
2179
        } else {
2180
            dol_print_error($this->db);
2181
            $this->error = $this->db->error();
2182
            return -1;
2183
        }
2184
    }
2185
}
2186