Passed
Branch develop (75104c)
by
unknown
85:26
created

Subscription::update()   B

Complexity

Conditions 11
Paths 65

Size

Total Lines 55
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 38
c 0
b 0
f 0
nc 65
nop 2
dl 0
loc 55
rs 7.3166

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) 2002-2004 Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2006-2015 Laurent Destailleur  <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 *		\file 		htdocs/adherents/class/subscription.class.php
21
 *		\ingroup	member
22
 *		\brief		File of class to manage subscriptions of foundation members
23
 */
24
25
//namespace DolibarrMember;
26
27
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28
29
30
/**
31
 *	Class to manage subscriptions of foundation members
32
 */
33
class Subscription extends CommonObject
34
{
35
	/**
36
	 * @var string ID to identify managed object
37
	 */
38
	public $element = 'subscription';
39
40
	/**
41
	 * @var string Name of table without prefix where object is stored
42
	 */
43
	public $table_element = 'subscription';
44
45
	/**
46
	 * @var int  Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by fk_soc, 'field@table'=Test with link by field@table
47
	 */
48
	public $ismultientitymanaged = 'fk_adherent@adherent';
49
50
	/**
51
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
52
	 */
53
	public $picto = 'payment';
54
55
	/**
56
	 * Date creation record (datec)
57
	 *
58
	 * @var integer
59
	 */
60
	public $datec;
61
62
	/**
63
	 * Date modification record (tms)
64
	 *
65
	 * @var integer
66
	 */
67
	public $datem;
68
69
	/**
70
	 * Subscription start date (date subscription)
71
	 *
72
	 * @var integer
73
	 */
74
	public $dateh;
75
76
	/**
77
	 * Subscription end date
78
	 *
79
	 * @var integer
80
	 */
81
	public $datef;
82
83
	/**
84
	 * @var int ID
85
	 */
86
	public $fk_type;
87
88
	/**
89
	 * @var int Member ID
90
	 */
91
	public $fk_adherent;
92
93
	/**
94
	 * @var double amount subscription
95
	 */
96
	public $amount;
97
98
	/**
99
	 * @var int ID
100
	 */
101
	public $fk_bank;
102
103
	public $fields = array(
104
		'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
105
		'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
106
		'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
107
		'fk_adherent' =>array('type'=>'integer', 'label'=>'Member', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
108
		'dateadh' =>array('type'=>'datetime', 'label'=>'DateSubscription', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
109
		'datef' =>array('type'=>'datetime', 'label'=>'DateEndSubscription', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
110
		'subscription' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'position'=>40, 'isameasure'=>1),
111
		'fk_bank' =>array('type'=>'integer', 'label'=>'BankId', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
112
		'note' =>array('type'=>'text', 'label'=>'Note', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
113
		'fk_type' =>array('type'=>'integer', 'label'=>'MemberType', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
114
		'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>60),
115
		'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
116
	);
117
118
119
	/**
120
	 *	Constructor
121
	 *
122
	 *	@param 		DoliDB		$db		Database handler
123
	 */
124
	public function __construct($db)
125
	{
126
		$this->db = $db;
127
	}
128
129
130
	/**
131
	 *	Function who permitted cretaion of the subscription
132
	 *
133
	 *	@param	User	$user			User that create
134
	 *	@param  bool 	$notrigger 		false=launch triggers after, true=disable triggers
135
	 *	@return	int						<0 if KO, Id subscription created if OK
136
	 */
137
	public function create($user, $notrigger = false)
138
	{
139
		global $langs;
140
141
		$error = 0;
142
143
		$now = dol_now();
144
145
		// Check parameters
146
		if ($this->datef <= $this->dateh) {
147
			$this->error = $langs->trans("ErrorBadValueForDate");
148
			return -1;
149
		}
150
		if (empty($this->datec)) {
151
			$this->datec = $now;
152
		}
153
154
155
		$this->db->begin();
156
157
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."subscription (fk_adherent, fk_type, datec, dateadh, datef, subscription, note)";
158
159
		require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
160
		$member = new Adherent($this->db);
161
		$result = $member->fetch($this->fk_adherent);
162
163
		if ($this->fk_type == null) {	// If type not defined, we use the type of member
164
			$type = $member->typeid;
165
		} else {
166
			$type = $this->fk_type;
167
		}
168
		$sql .= " VALUES (".((int) $this->fk_adherent).", '".$this->db->escape($type)."', '".$this->db->idate($now)."',";
169
		$sql .= " '".$this->db->idate($this->dateh)."',";
170
		$sql .= " '".$this->db->idate($this->datef)."',";
171
		$sql .= " ".((float) $this->amount).",";
172
		$sql .= " '".$this->db->escape($this->note_public ? $this->note_public : $this->note)."')";
173
174
		$resql = $this->db->query($sql);
175
		if (!$resql) {
176
			$error++;
177
			$this->errors[] = $this->db->lasterror();
178
		}
179
180
		if (!$error) {
181
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
182
			$this->fk_type = $type;
183
		}
184
185
		if (!$error && !$notrigger) {
186
			$this->context = array('member' => $member);
187
			// Call triggers
188
			$result = $this->call_trigger('MEMBER_SUBSCRIPTION_CREATE', $user);
189
			if ($result < 0) {
190
				$error++;
191
			}
192
			// End call triggers
193
		}
194
195
		// Commit or rollback
196
		if ($error) {
197
			$this->db->rollback();
198
			return -1;
199
		} else {
200
			$this->db->commit();
201
			return $this->id;
202
		}
203
	}
204
205
206
	/**
207
	 *  Method to load a subscription
208
	 *
209
	 *  @param	int		$rowid		Id subscription
210
	 *  @return	int					<0 if KO, =0 if not found, >0 if OK
211
	 */
212
	public function fetch($rowid)
213
	{
214
		$sql = "SELECT rowid, fk_type, fk_adherent, datec,";
215
		$sql .= " tms,";
216
		$sql .= " dateadh as dateh,";
217
		$sql .= " datef,";
218
		$sql .= " subscription, note as note_public, fk_bank";
219
		$sql .= " FROM ".MAIN_DB_PREFIX."subscription";
220
		$sql .= "	WHERE rowid=".((int) $rowid);
221
222
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
223
		$resql = $this->db->query($sql);
224
		if ($resql) {
225
			if ($this->db->num_rows($resql)) {
226
				$obj = $this->db->fetch_object($resql);
227
228
				$this->id             = $obj->rowid;
229
				$this->ref            = $obj->rowid;
230
231
				$this->fk_type        = $obj->fk_type;
232
				$this->fk_adherent    = $obj->fk_adherent;
233
				$this->datec          = $this->db->jdate($obj->datec);
234
				$this->datem          = $this->db->jdate($obj->tms);
235
				$this->dateh          = $this->db->jdate($obj->dateh);
236
				$this->datef          = $this->db->jdate($obj->datef);
237
				$this->amount         = $obj->subscription;
238
				$this->note           = $obj->note_public;	// deprecated
239
				$this->note_public    = $obj->note_public;
240
				$this->fk_bank        = $obj->fk_bank;
241
				return 1;
242
			} else {
243
				return 0;
244
			}
245
		} else {
246
			$this->error = $this->db->lasterror();
247
			return -1;
248
		}
249
	}
250
251
252
	/**
253
	 *	Update subscription
254
	 *
255
	 *	@param	User	$user			User who updated
256
	 *	@param 	int		$notrigger		0=Disable triggers
257
	 *	@return	int						<0 if KO, >0 if OK
258
	 */
259
	public function update($user, $notrigger = 0)
260
	{
261
		$error = 0;
262
263
		$this->db->begin();
264
265
		if (!is_numeric($this->amount)) {
266
			$this->error = 'BadValueForParameterAmount';
267
			return -1;
268
		}
269
270
		if (empty($this->note_public) && !empty($this->note)) {	// For backward compatibility
271
			$this->note_public = $this->note;
272
		}
273
274
		$sql = "UPDATE ".MAIN_DB_PREFIX."subscription SET ";
275
		$sql .= " fk_type = ".((int) $this->fk_type).",";
276
		$sql .= " fk_adherent = ".((int) $this->fk_adherent).",";
277
		$sql .= " note=".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null').",";
278
		$sql .= " subscription = ".price2num($this->amount).",";
279
		$sql .= " dateadh='".$this->db->idate($this->dateh)."',";
280
		$sql .= " datef='".$this->db->idate($this->datef)."',";
281
		$sql .= " datec='".$this->db->idate($this->datec)."',";
282
		$sql .= " fk_bank = ".($this->fk_bank ? ((int) $this->fk_bank) : 'null');
283
		$sql .= " WHERE rowid = ".((int) $this->id);
284
285
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
286
		$resql = $this->db->query($sql);
287
		if ($resql) {
288
			require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
289
			$member = new Adherent($this->db);
290
			$result = $member->fetch($this->fk_adherent);
291
			$result = $member->update_end_date($user);
292
293
			if (!$error && !$notrigger) {
294
				$this->context = array('member'=>$member);
295
				// Call triggers
296
				$result = $this->call_trigger('MEMBER_SUBSCRIPTION_MODIFY', $user);
297
				if ($result < 0) {
298
					$error++;
299
				} //Do also here what you must do to rollback action if trigger fail
300
				// End call triggers
301
			}
302
		} else {
303
			$error++;
304
			$this->error = $this->db->lasterror();
305
		}
306
307
		// Commit or rollback
308
		if ($error) {
309
			$this->db->rollback();
310
			return -1;
311
		} else {
312
			$this->db->commit();
313
			return $this->id;
314
		}
315
	}
316
317
	/**
318
	 *	Delete a subscription
319
	 *
320
	 *	@param	User	$user		User that delete
321
	 *	@param 	bool 	$notrigger  false=launch triggers after, true=disable triggers
322
	 *	@return	int					<0 if KO, 0 if not found, >0 if OK
323
	 */
324
	public function delete($user, $notrigger = false)
325
	{
326
		$error = 0;
327
328
		// It subscription is linked to a bank transaction, we get it
329
		if ($this->fk_bank > 0) {
330
			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
331
			$accountline = new AccountLine($this->db);
332
			$result = $accountline->fetch($this->fk_bank);
333
		}
334
335
		$this->db->begin();
336
337
		if (!$error) {
338
			if (!$notrigger) {
339
				// Call triggers
340
				$result = $this->call_trigger('MEMBER_SUBSCRIPTION_DELETE', $user);
341
				if ($result < 0) {
342
					$error++;
343
				} // Do also here what you must do to rollback action if trigger fail
344
				// End call triggers
345
			}
346
		}
347
348
		if (!$error) {
349
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."subscription WHERE rowid = ".((int) $this->id);
350
			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
351
			$resql = $this->db->query($sql);
352
			if ($resql) {
353
				$num = $this->db->affected_rows($resql);
354
				if ($num) {
355
					require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
356
					$member = new Adherent($this->db);
357
					$result = $member->fetch($this->fk_adherent);
358
					$result = $member->update_end_date($user);
359
360
					if ($this->fk_bank > 0 && is_object($accountline) && $accountline->id > 0) {	// If we found bank account line (this means this->fk_bank defined)
361
						$result = $accountline->delete($user); // Return false if refused because line is reconciled
362
						if ($result > 0) {
363
							$this->db->commit();
364
							return 1;
365
						} else {
366
							$this->error = $accountline->error;
367
							$this->db->rollback();
368
							return -1;
369
						}
370
					} else {
371
						$this->db->commit();
372
						return 1;
373
					}
374
				} else {
375
					$this->db->commit();
376
					return 0;
377
				}
378
			} else {
379
				$error++;
380
				$this->error = $this->db->lasterror();
381
			}
382
		}
383
384
		// Commit or rollback
385
		if ($error) {
386
			$this->db->rollback();
387
			return -1;
388
		} else {
389
			$this->db->commit();
390
			return 1;
391
		}
392
	}
393
394
395
	/**
396
	 *  Return clicable name (with picto eventually)
397
	 *
398
	 *	@param	int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
399
	 *  @param	int  	$notooltip					1=Disable tooltip
400
	 *	@param	string	$option						Page for link ('', 'nolink', ...)
401
	 *  @param  string  $morecss        			Add more css on link
402
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
403
	 *	@return	string								Chaine avec URL
404
	 */
405
	public function getNomUrl($withpicto = 0, $notooltip = 0, $option = '', $morecss = '', $save_lastsearch_value = -1)
406
	{
407
		global $langs;
408
409
		$result = '';
410
411
		$langs->load("members");
412
413
		$label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Subscription").'</u>';
414
		/*if (isset($this->statut)) {
415
			$label .= ' '.$this->getLibStatut(5);
416
		}*/
417
		$label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
418
		if (!empty($this->dateh)) {
419
			$label .= '<br><b>'.$langs->trans('DateStart').':</b> '.dol_print_date($this->dateh, 'day');
420
		}
421
		if (!empty($this->datef)) {
422
			$label .= '<br><b>'.$langs->trans('DateEnd').':</b> '.dol_print_date($this->datef, 'day');
423
		}
424
425
		$url = DOL_URL_ROOT.'/adherents/subscription/card.php?rowid='.((int) $this->id);
426
427
		if ($option != 'nolink') {
428
			// Add param to save lastsearch_values or not
429
			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
430
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
431
				$add_save_lastsearch_values = 1;
432
			}
433
			if ($add_save_lastsearch_values) {
434
				$url .= '&save_lastsearch_values=1';
435
			}
436
		}
437
438
		$linkstart = '<a href="'.$url.'" class="classfortooltip" title="'.dol_escape_htmltag($label, 1).'">';
439
		$linkend = '</a>';
440
441
		$result .= $linkstart;
442
		if ($withpicto) {
443
			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
444
		}
445
		if ($withpicto != 2) {
446
			$result .= $this->ref;
447
		}
448
		$result .= $linkend;
449
450
		return $result;
451
	}
452
453
454
	/**
455
	 *  Retourne le libelle du statut d'une adhesion
456
	 *
457
	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
458
	 *  @return string				Label
459
	 */
460
	public function getLibStatut($mode = 0)
461
	{
462
		return '';
463
	}
464
465
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
466
	/**
467
	 *  Renvoi le libelle d'un statut donne
468
	 *
469
	 *  @param	int			$status      			Id status
470
	 *  @return string      						Label
471
	 */
472
	public function LibStatut($status)
473
	{
474
		// phpcs:enable
475
		global $langs;
476
		$langs->load("members");
477
		return '';
478
	}
479
480
	/**
481
	 *  Load information of the subscription object
482
	 *
483
	 *  @param	int		$id       Id subscription
484
	 *  @return	void
485
	 */
486
	public function info($id)
487
	{
488
		$sql = 'SELECT c.rowid, c.datec,';
489
		$sql .= ' c.tms as datem';
490
		$sql .= ' FROM '.MAIN_DB_PREFIX.'subscription as c';
491
		$sql .= ' WHERE c.rowid = '.((int) $id);
492
493
		$resql = $this->db->query($sql);
494
		if ($resql) {
495
			if ($this->db->num_rows($resql)) {
496
				$obj = $this->db->fetch_object($resql);
497
				$this->id = $obj->rowid;
498
499
				$this->date_creation = $this->db->jdate($obj->datec);
500
				$this->date_modification = $this->db->jdate($obj->datem);
501
			}
502
503
			$this->db->free($resql);
504
		} else {
505
			dol_print_error($this->db);
506
		}
507
	}
508
509
	/**
510
	 *	Return clicable link of object (with eventually picto)
511
	 *
512
	 *	@param      string	    $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
513
	 *  @return		string								HTML Code for Kanban thumb.
514
	 */
515
	public function getKanbanView($option = '')
516
	{
517
		$return = '<div class="box-flex-item box-flex-grow-zero">';
518
		$return .= '<div class="info-box info-box-sm">';
519
		$return .= '<span class="info-box-icon bg-infobox-action">';
520
		$return .= img_picto('', $this->picto);
521
		$return .= '</span>';
522
523
		$return .= '<div class="info-box-content">';
524
		$return .= '<span class="info-box-ref">'.(property_exists($this, 'fk_adherent')? $this->fk_adherent: $this->ref ).'</span>';
525
		if (property_exists($this, 'dateh') || property_exists($this, 'datef')) {
526
			$return .= '<br><span class="info-box-status opacitymedium">'.dol_print_date($this->dateh, 'day').' - '.dol_print_date($this->datef, 'day').'</span>';
527
		}
528
529
		if (property_exists($this, 'fk_bank')) {
530
			$return .= '<br><span class="info-box-label ">'.$this->fk_bank.'</span>';
531
		}
532
		if (property_exists($this, 'amount')) {
533
			$return .= '<br><div class="info-box-label margintoponly amount">'.price($this->amount).'</div>';
534
		}
535
		$return .= '</div>';
536
		$return .= '</div>';
537
		$return .= '</div>';
538
		return $return;
539
	}
540
}
541