dolibarr  13.0.2
societe.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9  * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2013 Alexandre Spangaro <aspangaro@open-dsi.fr>
12  * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16  * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17  * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18  * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program. If not, see <https://www.gnu.org/licenses/>.
33  */
34 
40 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
43 
47 class Societe extends CommonObject
48 {
49  use CommonIncoterm;
50 
54  public $element = 'societe';
55 
59  public $table_element = 'societe';
60 
64  public $fk_element = 'fk_soc';
65 
69  public $fieldsforcombobox = 'nom,name_alias';
70 
74  protected $childtables = array(
75  "supplier_proposal" => 'SupplierProposal',
76  "propal" => 'Proposal',
77  "commande" => 'Order',
78  "facture" => 'Invoice',
79  "facture_rec" => 'RecurringInvoiceTemplate',
80  "contrat" => 'Contract',
81  "fichinter" => 'Fichinter',
82  "facture_fourn" => 'SupplierInvoice',
83  "commande_fournisseur" => 'SupplierOrder',
84  "projet" => 'Project',
85  "expedition" => 'Shipment',
86  "prelevement_lignes" => 'DirectDebitRecord',
87  );
88 
93  protected $childtablesoncascade = array(
94  "societe_prices",
95  "societe_address",
96  "product_fournisseur_price",
97  "product_customer_price_log",
98  "product_customer_price",
99  "@Contact:/contact/class/contact.class.php:fk_soc",
100  "adherent",
101  "societe_account",
102  "societe_rib",
103  "societe_remise",
104  "societe_remise_except",
105  "societe_commerciaux",
106  "categorie",
107  "notify",
108  "notify_def",
109  "actioncomm",
110  );
111 
115  public $picto = 'company';
116 
121  public $ismultientitymanaged = 1;
122 
127  public $restrictiononfksoc = 1;
128 
132  public $fields = array(
133  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
134  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
135  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
136  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
137  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
138  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>1),
139  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
140  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
141  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
142  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
143  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CodeCompta', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
144  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'CodeComptaSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
145  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
146  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
147  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
148  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
149  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
150  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
151  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
152  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
153  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
154  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
155  /*'skype' =>array('type'=>'varchar(255)', 'label'=>'Skype', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
156  'whatsapp' =>array('type'=>'varchar(255)', 'label'=>'Whatsapp', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
157  'linkedin' =>array('type'=>'varchar(255)', 'label'=>'Linkedin', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
158  'youtube' =>array('type'=>'varchar(255)', 'label'=>'Youtube', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
159  'googleplus' =>array('type'=>'varchar(255)', 'label'=>'Googleplus', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
160  'snapchat' =>array('type'=>'varchar(255)', 'label'=>'Snapchat', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
161  'instagram' =>array('type'=>'varchar(255)', 'label'=>'Instagram', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
162  'facebook' =>array('type'=>'varchar(255)', 'label'=>'Facebook', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
163  'twitter' =>array('type'=>'varchar(255)', 'label'=>'Twitter', 'enabled'=>1, 'visible'=>-1, 'position'=>165),*/
164  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
165  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
166  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
167  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
168  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
169  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
170  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
171  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
172  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
173  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
174  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
175  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
176  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
177  'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
178  'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
179  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>'$conf->global->SOCIETE_USEPREFIX', 'visible'=>-1, 'position'=>235),
180  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
181  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
182  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
183  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
184  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
185  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
186  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
187  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
188  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
189  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
190  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
191  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
192  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
193  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
194  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
195  'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
196  'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
197  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>325),
198  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
199  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
200  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
201  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
202  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
203  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
204  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
205  'price_level' =>array('type'=>'integer', 'label'=>'Price level', 'enabled'=>'$conf->global->PRODUIT_MULTIPRICES || $conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES', 'visible'=>-1, 'position'=>365),
206  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
207  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
208  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
209  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
210  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
211  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
212  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
213  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
214  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
215  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
216  'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
217  'fk_entrepot' =>array('type'=>'integer', 'label'=>'Fk entrepot', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
218  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
219  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
220  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
221  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
222  );
223 
227  public $entity;
228 
235  public $nom;
236 
240  public $name;
241 
246  public $name_alias;
247 
251  public $particulier;
252 
256  public $address;
257 
261  public $zip;
262 
266  public $town;
267 
272  public $status = 1;
273 
278  public $state_id;
279 
283  public $state_code;
284 
288  public $state;
289 
294  public $region_code;
295 
299  public $region;
300 
306  public $departement_code;
307 
313  public $departement;
314 
320  public $pays;
321 
326  public $phone;
331  public $fax;
336  public $email;
337 
341  public $socialnetworks;
342 
348  public $skype;
349 
355  public $twitter;
356 
362  public $facebook;
363 
369  public $linkedin;
370 
375  public $url;
376 
381  public $barcode;
382 
383  // 6 professional id (usage depends on country)
384 
389  public $idprof1;
390 
395  public $idprof2;
396 
401  public $idprof3;
402 
407  public $idprof4;
408 
413  public $idprof5;
414 
419  public $idprof6;
420 
424  public $prefix_comm;
425 
429  public $tva_assuj = 1;
430 
435  public $tva_intra;
436 
437  // Local taxes
438  public $localtax1_assuj;
439  public $localtax1_value;
440  public $localtax2_assuj;
441  public $localtax2_value;
442 
446  public $managers;
447 
451  public $capital;
452 
456  public $typent_id = 0;
457  public $typent_code;
458  public $effectif;
459  public $effectif_id = 0;
460  public $forme_juridique_code;
461  public $forme_juridique = 0;
462 
463  public $remise_percent;
464  public $remise_supplier_percent;
465  public $mode_reglement_supplier_id;
466  public $cond_reglement_supplier_id;
467  public $transport_mode_supplier_id;
468 
472  public $fk_prospectlevel;
473 
477  public $name_bis;
478 
479  //Log data
480 
485  public $date_modification;
486 
491  public $user_modification;
492 
496  public $date_creation;
497 
502  public $user_creation;
503 
508  public $client = 0;
509 
514  public $prospect = 0;
515 
520  public $fournisseur;
521 
526  public $code_client;
527 
532  public $code_fournisseur;
533 
538  public $code_compta;
539 
544  public $code_compta_client;
545 
550  public $code_compta_fournisseur;
551 
557  public $note;
558 
563  public $note_private;
564 
569  public $note_public;
570 
575  public $stcomm_id;
576 
581  public $stcomm_picto;
582 
587  public $status_prospect_label;
588 
593  public $price_level;
594 
598  public $outstanding_limit;
599 
603  public $order_min_amount;
604 
608  public $supplier_order_min_amount;
609 
614  public $commercial_id;
615 
620  public $parent;
621 
626  public $default_lang;
627 
631  public $ref;
632 
637  public $ref_int;
638 
644  public $ref_ext;
645 
652  public $import_key;
653 
658  public $webservices_url;
659 
664  public $webservices_key;
665 
669  public $logo;
670 
674  public $logo_small;
675 
679  public $logo_mini;
680 
684  public $logo_squarred;
685 
689  public $logo_squarred_small;
690 
694  public $logo_squarred_mini;
695 
696 
697  // Multicurrency
701  public $fk_multicurrency;
702 
706  public $multicurrency_code;
707 
708 
712  public $bank_account;
713 
717  const NO_CUSTOMER = 0;
718 
722  const CUSTOMER = 1;
723 
727  const PROSPECT = 2;
728 
733 
737  const NO_SUPPLIER = 0;
738 
742  const SUPPLIER = 1;
743 
749  public function __construct($db)
750  {
751  global $conf;
752 
753  $this->db = $db;
754 
755  $this->client = 0;
756  $this->prospect = 0;
757  $this->fournisseur = 0;
758  $this->typent_id = 0;
759  $this->effectif_id = 0;
760  $this->forme_juridique_code = 0;
761  $this->tva_assuj = 1;
762  $this->status = 1;
763 
764  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
765  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
766  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
767  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
768  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
769  }
770  }
771 
772 
780  public function create(User $user)
781  {
782  global $langs, $conf, $mysoc;
783 
784  $error = 0;
785 
786  // Clean parameters
787  if (empty($this->status)) {
788  $this->status = 0;
789  }
790  $this->name = $this->name ?trim($this->name) : trim($this->nom);
791  $this->setUpperOrLowerCase();
792  $this->nom = $this->name; // For backward compatibility
793  if (empty($this->client)) {
794  $this->client = 0;
795  }
796  if (empty($this->fournisseur)) {
797  $this->fournisseur = 0;
798  }
799  $this->import_key = trim($this->import_key);
800 
801  if (!empty($this->multicurrency_code)) {
802  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
803  }
804  if (empty($this->fk_multicurrency)) {
805  $this->multicurrency_code = '';
806  $this->fk_multicurrency = 0;
807  }
808 
809  dol_syslog(get_class($this)."::create ".$this->name);
810 
811  $now = dol_now();
812 
813  $this->db->begin();
814 
815  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
816  if ($this->code_client == -1 || $this->code_client === 'auto') {
817  $this->get_codeclient($this, 0);
818  }
819  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
820  $this->get_codefournisseur($this, 1);
821  }
822 
823  // Check more parameters (including mandatory setup
824  // If error, this->errors[] is filled
825  $result = $this->verify();
826 
827  if ($result >= 0) {
828  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
829 
830  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
831  $sql .= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'";
832  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
833  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
834  $sql .= ", ".$this->status;
835  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
836  $sql .= ", 0";
837  $sql .= ", ".(int) $this->fk_incoterms;
838  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
839  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
840  $sql .= ", ".(int) $this->fk_multicurrency;
841  $sql .= ", '".$this->db->escape($this->multicurrency_code)."')";
842 
843  dol_syslog(get_class($this)."::create", LOG_DEBUG);
844  $result = $this->db->query($sql);
845  if ($result) {
846  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
847 
848  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
849 
850  // Ajout du commercial affecte
851  if ($this->commercial_id != '' && $this->commercial_id != -1) {
852  $this->add_commercial($user, $this->commercial_id);
853  }
854  // si un commercial cree un client il lui est affecte automatiquement
855  elseif (empty($user->rights->societe->client->voir)) {
856  $this->add_commercial($user, $user->id);
857  }
858 
859  if ($ret >= 0) {
860  // Call trigger
861  $result = $this->call_trigger('COMPANY_CREATE', $user);
862  if ($result < 0) {
863  $error++;
864  }
865  // End call triggers
866  } else {
867  $error++;
868  }
869 
870  if (!$error) {
871  dol_syslog(get_class($this)."::Create success id=".$this->id);
872  $this->db->commit();
873  return $this->id;
874  } else {
875  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
876  $this->db->rollback();
877  return -4;
878  }
879  } else {
880  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
881  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
882  $result = -1;
883  } else {
884  $this->error = $this->db->lasterror();
885  $result = -2;
886  }
887  $this->db->rollback();
888  return $result;
889  }
890  } else {
891  $this->db->rollback();
892  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
893  return -3;
894  }
895  }
896 
897 
898  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
905  public function create_individual(User $user)
906  {
907  // phpcs:enable
908  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
909  $contact = new Contact($this->db);
910 
911  $contact->name = $this->name_bis;
912  $contact->firstname = $this->firstname;
913  $contact->civility_id = $this->civility_id;
914  $contact->socid = $this->id; // fk_soc
915  $contact->statut = 1; // deprecated
916  $contact->status = 1;
917  $contact->priv = 0;
918  $contact->country_id = $this->country_id;
919  $contact->state_id = $this->state_id;
920  $contact->address = $this->address;
921  $contact->email = $this->email;
922  $contact->zip = $this->zip;
923  $contact->town = $this->town;
924  $contact->phone_pro = $this->phone;
925 
926  $result = $contact->create($user);
927  if ($result < 0) {
928  $this->error = $contact->error;
929  $this->errors = $contact->errors;
930  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
931  }
932 
933  return $result;
934  }
935 
942  public function verify()
943  {
944  global $conf, $langs, $mysoc;
945 
946  $error = 0;
947  $this->errors = array();
948 
949  $result = 0;
950  $this->name = trim($this->name);
951  $this->nom = $this->name; // For backward compatibility
952 
953  if (!$this->name) {
954  $this->errors[] = 'ErrorBadThirdPartyName';
955  $result = -2;
956  }
957 
958  if ($this->client) {
959  $rescode = $this->check_codeclient();
960  if ($rescode != 0 && $rescode != -5) {
961  if ($rescode == -1) {
962  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
963  } elseif ($rescode == -2) {
964  $this->errors[] = 'ErrorCustomerCodeRequired';
965  } elseif ($rescode == -3) {
966  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
967  } elseif ($rescode == -4) {
968  $this->errors[] = 'ErrorPrefixRequired';
969  } else {
970  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
971  }
972 
973  $result = -3;
974  }
975  }
976 
977  if ($this->fournisseur) {
978  $rescode = $this->check_codefournisseur();
979  if ($rescode != 0 && $rescode != -5) {
980  if ($rescode == -1) {
981  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
982  } elseif ($rescode == -2) {
983  $this->errors[] = 'ErrorSupplierCodeRequired';
984  } elseif ($rescode == -3) {
985  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
986  } elseif ($rescode == -4) {
987  $this->errors[] = 'ErrorPrefixRequired';
988  } else {
989  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
990  }
991  $result = -3;
992  }
993  }
994 
995  // Check for duplicate or mandatory fields defined into setup
996  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
997  foreach ($array_to_check as $key) {
998  $keymin = strtolower($key);
999  $i = (int) preg_replace('/[^0-9]/', '', $key);
1000  $vallabel = $this->$keymin;
1001 
1002  if ($i > 0) {
1003  if ($this->isACompany()) {
1004  // Check for mandatory prof id (but only if country is same than ours)
1005  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1006  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1007  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1008  $langs->load("errors");
1009  $error++;
1010  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1011  }
1012  }
1013  }
1014 
1015  // Check for unicity on profid
1016  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1017  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1018  $langs->load("errors");
1019  $error++;
1020  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1021  }
1022  }
1023  } else {
1024  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1025  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1026  if ($key == 'EMAIL') {
1027  // Check for mandatory
1028  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1029  $langs->load("errors");
1030  $error++;
1031  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1032  }
1033 
1034  // Check for unicity
1035  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1036  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1037  $langs->load("errors");
1038  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1039  }
1040  }
1041  }
1042  }
1043  }
1044 
1045  if ($error) {
1046  $result = -4;
1047  }
1048 
1049  return $result;
1050  }
1051 
1064  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1065  {
1066  global $langs, $conf, $hookmanager;
1067 
1068  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1069 
1070  if (empty($id)) {
1071  $id = $this->id;
1072  }
1073 
1074  $error = 0;
1075 
1076  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1077 
1078  $now = dol_now();
1079 
1080  // Clean parameters
1081  $this->id = $id;
1082  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1083  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1084  $this->nom = $this->name; // For backward compatibility
1085  $this->name_alias = trim($this->name_alias);
1086  $this->ref_ext = trim($this->ref_ext);
1087  $this->address = $this->address ?trim($this->address) : trim($this->address);
1088  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1089  $this->town = $this->town ?trim($this->town) : trim($this->town);
1090  $this->setUpperOrLowerCase();
1091  $this->state_id = trim($this->state_id);
1092  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1093  $this->phone = trim($this->phone);
1094  $this->phone = preg_replace("/\s/", "", $this->phone);
1095  $this->phone = preg_replace("/\./", "", $this->phone);
1096  $this->fax = trim($this->fax);
1097  $this->fax = preg_replace("/\s/", "", $this->fax);
1098  $this->fax = preg_replace("/\./", "", $this->fax);
1099  $this->email = trim($this->email);
1100  $this->url = $this->url ?clean_url($this->url, 0) : '';
1101  $this->note_private = trim($this->note_private);
1102  $this->note_public = trim($this->note_public);
1103  $this->idprof1 = trim($this->idprof1);
1104  $this->idprof2 = trim($this->idprof2);
1105  $this->idprof3 = trim($this->idprof3);
1106  $this->idprof4 = trim($this->idprof4);
1107  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1108  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1109  $this->prefix_comm = trim($this->prefix_comm);
1110  $this->outstanding_limit = price2num($this->outstanding_limit);
1111  $this->order_min_amount = price2num($this->order_min_amount);
1112  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1113 
1114  $this->tva_assuj = trim($this->tva_assuj);
1115  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1116  if (empty($this->status)) {
1117  $this->status = 0;
1118  }
1119 
1120  if (!empty($this->multicurrency_code)) {
1121  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1122  }
1123  if (empty($this->fk_multicurrency)) {
1124  $this->multicurrency_code = '';
1125  $this->fk_multicurrency = 0;
1126  }
1127 
1128  // Local taxes
1129  $this->localtax1_assuj = trim($this->localtax1_assuj);
1130  $this->localtax2_assuj = trim($this->localtax2_assuj);
1131 
1132  $this->localtax1_value = trim($this->localtax1_value);
1133  $this->localtax2_value = trim($this->localtax2_value);
1134 
1135  if ($this->capital != '') {
1136  $this->capital = price2num(trim($this->capital));
1137  }
1138  if (!is_numeric($this->capital)) {
1139  $this->capital = ''; // '' = undef
1140  }
1141 
1142  $this->effectif_id = trim($this->effectif_id);
1143  $this->forme_juridique_code = trim($this->forme_juridique_code);
1144 
1145  //Gencod
1146  $this->barcode = trim($this->barcode);
1147 
1148  // For automatic creation
1149  if ($this->code_client == -1 || $this->code_client === 'auto') {
1150  $this->get_codeclient($this, 0);
1151  }
1152  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1153  $this->get_codefournisseur($this, 1);
1154  }
1155 
1156  $this->code_compta = trim($this->code_compta);
1157  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1158 
1159  // Check parameters. More tests are done later in the ->verify()
1160  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1161  $langs->load("errors");
1162  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1163  return -1;
1164  }
1165 
1166  $customer = false;
1167  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1168  // Attention get_codecompta peut modifier le code suivant le module utilise
1169  if (empty($this->code_compta)) {
1170  $ret = $this->get_codecompta('customer');
1171  if ($ret < 0) {
1172  return -1;
1173  }
1174  }
1175 
1176  $customer = true;
1177  }
1178 
1179  $supplier = false;
1180  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1181  // Attention get_codecompta peut modifier le code suivant le module utilise
1182  if ($this->code_compta_fournisseur == "") {
1183  $ret = $this->get_codecompta('supplier');
1184  if ($ret < 0) {
1185  return -1;
1186  }
1187  }
1188 
1189  $supplier = true;
1190  }
1191 
1192  //Web services
1193  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1194  $this->webservices_key = trim($this->webservices_key);
1195 
1196  //Incoterms
1197  $this->fk_incoterms = (int) $this->fk_incoterms;
1198  $this->location_incoterms = trim($this->location_incoterms);
1199 
1200  $this->db->begin();
1201 
1202  // Check name is required and codes are ok or unique.
1203  // If error, this->errors[] is filled
1204  $result = 0;
1205  if ($action != 'add' && $action != 'merge') {
1206  // We don't check when update called during a create because verify was already done.
1207  // 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
1208  $result = $this->verify();
1209 
1210  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1211  // So we can update record that were using and old numbering rule.
1212  if (is_array($this->errors)) {
1213  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1214  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1215  unset($this->errors[$key]); // Remove error message
1216  }
1217  }
1218  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1219  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1220  unset($this->errors[$key]); // Remove error message
1221  }
1222  }
1223  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1224  $result = 0;
1225  }
1226  }
1227  }
1228 
1229  if ($result >= 0) {
1230  dol_syslog(get_class($this)."::update verify ok or not done");
1231 
1232  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1233  $sql .= "entity = ".$this->db->escape($this->entity);
1234  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1235  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1236  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1237  $sql .= ",address = '".$this->db->escape($this->address)."'";
1238 
1239  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1240  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1241 
1242  $sql .= ",fk_departement = '".(!empty($this->state_id) ? $this->state_id : '0')."'";
1243  $sql .= ",fk_pays = '".(!empty($this->country_id) ? $this->country_id : '0')."'";
1244 
1245  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1246  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1247  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1248  $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1249  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1250 
1251  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1252 
1253  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1254  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1255 
1256  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1257  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1258  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1259  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1260  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1261  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1262 
1263  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1264  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1265  $sql .= ",status = ".$this->status;
1266 
1267  // Local taxes
1268  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1269  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1270  if ($this->localtax1_assuj == 1) {
1271  if ($this->localtax1_value != '') {
1272  $sql .= ",localtax1_value =".$this->localtax1_value;
1273  } else {
1274  $sql .= ",localtax1_value =0.000";
1275  }
1276  } else {
1277  $sql .= ",localtax1_value =0.000";
1278  }
1279 
1280  if ($this->localtax2_assuj == 1) {
1281  if ($this->localtax2_value != '') {
1282  $sql .= ",localtax2_value =".$this->localtax2_value;
1283  } else {
1284  $sql .= ",localtax2_value =0.000";
1285  }
1286  } else {
1287  $sql .= ",localtax2_value =0.000";
1288  }
1289 
1290  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1291 
1292  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1293 
1294  $sql .= ",fk_effectif = ".(!empty($this->effectif_id) ? "'".$this->db->escape($this->effectif_id)."'" : "null");
1295  if (isset($this->stcomm_id)) {
1296  $sql .= ",fk_stcomm=".(!empty($this->stcomm_id) ? $this->stcomm_id : "0");
1297  }
1298  $sql .= ",fk_typent = ".(!empty($this->typent_id) ? "'".$this->db->escape($this->typent_id)."'" : "0");
1299 
1300  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1301 
1302  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1303  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1304  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1305  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1306  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1307  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1308  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1309 
1310  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1311  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1312  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1313  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1314  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1315  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1316  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1317  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1318  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1319  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1320 
1321  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1322  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1323 
1324  //Incoterms
1325  $sql .= ", fk_incoterms = ".$this->fk_incoterms;
1326  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1327 
1328  if ($customer) {
1329  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1330  $sql .= ", code_compta = ".(!empty($this->code_compta) ? "'".$this->db->escape($this->code_compta)."'" : "null");
1331  }
1332 
1333  if ($supplier) {
1334  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1335  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1336  }
1337  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1338  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1339  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1340  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1341  $sql .= " WHERE rowid = ".(int) $id;
1342 
1343  $resql = $this->db->query($sql);
1344  if ($resql) {
1345  if (is_object($this->oldcopy)) { // If we have information on old values
1346  if ($this->oldcopy->country_id != $this->country_id) {
1347  unset($this->country_code);
1348  unset($this->country);
1349  }
1350  if ($this->oldcopy->state_id != $this->state_id) {
1351  unset($this->state_code);
1352  unset($this->state);
1353  }
1354  } else {
1355  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1356  unset($this->country);
1357  unset($this->state_code);
1358  unset($this->state);
1359  }
1360 
1361  $nbrowsaffected = $this->db->affected_rows($resql);
1362 
1363  if (!$error && $nbrowsaffected) {
1364  // Update information on linked member if it is an update
1365  if (!$nosyncmember && !empty($conf->adherent->enabled)) {
1366  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1367 
1368  dol_syslog(get_class($this)."::update update linked member");
1369 
1370  $lmember = new Adherent($this->db);
1371  $result = $lmember->fetch(0, 0, $this->id);
1372 
1373  if ($result > 0) {
1374  $lmember->company = $this->name;
1375  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1376  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1377  $lmember->address = $this->address;
1378  $lmember->zip = $this->zip;
1379  $lmember->town = $this->town;
1380  $lmember->email = $this->email;
1381  $lmember->socialnetworks = $this->socialnetworks;
1382  $lmember->phone = $this->phone;
1383  $lmember->state_id = $this->state_id;
1384  $lmember->country_id = $this->country_id;
1385 
1386  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1387  if ($result < 0) {
1388  $this->error = $lmember->error;
1389  $this->errors = array_merge($this->errors, $lmember->errors);
1390  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1391  $error++;
1392  }
1393  } elseif ($result < 0) {
1394  $this->error = $lmember->error;
1395  $error++;
1396  }
1397  }
1398  }
1399 
1400  $action = 'update';
1401 
1402  // Actions on extra fields
1403  if (!$error) {
1404  $result = $this->insertExtraFields();
1405  if ($result < 0) {
1406  $error++;
1407  }
1408  }
1409  // Actions on extra languages
1410  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1411  $result = $this->insertExtraLanguages();
1412  if ($result < 0) {
1413  $error++;
1414  }
1415  }
1416 
1417  if (!$error && $call_trigger) {
1418  // Call trigger
1419  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1420  if ($result < 0) {
1421  $error++;
1422  }
1423  // End call triggers
1424  }
1425 
1426  if (!$error) {
1427  dol_syslog(get_class($this)."::Update success");
1428  $this->db->commit();
1429  return 1;
1430  } else {
1431  $this->db->rollback();
1432  return -1;
1433  }
1434  } else {
1435  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1436  // Doublon
1437  $this->error = $langs->trans("ErrorDuplicateField");
1438  $result = -1;
1439  } else {
1440  $this->error = $this->db->lasterror();
1441  $result = -2;
1442  }
1443  $this->db->rollback();
1444  return $result;
1445  }
1446  } else {
1447  $this->db->rollback();
1448  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1449  return -3;
1450  }
1451  }
1452 
1470  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1471  {
1472  global $langs;
1473  global $conf;
1474 
1475  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1476  return -1;
1477  }
1478 
1479  $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.address, s.datec as date_creation, s.prefix_comm';
1480  $sql .= ', s.status';
1481  $sql .= ', s.price_level';
1482  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1483  $sql .= ', s.phone, s.fax, s.email';
1484  $sql .= ', s.socialnetworks';
1485  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1486  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1487  $sql .= ', s.capital, s.tva_intra';
1488  $sql .= ', s.fk_typent as typent_id';
1489  $sql .= ', s.fk_effectif as effectif_id';
1490  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1491  $sql .= ', s.webservices_url, s.webservices_key';
1492  $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1493  $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.transport_mode';
1494  $sql .= ', s.fk_account, s.tva_assuj';
1495  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1496  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1497  $sql .= ', s.fk_shipping_method';
1498  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1499  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1500  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1501  $sql .= ', fj.libelle as forme_juridique';
1502  $sql .= ', e.libelle as effectif';
1503  $sql .= ', c.code as country_code, c.label as country';
1504  $sql .= ', d.code_departement as state_code, d.nom as state';
1505  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1506  $sql .= ', te.code as typent_code';
1507  $sql .= ', i.libelle as label_incoterms';
1508  $sql .= ', sr.remise_client, model_pdf';
1509  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1510  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1511  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1512  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1513  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1514  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1515  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1516  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1517  $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 IN ('.getEntity('discount').'))';
1518 
1519  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1520  if ($rowid) {
1521  $sql .= ' AND s.rowid = '.$rowid;
1522  }
1523  if ($ref) {
1524  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1525  }
1526  if ($ref_alias) {
1527  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1528  }
1529  if ($ref_ext) {
1530  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1531  }
1532  if ($barcode) {
1533  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1534  }
1535  if ($idprof1) {
1536  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1537  }
1538  if ($idprof2) {
1539  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1540  }
1541  if ($idprof3) {
1542  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1543  }
1544  if ($idprof4) {
1545  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1546  }
1547  if ($idprof5) {
1548  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1549  }
1550  if ($idprof6) {
1551  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1552  }
1553  if ($email) {
1554  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1555  }
1556 
1557  $resql = $this->db->query($sql);
1558  if ($resql) {
1559  $num = $this->db->num_rows($resql);
1560  if ($num > 1) {
1561  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1562  dol_syslog($this->error, LOG_ERR);
1563  $result = -2;
1564  } elseif ($num) { // $num = 1
1565  $obj = $this->db->fetch_object($resql);
1566 
1567  $this->id = $obj->rowid;
1568  $this->entity = $obj->entity;
1569  $this->canvas = $obj->canvas;
1570 
1571  $this->ref = $obj->rowid;
1572  $this->name = $obj->name;
1573  $this->nom = $obj->name; // deprecated
1574  $this->name_alias = $obj->name_alias;
1575  $this->ref_ext = $obj->ref_ext;
1576 
1577  $this->date_creation = $this->db->jdate($obj->date_creation);
1578  $this->date_modification = $this->db->jdate($obj->date_modification);
1579  $this->user_creation = $obj->fk_user_creat;
1580  $this->user_modification = $obj->fk_user_modif;
1581 
1582  $this->address = $obj->address;
1583  $this->zip = $obj->zip;
1584  $this->town = $obj->town;
1585 
1586  $this->country_id = $obj->country_id;
1587  $this->country_code = $obj->country_id ? $obj->country_code : '';
1588  $this->country = $obj->country_id ? ($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1589 
1590  $this->state_id = $obj->state_id;
1591  $this->state_code = $obj->state_code;
1592  $this->state = ($obj->state != '-' ? $obj->state : '');
1593 
1594  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1595  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1596  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1597  $this->status_prospect_label = $label; // label status prospect
1598  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1599 
1600  $this->email = $obj->email;
1601  $this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
1602 
1603  $this->url = $obj->url;
1604  $this->phone = $obj->phone;
1605  $this->fax = $obj->fax;
1606 
1607  $this->parent = $obj->parent;
1608 
1609  $this->idprof1 = $obj->idprof1;
1610  $this->idprof2 = $obj->idprof2;
1611  $this->idprof3 = $obj->idprof3;
1612  $this->idprof4 = $obj->idprof4;
1613  $this->idprof5 = $obj->idprof5;
1614  $this->idprof6 = $obj->idprof6;
1615 
1616  $this->capital = $obj->capital;
1617 
1618  $this->code_client = $obj->code_client;
1619  $this->code_fournisseur = $obj->code_fournisseur;
1620 
1621  $this->code_compta = $obj->code_compta;
1622  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1623 
1624  $this->barcode = $obj->barcode;
1625 
1626  $this->tva_assuj = $obj->tva_assuj;
1627  $this->tva_intra = $obj->tva_intra;
1628  $this->status = $obj->status;
1629 
1630  // Local Taxes
1631  $this->localtax1_assuj = $obj->localtax1_assuj;
1632  $this->localtax2_assuj = $obj->localtax2_assuj;
1633 
1634  $this->localtax1_value = $obj->localtax1_value;
1635  $this->localtax2_value = $obj->localtax2_value;
1636 
1637  $this->typent_id = $obj->typent_id;
1638  $this->typent_code = $obj->typent_code;
1639 
1640  $this->effectif_id = $obj->effectif_id;
1641  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1642 
1643  $this->forme_juridique_code = $obj->forme_juridique_code;
1644  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1645 
1646  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1647 
1648  $this->prefix_comm = $obj->prefix_comm;
1649 
1650  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1651  $this->remise_supplier_percent = $obj->remise_supplier;
1652  $this->mode_reglement_id = $obj->mode_reglement;
1653  $this->cond_reglement_id = $obj->cond_reglement;
1654  $this->transport_mode_id = $obj->transport_mode;
1655  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1656  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1657  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1658  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1659  $this->fk_account = $obj->fk_account;
1660 
1661  $this->client = $obj->client;
1662  $this->fournisseur = $obj->fournisseur;
1663 
1664  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1665  $this->note_private = $obj->note_private;
1666  $this->note_public = $obj->note_public;
1667  $this->model_pdf = $obj->model_pdf;
1668  $this->modelpdf = $obj->model_pdf; // deprecated
1669  $this->default_lang = $obj->default_lang;
1670  $this->logo = $obj->logo;
1671  $this->logo_squarred = $obj->logo_squarred;
1672 
1673  $this->webservices_url = $obj->webservices_url;
1674  $this->webservices_key = $obj->webservices_key;
1675 
1676  $this->outstanding_limit = $obj->outstanding_limit;
1677  $this->order_min_amount = $obj->order_min_amount;
1678  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1679 
1680  // multiprix
1681  $this->price_level = $obj->price_level;
1682 
1683  $this->import_key = $obj->import_key;
1684 
1685  //Incoterms
1686  $this->fk_incoterms = $obj->fk_incoterms;
1687  $this->location_incoterms = $obj->location_incoterms;
1688  $this->label_incoterms = $obj->label_incoterms;
1689 
1690  // multicurrency
1691  $this->fk_multicurrency = $obj->fk_multicurrency;
1692  $this->multicurrency_code = $obj->multicurrency_code;
1693  $this->model_pdf = $obj->model_pdf;
1694 
1695  $result = 1;
1696 
1697  // fetch optionals attributes and labels
1698  $this->fetch_optionals();
1699  } else {
1700  $result = 0;
1701  }
1702 
1703  $this->db->free($resql);
1704  } else {
1705  $this->error = $this->db->lasterror();
1706  $result = -3;
1707  }
1708 
1709  // Use first price level if level not defined for third party
1710  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1711  $this->price_level = 1;
1712  }
1713 
1714  return $result;
1715  }
1716 
1725  public function delete($id, User $fuser = null, $call_trigger = 1)
1726  {
1727  global $langs, $conf, $user;
1728 
1729  if (empty($fuser)) {
1730  $fuser = $user;
1731  }
1732 
1733  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1734 
1735  $entity = isset($this->entity) ? $this->entity : $conf->entity;
1736 
1737  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1738  $error = 0;
1739 
1740  // Test if child exists
1741  $objectisused = $this->isObjectUsed($id);
1742  if (empty($objectisused)) {
1743  $this->db->begin();
1744 
1745  // User is mandatory for trigger call
1746  if (!$error && $call_trigger) {
1747  // Call trigger
1748  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
1749  if ($result < 0) {
1750  $error++;
1751  }
1752  // End call triggers
1753  }
1754 
1755  if (!$error) {
1756  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1757  $static_cat = new Categorie($this->db);
1758  $toute_categs = array();
1759 
1760  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1761  if ($this->client || $this->prospect) {
1762  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
1763  }
1764  if ($this->fournisseur) {
1765  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
1766  }
1767 
1768  // Remove each "Categorie"
1769  foreach ($toute_categs as $type => $categs_type) {
1770  foreach ($categs_type as $cat) {
1771  $cat->del_type($this, $type);
1772  }
1773  }
1774  }
1775 
1776  if (!$error) {
1777  foreach ($this->childtablesoncascade as $tabletodelete) {
1778  $deleteFromObject = explode(':', $tabletodelete);
1779  if (count($deleteFromObject) >= 2) {
1780  $className = str_replace('@', '', $deleteFromObject[0]);
1781  $filepath = $deleteFromObject[1];
1782  $columnName = $deleteFromObject[2];
1783  if (dol_include_once($filepath)) {
1784  $child_object = new $className($this->db);
1785  $result = $child_object->deleteByParentField($id, $columnName);
1786  if ($result < 0) {
1787  $error++;
1788  $this->errors[] = $child_object->error;
1789  break;
1790  }
1791  } else {
1792  $error++;
1793  $this->errors[] = 'Cannot include child class file '.$filepath;
1794  break;
1795  }
1796  } else {
1797  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1798  $sql .= " WHERE fk_soc = ".$id;
1799  if (!$this->db->query($sql)) {
1800  $error++;
1801  $this->errors[] = $this->db->lasterror();
1802  break;
1803  }
1804  }
1805  }
1806  }
1807 
1808  // Removed extrafields
1809  if (!$error) {
1810  $result = $this->deleteExtraFields();
1811  if ($result < 0) {
1812  $error++;
1813  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1814  }
1815  }
1816 
1817  // Remove links to subsidiaries companies
1818  if (!$error) {
1819  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1820  $sql .= " SET parent = NULL";
1821  $sql .= " WHERE parent = ".$id;
1822  if (!$this->db->query($sql)) {
1823  $error++;
1824  $this->errors[] = $this->db->lasterror();
1825  }
1826  }
1827 
1828  // Remove third party
1829  if (!$error) {
1830  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1831  $sql .= " WHERE rowid = ".$id;
1832  if (!$this->db->query($sql)) {
1833  $error++;
1834  $this->errors[] = $this->db->lasterror();
1835  }
1836  }
1837 
1838  if (!$error) {
1839  $this->db->commit();
1840 
1841  // Delete directory
1842  if (!empty($conf->societe->multidir_output[$entity])) {
1843  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
1844  if (dol_is_dir($docdir)) {
1845  dol_delete_dir_recursive($docdir);
1846  }
1847  }
1848 
1849  return 1;
1850  } else {
1851  dol_syslog($this->error, LOG_ERR);
1852  $this->db->rollback();
1853  return -1;
1854  }
1855  } else {
1856  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1857  }
1858  return 0;
1859  }
1860 
1861  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1867  public function set_as_client()
1868  {
1869  // phpcs:enable
1870  if ($this->id) {
1871  $newclient = 1;
1872  if ($this->client == 2 || $this->client == 3) {
1873  $newclient = 3; //If prospect, we keep prospect tag
1874  }
1875  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1876  $sql .= " SET client = ".$newclient;
1877  $sql .= " WHERE rowid = ".$this->id;
1878 
1879  $resql = $this->db->query($sql);
1880  if ($resql) {
1881  $this->client = $newclient;
1882  return 1;
1883  } else {
1884  return -1;
1885  }
1886  }
1887  return 0;
1888  }
1889 
1890  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1899  public function set_remise_client($remise, $note, User $user)
1900  {
1901  // phpcs:enable
1902  global $conf, $langs;
1903 
1904  // Parameter cleaning
1905  $note = trim($note);
1906  if (!$note) {
1907  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
1908  return -2;
1909  }
1910 
1911  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1912 
1913  if ($this->id) {
1914  $this->db->begin();
1915 
1916  $now = dol_now();
1917 
1918  // Position current discount
1919  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1920  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
1921  $sql .= " WHERE rowid = ".$this->id;
1922  $resql = $this->db->query($sql);
1923  if (!$resql) {
1924  $this->db->rollback();
1925  $this->error = $this->db->error();
1926  return -1;
1927  }
1928 
1929  // Writes trace in discount history
1930  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1931  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1932  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1933  $sql .= " '".$this->db->escape($note)."',";
1934  $sql .= " ".$user->id;
1935  $sql .= ")";
1936 
1937  $resql = $this->db->query($sql);
1938  if (!$resql) {
1939  $this->db->rollback();
1940  $this->error = $this->db->lasterror();
1941  return -1;
1942  }
1943 
1944  $this->db->commit();
1945  return 1;
1946  }
1947  }
1948 
1949  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1958  public function set_remise_supplier($remise, $note, User $user)
1959  {
1960  // phpcs:enable
1961  global $conf, $langs;
1962 
1963  // Parameter cleaning
1964  $note = trim($note);
1965  if (!$note) {
1966  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
1967  return -2;
1968  }
1969 
1970  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
1971 
1972  if ($this->id) {
1973  $this->db->begin();
1974 
1975  $now = dol_now();
1976 
1977  // Position current discount
1978  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1979  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
1980  $sql .= " WHERE rowid = ".$this->id;
1981  $resql = $this->db->query($sql);
1982  if (!$resql) {
1983  $this->db->rollback();
1984  $this->error = $this->db->error();
1985  return -1;
1986  }
1987 
1988  // Writes trace in discount history
1989  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
1990  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
1991  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1992  $sql .= " '".$this->db->escape($note)."',";
1993  $sql .= " ".$user->id;
1994  $sql .= ")";
1995 
1996  $resql = $this->db->query($sql);
1997  if (!$resql) {
1998  $this->db->rollback();
1999  $this->error = $this->db->lasterror();
2000  return -1;
2001  }
2002 
2003  $this->db->commit();
2004  return 1;
2005  }
2006  }
2007 
2008  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0)
2020  {
2021  // phpcs:enable
2022  global $langs;
2023 
2024  // Clean parameters
2025  $remise = price2num($remise);
2026  $desc = trim($desc);
2027 
2028  // Check parameters
2029  if (!$remise > 0) {
2030  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2031  return -1;
2032  }
2033  if (!$desc) {
2034  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2035  return -2;
2036  }
2037 
2038  if ($this->id > 0) {
2039  // Clean vat code
2040  $reg = array();
2041  $vat_src_code = '';
2042  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2043  $vat_src_code = $reg[1];
2044  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2045  }
2046 
2047  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2048 
2049  $discount = new DiscountAbsolute($this->db);
2050  $discount->fk_soc = $this->id;
2051 
2052  $discount->discount_type = $discount_type;
2053 
2054  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2055  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2056  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2057 
2058  $discount->tva_tx = price2num($vatrate);
2059  $discount->vat_src_code = $vat_src_code;
2060 
2061  $discount->description = $desc;
2062 
2063  $result = $discount->create($user);
2064  if ($result > 0) {
2065  return $result;
2066  } else {
2067  $this->error = $discount->error;
2068  return -3;
2069  }
2070  } else {
2071  return 0;
2072  }
2073  }
2074 
2084  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2085  {
2086  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2087 
2088  $discountstatic = new DiscountAbsolute($this->db);
2089  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2090  if ($result >= 0) {
2091  return $result;
2092  } else {
2093  $this->error = $discountstatic->error;
2094  return -1;
2095  }
2096  }
2097 
2107  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2108  {
2109  global $conf;
2110 
2111  $reparray = array();
2112 
2113  $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.office_phone, u.job, u.email, u.statut as status, u.entity, u.photo";
2114  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2115  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2116  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2117  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2118  $sql .= " AND ug.entity = ".$conf->entity.")";
2119  $sql .= " OR u.admin = 1)";
2120  } else {
2121  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2122  }
2123 
2124  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
2125  if (empty($sortfield) && empty($sortorder)) {
2126  $sortfield = 'u.lastname,u.firstname';
2127  $sortorder = 'ASC,ASC';
2128  }
2129  $sql .= $this->db->order($sortfield, $sortorder);
2130 
2131  $resql = $this->db->query($sql);
2132  if ($resql) {
2133  $num = $this->db->num_rows($resql);
2134  $i = 0;
2135  while ($i < $num) {
2136  $obj = $this->db->fetch_object($resql);
2137 
2138  if (empty($mode)) {
2139  $reparray[$i]['id'] = $obj->rowid;
2140  $reparray[$i]['lastname'] = $obj->lastname;
2141  $reparray[$i]['firstname'] = $obj->firstname;
2142  $reparray[$i]['email'] = $obj->email;
2143  $reparray[$i]['phone'] = $obj->office_phone;
2144  $reparray[$i]['job'] = $obj->job;
2145  $reparray[$i]['statut'] = $obj->status; // deprecated
2146  $reparray[$i]['status'] = $obj->status;
2147  $reparray[$i]['entity'] = $obj->entity;
2148  $reparray[$i]['login'] = $obj->login;
2149  $reparray[$i]['photo'] = $obj->photo;
2150  } else {
2151  $reparray[] = $obj->rowid;
2152  }
2153  $i++;
2154  }
2155  return $reparray;
2156  } else {
2157  dol_print_error($this->db);
2158  return -1;
2159  }
2160  }
2161 
2162  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2170  public function set_price_level($price_level, User $user)
2171  {
2172  // phpcs:enable
2173  if ($this->id) {
2174  $now = dol_now();
2175 
2176  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2177  $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
2178  $sql .= " WHERE rowid = ".$this->id;
2179 
2180  if (!$this->db->query($sql)) {
2181  dol_print_error($this->db);
2182  return -1;
2183  }
2184 
2185  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2186  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2187  $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
2188 
2189  if (!$this->db->query($sql)) {
2190  dol_print_error($this->db);
2191  return -1;
2192  }
2193  return 1;
2194  }
2195  return -1;
2196  }
2197 
2198  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2206  public function add_commercial(User $user, $commid)
2207  {
2208  // phpcs:enable
2209  $error = 0;
2210 
2211  if ($this->id > 0 && $commid > 0) {
2212  $this->db->begin();
2213 
2214  if (!$error) {
2215  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2216  $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
2217 
2218  $resql = $this->db->query($sql);
2219  if (!$resql) {
2220  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2221  $error++;
2222  }
2223  }
2224 
2225  if (!$error) {
2226  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2227  $sql .= " (fk_soc, fk_user)";
2228  $sql .= " VALUES (".$this->id.", ".$commid.")";
2229 
2230  $resql = $this->db->query($sql);
2231  if (!$resql) {
2232  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2233  $error++;
2234  }
2235  }
2236 
2237  if (!$error) {
2238  $this->context = array('commercial_modified'=>$commid);
2239 
2240  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2241  if ($result < 0) {
2242  $error++;
2243  }
2244  }
2245 
2246  if (!$error) {
2247  $this->db->commit();
2248  return 1;
2249  } else {
2250  $this->db->rollback();
2251  return -1;
2252  }
2253  }
2254 
2255  return 0;
2256  }
2257 
2258  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2266  public function del_commercial(User $user, $commid)
2267  {
2268  // phpcs:enable
2269  $error = 0;
2270  $this->context = array('commercial_modified'=>$commid);
2271 
2272  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2273  if ($result < 0) {
2274  $error++;
2275  }
2276 
2277  if ($this->id > 0 && $commid > 0) {
2278  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2279  $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
2280 
2281  if (!$this->db->query($sql)) {
2282  dol_syslog(get_class($this)."::del_commercial Erreur");
2283  }
2284  }
2285  }
2286 
2287 
2298  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1)
2299  {
2300  global $conf, $langs, $hookmanager;
2301 
2302  if (!empty($conf->dol_no_mouse_hover)) {
2303  $notooltip = 1; // Force disable tooltips
2304  }
2305 
2306  $name = $this->name ? $this->name : $this->nom;
2307 
2308  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2309  if (empty($option) && $this->client > 0) {
2310  $option = 'customer';
2311  }
2312  if (empty($option) && $this->fournisseur > 0) {
2313  $option = 'supplier';
2314  }
2315  }
2316 
2317  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2318  $code = '';
2319  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2320  $code = $this->code_client.' - ';
2321  }
2322 
2323  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2324  $code .= $this->code_fournisseur.' - ';
2325  }
2326 
2327  if ($code) {
2328  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2329  $name = $code.' '.$name;
2330  } else {
2331  $name = $code;
2332  }
2333  }
2334  }
2335 
2336  if (!empty($this->name_alias)) {
2337  $name .= ' ('.$this->name_alias.')';
2338  }
2339 
2340  $result = ''; $label = '';
2341  $linkstart = ''; $linkend = '';
2342 
2343  if (!empty($this->logo) && class_exists('Form')) {
2344  $label .= '<div class="photointooltip">';
2345  $label .= Form::showphoto('societe', $this, 0, 40, 0, '', '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.
2346  $label .= '</div><div style="clear: both;"></div>';
2347  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2348  /*$label.= '<div class="photointooltip">';
2349  $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.
2350  $label.= '</div><div style="clear: both;"></div>';*/
2351  }
2352 
2353  $label .= '<div class="centpercent">';
2354 
2355  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2356  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2357  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2358  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2359  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2360  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2361  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2362  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2363  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2364  } elseif ($option == 'agenda') {
2365  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2366  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2367  } elseif ($option == 'project') {
2368  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2369  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2370  } elseif ($option == 'margin') {
2371  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2372  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2373  } elseif ($option == 'contact') {
2374  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2375  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2376  } elseif ($option == 'ban') {
2377  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2378  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2379  }
2380 
2381  // By default
2382  if (empty($linkstart)) {
2383  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2384  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2385  }
2386  if (isset($this->status)) {
2387  $label .= ' '.$this->getLibStatut(5);
2388  }
2389 
2390  if (!empty($this->name)) {
2391  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag($this->name);
2392  if (!empty($this->name_alias)) {
2393  $label .= ' ('.dol_escape_htmltag($this->name_alias).')';
2394  }
2395  }
2396  $label .= '<br><b>'.$langs->trans('Email').':</b> '.$this->email;
2397  if (!empty($this->country_code)) {
2398  $label .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2399  }
2400  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2401  $label .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2402  }
2403  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2404  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) {
2405  $label .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2406  }
2407  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) {
2408  $label .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2409  }
2410  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) {
2411  $label .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2412  }
2413  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) {
2414  $label .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2415  }
2416  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) {
2417  $label .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2418  }
2419  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) {
2420  $label .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2421  }
2422  }
2423  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2424  $label .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2425  }
2426  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2427  $label .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2428  }
2429  if (!empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3)) {
2430  $label .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2431  }
2432  if (!empty($conf->accounting->enabled) && $this->fournisseur) {
2433  $label .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2434  }
2435  $label .= '</div>';
2436 
2437  // Add type of canvas
2438  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2439  // Add param to save lastsearch_values or not
2440  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2441  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2442  $add_save_lastsearch_values = 1;
2443  }
2444  if ($add_save_lastsearch_values) {
2445  $linkstart .= '&save_lastsearch_values=1';
2446  }
2447  $linkstart .= '"';
2448 
2449  $linkclose = '';
2450  if (empty($notooltip)) {
2451  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2452  $label = $langs->trans("ShowCompany");
2453  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2454  }
2455  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2456  $linkclose .= ' class="classfortooltip refurl"';
2457 
2458  /*
2459  $hookmanager->initHooks(array('thirdpartydao'));
2460  $parameters=array('id'=>$this->id);
2461  $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
2462  if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2463  */
2464  }
2465  $linkstart .= $linkclose.'>';
2466  $linkend = '</a>';
2467 
2468  global $user;
2469  if (!$user->rights->societe->client->voir && $user->socid > 0 && $this->id != $user->socid) {
2470  $linkstart = '';
2471  $linkend = '';
2472  }
2473 
2474  $result .= $linkstart;
2475  if ($withpicto) {
2476  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
2477  }
2478  if ($withpicto != 2) {
2479  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2480  }
2481  $result .= $linkend;
2482 
2483  global $action;
2484  $hookmanager->initHooks(array('thirdpartydao'));
2485  $parameters = array(
2486  'id'=>$this->id,
2487  'getnomurl'=>$result,
2488  'withpicto '=> $withpicto,
2489  'option'=> $option,
2490  'maxlen'=> $maxlen,
2491  'notooltip'=> $notooltip,
2492  'save_lastsearch_value'=> $save_lastsearch_value
2493  );
2494  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2495  if ($reshook > 0) {
2496  $result = $hookmanager->resPrint;
2497  } else {
2498  $result .= $hookmanager->resPrint;
2499  }
2500 
2501  return $result;
2502  }
2503 
2510  public function getLibStatut($mode = 0)
2511  {
2512  return $this->LibStatut($this->status, $mode);
2513  }
2514 
2515  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2523  public function LibStatut($status, $mode = 0)
2524  {
2525  // phpcs:enable
2526  global $langs;
2527  $langs->load('companies');
2528 
2529  $statusType = 'status4';
2530  if ($status == 0) {
2531  $statusType = 'status6';
2532  }
2533 
2534  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2535  $this->labelStatus[0] = $langs->trans("ActivityCeased");
2536  $this->labelStatus[1] = $langs->trans("InActivity");
2537  $this->labelStatusShort[0] = $langs->trans("ActivityCeased");
2538  $this->labelStatusShort[1] = $langs->trans("InActivity");
2539  }
2540 
2541  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2542  }
2543 
2544  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2551  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2552  {
2553  // phpcs:enable
2554  global $langs;
2555 
2556  $contact_emails = $this->contact_property_array('email', 1);
2557  if ($this->email && $addthirdparty) {
2558  if (empty($this->name)) {
2559  $this->name = $this->nom;
2560  }
2561  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2562  }
2563  //var_dump($contact_emails)
2564  return $contact_emails;
2565  }
2566 
2567  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2574  {
2575  // phpcs:enable
2576  global $langs;
2577 
2578  $contact_phone = $this->contact_property_array('mobile');
2579 
2580  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2581  if (empty($this->name)) {
2582  $this->name = $this->nom;
2583  }
2584  // TODO: Tester si tel non deja present dans tableau contact
2585  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2586  }
2587  return $contact_phone;
2588  }
2589 
2590  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2598  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2599  {
2600  // phpcs:enable
2601  global $langs;
2602 
2603  $contact_property = array();
2604 
2605 
2606  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2607  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2608  $sql .= " WHERE fk_soc = ".$this->id;
2609  $sql .= " ORDER BY lastname, firstname";
2610 
2611  $resql = $this->db->query($sql);
2612  if ($resql) {
2613  $nump = $this->db->num_rows($resql);
2614  if ($nump) {
2615  $sepa = "("; $sepb = ")";
2616  if ($mode == 'email') {
2617  //$sepa="&lt;"; $sepb="&gt;";
2618  $sepa = "<"; $sepb = ">";
2619  }
2620  $i = 0;
2621  while ($i < $nump) {
2622  $obj = $this->db->fetch_object($resql);
2623  if ($mode == 'email') {
2624  $property = $obj->email;
2625  } elseif ($mode == 'mobile') {
2626  $property = $obj->phone_mobile;
2627  } else {
2628  $property = $obj->$mode;
2629  }
2630 
2631  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2632  if ($obj->status == 1 || empty($hidedisabled)) {
2633  if (empty($property)) {
2634  if ($mode == 'email') {
2635  $property = $langs->transnoentitiesnoconv("NoEMail");
2636  } elseif ($mode == 'mobile') {
2637  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2638  }
2639  }
2640 
2641  if (!empty($obj->poste)) {
2642  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2643  } else {
2644  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2645  }
2646  }
2647  $i++;
2648  }
2649  }
2650  } else {
2651  dol_print_error($this->db);
2652  }
2653  return $contact_property;
2654  }
2655 
2656 
2657  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2663  public function contact_array()
2664  {
2665  // phpcs:enable
2666  $contacts = array();
2667 
2668  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2669  $resql = $this->db->query($sql);
2670  if ($resql) {
2671  $nump = $this->db->num_rows($resql);
2672  if ($nump) {
2673  $i = 0;
2674  while ($i < $nump) {
2675  $obj = $this->db->fetch_object($resql);
2676  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2677  $i++;
2678  }
2679  }
2680  } else {
2681  dol_print_error($this->db);
2682  }
2683  return $contacts;
2684  }
2685 
2686  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2692  public function contact_array_objects()
2693  {
2694  // phpcs:enable
2695  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2696  $contacts = array();
2697 
2698  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2699  $resql = $this->db->query($sql);
2700  if ($resql) {
2701  $nump = $this->db->num_rows($resql);
2702  if ($nump) {
2703  $i = 0;
2704  while ($i < $nump) {
2705  $obj = $this->db->fetch_object($resql);
2706  $contact = new Contact($this->db);
2707  $contact->fetch($obj->rowid);
2708  $contacts[] = $contact;
2709  $i++;
2710  }
2711  }
2712  } else {
2713  dol_print_error($this->db);
2714  }
2715  return $contacts;
2716  }
2717 
2718  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2726  public function contact_get_property($rowid, $mode)
2727  {
2728  // phpcs:enable
2729  $contact_property = '';
2730 
2731  if (empty($rowid)) {
2732  return '';
2733  }
2734 
2735  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2736  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2737  $sql .= " WHERE rowid = ".((int) $rowid);
2738 
2739  $resql = $this->db->query($sql);
2740  if ($resql) {
2741  $nump = $this->db->num_rows($resql);
2742 
2743  if ($nump) {
2744  $obj = $this->db->fetch_object($resql);
2745 
2746  if ($mode == 'email') {
2747  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
2748  } elseif ($mode == 'mobile') {
2749  $contact_property = $obj->phone_mobile;
2750  }
2751  }
2752  return $contact_property;
2753  } else {
2754  dol_print_error($this->db);
2755  }
2756  }
2757 
2758 
2759  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2766  public function display_rib($mode = 'label')
2767  {
2768  // phpcs:enable
2769  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
2770 
2771  $bac = new CompanyBankAccount($this->db);
2772  $bac->fetch(0, $this->id);
2773 
2774  if ($bac->id > 0) { // If a bank account has been found for company $this->id
2775  if ($mode == 'label') {
2776  return $bac->getRibLabel(true);
2777  } elseif ($mode == 'rum') {
2778  if (empty($bac->rum)) {
2779  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
2780  $prelevement = new BonPrelevement($this->db);
2781  $bac->fetch_thirdparty();
2782  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2783  }
2784  return $bac->rum;
2785  } elseif ($mode == 'format') {
2786  return $bac->frstrecur;
2787  } else {
2788  return 'BadParameterToFunctionDisplayRib';
2789  }
2790  } else {
2791  return '';
2792  }
2793  }
2794 
2795  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2801  public function get_all_rib()
2802  {
2803  // phpcs:enable
2804  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
2805  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id;
2806  $result = $this->db->query($sql);
2807  if (!$result) {
2808  $this->error++;
2809  $this->errors[] = $this->db->lasterror;
2810  return 0;
2811  } else {
2812  $num_rows = $this->db->num_rows($result);
2813  $rib_array = array();
2814  if ($num_rows) {
2815  while ($obj = $this->db->fetch_object($result)) {
2816  $rib = new CompanyBankAccount($this->db);
2817  $rib->fetch($obj->rowid);
2818  $rib_array[] = $rib;
2819  }
2820  }
2821  return $rib_array;
2822  }
2823  }
2824 
2825  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2834  public function get_codeclient($objsoc = 0, $type = 0)
2835  {
2836  // phpcs:enable
2837  global $conf;
2838  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2839  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2840 
2841  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2842  foreach ($dirsociete as $dirroot) {
2843  $res = dol_include_once($dirroot.$module.'.php');
2844  if ($res) {
2845  break;
2846  }
2847  }
2848  $mod = new $module();
2849 
2850  $this->code_client = $mod->getNextValue($objsoc, $type);
2851  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2852 
2853  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2854  }
2855  }
2856 
2857  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2866  public function get_codefournisseur($objsoc = 0, $type = 1)
2867  {
2868  // phpcs:enable
2869  global $conf;
2870  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2871  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2872 
2873  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2874  foreach ($dirsociete as $dirroot) {
2875  $res = dol_include_once($dirroot.$module.'.php');
2876  if ($res) {
2877  break;
2878  }
2879  }
2880  $mod = new $module();
2881 
2882  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
2883 
2884  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2885  }
2886  }
2887 
2888  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2895  public function codeclient_modifiable()
2896  {
2897  // phpcs:enable
2898  global $conf;
2899  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2900  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2901 
2902  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2903  foreach ($dirsociete as $dirroot) {
2904  $res = dol_include_once($dirroot.$module.'.php');
2905  if ($res) {
2906  break;
2907  }
2908  }
2909 
2910  $mod = new $module();
2911 
2912  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2913  if ($mod->code_modifiable_null && !$this->code_client) {
2914  return 1;
2915  }
2916  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
2917  return 1;
2918  }
2919  if ($mod->code_modifiable) {
2920  return 1; // A mettre en dernier
2921  }
2922  return 0;
2923  } else {
2924  return 0;
2925  }
2926  }
2927 
2928 
2929  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2935  public function codefournisseur_modifiable()
2936  {
2937  // phpcs:enable
2938  global $conf;
2939  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2940  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2941 
2942  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2943  foreach ($dirsociete as $dirroot) {
2944  $res = dol_include_once($dirroot.$module.'.php');
2945  if ($res) {
2946  break;
2947  }
2948  }
2949 
2950  $mod = new $module();
2951 
2952  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2953  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
2954  return 1;
2955  }
2956  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
2957  return 1;
2958  }
2959  if ($mod->code_modifiable) {
2960  return 1; // A mettre en dernier
2961  }
2962  return 0;
2963  } else {
2964  return 0;
2965  }
2966  }
2967 
2968 
2969  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2981  public function check_codeclient()
2982  {
2983  // phpcs:enable
2984  global $conf;
2985  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2986  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2987 
2988  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2989  foreach ($dirsociete as $dirroot) {
2990  $res = dol_include_once($dirroot.$module.'.php');
2991  if ($res) {
2992  break;
2993  }
2994  }
2995 
2996  $mod = new $module();
2997 
2998  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2999  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3000  if ($result) { // If error
3001  $this->error = $mod->error;
3002  $this->errors = $mod->errors;
3003  }
3004  return $result;
3005  } else {
3006  return 0;
3007  }
3008  }
3009 
3010  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3022  public function check_codefournisseur()
3023  {
3024  // phpcs:enable
3025  global $conf;
3026  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3027  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3028 
3029  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3030  foreach ($dirsociete as $dirroot) {
3031  $res = dol_include_once($dirroot.$module.'.php');
3032  if ($res) {
3033  break;
3034  }
3035  }
3036 
3037  $mod = new $module();
3038 
3039  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3040  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3041  if ($result) { // If error
3042  $this->error = $mod->error;
3043  $this->errors = $mod->errors;
3044  }
3045  return $result;
3046  } else {
3047  return 0;
3048  }
3049  }
3050 
3051  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3060  public function get_codecompta($type)
3061  {
3062  // phpcs:enable
3063  global $conf;
3064 
3065  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3066  $res = false;
3067  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3068  foreach ($dirsociete as $dirroot) {
3069  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3070  if ($res) {
3071  break;
3072  }
3073  }
3074 
3075  if ($res) {
3076  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3077  $mod = new $classname;
3078 
3079  // Set code count in $mod->code
3080  $result = $mod->get_code($this->db, $this, $type);
3081 
3082  if ($type == 'customer') {
3083  $this->code_compta = $mod->code;
3084  } elseif ($type == 'supplier') {
3085  $this->code_compta_fournisseur = $mod->code;
3086  }
3087 
3088  return $result;
3089  } else {
3090  $this->error = 'ErrorAccountancyCodeNotDefined';
3091  return -1;
3092  }
3093  } else {
3094  if ($type == 'customer') {
3095  $this->code_compta = '';
3096  } elseif ($type == 'supplier') {
3097  $this->code_compta_fournisseur = '';
3098  }
3099 
3100  return 0;
3101  }
3102  }
3103 
3104  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3111  public function set_parent($id)
3112  {
3113  // phpcs:enable
3114  if ($this->id) {
3115  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
3116  $sql .= " SET parent = ".($id > 0 ? $id : "null");
3117  $sql .= " WHERE rowid = ".$this->id;
3118  dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
3119  $resql = $this->db->query($sql);
3120  if ($resql) {
3121  $this->parent = $id;
3122  return 1;
3123  } else {
3124  return -1;
3125  }
3126  } else {
3127  return -1;
3128  }
3129  }
3130 
3131  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3138  public function id_prof_verifiable($idprof)
3139  {
3140  // phpcs:enable
3141  global $conf;
3142 
3143  switch ($idprof) {
3144  case 1:
3145  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3146  break;
3147  case 2:
3148  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3149  break;
3150  case 3:
3151  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3152  break;
3153  case 4:
3154  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3155  break;
3156  case 5:
3157  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3158  break;
3159  case 6:
3160  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3161  break;
3162  default:
3163  $ret = false;
3164  }
3165 
3166  return $ret;
3167  }
3168 
3169  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3178  public function id_prof_exists($idprof, $value, $socid = 0)
3179  {
3180  // phpcs:enable
3181  $field = $idprof;
3182 
3183  switch ($idprof) { // For backward compatibility
3184  case '1':
3185  case 'idprof1':
3186  $field = "siren";
3187  break;
3188  case '2':
3189  case 'idprof2':
3190  $field = "siret";
3191  break;
3192  case '3':
3193  case 'idprof3':
3194  $field = "ape";
3195  break;
3196  case '4':
3197  case 'idprof4':
3198  $field = "idprof4";
3199  break;
3200  case '5':
3201  $field = "idprof5";
3202  break;
3203  case '6':
3204  $field = "idprof6";
3205  break;
3206  }
3207 
3208  //Verify duplicate entries
3209  $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3210  if ($socid) {
3211  $sql .= " AND rowid <> ".$socid;
3212  }
3213  $resql = $this->db->query($sql);
3214  if ($resql) {
3215  $obj = $this->db->fetch_object($resql);
3216  $count = $obj->idprof;
3217  } else {
3218  $count = 0;
3219  print $this->db->error();
3220  }
3221  $this->db->free($resql);
3222 
3223  if ($count > 0) {
3224  return true;
3225  } else {
3226  return false;
3227  }
3228  }
3229 
3230  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3239  public function id_prof_check($idprof, $soc)
3240  {
3241  // phpcs:enable
3242  global $conf;
3243 
3244  $ok = 1;
3245 
3246  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3247  return 1;
3248  }
3249 
3250  // Check SIREN if country FR
3251  if ($idprof == 1 && $soc->country_code == 'FR') {
3252  $chaine = trim($this->idprof1);
3253  $chaine = preg_replace('/(\s)/', '', $chaine);
3254 
3255  if (!is_numeric($chaine)) {
3256  return -1;
3257  }
3258  if (dol_strlen($chaine) != 9) {
3259  return -1;
3260  }
3261 
3262  // on prend chaque chiffre un par un
3263  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3264  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3265  // on ajoute cette valeur à la somme totale
3266  $sum = 0;
3267  for ($index = 0; $index < 9; $index++) {
3268  $number = (int) $chaine[$index];
3269  if (($index % 2) != 0) {
3270  if (($number *= 2) > 9) {
3271  $number -= 9;
3272  }
3273  }
3274  $sum += $number;
3275  }
3276 
3277  // le numéro est valide si la somme des chiffres est multiple de 10
3278  if (($sum % 10) != 0) {
3279  return -1;
3280  }
3281  }
3282 
3283  // Verifie SIRET si pays FR
3284  if ($idprof == 2 && $soc->country_code == 'FR') {
3285  $chaine = trim($this->idprof2);
3286  $chaine = preg_replace('/(\s)/', '', $chaine);
3287 
3288  if (!is_numeric($chaine)) {
3289  return -1;
3290  }
3291  if (dol_strlen($chaine) != 14) {
3292  return -1;
3293  }
3294 
3295  // on prend chaque chiffre un par un
3296  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3297  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3298  // on ajoute cette valeur à la somme totale
3299  $sum = 0;
3300  for ($index = 0; $index < 14; $index++) {
3301  $number = (int) $chaine[$index];
3302  if (($index % 2) == 0) {
3303  if (($number *= 2) > 9) {
3304  $number -= 9;
3305  }
3306  }
3307  $sum += $number;
3308  }
3309 
3310  // le numéro est valide si la somme des chiffres est multiple de 10
3311  if (($sum % 10) != 0) {
3312  return -1;
3313  }
3314  }
3315 
3316  //Verify CIF/NIF/NIE if pays ES
3317  //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
3318  if ($idprof == 1 && $soc->country_code == 'ES') {
3319  $string = trim($this->idprof1);
3320  $string = preg_replace('/(\s)/', '', $string);
3321  $string = strtoupper($string);
3322 
3323  //Check format
3324  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)) {
3325  return 0;
3326  }
3327 
3328  $num = array();
3329  for ($i = 0; $i < 9; $i++) {
3330  $num[$i] = substr($string, $i, 1);
3331  }
3332 
3333  //Check NIF
3334  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3335  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3336  return 1;
3337  } else {
3338  return -1;
3339  }
3340  }
3341 
3342  //algorithm checking type code CIF
3343  $sum = $num[2] + $num[4] + $num[6];
3344  for ($i = 1; $i < 8; $i += 2) {
3345  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3346  }
3347  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3348 
3349  //Chek special NIF
3350  if (preg_match('/^[KLM]{1}/', $string)) {
3351  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3352  return 1;
3353  } else {
3354  return -1;
3355  }
3356  }
3357 
3358  //Check CIF
3359  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3360  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3361  return 2;
3362  } else {
3363  return -2;
3364  }
3365  }
3366 
3367  //Check NIE T
3368  if (preg_match('/^[T]{1}/', $string)) {
3369  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3370  return 3;
3371  } else {
3372  return -3;
3373  }
3374  }
3375 
3376  //Check NIE XYZ
3377  if (preg_match('/^[XYZ]{1}/', $string)) {
3378  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3379  return 3;
3380  } else {
3381  return -3;
3382  }
3383  }
3384 
3385  //Can not be verified
3386  return -4;
3387  }
3388 
3389  //Verify NIF if country is PT
3390  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3391  if ($idprof == 1 && $soc->country_code == 'PT') {
3392  $string = trim($this->idprof1);
3393  $string = preg_replace('/(\s)/', '', $string);
3394 
3395  //Check NIF
3396  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3397  return 1;
3398  } else {
3399  return -1;
3400  }
3401  }
3402 
3403  return $ok;
3404  }
3405 
3406  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3415  public function id_prof_url($idprof, $thirdparty)
3416  {
3417  // phpcs:enable
3418  global $conf, $langs, $hookmanager;
3419 
3420  $url = '';
3421  $action = '';
3422 
3423  $hookmanager->initHooks(array('idprofurl'));
3424  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3425  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3426  if (empty($reshook)) {
3427  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3428  return '';
3429  }
3430 
3431  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3432  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3433  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3434  $url = 'http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3435  }
3436  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3437  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3438  }
3439  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3440  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3441  }
3442  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3443  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3444  }
3445  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3446  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3447  }
3448 
3449  if ($url) {
3450  return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
3451  }
3452  } else {
3453  return $hookmanager->resPrint;
3454  }
3455 
3456  return '';
3457  }
3458 
3459  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3465  public function has_projects()
3466  {
3467  // phpcs:enable
3468  $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = '.$this->id;
3469  $resql = $this->db->query($sql);
3470  if ($resql) {
3471  $obj = $this->db->fetch_object($resql);
3472  $count = $obj->numproj;
3473  } else {
3474  $count = 0;
3475  print $this->db->error();
3476  }
3477  $this->db->free($resql);
3478  return ($count > 0);
3479  }
3480 
3481 
3488  public function info($id)
3489  {
3490  $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
3491  $sql .= " fk_user_creat, fk_user_modif";
3492  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3493  $sql .= " WHERE s.rowid = ".$id;
3494 
3495  $result = $this->db->query($sql);
3496  if ($result) {
3497  if ($this->db->num_rows($result)) {
3498  $obj = $this->db->fetch_object($result);
3499 
3500  $this->id = $obj->rowid;
3501 
3502  if ($obj->fk_user_creat) {
3503  $cuser = new User($this->db);
3504  $cuser->fetch($obj->fk_user_creat);
3505  $this->user_creation = $cuser;
3506  }
3507 
3508  if ($obj->fk_user_modif) {
3509  $muser = new User($this->db);
3510  $muser->fetch($obj->fk_user_modif);
3511  $this->user_modification = $muser;
3512  }
3513 
3514  $this->ref = $obj->name;
3515  $this->date_creation = $this->db->jdate($obj->date_creation);
3516  $this->date_modification = $this->db->jdate($obj->date_modification);
3517  }
3518 
3519  $this->db->free($result);
3520  } else {
3521  dol_print_error($this->db);
3522  }
3523  }
3524 
3530  public function isACompany()
3531  {
3532  global $conf;
3533 
3534  // Define if third party is treated as company (or not) when nature is unknown
3535  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3536  if (!empty($this->tva_intra)) {
3537  $isacompany = 1;
3538  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3539  $isacompany = 1;
3540  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3541  // TODO Add a field is_a_company into dictionary
3542  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3543  $isacompany = 0;
3544  } else {
3545  $isacompany = 1;
3546  }
3547  }
3548 
3549  return $isacompany;
3550  }
3551 
3557  public function isInEEC()
3558  {
3559  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3560  return isInEEC($this);
3561  }
3562 
3563  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3569  public function LoadSupplierCateg()
3570  {
3571  // phpcs:enable
3572  $this->SupplierCategories = array();
3573  $sql = "SELECT rowid, label";
3574  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
3575  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3576 
3577  $resql = $this->db->query($sql);
3578  if ($resql) {
3579  while ($obj = $this->db->fetch_object($resql)) {
3580  $this->SupplierCategories[$obj->rowid] = $obj->label;
3581  }
3582  return 0;
3583  } else {
3584  return -1;
3585  }
3586  }
3587 
3588  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3595  public function AddFournisseurInCategory($categorie_id)
3596  {
3597  // phpcs:enable
3598  if ($categorie_id > 0 && $this->id > 0) {
3599  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3600  $sql .= " VALUES (".$categorie_id.", ".$this->id.")";
3601 
3602  if ($resql = $this->db->query($sql)) {
3603  return 0;
3604  }
3605  } else {
3606  return 0;
3607  }
3608  return -1;
3609  }
3610 
3611 
3612  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3622  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
3623  {
3624  // phpcs:enable
3625  global $conf, $user, $langs;
3626 
3627  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3628 
3629  $name = $socname ? $socname : $member->societe;
3630  if (empty($name)) {
3631  $name = $member->getFullName($langs);
3632  }
3633 
3634  $alias = $socalias ? $socalias : '';
3635 
3636  // Positionne parametres
3637  $this->nom = $name; // TODO deprecated
3638  $this->name = $name;
3639  $this->name_alias = $alias;
3640  $this->address = $member->address;
3641  $this->zip = $member->zip;
3642  $this->town = $member->town;
3643  $this->country_code = $member->country_code;
3644  $this->country_id = $member->country_id;
3645  $this->phone = $member->phone; // Prof phone
3646  $this->email = $member->email;
3647  $this->socialnetworks = $member->socialnetworks;
3648  $this->entity = $member->entity;
3649 
3650  $this->client = 1; // A member is a customer by default
3651  $this->code_client = ($customercode ? $customercode : -1);
3652  $this->code_fournisseur = -1;
3653 
3654  $this->db->begin();
3655 
3656  // Cree et positionne $this->id
3657  $result = $this->create($user);
3658  if ($result >= 0) {
3659  // Auto-create contact on thirdparty creation
3660  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
3661  // Fill fields needed by contact
3662  $this->name_bis = $member->lastname;
3663  $this->firstname = $member->firstname;
3664  $this->civility_id = $member->civility_id;
3665 
3666  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
3667  $result = $this->create_individual($user);
3668  if ($result < 0)
3669  {
3670  setEventMessages($this->error, $this->errors, 'errors');
3671  $this->db->rollback();
3672  return -1;
3673  }
3674  }
3675 
3676  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3677  $sql .= " SET fk_soc=".$this->id;
3678  $sql .= " WHERE rowid=".$member->id;
3679 
3680  $resql = $this->db->query($sql);
3681  if ($resql) {
3682  $this->db->commit();
3683  return $this->id;
3684  } else {
3685  $this->error = $this->db->error();
3686 
3687  $this->db->rollback();
3688  return -1;
3689  }
3690  } else {
3691  // $this->error deja positionne
3692  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
3693 
3694  $this->db->rollback();
3695  return $result;
3696  }
3697  }
3698 
3705  public function setMysoc(Conf $conf)
3706  {
3707  global $langs;
3708 
3709  $this->id = 0;
3710  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
3711  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3712  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
3713  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
3714  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
3715  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
3716 
3717  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
3718 
3719  $this->nom = $this->name; // deprecated
3720 
3721  // We define country_id, country_code and country
3722  $country_id = $country_code = $country_label = '';
3723  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
3724  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3725  $country_id = $tmp[0];
3726  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3727  $country_code = $tmp[1];
3728  $country_label = $tmp[2];
3729  } else // For backward compatibility
3730  {
3731  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
3732  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3733  $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
3734  $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
3735  }
3736  }
3737  $this->country_id = $country_id;
3738  $this->country_code = $country_code;
3739  $this->country = $country_label;
3740  if (is_object($langs)) {
3741  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
3742  }
3743 
3744  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
3745  // We define state_id, state_code and state
3746  $state_id = 0; $state_code = $state_label = '';
3747  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
3748  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
3749  $state_id = $tmp[0];
3750  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
3751  $state_code = $tmp[1];
3752  $state_label = $tmp[2];
3753  } else { // For backward compatibility
3754  dol_syslog("Your state setup use an old syntax (entity=".$conf->entity."). Reedit it using setup area.", LOG_ERR);
3755  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3756  $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
3757  $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
3758  }
3759  }
3760  $this->state_id = $state_id;
3761  $this->state_code = $state_code;
3762  $this->state = $state_label;
3763  if (is_object($langs)) {
3764  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
3765  }
3766 
3767  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
3768  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
3769  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
3770 
3771  // Social networks
3772  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
3773  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
3774  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
3775  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
3776  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
3777  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
3778  $this->socialnetworks = array();
3779  if (!empty($this->facebook_url)) {
3780  $this->socialnetworks['facebook'] = $this->facebook_url;
3781  }
3782  if (!empty($this->twitter_url)) {
3783  $this->socialnetworks['twitter'] = $this->twitter_url;
3784  }
3785  if (!empty($this->linkedin_url)) {
3786  $this->socialnetworks['linkedin'] = $this->linkedin_url;
3787  }
3788  if (!empty($this->instagram_url)) {
3789  $this->socialnetworks['instagram'] = $this->instagram_url;
3790  }
3791  if (!empty($this->youtube_url)) {
3792  $this->socialnetworks['youtube'] = $this->youtube_url;
3793  }
3794  if (!empty($this->github_url)) {
3795  $this->socialnetworks['github'] = $this->github_url;
3796  }
3797 
3798  // Id prof generiques
3799  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
3800  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
3801  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
3802  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
3803  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
3804  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
3805  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
3806  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3807  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
3808  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3809  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
3810  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
3811  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
3812  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3813  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3814  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
3815  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
3816  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
3817 
3818  // Define if company use vat or not
3819  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
3820 
3821  // Define if company use local taxes
3822  $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);
3823  $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);
3824  }
3825 
3833  public function initAsSpecimen()
3834  {
3835  $now = dol_now();
3836 
3837  // Initialize parameters
3838  $this->id = 0;
3839  $this->entity = 1;
3840  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
3841  $this->nom = $this->name; // For backward compatibility
3842  $this->ref_ext = 'Ref ext';
3843  $this->specimen = 1;
3844  $this->address = '21 jump street';
3845  $this->zip = '99999';
3846  $this->town = 'MyTown';
3847  $this->state_id = 1;
3848  $this->state_code = 'AA';
3849  $this->state = 'MyState';
3850  $this->country_id = 1;
3851  $this->country_code = 'FR';
3852  $this->email = 'specimen@specimen.com';
3853  $this->socialnetworks = array(
3854  'skype' => 'tom.hanson',
3855  'twitter' => 'tomhanson',
3856  'facebook' => 'tomhanson',
3857  'linkedin' => 'tomhanson',
3858  );
3859  $this->url = 'http://www.specimen.com';
3860 
3861  $this->phone = '0909090901';
3862  $this->fax = '0909090909';
3863 
3864  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
3865  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
3866  $this->capital = 10000;
3867  $this->client = 1;
3868  $this->prospect = 1;
3869  $this->fournisseur = 1;
3870  $this->tva_assuj = 1;
3871  $this->tva_intra = 'EU1234567';
3872  $this->note_public = 'This is a comment (public)';
3873  $this->note_private = 'This is a comment (private)';
3874 
3875  $this->idprof1 = 'idprof1';
3876  $this->idprof2 = 'idprof2';
3877  $this->idprof3 = 'idprof3';
3878  $this->idprof4 = 'idprof4';
3879  $this->idprof5 = 'idprof5';
3880  $this->idprof6 = 'idprof6';
3881  return 1;
3882  }
3883 
3890  public function useLocalTax($localTaxNum = 0)
3891  {
3892  $sql = "SELECT t.localtax1, t.localtax2";
3893  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3894  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3895  $sql .= " AND t.active = 1";
3896  if (empty($localTaxNum)) {
3897  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3898  } elseif ($localTaxNum == 1) {
3899  $sql .= " AND t.localtax1_type <> '0'";
3900  } elseif ($localTaxNum == 2) {
3901  $sql .= " AND t.localtax2_type <> '0'";
3902  }
3903 
3904  $resql = $this->db->query($sql);
3905  if ($resql) {
3906  return ($this->db->num_rows($resql) > 0);
3907  } else {
3908  return false;
3909  }
3910  }
3911 
3917  public function useNPR()
3918  {
3919  $sql = "SELECT t.rowid";
3920  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3921  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3922  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3923 
3924  dol_syslog("useNPR", LOG_DEBUG);
3925  $resql = $this->db->query($sql);
3926  if ($resql) {
3927  return ($this->db->num_rows($resql) > 0);
3928  } else {
3929  return false;
3930  }
3931  }
3932 
3939  public function useRevenueStamp()
3940  {
3941  $sql = "SELECT COUNT(*) as nb";
3942  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3943  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3944  $sql .= " AND r.active = 1";
3945 
3946  dol_syslog("useRevenueStamp", LOG_DEBUG);
3947  $resql = $this->db->query($sql);
3948  if ($resql) {
3949  $obj = $this->db->fetch_object($resql);
3950  return (($obj->nb > 0) ?true:false);
3951  } else {
3952  $this->error = $this->db->lasterror();
3953  return false;
3954  }
3955  }
3956 
3962  public function getLibProspLevel()
3963  {
3964  return $this->LibProspLevel($this->fk_prospectlevel);
3965  }
3966 
3967  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3974  public function LibProspLevel($fk_prospectlevel)
3975  {
3976  // phpcs:enable
3977  global $langs;
3978 
3979  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
3980  // If lib not found in language file, we get label from cache/databse
3981  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
3982  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
3983  }
3984  return $lib;
3985  }
3986 
3987 
3988  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3996  public function set_prospect_level(User $user)
3997  {
3998  // phpcs:enable
3999  return $this->update($this->id, $user);
4000  }
4001 
4009  public function getLibProspCommStatut($mode = 0, $label = '')
4010  {
4011  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4012  }
4013 
4014  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4028  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4029  {
4030  // phpcs:enable
4031  global $langs;
4032  $langs->load('customers');
4033 
4034  if ($mode == 2) {
4035  if ($status == '-1' || $status == 'ST_NO') {
4036  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4037  } elseif ($status == '0' || $status == 'ST_NEVER') {
4038  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4039  } elseif ($status == '1' || $status == 'ST_TODO') {
4040  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4041  } elseif ($status == '2' || $status == 'ST_PEND') {
4042  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4043  } elseif ($status == '3' || $status == 'ST_DONE') {
4044  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4045  } else {
4046  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4047  }
4048  } elseif ($mode == 3) {
4049  if ($status == '-1' || $status == 'ST_NO') {
4050  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4051  } elseif ($status == '0' || $status == 'ST_NEVER') {
4052  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4053  } elseif ($status == '1' || $status == 'ST_TODO') {
4054  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4055  } elseif ($status == '2' || $status == 'ST_PEND') {
4056  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4057  } elseif ($status == '3' || $status == 'ST_DONE') {
4058  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4059  } else {
4060  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4061  }
4062  } elseif ($mode == 4) {
4063  if ($status == '-1' || $status == 'ST_NO') {
4064  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4065  } elseif ($status == '0' || $status == 'ST_NEVER') {
4066  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4067  } elseif ($status == '1' || $status == 'ST_TODO') {
4068  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4069  } elseif ($status == '2' || $status == 'ST_PEND') {
4070  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4071  } elseif ($status == '3' || $status == 'ST_DONE') {
4072  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4073  } else {
4074  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4075  }
4076  }
4077 
4078  return "Error, mode/status not found";
4079  }
4080 
4081  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4089  public function set_OutstandingBill(User $user)
4090  {
4091  // phpcs:enable
4092  return $this->update($this->id, $user);
4093  }
4094 
4101  public function getOutstandingProposals($mode = 'customer')
4102  {
4103  $table = 'propal';
4104  if ($mode == 'supplier') {
4105  $table = 'supplier_proposal';
4106  }
4107 
4108  $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4109  $sql .= " WHERE fk_soc = ".$this->id;
4110  if ($mode == 'supplier') {
4111  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4112  } else {
4113  $sql .= " AND entity IN (".getEntity('propal').")";
4114  }
4115 
4116  dol_syslog("getOutstandingProposals", LOG_DEBUG);
4117  $resql = $this->db->query($sql);
4118  if ($resql) {
4119  $outstandingOpened = 0;
4120  $outstandingTotal = 0;
4121  $outstandingTotalIncTax = 0;
4122  while ($obj = $this->db->fetch_object($resql)) {
4123  $outstandingTotal += $obj->total_ht;
4124  $outstandingTotalIncTax += $obj->total_ttc;
4125  if ($obj->status != 0) {
4126  // Not a draft
4127  $outstandingOpened += $obj->total_ttc;
4128  }
4129  }
4130  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
4131  } else {
4132  return array();
4133  }
4134  }
4135 
4142  public function getOutstandingOrders($mode = 'customer')
4143  {
4144  $table = 'commande';
4145  if ($mode == 'supplier') {
4146  $table = 'commande_fournisseur';
4147  }
4148 
4149  $sql = "SELECT rowid, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4150  $sql .= " WHERE fk_soc = ".$this->id;
4151  if ($mode == 'supplier') {
4152  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4153  } else {
4154  $sql .= " AND entity IN (".getEntity('commande').")";
4155  }
4156 
4157  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4158  $resql = $this->db->query($sql);
4159  if ($resql) {
4160  $outstandingOpened = 0;
4161  $outstandingTotal = 0;
4162  $outstandingTotalIncTax = 0;
4163  while ($obj = $this->db->fetch_object($resql)) {
4164  $outstandingTotal += $obj->total_ht;
4165  $outstandingTotalIncTax += $obj->total_ttc;
4166  if ($obj->status != 0) {
4167  // Not a draft
4168  $outstandingOpened += $obj->total_ttc;
4169  }
4170  }
4171  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
4172  } else {
4173  return array();
4174  }
4175  }
4176 
4184  public function getOutstandingBills($mode = 'customer', $late = 0)
4185  {
4186  $table = 'facture';
4187  if ($mode == 'supplier') {
4188  $table = 'facture_fourn';
4189  }
4190 
4191  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4192  $paiement = $invoice->getSommePaiement();
4193  $creditnotes=$invoice->getSumCreditNotesUsed();
4194  $deposits=$invoice->getSumDepositsUsed();
4195  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4196  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4197  */
4198  if ($mode == 'supplier') {
4199  $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4200  } else {
4201  $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4202  }
4203  $sql .= " WHERE fk_soc = ".$this->id;
4204  if (!empty($late)) {
4205  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4206  }
4207  if ($mode == 'supplier') {
4208  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4209  } else {
4210  $sql .= " AND entity IN (".getEntity('invoice').")";
4211  }
4212 
4213  dol_syslog("getOutstandingBills", LOG_DEBUG);
4214  $resql = $this->db->query($sql);
4215  if ($resql) {
4216  $outstandingOpened = 0;
4217  $outstandingTotal = 0;
4218  $outstandingTotalIncTax = 0;
4219  if ($mode == 'supplier') {
4220  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4221  $tmpobject = new FactureFournisseur($this->db);
4222  } else {
4223  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4224  $tmpobject = new Facture($this->db);
4225  }
4226  while ($obj = $this->db->fetch_object($resql)) {
4227  $tmpobject->id = $obj->rowid;
4228 
4229  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4230  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4231  ) {
4232  $outstandingTotal += $obj->total_ht;
4233  $outstandingTotalIncTax += $obj->total_ttc;
4234  }
4235  if ($obj->paye == 0
4236  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4237  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4238  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4239  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4240  $paiement = $tmpobject->getSommePaiement();
4241  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4242  $deposits = $tmpobject->getSumDepositsUsed();
4243 
4244  $outstandingOpened += $obj->total_ttc - $paiement - $creditnotes - $deposits;
4245  }
4246 
4247  //if credit note is converted but not used
4248  // TODO Do this also for customer ?
4249  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4250  $outstandingOpened -= $tmpobject->getSumFromThisCreditNotesNotUsed();
4251  }
4252  }
4253  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
4254  } else {
4255  return array();
4256  }
4257  }
4258 
4264  public function getLibCustProspStatut()
4265  {
4266  return $this->LibCustProspStatut($this->client);
4267  }
4268 
4269  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4276  public function LibCustProspStatut($status)
4277  {
4278  // phpcs:enable
4279  global $langs;
4280  $langs->load('companies');
4281 
4282  if ($status == 0) {
4283  return $langs->trans("NorProspectNorCustomer");
4284  } elseif ($status == 1) {
4285  return $langs->trans("Customer");
4286  } elseif ($status == 2) {
4287  return $langs->trans("Prospect");
4288  } elseif ($status == 3) {
4289  return $langs->trans("ProspectCustomer");
4290  }
4291  }
4292 
4293 
4305  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4306  {
4307  global $conf, $user, $langs;
4308 
4309  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4310  $modelpath = "core/modules/bank/doc/";
4311 
4312  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4313  $companybankaccount = new CompanyBankAccount($this->db);
4314  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4315  if (!$result) {
4316  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4317  }
4318  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4319  } else {
4320  // Positionne le modele sur le nom du modele a utiliser
4321  if (!dol_strlen($modele)) {
4322  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4323  $modele = $conf->global->COMPANY_ADDON_PDF;
4324  } else {
4325  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4326  return 0;
4327  }
4328  }
4329 
4330  if (!isset($this->bank_account)) {
4331  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4332  $bac = new CompanyBankAccount($this->db);
4333  $result = $bac->fetch(0, $this->id);
4334  if ($result > 0) {
4335  $this->bank_account = $bac;
4336  } else {
4337  $this->bank_account = '';
4338  }
4339  }
4340 
4341  $modelpath = "core/modules/societe/doc/";
4342 
4343  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4344  }
4345 
4346  return $result;
4347  }
4348 
4349 
4361  public function setCategories($categories, $type_categ)
4362  {
4363  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4364 
4365  // Decode type
4366  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4367  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4368  return -1;
4369  }
4370 
4371  // Handle single category
4372  if (!is_array($categories)) {
4373  $categories = array($categories);
4374  }
4375 
4376  // Get current categories
4377  $c = new Categorie($this->db);
4378  $existing = $c->containing($this->id, $type_categ, 'id');
4379 
4380  // Diff
4381  if (is_array($existing)) {
4382  $to_del = array_diff($existing, $categories);
4383  $to_add = array_diff($categories, $existing);
4384  } else {
4385  $to_del = array(); // Nothing to delete
4386  $to_add = $categories;
4387  }
4388 
4389  $error = 0;
4390 
4391  // Process
4392  foreach ($to_del as $del) {
4393  if ($c->fetch($del) > 0) {
4394  $c->del_type($this, $type_categ);
4395  }
4396  }
4397  foreach ($to_add as $add) {
4398  if ($c->fetch($add) > 0) {
4399  $result = $c->add_type($this, $type_categ);
4400  if ($result < 0) {
4401  $error++;
4402  $this->error = $c->error;
4403  $this->errors = $c->errors;
4404  break;
4405  }
4406  }
4407  }
4408 
4409  return $error ? -1 : 1;
4410  }
4411 
4419  public function setSalesRep($salesrep, $onlyAdd = false)
4420  {
4421  global $user;
4422 
4423  // Handle single user
4424  if (!is_array($salesrep)) {
4425  $salesrep = array($salesrep);
4426  }
4427 
4428  $to_del = array(); // Nothing to delete
4429  $to_add = $salesrep;
4430  if ($onlyAdd === false) {
4431  // Get current users
4432  $existing = $this->getSalesRepresentatives($user, 1);
4433 
4434  // Diff
4435  if (is_array($existing)) {
4436  $to_del = array_diff($existing, $salesrep);
4437  $to_add = array_diff($salesrep, $existing);
4438  }
4439  }
4440 
4441  $error = 0;
4442 
4443  // Process
4444  foreach ($to_del as $del) {
4445  $this->del_commercial($user, $del);
4446  }
4447  foreach ($to_add as $add) {
4448  $result = $this->add_commercial($user, $add);
4449  if ($result < 0) {
4450  $error++;
4451  break;
4452  }
4453  }
4454 
4455  return $error ? -1 : 1;
4456  }
4457 
4464  public function setThirdpartyType($typent_id)
4465  {
4466  if ($this->id) {
4467  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
4468  $sql .= " SET fk_typent = ".($typent_id > 0 ? $typent_id : "null");
4469  $sql .= " WHERE rowid = ".$this->id;
4470  dol_syslog(get_class($this).'::setThirdpartyType', LOG_DEBUG);
4471  $resql = $this->db->query($sql);
4472  if ($resql) {
4473  $this->typent_id = $typent_id;
4474  $this->typent_code = dol_getIdFromCode($this->db, $this->$typent_id, 'c_typent', 'id', 'code');
4475  return 1;
4476  } else {
4477  return -1;
4478  }
4479  } else {
4480  return -1;
4481  }
4482  }
4483 
4493  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
4494  {
4495  if ($origin_id == $dest_id) {
4496  dol_syslog('Error: Try to merge a thirdparty into itself');
4497  return false;
4498  }
4499 
4504  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4505  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4506  $sql .= ' SELECT fk_user ';
4507  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4508  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
4509 
4510  $resql = $db->query($sql);
4511  while ($obj = $db->fetch_object($resql)) {
4512  $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$obj->rowid);
4513  }
4514 
4519  $tables = array(
4520  'societe_address',
4521  'societe_commerciaux',
4522  'societe_prices',
4523  'societe_remise',
4524  'societe_remise_except',
4525  'societe_rib'
4526  );
4527 
4528  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
4529  }
4530 }
__construct($db)
Constructor.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases)...
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
check_codeclient()
Check customer code.
const PROSPECT
Third party is a prospect.
create(User $user)
Create third party in database.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
getLibStatut($mode=0)
Return label of status (activity, closed)
Class to stock current configuration.
Definition: conf.class.php:33
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
del_commercial(User $user, $commid)
Add link to sales representative.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
initAsSpecimen()
Initialise an instance with random values.
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
const CUSTOMER_AND_PROSPECT
Third party is a customer and a prospect.
add_commercial(User $user, $commid)
Add link to sales representative.
setCategories($categories, $type_categ)
Sets object to supplied categories.
isObjectUsed($id=0)
Function to check if an object is used by others.
Class to manage contact/addresses.
getOutstandingBills($mode= 'customer', $late=0)
Return amount of bill not paid and total.
foreach($object->fields as $key=> $val) if(is_array($extrafields->attributes[$object->table_element]['label'])&&count($extrafields->attributes[$object->table_element]['label']) > 0) $object fields
isInEEC()
Return if a company is inside the EEC (European Economic Community)
dol_now($mode= 'auto')
Return date for now.
const NO_CUSTOMER
Third party is no customer.
set_parent($id)
Define parent commany of current company.
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
getOutstandingProposals($mode= 'customer')
Return amount of order not paid and total.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Class to manage bank accounts description of third parties.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
clean_url($url, $http=1)
Clean an url string.
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:432
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
Class to manage suppliers invoices.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+&#39; &#39;+name+&#39; &#39;+lastname)
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:108
create_individual(User $user)
Create a contact/address from thirdparty.
has_projects()
Indicates if the company has projects.
$conf db
API class for accounts.
Definition: inc.php:54
img_action($titlealt, $numaction, $picto= '')
Show logo action.
create_from_member(Adherent $member, $socname= '', $socalias= '', $customercode= '')
Create a third party into database from a member object.
LoadSupplierCateg()
Load the list of provider categories.
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
const NO_SUPPLIER
Third party is no supplier.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
dol_string_nospecial($str, $newstr= '_', $badcharstoreplace= '')
Clean a string from all punctuation characters to use it as a ref or login.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
getOutstandingOrders($mode= 'customer')
Return amount of order not paid and total.
getLibProspLevel()
Return prostect level.
Class to manage third parties objects (customers, suppliers, prospects...)
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Class to manage categories.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
set_as_client()
Define third party as a customer.
const CUSTOMER
Third party is a customer.
if(!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'] s nom
Definition: list.php:560
Class to manage withdrawal receipts.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static getIdFromCode($db, $code)
Get id of currency from code.
query($query, $usesavepoint=0, $type= 'auto')
Execute a SQL request and return the resultset.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
contact_get_property($rowid, $mode)
Return property of contact from its id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1286
Class to manage members of a foundation.
fetch($rowid, $ref= '', $ref_ext= '', $barcode= '', $idprof1= '', $idprof2= '', $idprof3= '', $idprof4= '', $idprof5= '', $idprof6= '', $email= '', $ref_alias= '')
Load a third party from database into memory.
LibProspCommStatut($status, $mode=0, $label= '', $picto= '')
Return label of a given status.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
info($id)
Load information for tab info.
set_OutstandingBill(User $user)
Set outstanding value.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
deleteExtraFields()
Delete all extra fields values for the current object.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
getState($id, $withcode= '', $dbtouse=0, $withregion=0, $outputlangs= '', $entconv=1)
Return state translated from an id.
display_rib($mode= 'label')
Return bank number property of thirdparty (label or rum)
getAvailableDiscounts($user= '', $filter= '', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass= 'photowithmargin', $imagesize= '', $addlinktofullsize=1, $cache=0, $forcecapture= '', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
print $_SERVER["PHP_SELF"]
Edit parameters.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
set_prospect_level(User $user)
Set prospect level.
contact_array_objects()
Returns the contact list of this company.
getNomUrl($withpicto=0, $option= '', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
Return a link on thirdparty (with picto)
dol_getIdFromCode($db, $key, $tablename, $fieldkey= 'code', $fieldid= 'id', $entityfilter=0)
Return an id or code from a code or id.
const TYPE_CREDIT_NOTE
Credit note invoice.
trait CommonIncoterm
Superclass for incoterm classes.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
print
Draft customers invoices.
Definition: index.php:89
call_trigger($triggerName, $user)
Call trigger based on this instance.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Class to manage absolute discounts.
getLibProspCommStatut($mode=0, $label= '')
Return status of prospect.
const SUPPLIER
Third party is a supplier.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
contact_array()
Returns the contact list of this company.
Class to manage invoices.
setMysoc(Conf $conf)
Set properties with value into $conf.
set_remise_except($remise, User $user, $desc, $vatrate= '', $discount_type=0)
Add a discount for third party.
LibStatut($status, $mode=0)
Return the label of a given status.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
update($id, $user= '', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action= 'update', $nosyncmember=1)
Update parameters of third party.
check_codefournisseur()
Check supplier code.
set_price_level($price_level, User $user)
Set the price level.
setThirdpartyType($typent_id)
Define third-party type of current company.
get_all_rib()
Return Array of RIB.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren...
LibCustProspStatut($status)
Return the label of the customer/prospect status.
getCountry($searchkey, $withcode= '', $dbtouse=0, $outputlangs= '', $entconv=1, $searchlabel= '')
Return country label, code or id from an id, code or label.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
contact_property_array($mode= 'email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
insertExtraLanguages($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.