Passed
Branch develop (027d94)
by
unknown
26:09
created

Societe::isACompany()   C

Complexity

Conditions 12
Paths 10

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 10
c 1
b 0
f 0
nc 10
nop 0
dl 0
loc 20
rs 6.9666

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

553
		$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...
554
		if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
555
		$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

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

718
		/** @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...
719
720
		if (! $this->name)
721
		{
722
			$this->errors[] = 'ErrorBadThirdPartyName';
723
			$result = -2;
724
		}
725
726
		if ($this->client)
727
		{
728
			$rescode = $this->check_codeclient();
729
			if ($rescode <> 0)
730
			{
731
				if ($rescode == -1)
732
				{
733
					$this->errors[] = 'ErrorBadCustomerCodeSyntax';
734
				}
735
				elseif ($rescode == -2)
736
				{
737
					$this->errors[] = 'ErrorCustomerCodeRequired';
738
				}
739
				elseif ($rescode == -3)
740
				{
741
					$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
742
				}
743
				elseif ($rescode == -4)
744
				{
745
					$this->errors[] = 'ErrorPrefixRequired';
746
				}
747
				$result = -3;
748
			}
749
		}
750
751
		if ($this->fournisseur)
752
		{
753
			$rescode = $this->check_codefournisseur();
754
			if ($rescode <> 0)
755
			{
756
				if ($rescode == -1)
757
				{
758
					$this->errors[] = 'ErrorBadSupplierCodeSyntax';
759
				}
760
				elseif ($rescode == -2)
761
				{
762
					$this->errors[] = 'ErrorSupplierCodeRequired';
763
				}
764
				elseif ($rescode == -3)
765
				{
766
					$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
767
				}
768
				elseif ($rescode == -5)
769
				{
770
					$this->errors[] = 'ErrorprefixRequired';
771
				}
772
				$result = -3;
773
			}
774
		}
775
776
		// Check for duplicate or mandatory fields defined into setup
777
		$array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
778
		foreach($array_to_check as $key)
779
		{
780
			$keymin=strtolower($key);
781
			$i=(int) preg_replace('/[^0-9]/', '', $key);
782
			$vallabel=$this->$keymin;
783
784
			if ($i > 0)
785
			{
786
				if ($this->isACompany())
787
				{
788
					// Check for mandatory prof id (but only if country is same than ours)
789
					if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
790
					{
791
						$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
792
						if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
793
						{
794
							$langs->load("errors");
795
							$error++;
796
							$this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
797
						}
798
					}
799
				}
800
801
				// Check for unicity
802
				if (! $error && $vallabel && $this->id_prof_verifiable($i))
803
				{
804
					if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
805
					{
806
						$langs->load("errors");
807
						$error++;
808
						$this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
809
					}
810
				}
811
			}
812
			else
813
			{
814
				//var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
815
				//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
816
				if ($key == 'EMAIL')
817
				{
818
					// Check for mandatory
819
					if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
820
					{
821
						$langs->load("errors");
822
						$error++;
823
						$this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
824
					}
825
826
					// Check for unicity
827
					if (! $error && $vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
828
					{
829
						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
830
						{
831
							$langs->load("errors");
832
							$error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
833
						}
834
					}
835
				}
836
			}
837
		}
838
839
		if ($error) $result = -4;
840
841
		return $result;
842
	}
843
844
	/**
845
	 *      Update parameters of third party
846
	 *
847
	 *      @param	int		$id              			Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
848
	 *      @param  User	$user            			User who requests the update
849
	 *      @param  int		$call_trigger    			0=no, 1=yes
850
	 *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
851
	 *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
852
	 *		@param	string	$action						'add' or 'update' or 'merge'
853
	 *		@param	int		$nosyncmember				Do not synchronize info of linked member
854
	 *      @return int  			           			<0 if KO, >=0 if OK
855
	 */
856
    public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
857
	{
858
		global $langs,$conf,$hookmanager;
859
860
		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
861
862
		if (empty($id)) $id = $this->id;
863
864
		$error=0;
865
866
		dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
867
868
		$now=dol_now();
869
870
		// Clean parameters
871
		$this->id			= $id;
872
		$this->entity		= ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
873
		$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

873
		$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...
874
		$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

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

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

2326
			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...
2327
			$contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2328
		}
2329
		//var_dump($contact_emails)
2330
		return $contact_emails;
2331
	}
2332
2333
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2334
	/**
2335
	 *    Return list of contacts mobile phone existing for third party
2336
	 *
2337
	 *    @return     array       Array of contacts emails
2338
	 */
2339
    public function thirdparty_and_contact_phone_array()
2340
	{
2341
        // phpcs:enable
2342
		global $langs;
2343
2344
		$contact_phone = $this->contact_property_array('mobile');
2345
2346
		if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2347
		{
2348
			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

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

3386
		$name = $socname?$socname:/** @scrutinizer ignore-deprecated */ $member->societe;
Loading history...
3387
		if (empty($name)) $name=$member->getFullName($langs);
3388
3389
		$alias = $socalias?$socalias:'';
3390
3391
		// Positionne parametres
3392
		$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

3392
		/** @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...
3393
		$this->name=$name;
3394
		$this->name_alias=$alias;
3395
		$this->address=$member->address;
3396
		$this->zip=$member->zip;
3397
		$this->town=$member->town;
3398
		$this->country_code=$member->country_code;
3399
		$this->country_id=$member->country_id;
3400
		$this->phone=$member->phone;       // Prof phone
3401
		$this->email=$member->email;
3402
        $this->socialnetworks = $member->socialnetworks;
3403
3404
		$this->client = 1;				// A member is a customer by default
3405
		$this->code_client = ($customercode?$customercode:-1);
3406
		$this->code_fournisseur = -1;
3407
3408
		$this->db->begin();
3409
3410
		// Cree et positionne $this->id
3411
		$result=$this->create($user);
3412
		if ($result >= 0)
3413
		{
3414
			$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3415
			$sql.= " SET fk_soc=".$this->id;
3416
			$sql.= " WHERE rowid=".$member->id;
3417
3418
			$resql=$this->db->query($sql);
3419
			if ($resql)
3420
			{
3421
				$this->db->commit();
3422
				return $this->id;
3423
			}
3424
			else
3425
			{
3426
				$this->error=$this->db->error();
3427
3428
				$this->db->rollback();
3429
				return -1;
3430
			}
3431
		}
3432
		else
3433
		{
3434
			// $this->error deja positionne
3435
			dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
3436
3437
			$this->db->rollback();
3438
			return $result;
3439
		}
3440
	}
3441
3442
	/**
3443
	 * 	Set properties with value into $conf
3444
	 *
3445
	 * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3446
	 * 	@return	void
3447
	 */
3448
    public function setMysoc(Conf $conf)
3449
	{
3450
		global $langs;
3451
3452
		$this->id=0;
3453
		$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3454
		$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3455
		$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3456
		$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3457
		$this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION;
3458
		$this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT;
3459
3460
		$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3461
3462
		$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

3462
		/** @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...
3463
3464
		// We define country_id, country_code and country
3465
		$country_id=$country_code=$country_label='';
3466
		if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3467
		{
3468
			$tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3469
			$country_id=$tmp[0];
3470
			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3471
			{
3472
				$country_code=$tmp[1];
3473
				$country_label=$tmp[2];
3474
			}
3475
			else                    // For backward compatibility
3476
			{
3477
				dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
3478
				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3479
				$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
3480
				$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
3481
			}
3482
		}
3483
		$this->country_id=$country_id;
3484
		$this->country_code=$country_code;
3485
		$this->country=$country_label;
3486
		if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3487
3488
		//TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
3489
		// We define state_id, state_code and state
3490
		$state_id=0;$state_code=$state_label='';
3491
		if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE))
3492
		{
3493
			$tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
3494
			$state_id=$tmp[0];
3495
			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
3496
			{
3497
				$state_code=$tmp[1];
3498
				$state_label=$tmp[2];
3499
			}
3500
			else                    // For backward compatibility
3501
			{
3502
				dol_syslog("Your state setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3503
				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3504
				$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
3505
				$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
3506
			}
3507
		}
3508
		$this->state_id=$state_id;
3509
		$this->state_code=$state_code;
3510
		$this->state=$state_label;
3511
		if (is_object($langs)) $this->state=($langs->trans('State'.$state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label;
3512
3513
		$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3514
		$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3515
		$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3516
		// Id prof generiques
3517
		$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3518
		$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3519
		$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3520
		$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3521
		$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3522
		$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3523
		$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3524
		$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3525
		$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3526
		$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3527
		$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3528
		$this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT);
3529
		$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3530
		$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3531
		$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3532
		$this->logo_squarred=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
3533
		$this->logo_squarred_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
3534
		$this->logo_squarred_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
3535
3536
		// Define if company use vat or not
3537
		$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3538
3539
		// Define if company use local taxes
3540
		$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);
3541
		$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);
3542
	}
3543
3544
	/**
3545
	 *  Initialise an instance with random values.
3546
	 *  Used to build previews or test instances.
3547
	 *	id must be 0 if object instance is a specimen.
3548
	 *
3549
	 *  @return	int >0 if ok
3550
	 */
3551
    public function initAsSpecimen()
3552
	{
3553
		$now=dol_now();
3554
3555
		// Initialize parameters
3556
		$this->id=0;
3557
		$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
3558
		$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

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