Passed
Branch develop (a7390e)
by
unknown
25:38
created

Societe::useRevenueStamp()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 18
rs 9.8666
1
<?php
2
/* Copyright (C) 2002-2006  Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004-2015  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2004       Eric Seigne             <[email protected]>
5
 * Copyright (C) 2003       Brian Fraval            <[email protected]>
6
 * Copyright (C) 2006       Andre Cianfarani        <[email protected]>
7
 * Copyright (C) 2005-2017  Regis Houssin           <[email protected]>
8
 * Copyright (C) 2008       Patrick Raguin          <[email protected]>
9
 * Copyright (C) 2010-2018  Juanjo Menent           <[email protected]>
10
 * Copyright (C) 2013       Florian Henry           <[email protected]>
11
 * Copyright (C) 2013       Alexandre Spangaro      <[email protected]>
12
 * Copyright (C) 2013       Peter Fontaine          <[email protected]>
13
 * Copyright (C) 2014-2015  Marcos García           <[email protected]>
14
 * Copyright (C) 2015       Raphaël Doursenaud      <[email protected]>
15
 * Copyright (C) 2017       Rui Strecht			    <[email protected]>
16
 * Copyright (C) 2018	    Philippe Grand	        <[email protected]>
17
 * Copyright (C) 2019	    Josep Lluís Amador      <[email protected]>
18
 *
19
 * This program is free software; you can redistribute it and/or modify
20
 * it under the terms of the GNU General Public License as published by
21
 * the Free Software Foundation; either version 3 of the License, or
22
 * (at your option) any later version.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27
 * GNU General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU General Public License
30
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31
 */
32
33
/**
34
 *	\file       htdocs/societe/class/societe.class.php
35
 *	\ingroup    societe
36
 *	\brief      File for third party class
37
 */
38
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
39
require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
40
41
/**
42
 *	Class to manage third parties objects (customers, suppliers, prospects...)
43
 */
44
class Societe extends CommonObject
45
{
46
	/**
47
	 * @var string ID to identify managed object
48
	 */
49
	public $element='societe';
50
51
	/**
52
	 * @var string Name of table without prefix where object is stored
53
	 */
54
	public $table_element = 'societe';
55
56
	/**
57
	 * @var int Field with ID of parent key if this field has a parent
58
	 */
59
	public $fk_element='fk_soc';
60
61
	public $fieldsforcombobox='nom,name_alias';
62
63
	/**
64
	 * @var array	List of child tables. To test if we can delete object.
65
	 */
66
	protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');
67
	/**
68
	 * @var array	List of child tables. To know object to delete on cascade.
69
	 */
70
	protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_account", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
71
72
	public $picto = 'company';
73
74
	/**
75
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
76
	 * @var int
77
	 */
78
	public $ismultientitymanaged = 1;
79
80
	/**
81
	 * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
82
	 * @var integer
83
	 */
84
	public $restrictiononfksoc = 1;
85
86
87
	// BEGIN MODULEBUILDER PROPERTIES
88
	/**
89
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
90
	 */
91
	public $fields=array(
92
		'rowid'         =>array('type'=>'integer',      'label'=>'TechnicalID',      'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'index'=>1, 'position'=>1, 'comment'=>'Id'),
93
		'nom'           =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
94
		'name_alias'    =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
95
		'entity'        =>array('type'=>'integer',      'label'=>'Entity',           'enabled'=>1, 'visible'=>0,  'default'=>1,  'notnull'=>1,  'index'=>1, 'position'=>20),
96
		'note_public'   =>array('type'=>'text',			'label'=>'NotePublic',		 'enabled'=>1, 'visible'=>0,  'position'=>60),
97
		'note_private'  =>array('type'=>'text',			'label'=>'NotePrivate',		 'enabled'=>1, 'visible'=>0,  'position'=>61),
98
		'datec'			=>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>500),
99
		'tms'           =>array('type'=>'timestamp',    'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>501),
100
		//'date_valid'    =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'position'=>502),
101
		'fk_user_creat' =>array('type'=>'integer',      'label'=>'UserAuthor',       'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>510),
102
		'fk_user_modif' =>array('type'=>'integer',      'label'=>'UserModif',        'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
103
		//'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
104
		'import_key'    =>array('type'=>'varchar(14)',  'label'=>'ImportId',         'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1,  'position'=>1000),
105
	);
106
107
108
	/**
109
	 * @var int Entity
110
	 */
111
	public $entity;
112
113
	/**
114
	 * Thirdparty name
115
	 * @var string
116
	 * @deprecated Use $name instead
117
	 * @see $name
118
	 */
119
	public $nom;
120
121
	/**
122
	 * @var string name
123
	 */
124
	public $name;
125
126
	/**
127
	 * Alias names (commercial, trademark or alias names)
128
	 * @var string
129
	 */
130
	public $name_alias;
131
132
	public $particulier;
133
134
	/**
135
	 * @var string Address
136
	 */
137
	public $address;
138
139
	public $zip;
140
	public $town;
141
142
	/**
143
	 * Thirdparty status : 0=activity ceased, 1= in activity
144
	 * @var int
145
	 */
146
	public $status=1;
147
148
	/**
149
	 * Id of department
150
	 * @var int
151
	 */
152
	public $state_id;
153
	public $state_code;
154
	public $state;
155
156
	/**
157
	 * Id of region
158
	 * @var int
159
	 */
160
	public $region_code;
161
	public $region;
162
163
	/**
164
	 * State code
165
	 * @var string
166
	 * @deprecated Use state_code instead
167
	 * @see $state_code
168
	 */
169
	public $departement_code;
170
171
	/**
172
	 * @var string
173
	 * @deprecated Use state instead
174
	 * @see $state
175
	 */
176
	public $departement;
177
178
	/**
179
	 * @var string
180
	 * @deprecated Use country instead
181
	 * @see $country
182
	 */
183
	public $pays;
184
185
	/**
186
	 * Phone number
187
	 * @var string
188
	 */
189
	public $phone;
190
	/**
191
	 * Fax number
192
	 * @var string
193
	 */
194
	public $fax;
195
	/**
196
	 * Email
197
	 * @var string
198
	 */
199
	public $email;
200
	/**
201
	 * Skype username
202
	 * @var string
203
	 */
204
	public $skype;
205
	/**
206
	 * Twitter username
207
	 * @var string
208
	 */
209
	public $twitter;
210
	/**
211
	 * Facebook username
212
	 * @var string
213
	 */
214
	public $facebook;
215
    /**
216
     * LinkedIn username
217
     * @var string
218
     */
219
    public $linkedin;
220
	/**
221
	 * Webpage
222
	 * @var string
223
	 */
224
	public $url;
225
226
	//! barcode
227
	/**
228
	 * Barcode value
229
	 * @var string
230
	 */
231
	public $barcode;
232
233
	// 6 professional id (usage depends on country)
234
235
	/**
236
	 * Professional ID 1 (Ex: Siren in France)
237
	 * @var string
238
	 */
239
	public $idprof1;
240
241
	/**
242
	 * Professional ID 2 (Ex: Siret in France)
243
	 * @var string
244
	 */
245
	public $idprof2;
246
247
	/**
248
	 * Professional ID 3 (Ex: Ape in France)
249
	 * @var string
250
	 */
251
	public $idprof3;
252
253
	/**
254
	 * Professional ID 4 (Ex: RCS in France)
255
	 * @var string
256
	 */
257
	public $idprof4;
258
259
	/**
260
	 * Professional ID 5
261
	 * @var string
262
	 */
263
	public $idprof5;
264
265
	/**
266
	 * Professional ID 6
267
	 * @var string
268
	 */
269
	public $idprof6;
270
271
	public $prefix_comm;
272
273
	public $tva_assuj=1;
274
	/**
275
	 * Intracommunitary VAT ID
276
	 * @var string
277
	 */
278
	public $tva_intra;
279
280
	// Local taxes
281
	public $localtax1_assuj;
282
	public $localtax1_value;
283
	public $localtax2_assuj;
284
	public $localtax2_value;
285
286
	public $managers;
287
	public $capital;
288
	public $typent_id=0;
289
	public $typent_code;
290
	public $effectif;
291
	public $effectif_id=0;
292
	public $forme_juridique_code;
293
	public $forme_juridique=0;
294
295
	public $remise_percent;
296
	public $remise_supplier_percent;
297
	public $mode_reglement_supplier_id;
298
	public $cond_reglement_supplier_id;
299
300
	/**
301
     * @var int ID
302
     */
303
	public $fk_prospectlevel;
304
305
	public $name_bis;
306
307
	//Log data
308
309
	/**
310
	 * Date of last update
311
	 * @var string
312
	 */
313
	public $date_modification;
314
	/**
315
	 * User that made last update
316
	 * @var string
317
	 */
318
	public $user_modification;
319
	/**
320
	 * Date of creation
321
	 * @var string
322
	 */
323
	public $date_creation;
324
	/**
325
	 * User that created the thirdparty
326
	 * @var User
327
	 */
328
	public $user_creation;
329
330
331
	public $specimen;
332
333
	/**
334
	 * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
335
	 * @var int
336
	 */
337
	public $client=0;
338
	/**
339
	 * 0=no prospect, 1=prospect
340
	 * @var int
341
	 */
342
	public $prospect=0;
343
	/**
344
	 * 0=no supplier, 1=supplier
345
	 * @var int
346
	 */
347
	public $fournisseur;
348
349
	/**
350
	 * Client code. E.g: CU2014-003
351
	 * @var string
352
	 */
353
	public $code_client;
354
355
	/**
356
	 * Supplier code. E.g: SU2014-003
357
	 * @var string
358
	 */
359
	public $code_fournisseur;
360
361
	/**
362
	 * Accounting code for client
363
	 * @var string
364
	 */
365
	public $code_compta;
366
367
    /**
368
     * Accounting code for client
369
     * @var string
370
     */
371
    public $code_compta_client;
372
373
	/**
374
	 * Accounting code for suppliers
375
	 * @var string
376
	 */
377
	public $code_compta_fournisseur;
378
379
	/**
380
	 * @var string
381
	 * @deprecated Note is split in public and private notes
382
	 * @see $note_public, $note_private
383
	 */
384
	public $note;
385
386
	/**
387
	 * Private note
388
	 * @var string
389
	 */
390
	public $note_private;
391
392
	/**
393
	 * Public note
394
	 * @var string
395
	 */
396
	public $note_public;
397
398
	//! code statut prospect
399
	public $stcomm_id;
400
	public $statut_commercial;
401
402
	/**
403
	 * Assigned price level
404
	 * @var int
405
	 */
406
	public $price_level;
407
	public $outstanding_limit;
408
409
	/**
410
	 * Min order amounts
411
	 */
412
	public $order_min_amount;
413
	public $supplier_order_min_amount;
414
415
	/**
416
	 * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
417
	 * @var int
418
	 */
419
	public $commercial_id;
420
	/**
421
	 * Id of parent thirdparty (if one)
422
	 * @var int
423
	 */
424
	public $parent;
425
	/**
426
	 * Default language code of thirdparty (en_US, ...)
427
	 * @var string
428
	 */
429
	public $default_lang;
430
431
	/**
432
	 * @var string Ref
433
	 */
434
	public $ref;
435
436
	public $ref_int;
437
	/**
438
	 * External user reference.
439
	 * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
440
	 * build.
441
	 * @var string
442
	 */
443
	public $ref_ext;
444
445
	/**
446
	 * Import key.
447
	 * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
448
	 * to an import process
449
	 * @var string
450
	 */
451
	public $import_key;
452
453
	/**
454
	 * Supplier WebServices URL
455
	 * @var string
456
	 */
457
	public $webservices_url;
458
459
	/**
460
	 * Supplier WebServices Key
461
	 * @var string
462
	 */
463
	public $webservices_key;
464
465
	public $logo;
466
	public $logo_small;
467
	public $logo_mini;
468
469
	public $array_options;
470
471
	// Incoterms
472
	/**
473
     * @var int ID
474
     */
475
	public $fk_incoterms;
476
477
	public $location_incoterms;
478
	public $label_incoterms;  //Used into tooltip
479
480
	// Multicurrency
481
	/**
482
     * @var int ID
483
     */
484
	public $fk_multicurrency;
485
486
	public $multicurrency_code;
487
488
489
	// END MODULEBUILDER PROPERTIES
490
491
492
	/**
493
	 *    Constructor
494
	 *
495
	 *    @param	DoliDB		$db		Database handler
496
	 */
497
	public function __construct($db)
498
	{
499
		$this->db = $db;
500
501
		$this->client = 0;
502
		$this->prospect = 0;
503
		$this->fournisseur = 0;
504
		$this->typent_id  = 0;
505
		$this->effectif_id  = 0;
506
		$this->forme_juridique_code  = 0;
507
		$this->tva_assuj = 1;
508
		$this->status = 1;
509
	}
510
511
512
	/**
513
	 *    Create third party in database.
514
	 *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
515
	 *
516
	 *    @param	User	$user       Object of user that ask creation
517
	 *    @return   int         		>= 0 if OK, < 0 if KO
518
	 */
519
    public function create(User $user)
520
	{
521
		global $langs,$conf,$mysoc;
522
523
		$error=0;
524
525
		// Clean parameters
526
		if (empty($this->status)) $this->status=0;
527
		$this->name=$this->name?trim($this->name):trim($this->nom);
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

527
		$this->name=$this->name?trim($this->name):trim(/** @scrutinizer ignore-deprecated */ $this->nom);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
528
		if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
529
		$this->nom=$this->name; // For backward compatibility
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

529
		/** @scrutinizer ignore-deprecated */ $this->nom=$this->name; // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
530
		if (empty($this->client))      $this->client=0;
531
		if (empty($this->fournisseur)) $this->fournisseur=0;
532
		$this->import_key = trim($this->import_key);
533
534
		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
535
		if (empty($this->fk_multicurrency))
536
		{
537
			$this->multicurrency_code = '';
538
			$this->fk_multicurrency = 0;
539
		}
540
541
		dol_syslog(get_class($this)."::create ".$this->name);
542
543
		$now=dol_now();
544
545
		$this->db->begin();
546
547
		// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
548
		if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this, 0);
549
		if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this, 1);
550
551
		// Check more parameters (including mandatory setup
552
		// If error, this->errors[] is filled
553
		$result = $this->verify();
554
555
		if ($result >= 0)
556
		{
557
			$this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
558
559
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
560
			$sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'";
561
			$sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
562
			$sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
563
			$sql.= ", ".$this->status;
564
			$sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
565
			$sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
566
			$sql.= ", 0";
567
			$sql.= ", ".(int) $this->fk_incoterms;
568
			$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
569
			$sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
570
			$sql.= ", ".(int) $this->fk_multicurrency;
571
			$sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
572
573
			dol_syslog(get_class($this)."::create", LOG_DEBUG);
574
			$result=$this->db->query($sql);
575
			if ($result)
576
			{
577
				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
578
579
				$ret = $this->update($this->id, $user, 0, 1, 1, 'add');
580
581
				// Ajout du commercial affecte
582
				if ($this->commercial_id != '' && $this->commercial_id != -1)
583
				{
584
					$this->add_commercial($user, $this->commercial_id);
585
				}
586
				// si un commercial cree un client il lui est affecte automatiquement
587
				elseif (empty($user->rights->societe->client->voir))
588
				{
589
					$this->add_commercial($user, $user->id);
590
				}
591
592
				if ($ret >= 0)
593
				{
594
					// Call trigger
595
					$result=$this->call_trigger('COMPANY_CREATE', $user);
596
					if ($result < 0) $error++;
597
					// End call triggers
598
				}
599
				else $error++;
600
601
				if (! $error)
602
				{
603
					dol_syslog(get_class($this)."::Create success id=".$this->id);
604
					$this->db->commit();
605
					return $this->id;
606
				}
607
				else
608
				{
609
					dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',', $this->errors), LOG_ERR);
610
					$this->db->rollback();
611
					return -4;
612
				}
613
			}
614
			else
615
			{
616
				if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
617
				{
618
					$this->error=$langs->trans("ErrorCompanyNameAlreadyExists", $this->name);    // duplicate on a field (code or profid or ...)
619
					$result=-1;
620
				}
621
				else
622
				{
623
					$this->error=$this->db->lasterror();
624
					$result=-2;
625
				}
626
				$this->db->rollback();
627
				return $result;
628
			}
629
		}
630
		else
631
		{
632
			$this->db->rollback();
633
			dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
634
			return -3;
635
		}
636
	}
637
638
639
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
640
	/**
641
	 * Create a contact/address from thirdparty
642
	 *
643
	 * @param 	User	$user		Object user
644
	 * @return 	int					<0 if KO, >0 if OK
645
	 */
646
    public function create_individual(User $user)
647
	{
648
        // phpcs:enable
649
		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
650
		$contact=new Contact($this->db);
651
652
		$contact->name              = $this->name_bis;
653
		$contact->firstname         = $this->firstname;
654
		$contact->civility_id       = $this->civility_id;
655
		$contact->socid             = $this->id;	// fk_soc
656
		$contact->statut            = 1;
657
		$contact->priv              = 0;
658
		$contact->country_id        = $this->country_id;
659
		$contact->state_id          = $this->state_id;
660
		$contact->address           = $this->address;
661
		$contact->email             = $this->email;
662
		$contact->zip               = $this->zip;
663
		$contact->town              = $this->town;
664
		$contact->phone_pro         = $this->phone;
665
666
		$result = $contact->create($user);
667
		if ($result < 0)
668
		{
669
			$this->error = $contact->error;
670
			$this->errors = $contact->errors;
671
			dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
672
		}
673
674
		return $result;
675
	}
676
677
	/**
678
	 *    Check properties of third party are ok (like name, third party codes, ...)
679
	 *    Used before an add or update.
680
	 *
681
	 *    @return     int		0 if OK, <0 if KO
682
	 */
683
    public function verify()
684
	{
685
		global $conf, $langs, $mysoc;
686
687
		$error = 0;
688
		$this->errors=array();
689
690
		$result = 0;
691
		$this->name	= trim($this->name);
692
		$this->nom=$this->name; // For backward compatibility
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

692
		/** @scrutinizer ignore-deprecated */ $this->nom=$this->name; // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
693
694
		if (! $this->name)
695
		{
696
			$this->errors[] = 'ErrorBadThirdPartyName';
697
			$result = -2;
698
		}
699
700
		if ($this->client)
701
		{
702
			$rescode = $this->check_codeclient();
703
			if ($rescode <> 0)
704
			{
705
				if ($rescode == -1)
706
				{
707
					$this->errors[] = 'ErrorBadCustomerCodeSyntax';
708
				}
709
				elseif ($rescode == -2)
710
				{
711
					$this->errors[] = 'ErrorCustomerCodeRequired';
712
				}
713
				elseif ($rescode == -3)
714
				{
715
					$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
716
				}
717
				elseif ($rescode == -4)
718
				{
719
					$this->errors[] = 'ErrorPrefixRequired';
720
				}
721
				$result = -3;
722
			}
723
		}
724
725
		if ($this->fournisseur)
726
		{
727
			$rescode = $this->check_codefournisseur();
728
			if ($rescode <> 0)
729
			{
730
				if ($rescode == -1)
731
				{
732
					$this->errors[] = 'ErrorBadSupplierCodeSyntax';
733
				}
734
				elseif ($rescode == -2)
735
				{
736
					$this->errors[] = 'ErrorSupplierCodeRequired';
737
				}
738
				elseif ($rescode == -3)
739
				{
740
					$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
741
				}
742
				elseif ($rescode == -5)
743
				{
744
					$this->errors[] = 'ErrorprefixRequired';
745
				}
746
				$result = -3;
747
			}
748
		}
749
750
		// Check for duplicate or mandatory fields defined into setup
751
		$array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
752
		foreach($array_to_check as $key)
753
		{
754
			$keymin=strtolower($key);
755
			$i=(int) preg_replace('/[^0-9]/', '', $key);
756
			$vallabel=$this->$keymin;
757
758
			if ($i > 0)
759
			{
760
				if ($this->isACompany())
761
				{
762
					// Check for unicity
763
					if ($vallabel && $this->id_prof_verifiable($i))
764
					{
765
						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
766
						{
767
							$langs->load("errors");
768
							$error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
769
						}
770
					}
771
772
					// Check for mandatory prof id (but only if country is other than ours)
773
					if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
774
					{
775
						$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
776
						if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
777
						{
778
							$langs->load("errors");
779
							$error++;
780
							$this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
781
						}
782
					}
783
				}
784
			}
785
			else
786
			{
787
				//var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
788
				//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
789
				if ($key == 'EMAIL')
790
				{
791
					// Check for unicity
792
					if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
793
					{
794
						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
795
						{
796
							$langs->load("errors");
797
							$error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
798
						}
799
					}
800
801
					// Check for mandatory
802
					if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
803
					{
804
						$langs->load("errors");
805
						$error++;
806
						$this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
807
					}
808
				}
809
			}
810
		}
811
812
		if ($error) $result = -4;
813
814
		return $result;
815
	}
816
817
	/**
818
	 *      Update parameters of third party
819
	 *
820
	 *      @param	int		$id              			Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
821
	 *      @param  User	$user            			Utilisateur qui demande la mise a jour
822
	 *      @param  int		$call_trigger    			0=no, 1=yes
823
	 *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
824
	 *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
825
	 *		@param	string	$action						'add' or 'update' or 'merge'
826
	 *		@param	int		$nosyncmember				Do not synchronize info of linked member
827
	 *      @return int  			           			<0 if KO, >=0 if OK
828
	 */
829
    public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
830
	{
831
		global $langs,$conf,$hookmanager;
832
833
		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
834
835
		if (empty($id)) $id = $this->id;
836
837
		$error=0;
838
839
		dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
840
841
		$now=dol_now();
842
843
		// Clean parameters
844
		$this->id			= $id;
845
		$this->entity		= ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
846
		$this->name			= $this->name?trim($this->name):trim($this->nom);
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

846
		$this->name			= $this->name?trim($this->name):trim(/** @scrutinizer ignore-deprecated */ $this->nom);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
847
		$this->nom			= $this->name;	// For backward compatibility
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

847
		/** @scrutinizer ignore-deprecated */ $this->nom			= $this->name;	// For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
848
		$this->name_alias	= trim($this->name_alias);
849
		$this->ref_ext		= trim($this->ref_ext);
850
		$this->address		= $this->address?trim($this->address):trim($this->address);
851
		$this->zip			= $this->zip?trim($this->zip):trim($this->zip);
852
		$this->town			= $this->town?trim($this->town):trim($this->town);
853
		$this->state_id		= trim($this->state_id);
1 ignored issue
show
Documentation Bug introduced by
The property $state_id was declared of type integer, but trim($this->state_id) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
854
		$this->country_id	= ($this->country_id > 0)?$this->country_id:0;
855
		$this->phone		= trim($this->phone);
856
		$this->phone		= preg_replace("/\s/", "", $this->phone);
857
		$this->phone		= preg_replace("/\./", "", $this->phone);
858
		$this->fax			= trim($this->fax);
859
		$this->fax			= preg_replace("/\s/", "", $this->fax);
860
		$this->fax			= preg_replace("/\./", "", $this->fax);
861
		$this->email		= trim($this->email);
862
		$this->skype		= trim($this->skype);
863
		$this->twitter		= trim($this->twitter);
864
		$this->facebook		= trim($this->facebook);
865
        $this->linkedin		= trim($this->linkedin);
866
		$this->url			= $this->url?clean_url($this->url, 0):'';
867
		$this->note_private = trim($this->note_private);
868
		$this->note_public  = trim($this->note_public);
869
		$this->idprof1		= trim($this->idprof1);
870
		$this->idprof2		= trim($this->idprof2);
871
		$this->idprof3		= trim($this->idprof3);
872
		$this->idprof4		= trim($this->idprof4);
873
		$this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
874
		$this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
875
		$this->prefix_comm	= trim($this->prefix_comm);
876
		$this->outstanding_limit = price2num($this->outstanding_limit);
877
		$this->order_min_amount = price2num($this->order_min_amount);
878
		$this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
879
880
		$this->tva_assuj	= trim($this->tva_assuj);
881
		$this->tva_intra	= dol_sanitizeFileName($this->tva_intra, '');
882
		if (empty($this->status)) $this->status = 0;
883
884
		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
885
		if (empty($this->fk_multicurrency))
886
		{
887
			$this->multicurrency_code = '';
888
			$this->fk_multicurrency = 0;
889
		}
890
891
		// Local taxes
892
		$this->localtax1_assuj=trim($this->localtax1_assuj);
893
		$this->localtax2_assuj=trim($this->localtax2_assuj);
894
895
		$this->localtax1_value=trim($this->localtax1_value);
896
		$this->localtax2_value=trim($this->localtax2_value);
897
898
		if ($this->capital != '') $this->capital=price2num(trim($this->capital));
899
		if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
900
901
		$this->effectif_id=trim($this->effectif_id);
902
		$this->forme_juridique_code=trim($this->forme_juridique_code);
903
904
		//Gencod
905
		$this->barcode=trim($this->barcode);
906
907
		// For automatic creation
908
		if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this, 0);
909
		if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this, 1);
910
911
		$this->code_compta=trim($this->code_compta);
912
		$this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
913
914
		// Check parameters. More tests are done later in the ->verify()
915
		if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
1 ignored issue
show
introduced by
The condition is_numeric($this->client) is always true.
Loading history...
916
		{
917
			$langs->load("errors");
918
			$this->error = $langs->trans("BadValueForParameterClientOrSupplier");
919
			return -1;
920
		}
921
922
		$customer=false;
923
		if (! empty($allowmodcodeclient) && ! empty($this->client))
924
		{
925
			// Attention get_codecompta peut modifier le code suivant le module utilise
926
			if (empty($this->code_compta))
927
			{
928
				$ret=$this->get_codecompta('customer');
929
				if ($ret < 0) return -1;
930
			}
931
932
			$customer=true;
933
		}
934
935
		$supplier=false;
936
		if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
937
		{
938
			// Attention get_codecompta peut modifier le code suivant le module utilise
939
			if ($this->code_compta_fournisseur == "")
940
			{
941
				$ret=$this->get_codecompta('supplier');
942
				if ($ret < 0) return -1;
943
			}
944
945
			$supplier=true;
946
		}
947
948
		//Web services
949
		$this->webservices_url = $this->webservices_url?clean_url($this->webservices_url, 0):'';
950
		$this->webservices_key = trim($this->webservices_key);
951
952
		//Incoterms
953
		$this->fk_incoterms = (int) $this->fk_incoterms;
954
		$this->location_incoterms = trim($this->location_incoterms);
955
956
		$this->db->begin();
957
958
		// Check name is required and codes are ok or unique.
959
		// If error, this->errors[] is filled
960
		$result = 0;
961
		if ($action != 'add' && $action != 'merge')
962
		{
963
			// We don't check when update called during a create because verify was already done.
964
			// For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
965
			$result = $this->verify();
966
967
			// If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
968
			// So we can update record that were using and old numbering rule.
969
			if (is_array($this->errors))
1 ignored issue
show
introduced by
The condition is_array($this->errors) is always true.
Loading history...
970
			{
971
				if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client)
972
				{
973
					if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
974
				}
975
				if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur)
976
				{
977
					if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
978
				}
979
				if (empty($this->errors))	// If there is no more error, we can make like if there is no error at all
980
				{
981
					$result = 0;
982
				}
983
			}
984
		}
985
986
		if ($result >= 0)
987
		{
988
			dol_syslog(get_class($this)."::update verify ok or not done");
989
990
			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
991
			$sql .= "entity = " . $this->db->escape($this->entity);
992
			$sql .= ",nom = '" . $this->db->escape($this->name) ."'"; // Required
993
			$sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
994
			$sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
995
			$sql .= ",address = '" . $this->db->escape($this->address) ."'";
996
997
			$sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
998
			$sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
999
1000
			$sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
1001
			$sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
1002
1003
			$sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
1004
			$sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
1005
			$sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
1006
			$sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
1007
			$sql .= ",twitter = ".(! empty($this->twitter)?"'".$this->db->escape($this->twitter)."'":"null");
1008
			$sql .= ",facebook = ".(! empty($this->facebook)?"'".$this->db->escape($this->facebook)."'":"null");
1009
			$sql .= ",linkedin = ".(! empty($this->linkedin)?"'".$this->db->escape($this->linkedin)."'":"null");
1010
			$sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
1011
1012
			$sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null");
1013
1014
			$sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
1015
			$sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
1016
1017
			$sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
1018
			$sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
1019
			$sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
1020
			$sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
1021
			$sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
1022
			$sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
1023
1024
			$sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
1025
			$sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
1026
			$sql .= ",status = " .$this->status;
1027
1028
			// Local taxes
1029
			$sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
1030
			$sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
1031
			if($this->localtax1_assuj==1)
1032
			{
1033
				if($this->localtax1_value!='')
1034
				{
1035
					$sql .=",localtax1_value =".$this->localtax1_value;
1036
				}
1037
				else $sql .=",localtax1_value =0.000";
1038
			}
1039
			else $sql .=",localtax1_value =0.000";
1040
1041
			if($this->localtax2_assuj==1)
1042
			{
1043
				if($this->localtax2_value!='')
1044
				{
1045
					$sql .=",localtax2_value =".$this->localtax2_value;
1046
				}
1047
				else $sql .=",localtax2_value =0.000";
1048
			}
1049
			else $sql .=",localtax2_value =0.000";
1050
1051
			$sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1052
1053
			$sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
1054
1055
			$sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
1056
			if (isset($this->stcomm_id))
1057
			{
1058
				$sql .= ",fk_stcomm=".(!empty($this->stcomm_id)  ? $this->stcomm_id : "0");
1059
			}
1060
			$sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
1061
1062
			$sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
1063
1064
			$sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
1065
			$sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
1066
			$sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
1067
			$sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
1068
			$sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
1069
1070
			$sql .= ",client = " . (! empty($this->client)?$this->client:0);
1071
			$sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
1072
			$sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
1073
			$sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
1074
			$sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
1075
			$sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
1076
			$sql .= ",order_min_amount= ".($this->order_min_amount!=''?$this->order_min_amount:'null');
1077
			$sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount!=''?$this->supplier_order_min_amount:'null');
1078
			$sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1079
1080
			$sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
1081
			$sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
1082
1083
			//Incoterms
1084
			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
1085
			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
1086
1087
			if ($customer)
1088
			{
1089
				$sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
1090
				$sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
1091
			}
1092
1093
			if ($supplier)
1094
			{
1095
				$sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
1096
				$sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "")?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
1097
			}
1098
			$sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id:"null");
1099
			$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1100
			$sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1101
			$sql .= " WHERE rowid = " . (int) $id;
1102
1103
			$resql=$this->db->query($sql);
1104
			if ($resql)
1105
			{
1106
				if (is_object($this->oldcopy))	// If we have information on old values
1107
				{
1108
					if ($this->oldcopy->country_id != $this->country_id)
1109
					{
1110
						unset($this->country_code);
1111
						unset($this->country);
1112
					}
1113
					if ($this->oldcopy->state_id != $this->state_id)
1114
					{
1115
						unset($this->state_code);
1116
						unset($this->state);
1117
					}
1118
				}
1119
				else
1120
				{
1121
					unset($this->country_code);	// We clean this, in the doubt, because it may have been changed after an update of country_id
1122
					unset($this->country);
1123
					unset($this->state_code);
1124
					unset($this->state);
1125
				}
1126
1127
				$nbrowsaffected = $this->db->affected_rows($resql);
1128
1129
				if (! $error && $nbrowsaffected)
1130
				{
1131
					// Update information on linked member if it is an update
1132
					if (! $nosyncmember && ! empty($conf->adherent->enabled))
1133
					{
1134
						require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1135
1136
						dol_syslog(get_class($this)."::update update linked member");
1137
1138
						$lmember=new Adherent($this->db);
1139
						$result=$lmember->fetch(0, 0, $this->id);
1140
1141
						if ($result > 0)
1142
						{
1143
							$lmember->societe=$this->name;
1144
							//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
1145
							//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
1146
							$lmember->address=$this->address;
1147
							$lmember->zip=$this->zip;
1148
							$lmember->town=$this->town;
1149
							$lmember->email=$this->email;
1150
							$lmember->skype=$this->skype;
1151
							$lmember->twitter=$this->twitter;
1152
							$lmember->facebook=$this->facebook;
1153
							$lmember->linkedin=$this->linkedin;
1154
							$lmember->phone=$this->phone;
1155
							$lmember->state_id=$this->state_id;
1156
							$lmember->country_id=$this->country_id;
1157
1158
							$result=$lmember->update($user, 0, 1, 1, 1);	// Use nosync to 1 to avoid cyclic updates
1159
							if ($result < 0)
1160
							{
1161
								$this->error=$lmember->error;
1162
								dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1163
								$error++;
1164
							}
1165
						}
1166
						elseif ($result < 0)
1167
						{
1168
							$this->error=$lmember->error;
1169
							$error++;
1170
						}
1171
					}
1172
				}
1173
1174
				$action='update';
1175
1176
				// Actions on extra fields
1177
				if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1178
				{
1179
					$result=$this->insertExtraFields();
1180
					if ($result < 0)
1181
					{
1182
						$error++;
1183
					}
1184
				}
1185
1186
				if (! $error && $call_trigger)
1187
				{
1188
					// Call trigger
1189
					$result=$this->call_trigger('COMPANY_MODIFY', $user);
1190
					if ($result < 0) $error++;
1191
					// End call triggers
1192
				}
1193
1194
				if (! $error)
1195
				{
1196
					dol_syslog(get_class($this)."::Update success");
1197
					$this->db->commit();
1198
					return 1;
1199
				}
1200
				else
1201
				{
1202
					$this->db->rollback();
1203
					return -1;
1204
				}
1205
			}
1206
			else
1207
			{
1208
				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1209
				{
1210
					// Doublon
1211
					$this->error = $langs->trans("ErrorDuplicateField");
1212
					$result = -1;
1213
				}
1214
				else
1215
				{
1216
					$this->error = $this->db->lasterror();
1217
					$result = -2;
1218
				}
1219
				$this->db->rollback();
1220
				return $result;
1221
			}
1222
		}
1223
		else
1224
	   {
1225
			$this->db->rollback();
1226
			dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1227
			return -3;
1228
		}
1229
	}
1230
1231
	/**
1232
	 *    Load a third party from database into memory
1233
	 *
1234
	 *    @param	int		$rowid			Id of third party to load
1235
	 *    @param    string	$ref			Reference of third party, name (Warning, this can return several records)
1236
	 *    @param    string	$ref_ext       	External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1237
	 *    @param    string	$ref_int       	Internal reference of third party (not used by dolibarr)
1238
	 *    @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1239
	 *    @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1240
	 *    @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1241
	 *    @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1242
	 *    @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1243
	 *    @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1244
	 *    @param    string	$email   		Email of third party (Warning, this can return several records)
1245
	 *    @param    string	$ref_alias 		Name_alias of third party (Warning, this can return several records)
1246
	 *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1247
	 */
1248
    public function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1249
	{
1250
		global $langs;
1251
		global $conf;
1252
1253
		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1254
1255
		$sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1256
		$sql .= ', s.status';
1257
		$sql .= ', s.price_level';
1258
		$sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1259
		$sql .= ', s.phone, s.fax, s.email, s.skype, s.twitter, s.facebook, s.linkedin, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1260
		$sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1261
		$sql .= ', s.capital, s.tva_intra';
1262
		$sql .= ', s.fk_typent as typent_id';
1263
		$sql .= ', s.fk_effectif as effectif_id';
1264
		$sql .= ', s.fk_forme_juridique as forme_juridique_code';
1265
		$sql .= ', s.webservices_url, s.webservices_key';
1266
		$sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1267
		$sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1268
		$sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1269
		$sql .= ', s.fk_shipping_method';
1270
		$sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1271
		$sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1272
		$sql .= ', s.fk_multicurrency, s.multicurrency_code';
1273
		$sql .= ', fj.libelle as forme_juridique';
1274
		$sql .= ', e.libelle as effectif';
1275
		$sql .= ', c.code as country_code, c.label as country';
1276
		$sql .= ', d.code_departement as state_code, d.nom as state';
1277
		$sql .= ', st.libelle as stcomm';
1278
		$sql .= ', te.code as typent_code';
1279
		$sql .= ', i.libelle as label_incoterms';
1280
		$sql .= ', sr.remise_client';
1281
		$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1282
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1283
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1284
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1285
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1286
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1287
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1288
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1289
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity = '.$conf->entity.')';
1290
1291
		$sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1292
		if ($rowid)     $sql .= ' AND s.rowid = '.$rowid;
1293
		if ($ref)       $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1294
		if ($ref_alias) $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1295
		if ($ref_ext)   $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1296
		if ($ref_int)   $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1297
		if ($idprof1)   $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1298
		if ($idprof2)   $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1299
		if ($idprof3)   $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1300
		if ($idprof4)   $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1301
		if ($idprof5)   $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1302
		if ($idprof6)   $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1303
		if ($email)     $sql .= " AND s.email = '".$this->db->escape($email)."'";
1304
1305
		$resql=$this->db->query($sql);
1306
		if ($resql)
1307
		{
1308
			$num=$this->db->num_rows($resql);
1309
			if ($num > 1)
1310
			{
1311
				$this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1312
				dol_syslog($this->error, LOG_ERR);
1313
				$result = -2;
1314
			}
1315
			elseif ($num)   // $num = 1
1316
			{
1317
				$obj = $this->db->fetch_object($resql);
1318
1319
				$this->id           = $obj->rowid;
1320
				$this->entity       = $obj->entity;
1321
				$this->canvas		= $obj->canvas;
1322
1323
				$this->ref          = $obj->rowid;
1324
				$this->name 		= $obj->name;
1325
				$this->nom          = $obj->name;		// deprecated
1326
				$this->name_alias = $obj->name_alias;
1327
				$this->ref_ext      = $obj->ref_ext;
1328
				$this->ref_int      = $obj->ref_int;
1329
1330
				$this->date_creation     = $this->db->jdate($obj->date_creation);
1331
				$this->date_modification = $this->db->jdate($obj->date_modification);
1332
				$this->user_creation     = $obj->fk_user_creat;
1333
				$this->user_modification = $obj->fk_user_modif;
1334
1335
				$this->address 		= $obj->address;
1336
				$this->zip 			= $obj->zip;
1337
				$this->town 		= $obj->town;
1338
1339
				$this->country_id   = $obj->country_id;
1340
				$this->country_code = $obj->country_id?$obj->country_code:'';
1341
				$this->country 		= $obj->country_id?($langs->transnoentities('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1342
1343
				$this->state_id     = $obj->state_id;
1344
				$this->state_code   = $obj->state_code;
1345
				$this->state        = ($obj->state!='-'?$obj->state:'');
1346
1347
				$transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1348
				$libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1349
				$this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1350
				$this->statut_commercial = $libelle;    // libelle statut commercial
1351
1352
				$this->email = $obj->email;
1353
				$this->skype = $obj->skype;
1354
				$this->twitter = $obj->twitter;
1355
				$this->facebook = $obj->facebook;
1356
				$this->linkedin = $obj->linkedin;
1357
				$this->url = $obj->url;
1358
				$this->phone = $obj->phone;
1359
				$this->fax = $obj->fax;
1360
1361
				$this->parent    = $obj->parent;
1362
1363
				$this->idprof1		= $obj->idprof1;
1364
				$this->idprof2		= $obj->idprof2;
1365
				$this->idprof3		= $obj->idprof3;
1366
				$this->idprof4		= $obj->idprof4;
1367
				$this->idprof5		= $obj->idprof5;
1368
				$this->idprof6		= $obj->idprof6;
1369
1370
				$this->capital   = $obj->capital;
1371
1372
				$this->code_client = $obj->code_client;
1373
				$this->code_fournisseur = $obj->code_fournisseur;
1374
1375
				$this->code_compta = $obj->code_compta;
1376
				$this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1377
1378
				$this->barcode = $obj->barcode;
1379
1380
				$this->tva_assuj      = $obj->tva_assuj;
1381
				$this->tva_intra      = $obj->tva_intra;
1382
				$this->status = $obj->status;
1383
1384
				// Local Taxes
1385
				$this->localtax1_assuj      = $obj->localtax1_assuj;
1386
				$this->localtax2_assuj      = $obj->localtax2_assuj;
1387
1388
				$this->localtax1_value		= $obj->localtax1_value;
1389
				$this->localtax2_value		= $obj->localtax2_value;
1390
1391
				$this->typent_id      = $obj->typent_id;
1392
				$this->typent_code    = $obj->typent_code;
1393
1394
				$this->effectif_id    = $obj->effectif_id;
1395
				$this->effectif       = $obj->effectif_id?$obj->effectif:'';
1396
1397
				$this->forme_juridique_code= $obj->forme_juridique_code;
1398
				$this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1399
1400
				$this->fk_prospectlevel = $obj->fk_prospectlevel;
1401
1402
				$this->prefix_comm = $obj->prefix_comm;
1403
1404
				$this->remise_percent		= price2num($obj->remise_client);        // 0.000000 must be 0
1405
				$this->remise_supplier_percent		= $obj->remise_supplier;
1406
				$this->mode_reglement_id 	= $obj->mode_reglement;
1407
				$this->cond_reglement_id 	= $obj->cond_reglement;
1408
				$this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1409
				$this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1410
				$this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1411
				$this->fk_account			= $obj->fk_account;
1412
1413
				$this->client      = $obj->client;
1414
				$this->fournisseur = $obj->fournisseur;
1415
1416
				$this->note = $obj->note_private; // TODO Deprecated for backward comtability
1417
				$this->note_private = $obj->note_private;
1418
				$this->note_public = $obj->note_public;
1419
				$this->modelpdf = $obj->model_pdf;
1420
				$this->default_lang = $obj->default_lang;
1421
				$this->logo = $obj->logo;
1422
1423
				$this->webservices_url = $obj->webservices_url;
1424
				$this->webservices_key = $obj->webservices_key;
1425
1426
				$this->outstanding_limit		= $obj->outstanding_limit;
1427
				$this->order_min_amount			= $obj->order_min_amount;
1428
				$this->supplier_order_min_amount	= $obj->supplier_order_min_amount;
1429
1430
				// multiprix
1431
				$this->price_level = $obj->price_level;
1432
1433
				$this->import_key = $obj->import_key;
1434
1435
				//Incoterms
1436
				$this->fk_incoterms = $obj->fk_incoterms;
1437
				$this->location_incoterms = $obj->location_incoterms;
1438
				$this->label_incoterms = $obj->label_incoterms;
1439
1440
				// multicurrency
1441
				$this->fk_multicurrency = $obj->fk_multicurrency;
1442
				$this->multicurrency_code = $obj->multicurrency_code;
1443
1444
				$result = 1;
1445
1446
				// fetch optionals attributes and labels
1447
				$this->fetch_optionals();
1448
			}
1449
			else
1450
			{
1451
				$result = 0;
1452
			}
1453
1454
			$this->db->free($resql);
1455
		}
1456
		else
1457
		{
1458
			$this->error=$this->db->lasterror();
1459
			$result = -3;
1460
		}
1461
1462
		// Use first price level if level not defined for third party
1463
		if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) $this->price_level=1;
1464
1465
		return $result;
1466
	}
1467
1468
	/**
1469
	 *    Delete a third party from database and all its dependencies (contacts, rib...)
1470
	 *
1471
	 *    @param	int		$id             Id of third party to delete
1472
	 *    @param    User    $fuser          User who ask to delete thirdparty
1473
	 *    @param    int		$call_trigger   0=No, 1=yes
1474
	 *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1475
	 */
1476
    public function delete($id, User $fuser = null, $call_trigger = 1)
1477
	{
1478
		global $langs, $conf, $user;
1479
1480
		if (empty($fuser)) $fuser=$user;
1481
1482
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1483
1484
		$entity=isset($this->entity)?$this->entity:$conf->entity;
1485
1486
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1487
		$error = 0;
1488
1489
		// Test if child exists
1490
		$objectisused = $this->isObjectUsed($id);
1491
		if (empty($objectisused))
1492
		{
1493
			$this->db->begin();
1494
1495
			// User is mandatory for trigger call
1496
			if (! $error && $call_trigger)
1497
			{
1498
				// Call trigger
1499
				$result=$this->call_trigger('COMPANY_DELETE', $fuser);
1500
				if ($result < 0) $error++;
1501
				// End call triggers
1502
			}
1503
1504
			if (! $error)
1505
			{
1506
				require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1507
				$static_cat = new Categorie($this->db);
1508
				$toute_categs = array();
1509
1510
				// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1511
				if ($this->client || $this->prospect)
1512
				{
1513
					$toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
1514
				}
1515
				if ($this->fournisseur)
1516
				{
1517
					$toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
1518
				}
1519
1520
				// Remove each "Categorie"
1521
				foreach ($toute_categs as $type => $categs_type)
1522
				{
1523
					foreach ($categs_type as $cat)
1524
					{
1525
						$cat->del_type($this, $type);
1526
					}
1527
				}
1528
			}
1529
1530
			foreach ($this->childtablesoncascade as $tabletodelete)
1531
			{
1532
				if (! $error)
1533
				{
1534
					$sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1535
					$sql.= " WHERE fk_soc = " . $id;
1536
					if (! $this->db->query($sql))
1537
					{
1538
						$error++;
1539
						$this->errors[] = $this->db->lasterror();
1540
					}
1541
				}
1542
			}
1543
1544
			// Removed extrafields
1545
			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1546
			{
1547
				$result=$this->deleteExtraFields();
1548
				if ($result < 0)
1549
				{
1550
					$error++;
1551
					dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1552
				}
1553
			}
1554
1555
			// Remove links to subsidiaries companies
1556
			if (! $error)
1557
			{
1558
				$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1559
				$sql.= " SET parent = NULL";
1560
				$sql.= " WHERE parent = " . $id;
1561
				if (! $this->db->query($sql))
1562
				{
1563
					$error++;
1564
					$this->errors[] = $this->db->lasterror();
1565
				}
1566
			}
1567
1568
			// Remove third party
1569
			if (! $error)
1570
			{
1571
				$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1572
				$sql.= " WHERE rowid = " . $id;
1573
				if (! $this->db->query($sql))
1574
				{
1575
					$error++;
1576
					$this->errors[] = $this->db->lasterror();
1577
				}
1578
			}
1579
1580
			if (! $error)
1581
			{
1582
				$this->db->commit();
1583
1584
				// Delete directory
1585
				if (! empty($conf->societe->multidir_output[$entity]))
1586
				{
1587
					$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1588
					if (dol_is_dir($docdir))
1589
					{
1590
						dol_delete_dir_recursive($docdir);
1591
					}
1592
				}
1593
1594
				return 1;
1595
			}
1596
			else
1597
			{
1598
				dol_syslog($this->error, LOG_ERR);
1599
				$this->db->rollback();
1600
				return -1;
1601
			}
1602
		}
1603
		else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1604
		return 0;
1605
	}
1606
1607
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1608
	/**
1609
	 *  Define third party as a customer
1610
	 *
1611
	 *	@return		int		<0 if KO, >0 if OK
1612
	 */
1613
    public function set_as_client()
1614
	{
1615
        // phpcs:enable
1616
		if ($this->id)
1617
		{
1618
			$newclient=1;
1619
			if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1620
			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1621
			$sql.= " SET client = ".$newclient;
1622
			$sql.= " WHERE rowid = " . $this->id;
1623
1624
			$resql=$this->db->query($sql);
1625
			if ($resql)
1626
			{
1627
				$this->client = $newclient;
1628
				return 1;
1629
			}
1630
			else return -1;
1631
		}
1632
		return 0;
1633
	}
1634
1635
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1636
	/**
1637
	 *  Definit la societe comme un client
1638
	 *
1639
	 *  @param	float	$remise		Valeur en % de la remise
1640
	 *  @param  string	$note		Note/Motif de modification de la remise
1641
	 *  @param  User	$user		Utilisateur qui definie la remise
1642
	 *	@return	int					<0 if KO, >0 if OK
1643
	 */
1644
    public function set_remise_client($remise, $note, User $user)
1645
	{
1646
        // phpcs:enable
1647
		global $conf, $langs;
1648
1649
		// Nettoyage parametres
1650
		$note=trim($note);
1651
		if (! $note)
1652
		{
1653
			$this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
1654
			return -2;
1655
		}
1656
1657
		dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1658
1659
		if ($this->id)
1660
		{
1661
			$this->db->begin();
1662
1663
			$now=dol_now();
1664
1665
			// Positionne remise courante
1666
			$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1667
			$sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1668
			$sql.= " WHERE rowid = " . $this->id;
1669
			$resql=$this->db->query($sql);
1670
			if (! $resql)
1671
			{
1672
				$this->db->rollback();
1673
				$this->error=$this->db->error();
1674
				return -1;
1675
			}
1676
1677
			// Ecrit trace dans historique des remises
1678
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1679
			$sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1680
			$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1681
			$sql.= " '".$this->db->escape($note)."',";
1682
			$sql.= " ".$user->id;
1683
			$sql.= ")";
1684
1685
			$resql=$this->db->query($sql);
1686
			if (! $resql)
1687
			{
1688
				$this->db->rollback();
1689
				$this->error=$this->db->lasterror();
1690
				return -1;
1691
			}
1692
1693
			$this->db->commit();
1694
			return 1;
1695
		}
1696
	}
1697
1698
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1699
	/**
1700
	 *  Definit la societe comme un client
1701
	 *
1702
	 *  @param	float	$remise		Valeur en % de la remise
1703
	 *  @param  string	$note		Note/Motif de modification de la remise
1704
	 *  @param  User	$user		Utilisateur qui definie la remise
1705
	 *	@return	int					<0 if KO, >0 if OK
1706
	 */
1707
    public function set_remise_supplier($remise, $note, User $user)
1708
	{
1709
        // phpcs:enable
1710
		global $conf, $langs;
1711
1712
		// Nettoyage parametres
1713
		$note=trim($note);
1714
		if (! $note)
1715
		{
1716
			$this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
1717
			return -2;
1718
		}
1719
1720
		dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
1721
1722
		if ($this->id)
1723
		{
1724
			$this->db->begin();
1725
1726
			$now=dol_now();
1727
1728
			// Positionne remise courante
1729
			$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1730
			$sql.= " SET remise_supplier = '".$this->db->escape($remise)."'";
1731
			$sql.= " WHERE rowid = " . $this->id;
1732
			$resql=$this->db->query($sql);
1733
			if (! $resql)
1734
			{
1735
				$this->db->rollback();
1736
				$this->error=$this->db->error();
1737
				return -1;
1738
			}
1739
1740
			// Ecrit trace dans historique des remises
1741
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
1742
			$sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
1743
			$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1744
			$sql.= " '".$this->db->escape($note)."',";
1745
			$sql.= " ".$user->id;
1746
			$sql.= ")";
1747
1748
			$resql=$this->db->query($sql);
1749
			if (! $resql)
1750
			{
1751
				$this->db->rollback();
1752
				$this->error=$this->db->lasterror();
1753
				return -1;
1754
			}
1755
1756
			$this->db->commit();
1757
			return 1;
1758
		}
1759
	}
1760
1761
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1762
	/**
1763
	 *    	Add a discount for third party
1764
	 *
1765
	 *    	@param	float	$remise     	Amount of discount
1766
	 *    	@param  User	$user       	User adding discount
1767
	 *    	@param  string	$desc			Reason of discount
1768
	 *      @param  float	$tva_tx     	VAT rate
1769
	 *      @param	int		$discount_type	0 => customer discount, 1 => supplier discount
1770
	 *		@return	int					<0 if KO, id of discount record if OK
1771
	 */
1772
    public function set_remise_except($remise, User $user, $desc, $tva_tx = 0, $discount_type = 0)
1773
	{
1774
        // phpcs:enable
1775
		global $langs;
1776
1777
		// Clean parameters
1778
		$remise = price2num($remise);
1779
		$desc = trim($desc);
1780
1781
		// Check parameters
1782
		if (! $remise > 0)
1783
		{
1784
			$this->error=$langs->trans("ErrorWrongValueForParameter", "1");
1785
			return -1;
1786
		}
1787
		if (! $desc)
1788
		{
1789
			$this->error=$langs->trans("ErrorWrongValueForParameter", "3");
1790
			return -2;
1791
		}
1792
1793
		if ($this->id)
1794
		{
1795
			require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1796
1797
			$discount = new DiscountAbsolute($this->db);
1798
			$discount->fk_soc=$this->id;
1799
1800
			$discount->discount_type=$discount_type;
1801
1802
			$discount->amount_ht=$discount->multicurrency_amount_ht=price2num($remise, 'MT');
1803
			$discount->amount_tva=$discount->multicurrency_amount_tva=price2num($remise*$tva_tx/100, 'MT');
1804
			$discount->amount_ttc=$discount->multicurrency_amount_ttc=price2num($discount->amount_ht+$discount->amount_tva, 'MT');
1805
1806
			$discount->tva_tx=price2num($tva_tx, 'MT');
1807
			$discount->description=$desc;
1808
1809
			$result=$discount->create($user);
1810
			if ($result > 0)
1811
			{
1812
				return $result;
1813
			}
1814
			else
1815
			{
1816
				$this->error=$discount->error;
1817
				return -3;
1818
			}
1819
		}
1820
		else return 0;
1821
	}
1822
1823
	/**
1824
	 *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1825
	 *
1826
	 *	@param	User	$user			Filtre sur un user auteur des remises
1827
	 * 	@param	string	$filter			Filtre autre
1828
	 * 	@param	integer	$maxvalue		Filter on max value for discount
1829
	 * 	@param	int		$discount_type	0 => customer discount, 1 => supplier discount
1830
	 *	@return	int					<0 if KO, Credit note amount otherwise
1831
	 */
1832
    public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
1833
	{
1834
		require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1835
1836
		$discountstatic=new DiscountAbsolute($this->db);
1837
		$result=$discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
1838
		if ($result >= 0)
1839
		{
1840
			return $result;
1841
		}
1842
		else
1843
		{
1844
			$this->error=$discountstatic->error;
1845
			return -1;
1846
		}
1847
	}
1848
1849
	/**
1850
	 *  Return array of sales representatives
1851
	 *
1852
	 *  @param	User	$user		Object user
1853
	 *  @param	int		$mode		0=Array with properties, 1=Array of id.
1854
	 *  @return array       		Array of sales representatives of third party
1855
	 */
1856
    public function getSalesRepresentatives(User $user, $mode = 0)
1857
	{
1858
		global $conf;
1859
1860
		$reparray=array();
1861
1862
		$sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1863
		$sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1864
		if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1865
		{
1866
			$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1867
			$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1868
			$sql.= " AND ug.entity = ".$conf->entity.")";
1869
			$sql.= " OR u.admin = 1)";
1870
		}
1871
		else
1872
			$sql.= " WHERE entity in (0, ".$conf->entity.")";
1873
1874
		$sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1875
1876
		$resql = $this->db->query($sql);
1877
		if ($resql)
1878
		{
1879
			$num = $this->db->num_rows($resql);
1880
			$i=0;
1881
			while ($i < $num)
1882
			{
1883
				$obj = $this->db->fetch_object($resql);
1884
1885
				if (empty($mode))
1886
				{
1887
					$reparray[$i]['id']=$obj->rowid;
1888
					$reparray[$i]['lastname']=$obj->lastname;
1889
					$reparray[$i]['firstname']=$obj->firstname;
1890
					$reparray[$i]['email']=$obj->email;
1891
					$reparray[$i]['statut']=$obj->statut;
1892
					$reparray[$i]['entity']=$obj->entity;
1893
					$reparray[$i]['login']=$obj->login;
1894
					$reparray[$i]['photo']=$obj->photo;
1895
				}
1896
				else
1897
				{
1898
					$reparray[]=$obj->rowid;
1899
				}
1900
				$i++;
1901
			}
1902
			return $reparray;
1903
		}
1904
		else {
1905
			dol_print_error($this->db);
1906
			return -1;
1907
		}
1908
	}
1909
1910
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1911
	/**
1912
	 * Set the price level
1913
	 *
1914
	 * @param 	int		$price_level	Level of price
1915
	 * @param 	User	$user			Use making change
1916
	 * @return	int						<0 if KO, >0 if OK
1917
	 */
1918
    public function set_price_level($price_level, User $user)
1919
	{
1920
        // phpcs:enable
1921
		if ($this->id)
1922
		{
1923
			$now=dol_now();
1924
1925
			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1926
			$sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1927
			$sql .= " WHERE rowid = " . $this->id;
1928
1929
			if (! $this->db->query($sql))
1930
			{
1931
				dol_print_error($this->db);
1932
				return -1;
1933
			}
1934
1935
			$sql  = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1936
			$sql .= " (datec, fk_soc, price_level, fk_user_author)";
1937
			$sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1938
1939
			if (! $this->db->query($sql))
1940
			{
1941
				dol_print_error($this->db);
1942
				return -1;
1943
			}
1944
			return 1;
1945
		}
1946
		return -1;
1947
	}
1948
1949
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1950
	/**
1951
	 *	Add link to sales representative
1952
	 *
1953
	 *	@param	User	$user		Object user
1954
	 *	@param	int		$commid		Id of user
1955
	 *	@return	int					<=0 if KO, >0 if OK
1956
	 */
1957
    public function add_commercial(User $user, $commid)
1958
	{
1959
		// phpcs:enable
1960
		$error=0;
1961
1962
		if ($this->id > 0 && $commid > 0)
1963
		{
1964
		    $this->db->begin();
1965
1966
		    if (! $error)
1967
		    {
1968
    			$sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1969
    			$sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1970
1971
    			$resql = $this->db->query($sql);
1972
    			if (! $resql)
1973
    			{
1974
    			    dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
1975
    			    $error++;
1976
    			}
1977
		    }
1978
1979
		    if (! $error)
1980
    		{
1981
    			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1982
    			$sql.= " (fk_soc, fk_user)";
1983
    			$sql.= " VALUES (".$this->id.", ".$commid.")";
1984
1985
    			$resql = $this->db->query($sql);
1986
    			if (! $resql)
1987
    			{
1988
    				dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
1989
                    $error++;
1990
    			}
1991
    		}
1992
1993
			if (! $error)
1994
			{
1995
				$this->context=array('commercial_modified'=>$commid);
1996
1997
				$result=$this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
1998
                if ($result < 0)
1999
                {
2000
                    $error++;
2001
                }
2002
			}
2003
2004
			if (! $error)
2005
			{
2006
                $this->db->commit();
2007
                return 1;
2008
			}
2009
			else
2010
			{
2011
			    $this->db->rollback();
2012
			    return -1;
2013
			}
2014
		}
2015
2016
		return 0;
2017
	}
2018
2019
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2020
	/**
2021
	 *	Add link to sales representative
2022
	 *
2023
	 *	@param	User	$user		Object user
2024
	 *	@param	int		$commid		Id of user
2025
	 *	@return	void
2026
	 */
2027
    public function del_commercial(User $user, $commid)
2028
	{
2029
        // phpcs:enable
2030
		$error=0;
2031
		$this->context=array('commercial_modified'=>$commid);
2032
2033
		$result=$this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2034
        if ($result < 0) $error++;
2035
2036
		if ($this->id > 0 && $commid > 0)
2037
		{
2038
			$sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
2039
			$sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
2040
2041
			if (! $this->db->query($sql) )
2042
			{
2043
				dol_syslog(get_class($this)."::del_commercial Erreur");
2044
			}
2045
		}
2046
	}
2047
2048
2049
	/**
2050
	 *    	Return a link on thirdparty (with picto)
2051
	 *
2052
	 *		@param	int		$withpicto		          Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
2053
	 *		@param	string	$option			          Target of link ('', 'customer', 'prospect', 'supplier', 'project')
2054
	 *		@param	int		$maxlen			          Max length of name
2055
	 *      @param	int  	$notooltip		          1=Disable tooltip
2056
	 *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
2057
	 *		@return	string					          String with URL
2058
	 */
2059
    public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1)
2060
	{
2061
		global $conf, $langs, $hookmanager;
2062
2063
		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
2064
2065
		$name=$this->name?$this->name:$this->nom;
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

2065
		$name=$this->name?$this->name:/** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2066
2067
        if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
2068
            if (empty($option) && $this->client > 0) $option = 'customer';
2069
            if (empty($option) && $this->fournisseur > 0) $option = 'supplier';
2070
        }
2071
2072
2073
		if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
2074
		{
2075
			$code = '';
2076
			if (($this->client) && (! empty($this->code_client))
2077
				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2078
				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
2079
				)
2080
			)
2081
			{
2082
				$code = $this->code_client . ' - ';
2083
			}
2084
2085
			if (($this->fournisseur) && (! empty($this->code_fournisseur))
2086
				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2087
				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
2088
				)
2089
			)
2090
			{
2091
				$code .= $this->code_fournisseur . ' - ';
2092
			}
2093
2094
			if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
2095
			{
2096
				$name =$code.' '.$name;
2097
			}
2098
			else
2099
			{
2100
				$name =$code;
2101
			}
2102
		}
2103
2104
		if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
2105
2106
		$result=''; $label='';
2107
		$linkstart=''; $linkend='';
2108
2109
		if (! empty($this->logo) && class_exists('Form'))
2110
		{
2111
			$label.= '<div class="photointooltip">';
2112
			$label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0);	// Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
2113
			$label.= '</div><div style="clear: both;"></div>';
2114
		}
2115
2116
		$label.= '<div class="centpercent">';
2117
2118
		if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
2119
		{
2120
		   $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
2121
		   $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2122
		}
2123
		elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
2124
		{
2125
			$label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
2126
			$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2127
		}
2128
		elseif ($option == 'supplier')
2129
		{
2130
			$label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
2131
			$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2132
		}
2133
		elseif ($option == 'agenda')
2134
		{
2135
			$label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
2136
			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2137
		}
2138
		elseif ($option == 'project')
2139
		{
2140
			$label.= '<u>' . $langs->trans("ShowProject") . '</u>';
2141
			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2142
		}
2143
		elseif ($option == 'margin')
2144
		{
2145
			$label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
2146
			$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2147
		}
2148
		elseif ($option == 'contact')
2149
		{
2150
			$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
2151
			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2152
		}
2153
		elseif ($option == 'ban')
2154
		{
2155
			$label.= '<u>' . $langs->trans("ShowBan") . '</u>';
2156
			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2157
		}
2158
2159
		// By default
2160
		if (empty($linkstart))
2161
		{
2162
			$label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
2163
			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2164
		}
2165
2166
		if (! empty($this->name))
2167
		{
2168
			$label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
2169
			if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
2170
			$label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
2171
		}
2172
		if (! empty($this->country_code))
2173
			$label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
2174
		if (! empty($this->tva_intra) || (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false))
2175
			$label.= '<br><b>' . $langs->trans('VATIntra') . ':</b> '. $this->tva_intra;
2176
		if (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP))
2177
		{
2178
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) $label.= '<br><b>' . $langs->trans('ProfId1'.$this->country_code) . ':</b> '. $this->idprof1;
2179
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) $label.= '<br><b>' . $langs->trans('ProfId2'.$this->country_code) . ':</b> '. $this->idprof2;
2180
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) $label.= '<br><b>' . $langs->trans('ProfId3'.$this->country_code) . ':</b> '. $this->idprof3;
2181
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) $label.= '<br><b>' . $langs->trans('ProfId4'.$this->country_code) . ':</b> '. $this->idprof4;
2182
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) $label.= '<br><b>' . $langs->trans('ProfId5'.$this->country_code) . ':</b> '. $this->idprof5;
2183
			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) $label.= '<br><b>' . $langs->trans('ProfId6'.$this->country_code) . ':</b> '. $this->idprof6;
2184
		}
2185
		if (! empty($this->code_client) && ($this->client == 1 || $this->client == 3))
2186
			$label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
2187
		if (! empty($this->code_fournisseur) && $this->fournisseur)
2188
			$label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
2189
		if (! empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3))
2190
			$label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. ($this->code_compta ? $this->code_compta : $this->code_compta_client);
2191
		if (! empty($conf->accounting->enabled) && $this->fournisseur)
2192
			$label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
2193
2194
		$label.= '</div>';
2195
2196
		// Add type of canvas
2197
		$linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
2198
		// Add param to save lastsearch_values or not
2199
		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
2200
		if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
2201
		if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
2202
		$linkstart.='"';
2203
2204
		$linkclose='';
2205
		if (empty($notooltip))
2206
		{
2207
			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
2208
			{
2209
				$label=$langs->trans("ShowCompany");
2210
				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
2211
			}
2212
			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
2213
			$linkclose.=' class="classfortooltip refurl"';
2214
2215
		 	/*
2216
			$hookmanager->initHooks(array('thirdpartydao'));
2217
			$parameters=array('id'=>$this->id);
2218
			$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2219
			if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2220
			*/
2221
		}
2222
		$linkstart.=$linkclose.'>';
2223
		$linkend='</a>';
2224
2225
		global $user;
2226
		if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
2227
		{
2228
			$linkstart='';
2229
			$linkend='';
2230
		}
2231
2232
		$result.=$linkstart;
2233
		if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valignmiddle"'), 0, 0, $notooltip?0:1);
2234
		if ($withpicto != 2) $result.=($maxlen?dol_trunc($name, $maxlen):$name);
2235
		$result.=$linkend;
2236
2237
		global $action;
2238
		$hookmanager->initHooks(array('thirdpartydao'));
2239
		$parameters=array('id'=>$this->id, 'getnomurl'=>$result);
2240
		$reshook=$hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
2241
		if ($reshook > 0) $result = $hookmanager->resPrint;
2242
		else $result .= $hookmanager->resPrint;
2243
2244
		return $result;
2245
	}
2246
2247
	/**
2248
	 *    Return label of status (activity, closed)
2249
	 *
2250
	 *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2251
	 *    @return   string        		Libelle
2252
	 */
2253
    public function getLibStatut($mode = 0)
2254
	{
2255
		return $this->LibStatut($this->status, $mode);
2256
	}
2257
2258
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2259
	/**
2260
	 *  Renvoi le libelle d'un statut donne
2261
	 *
2262
	 *  @param	int		$statut         Id statut
2263
	 *  @param	int		$mode           0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2264
	 *  @return	string          		Libelle du statut
2265
	 */
2266
    public function LibStatut($statut, $mode = 0)
2267
	{
2268
        // phpcs:enable
2269
		global $langs;
2270
		$langs->load('companies');
2271
2272
		if ($mode == 0)
2273
		{
2274
			if ($statut==0) return $langs->trans("ActivityCeased");
2275
			elseif ($statut==1) return $langs->trans("InActivity");
2276
		}
2277
		elseif ($mode == 1)
2278
		{
2279
			if ($statut==0) return $langs->trans("ActivityCeased");
2280
			elseif ($statut==1) return $langs->trans("InActivity");
2281
		}
2282
		elseif ($mode == 2)
2283
		{
2284
			if ($statut==0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2285
			elseif ($statut==1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2286
		}
2287
		elseif ($mode == 3)
2288
		{
2289
			if ($statut==0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
2290
			elseif ($statut==1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
2291
		}
2292
		elseif ($mode == 4)
2293
		{
2294
			if ($statut==0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2295
			elseif ($statut==1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2296
		}
2297
		elseif ($mode == 5)
2298
		{
2299
			if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
2300
			elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
2301
		}
2302
		elseif ($mode == 6)
2303
		{
2304
			if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
2305
			elseif ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
2306
		}
2307
	}
2308
2309
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2310
	/**
2311
	 *    Return list of contacts emails existing for third party
2312
	 *
2313
	 *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2314
	 *    @return     array       					Array of contacts emails
2315
	 */
2316
    public function thirdparty_and_contact_email_array($addthirdparty = 0)
2317
	{
2318
        // phpcs:enable
2319
		global $langs;
2320
2321
		$contact_emails = $this->contact_property_array('email', 1);
2322
		if ($this->email && $addthirdparty)
2323
		{
2324
			if (empty($this->name)) $this->name=$this->nom;
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

2324
			if (empty($this->name)) $this->name=/** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2325
			$contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2326
		}
2327
		//var_dump($contact_emails)
2328
		return $contact_emails;
2329
	}
2330
2331
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2332
	/**
2333
	 *    Return list of contacts mobile phone existing for third party
2334
	 *
2335
	 *    @return     array       Array of contacts emails
2336
	 */
2337
    public function thirdparty_and_contact_phone_array()
2338
	{
2339
        // phpcs:enable
2340
		global $langs;
2341
2342
		$contact_phone = $this->contact_property_array('mobile');
2343
2344
		if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2345
		{
2346
			if (empty($this->name)) $this->name=$this->nom;
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

2346
			if (empty($this->name)) $this->name=/** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2347
			// TODO: Tester si tel non deja present dans tableau contact
2348
			$contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2349
		}
2350
		return $contact_phone;
2351
	}
2352
2353
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2354
	/**
2355
	 *  Return list of contacts emails or mobile existing for third party
2356
	 *
2357
	 *  @param	string	$mode       		'email' or 'mobile'
2358
	 * 	@param	int		$hidedisabled		1=Hide contact if disabled
2359
	 *  @return array       				Array of contacts emails or mobile. Example: array(id=>'Name <email>')
2360
	 */
2361
    public function contact_property_array($mode = 'email', $hidedisabled = 0)
2362
	{
2363
        // phpcs:enable
2364
		global $langs;
2365
2366
		$contact_property = array();
2367
2368
2369
		$sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2370
		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2371
		$sql.= " WHERE fk_soc = ".$this->id;
2372
2373
		$resql=$this->db->query($sql);
2374
		if ($resql)
2375
		{
2376
			$nump = $this->db->num_rows($resql);
2377
			if ($nump)
2378
			{
2379
				$sepa="("; $sepb=")";
2380
				if ($mode == 'email')
2381
				{
2382
					//$sepa="&lt;"; $sepb="&gt;";
2383
					$sepa="<"; $sepb=">";
2384
				}
2385
				$i = 0;
2386
				while ($i < $nump)
2387
				{
2388
					$obj = $this->db->fetch_object($resql);
2389
					if ($mode == 'email') $property=$obj->email;
2390
					elseif ($mode == 'mobile') $property=$obj->phone_mobile;
2391
					else $property=$obj->$mode;
2392
2393
					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2394
					if ($obj->statut == 1 || empty($hidedisabled))
2395
					{
2396
						if (empty($property))
2397
						{
2398
							if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail");
2399
							elseif ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone");
2400
						}
2401
2402
						if (!empty($obj->poste))
2403
						{
2404
							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2405
						}
2406
						else
2407
						{
2408
							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2409
						}
2410
					}
2411
					$i++;
2412
				}
2413
			}
2414
		}
2415
		else
2416
		{
2417
			dol_print_error($this->db);
2418
		}
2419
		return $contact_property;
2420
	}
2421
2422
2423
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2424
	/**
2425
	 *    Renvoie la liste des contacts de cette societe
2426
	 *
2427
	 *    @return     array      tableau des contacts
2428
	 */
2429
    public function contact_array()
2430
	{
2431
        // phpcs:enable
2432
		$contacts = array();
2433
2434
		$sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2435
		$resql=$this->db->query($sql);
2436
		if ($resql)
2437
		{
2438
			$nump = $this->db->num_rows($resql);
2439
			if ($nump)
2440
			{
2441
				$i = 0;
2442
				while ($i < $nump)
2443
				{
2444
					$obj = $this->db->fetch_object($resql);
2445
					$contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2446
					$i++;
2447
				}
2448
			}
2449
		}
2450
		else
2451
		{
2452
			dol_print_error($this->db);
2453
		}
2454
		return $contacts;
2455
	}
2456
2457
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2458
	/**
2459
	 *    Renvoie la liste des contacts de cette societe
2460
	 *
2461
	 *    @return    array    $contacts    tableau des contacts
2462
	 */
2463
    public function contact_array_objects()
2464
	{
2465
        // phpcs:enable
2466
		require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2467
		$contacts = array();
2468
2469
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2470
		$resql=$this->db->query($sql);
2471
		if ($resql)
2472
		{
2473
			$nump = $this->db->num_rows($resql);
2474
			if ($nump)
2475
			{
2476
				$i = 0;
2477
				while ($i < $nump)
2478
				{
2479
					$obj = $this->db->fetch_object($resql);
2480
					$contact = new Contact($this->db);
2481
					$contact->fetch($obj->rowid);
2482
					$contacts[] = $contact;
2483
					$i++;
2484
				}
2485
			}
2486
		}
2487
		else
2488
		{
2489
			dol_print_error($this->db);
2490
		}
2491
		return $contacts;
2492
	}
2493
2494
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2495
	/**
2496
	 *  Return property of contact from its id
2497
	 *
2498
	 *  @param	int		$rowid      id of contact
2499
	 *  @param  string	$mode       'email' or 'mobile'
2500
	 *  @return string  			Email of contact with format: "Full name <email>"
2501
	 */
2502
    public function contact_get_property($rowid, $mode)
2503
	{
2504
        // phpcs:enable
2505
		$contact_property='';
2506
2507
		if (empty($rowid)) return '';
2508
2509
		$sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2510
		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2511
		$sql.= " WHERE rowid = '".$rowid."'";
2512
2513
		$resql=$this->db->query($sql);
2514
		if ($resql)
2515
		{
2516
			$nump = $this->db->num_rows($resql);
2517
2518
			if ($nump)
2519
			{
2520
				$obj = $this->db->fetch_object($resql);
2521
2522
				if ($mode == 'email') $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
2523
				elseif ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2524
			}
2525
			return $contact_property;
2526
		}
2527
		else
2528
		{
2529
			dol_print_error($this->db);
2530
		}
2531
	}
2532
2533
2534
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2535
	/**
2536
	 *  Return bank number property of thirdparty (label or rum)
2537
	 *
2538
	 *	@param	string	$mode	'label' or 'rum' or 'format'
2539
	 *  @return	string			Bank number
2540
	 */
2541
    public function display_rib($mode = 'label')
2542
	{
2543
        // phpcs:enable
2544
		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2545
2546
		$bac = new CompanyBankAccount($this->db);
2547
		$bac->fetch(0, $this->id);
2548
2549
		if ($mode == 'label')
2550
		{
2551
			return $bac->getRibLabel(true);
2552
		}
2553
		elseif ($mode == 'rum')
2554
		{
2555
			if (empty($bac->rum))
2556
			{
2557
				require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2558
				$prelevement = new BonPrelevement($this->db);
2559
				$bac->fetch_thirdparty();
2560
				$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2561
			}
2562
			return $bac->rum;
2563
		}
2564
		elseif ($mode == 'format')
2565
		{
2566
			return $bac->frstrecur;
2567
		}
2568
2569
		return 'BadParameterToFunctionDisplayRib';
2570
	}
2571
2572
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2573
	/**
2574
	 * Return Array of RIB
2575
	 *
2576
	 * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
2577
	 */
2578
    public function get_all_rib()
2579
	{
2580
        // phpcs:enable
2581
		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2582
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id;
2583
		$result = $this->db->query($sql);
2584
		if (!$result) {
2585
			$this->error++;
2586
			$this->errors[] = $this->db->lasterror;
2587
			return 0;
2588
		} else {
2589
			$num_rows = $this->db->num_rows($result);
2590
			$rib_array = array();
2591
			if ($num_rows) {
2592
				while ($obj = $this->db->fetch_object($result)) {
2593
					$rib = new CompanyBankAccount($this->db);
2594
					$rib->fetch($obj->rowid);
2595
					$rib_array[] = $rib;
2596
				}
2597
			}
2598
			return $rib_array;
2599
		}
2600
	}
2601
2602
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2603
	/**
2604
	 *  Attribut un code client a partir du module de controle des codes.
2605
	 *  Return value is stored into this->code_client
2606
	 *
2607
	 *	@param	Societe		$objsoc		Object thirdparty
2608
	 *	@param	int			$type		Should be 0 to say customer
2609
	 *  @return void
2610
	 */
2611
    public function get_codeclient($objsoc = 0, $type = 0)
2612
	{
2613
        // phpcs:enable
2614
		global $conf;
2615
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2616
		{
2617
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2618
2619
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2620
			foreach ($dirsociete as $dirroot)
2621
			{
2622
				$res=dol_include_once($dirroot.$module.'.php');
2623
				if ($res) break;
2624
			}
2625
			$mod = new $module();
2626
2627
			$this->code_client = $mod->getNextValue($objsoc, $type);
2628
			$this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2629
2630
			dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2631
		}
2632
	}
2633
2634
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2635
	/**
2636
	 *  Attribut un code fournisseur a partir du module de controle des codes.
2637
	 *  Return value is stored into this->code_fournisseur
2638
	 *
2639
	 *	@param	Societe		$objsoc		Object thirdparty
2640
	 *	@param	int			$type		Should be 1 to say supplier
2641
	 *  @return void
2642
	 */
2643
    public function get_codefournisseur($objsoc = 0, $type = 1)
2644
	{
2645
        // phpcs:enable
2646
		global $conf;
2647
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2648
		{
2649
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2650
2651
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2652
			foreach ($dirsociete as $dirroot)
2653
			{
2654
				$res=dol_include_once($dirroot.$module.'.php');
2655
				if ($res) break;
2656
			}
2657
			$mod = new $module();
2658
2659
			$this->code_fournisseur = $mod->getNextValue($objsoc, $type);
2660
2661
			dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2662
		}
2663
	}
2664
2665
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2666
	/**
2667
	 *    Verifie si un code client est modifiable en fonction des parametres
2668
	 *    du module de controle des codes.
2669
	 *
2670
	 *    @return     int		0=No, 1=Yes
2671
	 */
2672
    public function codeclient_modifiable()
2673
	{
2674
        // phpcs:enable
2675
		global $conf;
2676
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2677
		{
2678
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2679
2680
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2681
			foreach ($dirsociete as $dirroot)
2682
			{
2683
				$res=dol_include_once($dirroot.$module.'.php');
2684
				if ($res) break;
2685
			}
2686
2687
			$mod = new $module();
2688
2689
			dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2690
			if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2691
			if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2692
			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2693
			return 0;
2694
		}
2695
		else
2696
		{
2697
			return 0;
2698
		}
2699
	}
2700
2701
2702
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2703
	/**
2704
	 *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
2705
	 *
2706
	 *    @return     int		0=No, 1=Yes
2707
	 */
2708
    public function codefournisseur_modifiable()
2709
	{
2710
        // phpcs:enable
2711
		global $conf;
2712
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2713
		{
2714
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2715
2716
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2717
			foreach ($dirsociete as $dirroot)
2718
			{
2719
				$res=dol_include_once($dirroot.$module.'.php');
2720
				if ($res) break;
2721
			}
2722
2723
			$mod = new $module();
2724
2725
			dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2726
			if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2727
			if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2728
			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2729
			return 0;
2730
		}
2731
		else
2732
		{
2733
			return 0;
2734
		}
2735
	}
2736
2737
2738
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2739
	/**
2740
	 *  Check customer code
2741
	 *
2742
	 *  @return     int				0 if OK
2743
	 * 								-1 ErrorBadCustomerCodeSyntax
2744
	 * 								-2 ErrorCustomerCodeRequired
2745
	 * 								-3 ErrorCustomerCodeAlreadyUsed
2746
	 * 								-4 ErrorPrefixRequired
2747
	 */
2748
    public function check_codeclient()
2749
	{
2750
        // phpcs:enable
2751
		global $conf;
2752
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2753
		{
2754
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2755
2756
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2757
			foreach ($dirsociete as $dirroot)
2758
			{
2759
				$res=dol_include_once($dirroot.$module.'.php');
2760
				if ($res) break;
2761
			}
2762
2763
			$mod = new $module();
2764
2765
		   	dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2766
		   	$result = $mod->verif($this->db, $this->code_client, $this, 0);
2767
			return $result;
2768
		}
2769
		else
2770
		{
2771
			return 0;
2772
		}
2773
	}
2774
2775
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2776
	/**
2777
	 *    Check supplier code
2778
	 *
2779
	 *    @return     int		0 if OK
2780
	 * 							-1 ErrorBadCustomerCodeSyntax
2781
	 * 							-2 ErrorCustomerCodeRequired
2782
	 * 							-3 ErrorCustomerCodeAlreadyUsed
2783
	 * 							-4 ErrorPrefixRequired
2784
	 */
2785
    public function check_codefournisseur()
2786
	{
2787
        // phpcs:enable
2788
		global $conf;
2789
		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2790
		{
2791
			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2792
2793
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2794
			foreach ($dirsociete as $dirroot)
2795
			{
2796
				$res=dol_include_once($dirroot.$module.'.php');
2797
				if ($res) break;
2798
			}
2799
2800
			$mod = new $module();
2801
2802
			dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2803
			$result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2804
			return $result;
2805
		}
2806
		else
2807
		{
2808
			return 0;
2809
		}
2810
	}
2811
2812
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2813
	/**
2814
	 *    	Renvoie un code compta, suivant le module de code compta.
2815
	 *      Peut etre identique a celui saisit ou genere automatiquement.
2816
	 *      A ce jour seule la generation automatique est implementee
2817
	 *
2818
	 *    	@param	string	$type		Type of thirdparty ('customer' or 'supplier')
2819
	 *		@return	string				Code compta si ok, 0 si aucun, <0 si ko
2820
	 */
2821
    public function get_codecompta($type)
2822
	{
2823
        // phpcs:enable
2824
		global $conf;
2825
2826
		if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2827
		{
2828
			$res=false;
2829
			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2830
			foreach ($dirsociete as $dirroot)
2831
			{
2832
				$res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
2833
				if ($res) break;
2834
			}
2835
2836
			if ($res)
2837
			{
2838
				$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2839
				$mod = new $classname;
2840
2841
				// Defini code compta dans $mod->code
2842
				$result = $mod->get_code($this->db, $this, $type);
2843
2844
				if ($type == 'customer') $this->code_compta = $mod->code;
2845
				elseif ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2846
2847
				return $result;
2848
			}
2849
			else
2850
			{
2851
				$this->error = 'ErrorAccountancyCodeNotDefined';
2852
				return -1;
2853
			}
2854
		}
2855
		else
2856
		{
2857
			if ($type == 'customer') $this->code_compta = '';
2858
			elseif ($type == 'supplier') $this->code_compta_fournisseur = '';
2859
2860
			return 0;
2861
		}
2862
	}
2863
2864
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2865
	/**
2866
	 *    Define parent commany of current company
2867
	 *
2868
	 *    @param	int		$id     Id of thirdparty to set or '' to remove
2869
	 *    @return	int     		<0 if KO, >0 if OK
2870
	 */
2871
    public function set_parent($id)
2872
	{
2873
        // phpcs:enable
2874
		if ($this->id)
2875
		{
2876
			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2877
			$sql.= " SET parent = ".($id > 0 ? $id : "null");
2878
			$sql.= " WHERE rowid = " . $this->id;
2879
			dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2880
			$resql=$this->db->query($sql);
2881
			if ($resql)
2882
			{
2883
				$this->parent = $id;
2884
				return 1;
2885
			}
2886
			else
2887
			{
2888
				return -1;
2889
			}
2890
		}
2891
		else return -1;
2892
	}
2893
2894
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2895
	/**
2896
	 *  Returns if a profid sould be verified
2897
	 *
2898
	 *  @param	int		$idprof		1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2899
	 *  @return boolean         	true , false
2900
	 */
2901
    public function id_prof_verifiable($idprof)
2902
	{
2903
        // phpcs:enable
2904
		global $conf;
2905
2906
	 	switch($idprof)
2907
		{
2908
			case 1:
2909
				$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2910
				break;
2911
			case 2:
2912
				$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2913
				break;
2914
			case 3:
2915
				$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2916
				break;
2917
			case 4:
2918
				$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2919
				break;
2920
			case 5:
2921
				$ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2922
				break;
2923
			case 6:
2924
				$ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2925
				break;
2926
			default:
2927
				$ret=false;
2928
		}
2929
2930
		return $ret;
2931
	}
2932
2933
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2934
	/**
2935
	 *    Verify if a profid exists into database for others thirds
2936
	 *
2937
	 *    @param	string	$idprof		'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2938
	 *    @param	string	$value		Value of profid
2939
	 *    @param	int		$socid		Id of thirdparty to exclude (if update)
2940
	 *    @return   boolean				True if exists, False if not
2941
	 */
2942
    public function id_prof_exists($idprof, $value, $socid = 0)
2943
	{
2944
        // phpcs:enable
2945
		$field = $idprof;
2946
2947
	 	switch($idprof)	// For backward compatibility
2948
		{
2949
			case '1':
2950
			case 'idprof1':
2951
				$field="siren";
2952
				break;
2953
			case '2':
2954
			case 'idprof2':
2955
				$field="siret";
2956
				break;
2957
			case '3':
2958
			case 'idprof3':
2959
				$field="ape";
2960
				break;
2961
			case '4':
2962
			case 'idprof4':
2963
				$field="idprof4";
2964
				break;
2965
			case '5':
2966
				$field="idprof5";
2967
				break;
2968
			case '6':
2969
				$field="idprof6";
2970
				break;
2971
	 	}
2972
2973
		 //Verify duplicate entries
2974
		$sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2975
		if($socid) $sql .= " AND rowid <> ".$socid;
2976
		$resql = $this->db->query($sql);
2977
		if ($resql)
2978
		{
2979
			$obj = $this->db->fetch_object($resql);
2980
			$count = $obj->idprof;
2981
		}
2982
		else
2983
		{
2984
			$count = 0;
2985
			print $this->db->error();
2986
		}
2987
		$this->db->free($resql);
2988
2989
		if ($count > 0) return true;
2990
		else return false;
2991
	}
2992
2993
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2994
	/**
2995
	 *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
2996
	 *
2997
	 *  @param	int			$idprof         1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
2998
	 *  @param  Societe		$soc            Objet societe
2999
	 *  @return int             			<=0 if KO, >0 if OK
3000
	 *  TODO better to have this in a lib than into a business class
3001
	 */
3002
    public function id_prof_check($idprof, $soc)
3003
	{
3004
        // phpcs:enable
3005
		global $conf;
3006
3007
		$ok=1;
3008
3009
		if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
3010
3011
		// Verifie SIREN si pays FR
3012
		if ($idprof == 1 && $soc->country_code == 'FR')
3013
		{
3014
			$chaine=trim($this->idprof1);
3015
			$chaine=preg_replace('/(\s)/', '', $chaine);
3016
3017
			if (!is_numeric($chaine)) return -1;
3018
			if (dol_strlen($chaine) != 9) return -1;
3019
3020
			// on prend chaque chiffre un par un
3021
			// si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3022
			// on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3023
			// on ajoute cette valeur à la somme totale
3024
3025
			for ($index = 0; $index < 9; $index ++)
3026
			{
3027
				$number = (int) $chaine[$index];
3028
				if (($index % 2) != 0) { if (($number *= 2) > 9) $number -= 9; }
3029
				$sum += $number;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sum seems to be never defined.
Loading history...
3030
			}
3031
3032
			// le numéro est valide si la somme des chiffres est multiple de 10
3033
			if (($sum % 10) != 0) return -1;
3034
		}
3035
3036
		// Verifie SIRET si pays FR
3037
		if ($idprof == 2 && $soc->country_code == 'FR')
3038
		{
3039
			$chaine=trim($this->idprof2);
3040
			$chaine=preg_replace('/(\s)/', '', $chaine);
3041
3042
			if (!is_numeric($chaine)) return -1;
3043
			if (dol_strlen($chaine) != 14) return -1;
3044
3045
			// on prend chaque chiffre un par un
3046
			// si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3047
			// on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3048
			// on ajoute cette valeur à la somme totale
3049
3050
			for ($index = 0; $index < 14; $index ++)
3051
			{
3052
				$number = (int) $chaine[$index];
3053
				if (($index % 2) == 0) { if (($number *= 2) > 9) $number -= 9; }
3054
				$sum += $number;
3055
			}
3056
3057
			// le numéro est valide si la somme des chiffres est multiple de 10
3058
			if (($sum % 10) != 0) return -1;
3059
		}
3060
3061
		//Verify CIF/NIF/NIE if pays ES
3062
		//Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
3063
		if ($idprof == 1 && $soc->country_code == 'ES')
3064
		{
3065
			$string=trim($this->idprof1);
3066
			$string=preg_replace('/(\s)/', '', $string);
3067
			$string = strtoupper($string);
3068
3069
			//Check format
3070
			if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
3071
			return 0;
3072
3073
			$num = array();
3074
			for ($i = 0; $i < 9; $i ++)
3075
			{
3076
				$num[$i] = substr($string, $i, 1);
3077
			}
3078
3079
			//Check NIF
3080
			if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
3081
				if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
3082
				return 1;
3083
				else
3084
				return -1;
3085
3086
			//algorithm checking type code CIF
3087
			$sum = $num[2] + $num[4] + $num[6];
3088
			for ($i = 1; $i < 8; $i += 2)
3089
			$sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3090
			$n = 10 - substr($sum, strlen($sum) - 1, 1);
3091
3092
			//Chek special NIF
3093
			if (preg_match('/^[KLM]{1}/', $string))
3094
				if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
3095
				return 1;
3096
				else
3097
				return -1;
3098
3099
			//Check CIF
3100
			if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
3101
				if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
3102
				return 2;
3103
				else
3104
				return -2;
3105
3106
			//Check NIE T
3107
			if (preg_match('/^[T]{1}/', $string))
3108
				if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
3109
				return 3;
3110
				else
3111
				return -3;
3112
3113
			//Check NIE XYZ
3114
			if (preg_match('/^[XYZ]{1}/', $string))
3115
				if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
3116
				return 3;
3117
				else
3118
				return -3;
3119
3120
			//Can not be verified
3121
			return -4;
3122
		}
3123
3124
		//Verify NIF if country is PT
3125
		//Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3126
		if ($idprof == 1 && $soc->country_code == 'PT')
3127
		{
3128
			$string=trim($this->idprof1);
3129
			$string=preg_replace('/(\s)/', '', $string);
3130
3131
			for ($i = 0; $i < 9; $i ++) {
3132
				$num[$i] = substr($string, $i, 1);
3133
			}
3134
3135
			//Check NIF
3136
			if (preg_match('/(^[0-9]{9}$)/', $string)) {
3137
				return 1;
3138
			}
3139
			else {
3140
				return -1;
3141
			}
3142
		}
3143
3144
		return $ok;
3145
	}
3146
3147
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3148
	/**
3149
	 *   Return an url to check online a professional id or empty string
3150
	 *
3151
	 *   @param		int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
3152
	 *   @param 	Societe	$thirdparty     Object thirdparty
3153
	 *   @return	string          		Url or empty string if no URL known
3154
	 *   TODO better in a lib than into business class
3155
	 */
3156
    public function id_prof_url($idprof, $thirdparty)
3157
	{
3158
        // phpcs:enable
3159
		global $conf,$langs,$hookmanager;
3160
3161
		$url='';
3162
		$action = '';
3163
3164
		$hookmanager->initHooks(array('idprofurl'));
3165
		$parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
3166
		$reshook=$hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3167
		if (empty($reshook)) {
3168
			if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3169
				return '';
3170
			}
3171
3172
			// TODO Move links to validate professional ID into a dictionary table "country" + "link"
3173
            $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3174
			if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3175
				$url='http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1;    // See also http://avis-situation-sirene.insee.fr/
3176
			}
3177
			if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3178
				$url='https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3179
			}
3180
			if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3181
				$url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3182
			}
3183
			if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3184
				$url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3185
			}
3186
			if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3187
				$url='http://www.nif.pt/'.$strippedIdProf1;
3188
			}
3189
3190
			if ($url) {
3191
				return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
3192
			}
3193
		}
3194
		else {
3195
			return $hookmanager->resPrint;
3196
		}
3197
3198
		return '';
3199
	}
3200
3201
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3202
	/**
3203
	 *   Indique si la societe a des projets
3204
	 *
3205
	 *   @return     bool	   true si la societe a des projets, false sinon
3206
	 */
3207
    public function has_projects()
3208
	{
3209
        // phpcs:enable
3210
		$sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
3211
		$resql = $this->db->query($sql);
3212
		if ($resql)
3213
		{
3214
			$obj = $this->db->fetch_object($resql);
3215
			$count = $obj->numproj;
3216
		}
3217
		else
3218
		{
3219
			$count = 0;
3220
			print $this->db->error();
3221
		}
3222
		$this->db->free($resql);
3223
		return ($count > 0);
3224
	}
3225
3226
3227
	/**
3228
	 *  Load information for tab info
3229
	 *
3230
	 *  @param  int		$id     Id of thirdparty to load
3231
	 *  @return	void
3232
	 */
3233
    public function info($id)
3234
	{
3235
		$sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
3236
		$sql.= " fk_user_creat, fk_user_modif";
3237
		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
3238
		$sql.= " WHERE s.rowid = ".$id;
3239
3240
		$result=$this->db->query($sql);
3241
		if ($result)
3242
		{
3243
			if ($this->db->num_rows($result))
3244
			{
3245
				$obj = $this->db->fetch_object($result);
3246
3247
				$this->id = $obj->rowid;
3248
3249
				if ($obj->fk_user_creat) {
3250
					$cuser = new User($this->db);
3251
					$cuser->fetch($obj->fk_user_creat);
3252
					$this->user_creation     = $cuser;
3253
				}
3254
3255
				if ($obj->fk_user_modif) {
3256
					$muser = new User($this->db);
3257
					$muser->fetch($obj->fk_user_modif);
3258
					$this->user_modification = $muser;
3259
				}
3260
3261
				$this->ref			     = $obj->name;
3262
				$this->date_creation     = $this->db->jdate($obj->date_creation);
3263
				$this->date_modification = $this->db->jdate($obj->date_modification);
3264
			}
3265
3266
			$this->db->free($result);
3267
		}
3268
		else
3269
		{
3270
			dol_print_error($this->db);
3271
		}
3272
	}
3273
3274
	/**
3275
	 *  Return if third party is a company (Business) or an end user (Consumer)
3276
	 *
3277
	 *  @return    boolean     true=is a company, false=a and user
3278
	 */
3279
    public function isACompany()
3280
	{
3281
		global $conf;
3282
3283
		// Define if third party is treated as company (or not) when nature is unknown
3284
		$isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
3285
		if (! empty($this->tva_intra)) $isacompany=1;
3286
		elseif (! empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN')
3287
		{
3288
			// TODO Add a field is_a_company into dictionary
3289
			if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany=0;
3290
			else $isacompany=1;
3291
		}
3292
3293
		return $isacompany;
3294
	}
3295
3296
	/**
3297
	 *  Return if a company is inside the EEC (European Economic Community)
3298
	 *
3299
	 *  @return     boolean		true = country inside EEC, false = country outside EEC
3300
	 */
3301
    public function isInEEC()
3302
	{
3303
		require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3304
		return isInEEC($this);
3305
	}
3306
3307
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3308
	/**
3309
	 *  Charge la liste des categories fournisseurs
3310
	 *
3311
	 *  @return    int      0 if success, <> 0 if error
3312
	 */
3313
    public function LoadSupplierCateg()
3314
	{
3315
        // phpcs:enable
3316
		$this->SupplierCategories = array();
3317
		$sql = "SELECT rowid, label";
3318
		$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
3319
		$sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3320
3321
		$resql=$this->db->query($sql);
3322
		if ($resql)
3323
		{
3324
			while ($obj = $this->db->fetch_object($resql) )
3325
			{
3326
				$this->SupplierCategories[$obj->rowid] = $obj->label;
3327
			}
3328
			return 0;
3329
		}
3330
		else
3331
		{
3332
			return -1;
3333
		}
3334
	}
3335
3336
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3337
	/**
3338
	 *  Insert link supplier - category
3339
	 *
3340
	 *	@param	int		$categorie_id		Id of category
3341
	 *  @return int      					0 if success, <> 0 if error
3342
	 */
3343
    public function AddFournisseurInCategory($categorie_id)
3344
	{
3345
        // phpcs:enable
3346
		if ($categorie_id > 0 && $this->id > 0)
3347
		{
3348
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3349
			$sql.= " VALUES (".$categorie_id.", ".$this->id.")";
3350
3351
			if ($resql=$this->db->query($sql)) return 0;
3352
		}
3353
		else
3354
		{
3355
			return 0;
3356
		}
3357
		return -1;
3358
	}
3359
3360
3361
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3362
	/**
3363
	 *  Create a third party into database from a member object
3364
	 *
3365
	 *  @param	Adherent	$member			Object member
3366
	 * 	@param	string		$socname		Name of third party to force
3367
	 *	@param	string		$socalias		Alias name of third party to force
3368
	 *  @param	string		$customercode	Customer code
3369
	 *  @return int							<0 if KO, id of created account if OK
3370
	 */
3371
    public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
3372
	{
3373
        // phpcs:enable
3374
		global $user,$langs;
3375
3376
		dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3377
3378
		$name = $socname?$socname:$member->societe;
1 ignored issue
show
Deprecated Code introduced by
The property Adherent::$societe has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

3378
		$name = $socname?$socname:/** @scrutinizer ignore-deprecated */ $member->societe;
Loading history...
3379
		if (empty($name)) $name=$member->getFullName($langs);
3380
3381
		$alias = $socalias?$socalias:'';
3382
3383
		// Positionne parametres
3384
		$this->nom=$name;				// TODO deprecated
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

3384
		/** @scrutinizer ignore-deprecated */ $this->nom=$name;				// TODO deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3385
		$this->name=$name;
3386
		$this->name_alias=$alias;
3387
		$this->address=$member->address;
3388
		$this->zip=$member->zip;
3389
		$this->town=$member->town;
3390
		$this->country_code=$member->country_code;
3391
		$this->country_id=$member->country_id;
3392
		$this->phone=$member->phone;       // Prof phone
3393
		$this->email=$member->email;
3394
		$this->skype=$member->skype;
3395
		$this->twitter=$member->twitter;
3396
		$this->facebook=$member->facebook;
3397
		$this->linkedin=$member->linkedin;
3398
3399
		$this->client = 1;				// A member is a customer by default
3400
		$this->code_client = ($customercode?$customercode:-1);
3401
		$this->code_fournisseur = -1;
3402
3403
		$this->db->begin();
3404
3405
		// Cree et positionne $this->id
3406
		$result=$this->create($user);
3407
		if ($result >= 0)
3408
		{
3409
			$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3410
			$sql.= " SET fk_soc=".$this->id;
3411
			$sql.= " WHERE rowid=".$member->id;
3412
3413
			$resql=$this->db->query($sql);
3414
			if ($resql)
3415
			{
3416
				$this->db->commit();
3417
				return $this->id;
3418
			}
3419
			else
3420
			{
3421
				$this->error=$this->db->error();
3422
3423
				$this->db->rollback();
3424
				return -1;
3425
			}
3426
		}
3427
		else
3428
		{
3429
			// $this->error deja positionne
3430
			dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
3431
3432
			$this->db->rollback();
3433
			return $result;
3434
		}
3435
	}
3436
3437
	/**
3438
	 * 	Set properties with value into $conf
3439
	 *
3440
	 * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3441
	 * 	@return	void
3442
	 */
3443
    public function setMysoc(Conf $conf)
3444
	{
3445
		global $langs;
3446
3447
		$this->id=0;
3448
		$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3449
		$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3450
		$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3451
		$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3452
		$this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION;
1 ignored issue
show
Documentation Bug introduced by
It seems like empty($conf->global->MAI...AIN_INFO_SOCIETE_REGION can also be of type string. However, the property $region_code is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3453
		$this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT;
3454
3455
		$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3456
3457
		$this->nom=$this->name; 									// deprecated
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

3457
		/** @scrutinizer ignore-deprecated */ $this->nom=$this->name; 									// deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3458
3459
		// We define country_id, country_code and country
3460
		$country_id=$country_code=$country_label='';
3461
		if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3462
		{
3463
			$tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3464
			$country_id=$tmp[0];
3465
			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3466
			{
3467
				$country_code=$tmp[1];
3468
				$country_label=$tmp[2];
3469
			}
3470
			else                    // For backward compatibility
3471
			{
3472
				dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
3473
				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3474
				$country_code=getCountry($country_id, 2, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3475
				$country_label=getCountry($country_id, 0, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3476
			}
3477
		}
3478
		$this->country_id=$country_id;
1 ignored issue
show
Documentation Bug introduced by
The property $country_id was declared of type integer, but $country_id is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
3479
		$this->country_code=$country_code;
3480
		$this->country=$country_label;
3481
		if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3482
3483
		//TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
3484
		// We define state_id, state_code and state
3485
		$state_id=0;$state_code=$state_label='';
3486
		if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE))
3487
		{
3488
			$tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
3489
			$state_id=$tmp[0];
3490
			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
3491
			{
3492
				$state_code=$tmp[1];
3493
				$state_label=$tmp[2];
3494
			}
3495
			else                    // For backward compatibility
3496
			{
3497
				dol_syslog("Your state setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3498
				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3499
				$state_code=getState($state_id, 2, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3500
				$state_label=getState($state_id, 0, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3501
			}
3502
		}
3503
		$this->state_id=$state_id;
1 ignored issue
show
Documentation Bug introduced by
It seems like $state_id can also be of type string. However, the property $state_id is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3504
		$this->state_code=$state_code;
3505
		$this->state=$state_label;
3506
		if (is_object($langs)) $this->state=($langs->trans('State'.$state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label;
1 ignored issue
show
Bug introduced by
Are you sure $state_code of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3506
		if (is_object($langs)) $this->state=($langs->trans('State'./** @scrutinizer ignore-type */ $state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label;
Loading history...
3507
3508
		$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3509
		$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3510
		$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3511
		// Id prof generiques
3512
		$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3513
		$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3514
		$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3515
		$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3516
		$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3517
		$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3518
		$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3519
		$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3520
		$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3521
		$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3522
		$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3523
		$this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT);
3524
		$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3525
		$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3526
		$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3527
3528
		// Define if company use vat or not
3529
		$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3530
3531
		// Define if company use local taxes
3532
		$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3533
		$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3534
	}
3535
3536
	/**
3537
	 *  Initialise an instance with random values.
3538
	 *  Used to build previews or test instances.
3539
	 *	id must be 0 if object instance is a specimen.
3540
	 *
3541
	 *  @return	void
3542
	 */
3543
    public function initAsSpecimen()
3544
	{
3545
		$now=dol_now();
3546
3547
		// Initialize parameters
3548
		$this->id=0;
3549
		$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
3550
		$this->nom = $this->name;   // For backward compatibility
1 ignored issue
show
Deprecated Code introduced by
The property Societe::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

3550
		/** @scrutinizer ignore-deprecated */ $this->nom = $this->name;   // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3551
		$this->ref_ext = 'Ref ext';
3552
		$this->specimen=1;
3553
		$this->address='21 jump street';
3554
		$this->zip='99999';
3555
		$this->town='MyTown';
3556
		$this->state_id=1;
3557
		$this->state_code='AA';
3558
		$this->state='MyState';
3559
		$this->country_id=1;
3560
		$this->country_code='FR';
3561
		$this->email='[email protected]';
3562
		$this->skype='tom.hanson';
3563
		$this->twitter='tomhanson';
3564
		$this->facebook='tomhanson';
3565
		$this->linkedin='tomhanson';
3566
		$this->url='http://www.specimen.com';
3567
3568
		$this->phone='0909090901';
3569
		$this->fax='0909090909';
3570
3571
		$this->code_client='CC-'.dol_print_date($now, 'dayhourlog');
3572
		$this->code_fournisseur='SC-'.dol_print_date($now, 'dayhourlog');
3573
		$this->capital=10000;
3574
		$this->client=1;
3575
		$this->prospect=1;
3576
		$this->fournisseur=1;
3577
		$this->tva_assuj=1;
3578
		$this->tva_intra='EU1234567';
3579
		$this->note_public='This is a comment (public)';
3580
		$this->note_private='This is a comment (private)';
3581
3582
		$this->idprof1='idprof1';
3583
		$this->idprof2='idprof2';
3584
		$this->idprof3='idprof3';
3585
		$this->idprof4='idprof4';
3586
		$this->idprof5='idprof5';
3587
		$this->idprof6='idprof6';
3588
	}
3589
3590
	/**
3591
	 *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3592
	 *
3593
	 *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3594
	 *  @return		boolean					true or false
3595
	 */
3596
    public function useLocalTax($localTaxNum = 0)
3597
	{
3598
		$sql  = "SELECT t.localtax1, t.localtax2";
3599
		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3600
		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3601
		$sql .= " AND t.active = 1";
3602
		if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3603
		elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3604
		elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3605
3606
		dol_syslog("useLocalTax", LOG_DEBUG);
3607
		$resql=$this->db->query($sql);
3608
		if ($resql)
3609
		{
3610
   			return ($this->db->num_rows($resql) > 0);
3611
		}
3612
		else return false;
3613
	}
3614
3615
	/**
3616
	 *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3617
	 *
3618
	 *  @return		boolean					true or false
3619
	 */
3620
    public function useNPR()
3621
	{
3622
		$sql  = "SELECT t.rowid";
3623
		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3624
		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3625
		$sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3626
3627
		dol_syslog("useNPR", LOG_DEBUG);
3628
		$resql=$this->db->query($sql);
3629
		if ($resql)
3630
		{
3631
			return ($this->db->num_rows($resql) > 0);
3632
		}
3633
		else return false;
3634
	}
3635
3636
	/**
3637
	 *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3638
	 *
3639
	 *  @return		boolean			true or false
3640
	 */
3641
    public function useRevenueStamp()
3642
	{
3643
		$sql  = "SELECT COUNT(*) as nb";
3644
		$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3645
		$sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3646
		$sql .= " AND r.active = 1";
3647
3648
		dol_syslog("useRevenueStamp", LOG_DEBUG);
3649
		$resql=$this->db->query($sql);
3650
		if ($resql)
3651
		{
3652
			$obj=$this->db->fetch_object($resql);
3653
   			return (($obj->nb > 0)?true:false);
3654
		}
3655
		else
3656
		{
3657
			$this->error=$this->db->lasterror();
3658
			return false;
3659
		}
3660
	}
3661
3662
	/**
3663
	 *	Return prostect level
3664
	 *
3665
	 *  @return     string        Libelle
3666
	 */
3667
    public function getLibProspLevel()
3668
	{
3669
		return $this->LibProspLevel($this->fk_prospectlevel);
3670
	}
3671
3672
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3673
	/**
3674
	 *  Return label of prospect level
3675
	 *
3676
	 *  @param	int		$fk_prospectlevel   	Prospect level
3677
	 *  @return string        					label of level
3678
	 */
3679
    public function LibProspLevel($fk_prospectlevel)
3680
	{
3681
        // phpcs:enable
3682
		global $langs;
3683
3684
		$lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
3685
		// If lib not found in language file, we get label from cache/databse
3686
		if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
3687
		{
3688
			$lib=$langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
3689
		}
3690
		return $lib;
3691
	}
3692
3693
3694
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3695
	/**
3696
	 *  Set prospect level
3697
	 *
3698
	 *  @param  User	$user		Utilisateur qui definie la remise
3699
	 *	@return	int					<0 if KO, >0 if OK
3700
	 * @deprecated Use update function instead
3701
	 */
3702
    public function set_prospect_level(User $user)
3703
	{
3704
        // phpcs:enable
3705
		return $this->update($this->id, $user);
3706
	}
3707
3708
	/**
3709
	 *  Return status of prospect
3710
	 *
3711
	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
3712
	 *  @param	string	$label		Label to use for status for added status
3713
	 *  @return string        		Libelle
3714
	 */
3715
    public function getLibProspCommStatut($mode = 0, $label = '')
3716
	{
3717
		return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3718
	}
3719
3720
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3721
	/**
3722
	 *  Return label of a given status
3723
	 *
3724
	 *  @param	int|string	$statut        	Id or code for prospection status
3725
	 *  @param  int			$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
3726
	 *  @param	string		$label			Label to use for status for added status
3727
	 *  @return string       	 			Libelle du statut
3728
	 */
3729
    public function LibProspCommStatut($statut, $mode = 0, $label = '')
3730
	{
3731
        // phpcs:enable
3732
		global $langs;
3733
		$langs->load('customers');
3734
3735
		if ($mode == 2)
3736
		{
3737
			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1");
3738
			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3739
			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3740
			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3741
			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3742
			else
3743
			{
3744
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3745
			}
3746
		}
3747
		if ($mode == 3)
3748
		{
3749
			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1);
3750
			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3751
			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3752
			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3753
			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3754
			else
3755
			{
3756
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
3757
			}
3758
		}
3759
		if ($mode == 4)
3760
		{
3761
			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1");
3762
			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3763
			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3764
			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3765
			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3766
			else
3767
			{
3768
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3769
			}
3770
		}
3771
3772
		return "Error, mode/status not found";
3773
	}
3774
3775
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3776
	/**
3777
	 *  Set outstanding value
3778
	 *
3779
	 *  @param  User	$user		User making change
3780
	 *	@return	int					<0 if KO, >0 if OK
3781
	 * @deprecated Use update function instead
3782
	 */
3783
    public function set_OutstandingBill(User $user)
3784
	{
3785
        // phpcs:enable
3786
		return $this->update($this->id, $user);
3787
	}
3788
3789
	/**
3790
	 *  Return amount of order not paid and total
3791
	 *
3792
	 *  @param     string      $mode    'customer' or 'supplier'
3793
	 *  @return    array				array('opened'=>Amount, 'total'=>Total amount)
3794
	 */
3795
    public function getOutstandingProposals($mode = 'customer')
3796
	{
3797
		$table='propal';
3798
		if ($mode == 'supplier') $table = 'supplier_proposal';
3799
3800
		$sql  = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3801
		$sql .= " WHERE fk_soc = ". $this->id;
3802
		if ($mode == 'supplier') {
3803
			$sql .= " AND entity IN (".getEntity('supplier_proposal').")";
3804
		} else {
3805
			$sql .= " AND entity IN (".getEntity('propal').")";
3806
		}
3807
3808
		dol_syslog("getOutstandingProposals", LOG_DEBUG);
3809
		$resql=$this->db->query($sql);
3810
		if ($resql)
3811
		{
3812
			$outstandingOpened = 0;
3813
			$outstandingTotal = 0;
3814
			$outstandingTotalIncTax = 0;
3815
			while($obj=$this->db->fetch_object($resql)) {
3816
				$outstandingTotal+= $obj->total_ht;
3817
				$outstandingTotalIncTax+= $obj->total_ttc;
3818
				if ($obj->fk_statut != 0)    // Not a draft
3819
				{
3820
					$outstandingOpened+=$obj->total_ttc;
3821
				}
3822
			}
3823
			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3824
		}
3825
		else
3826
			return array();
3827
	}
3828
3829
	/**
3830
	 *  Return amount of order not paid and total
3831
	 *
3832
	 *  @param     string      $mode    'customer' or 'supplier'
3833
	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3834
	 */
3835
    public function getOutstandingOrders($mode = 'customer')
3836
	{
3837
		$table='commande';
3838
		if ($mode == 'supplier') $table = 'commande_fournisseur';
3839
3840
		$sql  = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3841
		$sql .= " WHERE fk_soc = ". $this->id;
3842
		if ($mode == 'supplier') {
3843
			$sql .= " AND entity IN (".getEntity('supplier_order').")";
3844
		} else {
3845
			$sql .= " AND entity IN (".getEntity('commande').")";
3846
		}
3847
3848
		dol_syslog("getOutstandingOrders", LOG_DEBUG);
3849
		$resql=$this->db->query($sql);
3850
		if ($resql)
3851
		{
3852
			$outstandingOpened = 0;
3853
			$outstandingTotal = 0;
3854
			$outstandingTotalIncTax = 0;
3855
			while($obj=$this->db->fetch_object($resql)) {
3856
				$outstandingTotal+= $obj->total_ht;
3857
				$outstandingTotalIncTax+= $obj->total_ttc;
3858
				if ($obj->fk_statut != 0)    // Not a draft
3859
				{
3860
					$outstandingOpened+=$obj->total_ttc;
3861
				}
3862
			}
3863
			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3864
		}
3865
		else
3866
			return array();
3867
	}
3868
3869
	/**
3870
	 *  Return amount of bill not paid and total
3871
	 *
3872
	 *  @param     string      $mode    'customer' or 'supplier'
3873
	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3874
	 */
3875
    public function getOutstandingBills($mode = 'customer')
3876
	{
3877
		$table='facture';
3878
		if ($mode == 'supplier') $table = 'facture_fourn';
3879
3880
		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3881
		 $paiement = $invoice->getSommePaiement();
3882
		 $creditnotes=$invoice->getSumCreditNotesUsed();
3883
		 $deposits=$invoice->getSumDepositsUsed();
3884
		 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3885
		 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3886
		 */
3887
		if ($mode == 'supplier') $sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3888
		else $sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3889
		$sql .= " WHERE fk_soc = ". $this->id;
3890
		if ($mode == 'supplier') {
3891
			$sql .= " AND entity IN (".getEntity('facture_fourn').")";
3892
		} else {
3893
			$sql .= " AND entity IN (".getEntity('invoice').")";
3894
		}
3895
3896
		dol_syslog("getOutstandingBills", LOG_DEBUG);
3897
		$resql=$this->db->query($sql);
3898
		if ($resql)
3899
		{
3900
			$outstandingOpened = 0;
3901
			$outstandingTotal = 0;
3902
			$outstandingTotalIncTax = 0;
3903
			if ($mode == 'supplier')
3904
			{
3905
				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3906
				$tmpobject=new FactureFournisseur($this->db);
3907
			}
3908
			else
3909
			{
3910
				require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3911
				$tmpobject=new Facture($this->db);
3912
			}
3913
			while($obj=$this->db->fetch_object($resql)) {
3914
				$tmpobject->id=$obj->rowid;
3915
				if ($obj->fk_statut != 0                                           // Not a draft
3916
					&& ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3917
					)
3918
				{
3919
					$outstandingTotal+= $obj->total_ht;
3920
					$outstandingTotalIncTax+= $obj->total_ttc;
3921
				}
3922
				if ($obj->paye == 0
3923
					&& $obj->fk_statut != 0    // Not a draft
3924
					&& $obj->fk_statut != 3	   // Not abandonned
3925
					&& $obj->fk_statut != 2)   // Not classified as paid
3926
				//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3927
				{
3928
					$paiement = $tmpobject->getSommePaiement();
3929
					$creditnotes = $tmpobject->getSumCreditNotesUsed();
3930
					$deposits = $tmpobject->getSumDepositsUsed();
3931
					$outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3932
				}
3933
			}
3934
			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3935
		}
3936
		else
3937
		{
3938
			return array();
3939
		}
3940
	}
3941
3942
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3943
    /**
3944
     *  Return amount of bill not paid
3945
     *
3946
     *  @return		int				Amount in debt for thirdparty
3947
     *  @deprecated
3948
     *  @see getOutstandingBills()
3949
     */
3950
    public function get_OutstandingBill()
3951
    {
3952
        // phpcs:enable
3953
		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3954
	     $paiement = $invoice->getSommePaiement();
3955
	     $creditnotes=$invoice->getSumCreditNotesUsed();
3956
	     $deposits=$invoice->getSumDepositsUsed();
3957
	     $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3958
	     $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3959
	     */
3960
		$sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3961
		$sql .= " WHERE fk_soc = ". $this->id;
3962
		$sql .= " AND entity IN (".getEntity('invoice').")";
3963
		$sql .= " AND paye = 0";
3964
		$sql .= " AND fk_statut <> 0";	// Not a draft
3965
		$sql .= " AND entity IN (".getEntity('invoice').")";
3966
		//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3967
		$sql .= " AND fk_statut <> 3";		// Not abandonned
3968
		$sql .= " AND fk_statut <> 2";		// Not clasified as paid
3969
3970
		dol_syslog("get_OutstandingBill", LOG_DEBUG);
3971
		$resql=$this->db->query($sql);
3972
		if ($resql)
3973
		{
3974
			$outstandingAmount = 0;
3975
			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3976
			$tmpobject=new Facture($this->db);
3977
			while($obj=$this->db->fetch_object($resql)) {
3978
				$tmpobject->id=$obj->rowid;
3979
				$paiement = $tmpobject->getSommePaiement();
3980
				$creditnotes = $tmpobject->getSumCreditNotesUsed();
3981
				$deposits = $tmpobject->getSumDepositsUsed();
3982
				$outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3983
			}
3984
			return $outstandingAmount;
3985
		}
3986
		else
3987
			return 0;
3988
	}
3989
3990
	/**
3991
	 * Return label of status customer is prospect/customer
3992
	 *
3993
	 * @return   string        	Label
3994
	 */
3995
    public function getLibCustProspStatut()
3996
	{
3997
		return $this->LibCustProspStatut($this->client);
3998
	}
3999
4000
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4001
	/**
4002
	 *  Renvoi le libelle d'un statut donne
4003
	 *
4004
	 *  @param	int		$statut         Id statut
4005
	 *  @return	string          		Libelle du statut
4006
	 */
4007
    public function LibCustProspStatut($statut)
4008
	{
4009
        // phpcs:enable
4010
		global $langs;
4011
		$langs->load('companies');
4012
4013
		if ($statut==0) return $langs->trans("NorProspectNorCustomer");
4014
		elseif ($statut==1) return $langs->trans("Customer");
4015
		elseif ($statut==2) return $langs->trans("Prospect");
4016
		elseif ($statut==3) return $langs->trans("ProspectCustomer");
4017
	}
4018
4019
4020
	/**
4021
	 *  Create a document onto disk according to template module.
4022
	 *
4023
	 *	@param	string		$modele			Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf','alpha') for example.
4024
	 *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
4025
	 *  @param  int			$hidedetails    Hide details of lines
4026
	 *  @param  int			$hidedesc       Hide description
4027
	 *  @param  int			$hideref        Hide ref
4028
	 *  @param  null|array  $moreparams     Array to provide more information
4029
	 *	@return int        					<0 if KO, >0 if OK
4030
	 */
4031
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4032
	{
4033
		global $conf,$user,$langs;
4034
4035
		if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
4036
		{
4037
			$modelpath = "core/modules/bank/doc/";
4038
4039
			include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4040
			$companybankaccount = new CompanyBankAccount($this->db);
4041
			$result = $companybankaccount->fetch($moreparams['use_companybankid']);
4042
			if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4043
			$result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4044
		}
4045
		else
4046
		{
4047
			// Positionne le modele sur le nom du modele a utiliser
4048
			if (! dol_strlen($modele))
4049
			{
4050
				if (! empty($conf->global->COMPANY_ADDON_PDF))
4051
				{
4052
					$modele = $conf->global->COMPANY_ADDON_PDF;
4053
				}
4054
				else
4055
				{
4056
					print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4057
					return 0;
4058
				}
4059
			}
4060
4061
			$modelpath = "core/modules/societe/doc/";
4062
4063
			$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4064
		}
4065
4066
		return $result;
4067
	}
4068
4069
4070
	/**
4071
	 * Sets object to supplied categories.
4072
	 *
4073
	 * Deletes object from existing categories not supplied.
4074
	 * Adds it to non existing supplied categories.
4075
	 * Existing categories are left untouch.
4076
	 *
4077
	 * @param 	int[]|int 	$categories 	Category ID or array of Categories IDs
4078
	 * @param 	string 		$type 			Category type ('customer' or 'supplier')
4079
	 * @return	int							<0 if KO, >0 if OK
4080
	 */
4081
	public function setCategories($categories, $type)
4082
	{
4083
		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
4084
4085
		// Decode type
4086
		if ($type == 'customer') {
4087
			$type_id = Categorie::TYPE_CUSTOMER;
4088
			$type_text = 'customer';
4089
		} elseif ($type == 'supplier') {
4090
			$type_id = Categorie::TYPE_SUPPLIER;
4091
			$type_text = 'supplier';
4092
		} else {
4093
			dol_syslog(__METHOD__ . ': Type ' . $type .  'is an unknown company category type. Done nothing.', LOG_ERR);
4094
			return -1;
4095
		}
4096
4097
		// Handle single category
4098
		if (!is_array($categories)) {
4099
			$categories = array($categories);
4100
		}
4101
4102
		// Get current categories
4103
		$c = new Categorie($this->db);
4104
		$existing = $c->containing($this->id, $type_id, 'id');
4105
4106
		// Diff
4107
		if (is_array($existing)) {
0 ignored issues
show
introduced by
The condition is_array($existing) is always false.
Loading history...
4108
			$to_del = array_diff($existing, $categories);
4109
			$to_add = array_diff($categories, $existing);
4110
		} else {
4111
			$to_del = array(); // Nothing to delete
4112
			$to_add = $categories;
4113
		}
4114
4115
		$error = 0;
4116
4117
		// Process
4118
		foreach ($to_del as $del) {
4119
			if ($c->fetch($del) > 0) {
4120
				$c->del_type($this, $type_text);
4121
			}
4122
		}
4123
		foreach ($to_add as $add) {
4124
			if ($c->fetch($add) > 0)
4125
			{
4126
				$result = $c->add_type($this, $type_text);
4127
				if ($result < 0)
4128
				{
4129
					$error++;
4130
					$this->error = $c->error;
4131
					$this->errors = $c->errors;
4132
					break;
4133
				}
4134
			}
4135
		}
4136
4137
		return $error ? -1 : 1;
4138
	}
4139
4140
	/**
4141
	 * Sets sales representatives of the thirdparty
4142
	 *
4143
	 * @param 	int[]|int 	$salesrep	 	User ID or array of user IDs
4144
	 * @return	int							<0 if KO, >0 if OK
4145
	 */
4146
	public function setSalesRep($salesrep)
4147
	{
4148
		global $user;
4149
4150
		// Handle single user
4151
		if (!is_array($salesrep)) {
4152
			$salesrep = array($salesrep);
4153
		}
4154
4155
		// Get current users
4156
		$existing = $this->getSalesRepresentatives($user, 1);
4157
4158
		// Diff
4159
		if (is_array($existing)) {
1 ignored issue
show
introduced by
The condition is_array($existing) is always true.
Loading history...
4160
			$to_del = array_diff($existing, $salesrep);
4161
			$to_add = array_diff($salesrep, $existing);
4162
		} else {
4163
			$to_del = array(); // Nothing to delete
4164
			$to_add = $salesrep;
4165
		}
4166
4167
		$error = 0;
4168
4169
		// Process
4170
		foreach ($to_del as $del) {
4171
			$this->del_commercial($user, $del);
4172
		}
4173
		foreach ($to_add as $add) {
4174
			$result = $this->add_commercial($user, $add);
4175
			if ($result < 0)
4176
			{
4177
				$error++;
4178
				break;
4179
			}
4180
		}
4181
4182
		return $error ? -1 : 1;
4183
	}
4184
4185
4186
	/**
4187
	 * Function used to replace a thirdparty id with another one.
4188
	 * It must be used within a transaction to avoid trouble
4189
	 *
4190
	 * @param 	DoliDB 	$db 		Database handler
4191
	 * @param 	int 	$origin_id 	Old thirdparty id (will be removed)
4192
	 * @param 	int 	$dest_id 	New thirdparty id
4193
	 * @return 	bool				True if success, False if error
4194
	 */
4195
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
4196
	{
4197
		if ($origin_id == $dest_id)
4198
		{
4199
			dol_syslog('Error: Try to merge a thirdparty into itself');
4200
			return false;
4201
		}
4202
4203
		/**
4204
		 * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
4205
		 * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
4206
		 */
4207
		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4208
		$sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4209
		$sql .= ' SELECT fk_user ';
4210
		$sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4211
		$sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
4212
4213
		$query = $db->query($sql);
4214
4215
		while ($result = $db->fetch_object($query)) {
4216
			$db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
4217
		}
4218
4219
		/**
4220
		 * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
4221
		 * Do not include llx_societe because it will be replaced later
4222
		 */
4223
		$tables = array(
4224
			'societe_address',
4225
			'societe_commerciaux',
4226
			'societe_log',
4227
			'societe_prices',
4228
			'societe_remise',
4229
			'societe_remise_except',
4230
			'societe_rib'
4231
		);
4232
4233
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
4234
	}
4235
}
4236