dolibarr  x.y.z
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-2021 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-2021 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-2022 Frédéric France <frederic.france@netlogic.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21  *
22  * This program is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as published by
24  * the Free Software Foundation; either version 3 of the License, or
25  * (at your option) any later version.
26  *
27  * This program is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License
33  * along with this program. If not, see <https://www.gnu.org/licenses/>.
34  */
35 
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
44 
45 
49 class Societe extends CommonObject
50 {
51  use CommonIncoterm;
52 
56  public $element = 'societe';
57 
61  public $table_element = 'societe';
62 
66  public $fk_element = 'fk_soc';
67 
71  public $fieldsforcombobox = 'nom,name_alias';
72 
76  protected $childtables = array(
77  'supplier_proposal' => array('name' => 'SupplierProposal'),
78  'propal' => array('name' => 'Proposal'),
79  'commande' => array('name' => 'Order'),
80  'facture' => array('name' => 'Invoice'),
81  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
82  'contrat' => array('name' => 'Contract'),
83  'fichinter' => array('name' => 'Fichinter'),
84  'facture_fourn' => array('name' => 'SupplierInvoice'),
85  'commande_fournisseur' => array('name' => 'SupplierOrder'),
86  'projet' => array('name' => 'Project'),
87  'expedition' => array('name' => 'Shipment'),
88  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
89  );
90 
95  protected $childtablesoncascade = array(
96  'societe_prices',
97  'societe_address',
98  'product_fournisseur_price',
99  'product_customer_price_log',
100  'product_customer_price',
101  '@Contact:/contact/class/contact.class.php:fk_soc',
102  'adherent',
103  'societe_account',
104  'societe_rib',
105  'societe_remise',
106  'societe_remise_except',
107  'societe_commerciaux',
108  'categorie',
109  'notify',
110  'notify_def',
111  'actioncomm',
112  );
113 
117  public $picto = 'company';
118 
123  public $ismultientitymanaged = 1;
124 
129  public $restrictiononfksoc = 1;
130 
131 
161  public $fields = array(
162  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
163  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
164  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
165  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
166  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
167  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
168  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
169  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
170  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
171  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
172  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CodeCompta', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
173  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'CodeComptaSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
174  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
175  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
176  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
177  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
178  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
179  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
180  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
181  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
182  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
183  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
184  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
185  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
186  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
187  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
188  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
189  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
190  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
191  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
192  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
193  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
194  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
195  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
196  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
197  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
198  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
199  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>"getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible'=>-1, 'position'=>235),
200  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
201  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
202  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
203  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
204  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
205  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
206  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
207  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
208  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
209  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
210  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
211  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
212  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
213  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
214  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
215  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
216  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
217  'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
218  'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
219  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
220  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
221  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
222  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
223  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
224  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
225  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
226  '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),
227  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
228  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
229  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
230  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
231  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
232  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
233  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
234  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
235  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
236  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
237  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
238  'fk_account' =>array('type'=>'integer', 'label'=>'AccountingAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
239  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
240  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
241  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
242  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
243  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
244  );
245 
249  public $entity;
250 
257  public $nom;
258 
262  public $name;
263 
268  public $name_alias;
269 
273  public $particulier;
274 
278  public $address;
279 
283  public $zip;
284 
288  public $town;
289 
294  public $status = 1;
295 
300  public $state_id;
301 
305  public $state_code;
306 
310  public $state;
311 
316  public $region_code;
317 
321  public $region;
322 
328  public $departement_code;
329 
335  public $departement;
336 
342  public $pays;
343 
348  public $phone;
353  public $fax;
358  public $email;
359 
363  public $socialnetworks;
364 
370  public $skype;
371 
377  public $twitter;
378 
384  public $facebook;
385 
391  public $linkedin;
392 
397  public $url;
398 
403  public $barcode;
404 
405  // 6 professional id (usage depends on country)
406 
411  public $idprof1;
412 
418  public $siren;
419 
420 
425  public $idprof2;
426 
432  public $siret;
433 
438  public $idprof3;
439 
445  public $ape;
446 
451  public $idprof4;
452 
457  public $idprof5;
458 
463  public $idprof6;
464 
468  public $prefix_comm;
469 
473  public $tva_assuj = 1;
474 
479  public $tva_intra;
480 
481  // Local taxes
482  public $localtax1_assuj;
483  public $localtax1_value;
484  public $localtax2_assuj;
485  public $localtax2_value;
486 
490  public $managers;
491 
495  public $capital;
496 
500  public $typent_id = 0;
501  public $typent_code;
502  public $effectif;
503  public $effectif_id = 0;
504  public $forme_juridique_code;
505  public $forme_juridique = 0;
506 
507  public $remise_percent;
508  public $remise_supplier_percent;
509 
510  public $mode_reglement_id;
511  public $cond_reglement_id;
512  public $deposit_percent;
513  public $mode_reglement_supplier_id;
514  public $cond_reglement_supplier_id;
515  public $transport_mode_supplier_id;
516 
520  public $fk_prospectlevel;
521 
525  public $name_bis;
526 
527  //Log data
528 
533  public $date_modification;
534 
539  public $user_modification;
540 
545  public $date_creation;
546 
551  public $user_creation;
552 
557  public $client = 0;
558 
563  public $prospect = 0;
564 
569  public $fournisseur;
570 
575  public $code_client;
576 
581  public $code_fournisseur;
582 
587  public $code_compta_client;
588 
593  public $code_compta;
594 
595 
600  public $accountancy_code_customer;
601 
606  public $code_compta_fournisseur;
607 
612  public $accountancy_code_supplier;
613 
614 
619  public $code_compta_product;
620 
621 
627  public $note;
628 
633  public $note_private;
634 
639  public $note_public;
640 
645  public $stcomm_id;
646 
651  public $stcomm_picto;
652 
657  public $status_prospect_label;
658 
663  public $price_level;
664 
668  public $outstanding_limit;
669 
673  public $order_min_amount;
674 
678  public $supplier_order_min_amount;
679 
684  public $commercial_id;
685 
690  public $parent;
691 
696  public $default_lang;
697 
701  public $ref;
702 
708  public $ref_ext;
709 
716  public $import_key;
717 
722  public $webservices_url;
723 
728  public $webservices_key;
729 
733  public $logo;
734 
738  public $logo_small;
739 
743  public $logo_mini;
744 
748  public $logo_squarred;
749 
753  public $logo_squarred_small;
754 
758  public $logo_squarred_mini;
759 
763  public $accountancy_code_sell;
764 
768  public $accountancy_code_buy;
769 
770  // Multicurrency
774  public $fk_multicurrency;
775 
776  // Warehouse
780  public $fk_warehouse;
781 
785  public $multicurrency_code;
786 
787 
788  // Fields loaded by fetchPartnerships()
789 
790  public $partnerships = array();
791 
792 
793 
797  public $bank_account;
798 
799 
800  const STATUS_CEASED = 0;
801  const STATUS_INACTIVITY = 1;
802 
806  const NO_CUSTOMER = 0;
807 
811  const CUSTOMER = 1;
812 
816  const PROSPECT = 2;
817 
822 
826  const NO_SUPPLIER = 0;
827 
831  const SUPPLIER = 1;
832 
833 
839  public function __construct($db)
840  {
841  global $conf;
842 
843  $this->db = $db;
844 
845  $this->client = 0;
846  $this->prospect = 0;
847  $this->fournisseur = 0;
848  $this->typent_id = 0;
849  $this->effectif_id = 0;
850  $this->forme_juridique_code = 0;
851  $this->tva_assuj = 1;
852  $this->status = 1;
853 
854  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
855  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
856  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
857  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
858  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
859  }
860  }
861 
862 
870  public function create(User $user)
871  {
872  global $langs, $conf, $mysoc;
873 
874  $error = 0;
875 
876  // Clean parameters
877  if (empty($this->status)) {
878  $this->status = 0;
879  }
880  $this->name = $this->name ?trim($this->name) : trim($this->nom);
881  $this->setUpperOrLowerCase();
882  $this->nom = $this->name; // For backward compatibility
883  if (empty($this->client)) {
884  $this->client = 0;
885  }
886  if (empty($this->fournisseur)) {
887  $this->fournisseur = 0;
888  }
889  $this->import_key = trim($this->import_key);
890 
891  $this->accountancy_code_customer = trim($this->code_compta);
892  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
893  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
894  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
895 
896  if (!empty($this->multicurrency_code)) {
897  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
898  }
899  if (empty($this->fk_multicurrency)) {
900  $this->multicurrency_code = '';
901  $this->fk_multicurrency = 0;
902  }
903 
904  dol_syslog(get_class($this)."::create ".$this->name);
905 
906  $now = dol_now();
907 
908  $this->db->begin();
909 
910  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
911  if ($this->code_client == -1 || $this->code_client === 'auto') {
912  $this->get_codeclient($this, 0);
913  }
914  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
915  $this->get_codefournisseur($this, 1);
916  }
917 
918  // Check more parameters (including mandatory setup
919  // If error, this->errors[] is filled
920  $result = $this->verify();
921 
922  if ($result >= 0) {
923  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
924 
925  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
926  $sql .= "nom";
927  $sql .= ", name_alias";
928  $sql .= ", entity";
929  $sql .= ", datec";
930  $sql .= ", fk_user_creat";
931  $sql .= ", fk_typent";
932  $sql .= ", canvas";
933  $sql .= ", status";
934  $sql .= ", ref_ext";
935  $sql .= ", fk_stcomm";
936  $sql .= ", fk_incoterms";
937  $sql .= ", location_incoterms";
938  $sql .= ", import_key";
939  $sql .= ", fk_multicurrency";
940  $sql .= ", multicurrency_code";
941  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
942  $sql .= ", accountancy_code_buy";
943  $sql .= ", accountancy_code_sell";
944  }
945  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
946  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
947  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
948  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
949  $sql .= ", ".((int) $this->status);
950  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
951  $sql .= ", 0";
952  $sql .= ", ".(int) $this->fk_incoterms;
953  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
954  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
955  $sql .= ", ".(int) $this->fk_multicurrency;
956  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
957  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
958  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
959  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
960  }
961  $sql .= ")";
962 
963  dol_syslog(get_class($this)."::create", LOG_DEBUG);
964  $result = $this->db->query($sql);
965  if ($result) {
966  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
967 
968  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
969 
970  // update accountancy for this entity
971  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
972  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
973 
974  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
975  $sql .= " fk_soc";
976  $sql .= ", entity";
977  $sql .= ", accountancy_code_customer";
978  $sql .= ", accountancy_code_supplier";
979  $sql .= ", accountancy_code_buy";
980  $sql .= ", accountancy_code_sell";
981  $sql .= ") VALUES (";
982  $sql .= $this->id;
983  $sql .= ", ".((int) $conf->entity);
984  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
985  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
986  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
987  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
988  $sql .= ")";
989  $result = $this->db->query($sql);
990  if (!$result) {
991  $error++;
992  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
993  }
994  }
995 
996  // Ajout du commercial affecte
997  if ($this->commercial_id != '' && $this->commercial_id != -1) {
998  $this->add_commercial($user, $this->commercial_id);
999  } elseif (empty($user->rights->societe->client->voir)) {
1000  // si un commercial cree un client il lui est affecte automatiquement
1001  $this->add_commercial($user, $user->id);
1002  }
1003 
1004  if ($ret >= 0) {
1005  // Call trigger
1006  $result = $this->call_trigger('COMPANY_CREATE', $user);
1007  if ($result < 0) {
1008  $error++;
1009  }
1010  // End call triggers
1011  } else {
1012  $error++;
1013  }
1014 
1015  if (!$error) {
1016  dol_syslog(get_class($this)."::Create success id=".$this->id);
1017  $this->db->commit();
1018  return $this->id;
1019  } else {
1020  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1021  $this->db->rollback();
1022  return -4;
1023  }
1024  } else {
1025  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1026  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1027  $result = -1;
1028  } else {
1029  $this->error = $this->db->lasterror();
1030  $result = -2;
1031  }
1032  $this->db->rollback();
1033  return $result;
1034  }
1035  } else {
1036  $this->db->rollback();
1037  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1038  return -3;
1039  }
1040  }
1041 
1042 
1043  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1052  public function create_individual(User $user, $no_email = 0, $tags = array())
1053  {
1054  global $conf;
1055 
1056  $error = 0;
1057 
1058  $this->db->begin();
1059 
1060  // phpcs:enable
1061  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1062  $contact = new Contact($this->db);
1063 
1064  $contact->name = $this->name_bis;
1065  $contact->firstname = $this->firstname;
1066  $contact->civility_id = $this->civility_id;
1067  $contact->socid = $this->id; // fk_soc
1068  $contact->statut = 1; // deprecated
1069  $contact->status = 1;
1070  $contact->priv = 0;
1071  $contact->country_id = $this->country_id;
1072  $contact->state_id = $this->state_id;
1073  $contact->address = $this->address;
1074  $contact->email = $this->email;
1075  $contact->zip = $this->zip;
1076  $contact->town = $this->town;
1077  $this->setUpperOrLowerCase();
1078  $contact->phone_pro = $this->phone;
1079 
1080  $contactId = $contact->create($user);
1081  if ($contactId < 0) {
1082  $error++;
1083  $this->error = $contact->error;
1084  $this->errors = $contact->errors;
1085  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1086  }
1087 
1088  if (empty($error) && is_array($tags) && !empty($tags)) {
1089  $result = $contact->setCategories($tags);
1090  if ($result < 0) {
1091  $error++;
1092  $this->error = $contact->error;
1093  $this->errors = array_merge($this->errors, $contact->errors);
1094  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1095  $contactId = $result;
1096  }
1097  }
1098 
1099  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1100  $result = $contact->setNoEmail($no_email);
1101  if ($result < 0) {
1102  $this->error = $contact->error;
1103  $this->errors = array_merge($this->errors, $contact->errors);
1104  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1105  $contactId = $result;
1106  }
1107  }
1108 
1109  if (empty($error)) {
1110  dol_syslog(get_class($this)."::create_individual success");
1111  $this->db->commit();
1112  } else {
1113  $this->db->rollback();
1114  }
1115 
1116  return $contactId;
1117  }
1118 
1125  public function verify()
1126  {
1127  global $conf, $langs, $mysoc;
1128 
1129  $error = 0;
1130  $this->errors = array();
1131 
1132  $result = 0;
1133  $this->name = trim($this->name);
1134  $this->nom = $this->name; // For backward compatibility
1135 
1136  if (!$this->name) {
1137  $this->errors[] = 'ErrorBadThirdPartyName';
1138  $result = -2;
1139  }
1140 
1141  if ($this->client) {
1142  $rescode = $this->check_codeclient();
1143  if ($rescode != 0 && $rescode != -5) {
1144  if ($rescode == -1) {
1145  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1146  } elseif ($rescode == -2) {
1147  $this->errors[] = 'ErrorCustomerCodeRequired';
1148  } elseif ($rescode == -3) {
1149  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1150  } elseif ($rescode == -4) {
1151  $this->errors[] = 'ErrorPrefixRequired';
1152  } else {
1153  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1154  }
1155 
1156  $result = -3;
1157  }
1158  }
1159 
1160  if ($this->fournisseur) {
1161  $rescode = $this->check_codefournisseur();
1162  if ($rescode != 0 && $rescode != -5) {
1163  if ($rescode == -1) {
1164  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1165  } elseif ($rescode == -2) {
1166  $this->errors[] = 'ErrorSupplierCodeRequired';
1167  } elseif ($rescode == -3) {
1168  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1169  } elseif ($rescode == -4) {
1170  $this->errors[] = 'ErrorPrefixRequired';
1171  } else {
1172  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1173  }
1174  $result = -3;
1175  }
1176  }
1177 
1178  // Check for duplicate or mandatory fields defined into setup
1179  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1180  foreach ($array_to_check as $key) {
1181  $keymin = strtolower($key);
1182  $i = (int) preg_replace('/[^0-9]/', '', $key);
1183  $vallabel = $this->$keymin;
1184 
1185  if ($i > 0) {
1186  if ($this->isACompany()) {
1187  // Check for mandatory prof id (but only if country is same than ours)
1188  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1189  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1190  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1191  $langs->load("errors");
1192  $error++;
1193  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1194  }
1195  }
1196  }
1197 
1198  // Check for unicity on profid
1199  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1200  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1201  $langs->load("errors");
1202  $error++;
1203  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1204  }
1205  }
1206  } else {
1207  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1208  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1209  if ($key == 'EMAIL') {
1210  // Check for mandatory
1211  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1212  $langs->load("errors");
1213  $error++;
1214  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1215  }
1216 
1217  // Check for unicity
1218  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1219  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1220  $langs->load("errors");
1221  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1222  }
1223  }
1224  } elseif ($key == 'TVA_INTRA') {
1225  // Check for unicity
1226  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1227  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1228  $langs->load("errors");
1229  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1230  }
1231  }
1232  }
1233  }
1234  }
1235 
1236  if ($error) {
1237  $result = -4;
1238  }
1239 
1240  return $result;
1241  }
1242 
1255  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1256  {
1257  global $langs, $conf, $hookmanager;
1258 
1259  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1260 
1261  if (empty($id)) {
1262  $id = $this->id;
1263  }
1264 
1265  $error = 0;
1266 
1267  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1268 
1269  $now = dol_now();
1270 
1271  // Clean parameters
1272  $this->id = $id;
1273  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1274  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1275  $this->nom = $this->name; // For backward compatibility
1276  $this->name_alias = trim($this->name_alias);
1277  $this->ref_ext = trim($this->ref_ext);
1278  $this->address = $this->address ?trim($this->address) : trim($this->address);
1279  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1280  $this->town = $this->town ?trim($this->town) : trim($this->town);
1281  $this->state_id = trim($this->state_id);
1282  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1283  $this->phone = trim($this->phone);
1284  $this->phone = preg_replace("/\s/", "", $this->phone);
1285  $this->phone = preg_replace("/\./", "", $this->phone);
1286  $this->fax = trim($this->fax);
1287  $this->fax = preg_replace("/\s/", "", $this->fax);
1288  $this->fax = preg_replace("/\./", "", $this->fax);
1289  $this->email = trim($this->email);
1290  $this->url = $this->url ?clean_url($this->url, 0) : '';
1291  $this->note_private = trim($this->note_private);
1292  $this->note_public = trim($this->note_public);
1293  $this->idprof1 = trim($this->idprof1);
1294  $this->idprof2 = trim($this->idprof2);
1295  $this->idprof3 = trim($this->idprof3);
1296  $this->idprof4 = trim($this->idprof4);
1297  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1298  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1299  $this->prefix_comm = trim($this->prefix_comm);
1300  $this->outstanding_limit = price2num($this->outstanding_limit);
1301  $this->order_min_amount = price2num($this->order_min_amount);
1302  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1303 
1304  $this->tva_assuj = trim($this->tva_assuj);
1305  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1306  if (empty($this->status)) {
1307  $this->status = 0;
1308  }
1309 
1310  if (!empty($this->multicurrency_code)) {
1311  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1312  }
1313  if (empty($this->fk_multicurrency)) {
1314  $this->multicurrency_code = '';
1315  $this->fk_multicurrency = 0;
1316  }
1317 
1318  // Local taxes
1319  $this->localtax1_assuj = trim($this->localtax1_assuj);
1320  $this->localtax2_assuj = trim($this->localtax2_assuj);
1321 
1322  $this->localtax1_value = trim($this->localtax1_value);
1323  $this->localtax2_value = trim($this->localtax2_value);
1324 
1325  if ($this->capital != '') {
1326  $this->capital = price2num(trim($this->capital));
1327  }
1328  if (!is_numeric($this->capital)) {
1329  $this->capital = ''; // '' = undef
1330  }
1331 
1332  $this->effectif_id = trim($this->effectif_id);
1333  $this->forme_juridique_code = trim($this->forme_juridique_code);
1334 
1335  //Gencod
1336  $this->barcode = trim($this->barcode);
1337 
1338  // For automatic creation
1339  if ($this->code_client == -1 || $this->code_client === 'auto') {
1340  $this->get_codeclient($this, 0);
1341  }
1342  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1343  $this->get_codefournisseur($this, 1);
1344  }
1345 
1346  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1347  $this->code_compta = $this->code_compta_client; // for backward compatibility
1348  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1349 
1350  // Check parameters. More tests are done later in the ->verify()
1351  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1352  $langs->load("errors");
1353  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1354  return -1;
1355  }
1356 
1357  $customer = false;
1358  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1359  // If $allowmodcodeclient is set and value is not set, we generate it
1360  if (empty($this->code_compta_client)) {
1361  $ret = $this->get_codecompta('customer');
1362  if ($ret < 0) {
1363  return -1;
1364  }
1365  }
1366 
1367  $customer = true;
1368  }
1369 
1370  $supplier = false;
1371  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1372  // If $allowmodcodefournisseur is set and value is not set, we generate it
1373  if (empty($this->code_compta_fournisseur)) {
1374  $ret = $this->get_codecompta('supplier');
1375  if ($ret < 0) {
1376  return -1;
1377  }
1378  }
1379 
1380  $supplier = true;
1381  }
1382 
1383  //Web services
1384  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1385  $this->webservices_key = trim($this->webservices_key);
1386 
1387  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1388  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1389 
1390  //Incoterms
1391  $this->fk_incoterms = (int) $this->fk_incoterms;
1392  $this->location_incoterms = trim($this->location_incoterms);
1393 
1394  $this->db->begin();
1395 
1396  // Check name is required and codes are ok or unique.
1397  // If error, this->errors[] is filled
1398  $result = 0;
1399  if ($action != 'add' && $action != 'merge') {
1400  // We don't check when update called during a create because verify was already done.
1401  // 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
1402  $result = $this->verify();
1403 
1404  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1405  // So we can update record that were using and old numbering rule.
1406  if (is_array($this->errors)) {
1407  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1408  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1409  unset($this->errors[$key]); // Remove error message
1410  }
1411  }
1412  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1413  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1414  unset($this->errors[$key]); // Remove error message
1415  }
1416  }
1417  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1418  $result = 0;
1419  }
1420  }
1421  }
1422  $this->setUpperOrLowerCase();
1423  if ($result >= 0) {
1424  dol_syslog(get_class($this)."::update verify ok or not done");
1425 
1426  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1427  $sql .= "entity = ".$this->db->escape($this->entity);
1428  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1429  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1430  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1431  $sql .= ",address = '".$this->db->escape($this->address)."'";
1432 
1433  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1434  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1435 
1436  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1437  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1438 
1439  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1440  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1441  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1442  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1443  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1444 
1445  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1446 
1447  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1448  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1449 
1450  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1451  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1452  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1453  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1454  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1455  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1456 
1457  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1458  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1459  $sql .= ",status = ".((int) $this->status);
1460 
1461  // Local taxes
1462  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1463  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1464  if ($this->localtax1_assuj == 1) {
1465  if ($this->localtax1_value != '') {
1466  $sql .= ",localtax1_value =".$this->localtax1_value;
1467  } else {
1468  $sql .= ",localtax1_value =0.000";
1469  }
1470  } else {
1471  $sql .= ",localtax1_value =0.000";
1472  }
1473 
1474  if ($this->localtax2_assuj == 1) {
1475  if ($this->localtax2_value != '') {
1476  $sql .= ",localtax2_value =".$this->localtax2_value;
1477  } else {
1478  $sql .= ",localtax2_value =0.000";
1479  }
1480  } else {
1481  $sql .= ",localtax2_value =0.000";
1482  }
1483 
1484  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1485 
1486  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1487 
1488  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1489  if (isset($this->stcomm_id)) {
1490  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1491  }
1492  if (isset($this->typent_id)) {
1493  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1494  }
1495 
1496  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1497 
1498  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1499  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1500  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1501  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1502  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1503  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1504  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1505  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1506 
1507  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1508  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1509  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1510  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1511  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1512  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1513  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1514  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1515  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1516  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1517  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1518  $sql .= ", accountancy_code_buy = '".$this->db->escape($this->accountancy_code_buy)."'";
1519  $sql .= ", accountancy_code_sell= '".$this->db->escape($this->accountancy_code_sell)."'";
1520 
1521  if ($customer) {
1522  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1523  }
1524 
1525  if ($supplier) {
1526  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1527  }
1528  }
1529  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1530  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1531 
1532  //Incoterms
1533  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1534  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1535 
1536  if ($customer) {
1537  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1538  }
1539 
1540  if ($supplier) {
1541  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1542  }
1543  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1544  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1545  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1546  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1547  $sql .= " WHERE rowid = ".(int) $id;
1548 
1549  $resql = $this->db->query($sql);
1550  if ($resql) {
1551  if (is_object($this->oldcopy)) { // If we have information on old values
1552  if ($this->oldcopy->country_id != $this->country_id) {
1553  unset($this->country_code);
1554  unset($this->country);
1555  }
1556  if ($this->oldcopy->state_id != $this->state_id) {
1557  unset($this->state_code);
1558  unset($this->state);
1559  }
1560  } else {
1561  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1562  unset($this->country);
1563  unset($this->state_code);
1564  unset($this->state);
1565  }
1566 
1567  $nbrowsaffected = $this->db->affected_rows($resql);
1568 
1569  if (!$error && $nbrowsaffected) {
1570  // Update information on linked member if it is an update
1571  if (!$nosyncmember && isModEnabled('adherent')) {
1572  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1573 
1574  dol_syslog(get_class($this)."::update update linked member");
1575 
1576  $lmember = new Adherent($this->db);
1577  $result = $lmember->fetch(0, 0, $this->id);
1578 
1579  if ($result > 0) {
1580  $lmember->company = $this->name;
1581  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1582  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1583  $lmember->address = $this->address;
1584  $lmember->zip = $this->zip;
1585  $lmember->town = $this->town;
1586  $lmember->email = $this->email;
1587  $lmember->socialnetworks = $this->socialnetworks;
1588  $lmember->phone = $this->phone;
1589  $lmember->state_id = $this->state_id;
1590  $lmember->country_id = $this->country_id;
1591  $lmember->default_lang = $this->default_lang;
1592 
1593  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1594  if ($result < 0) {
1595  $this->error = $lmember->error;
1596  $this->errors = array_merge($this->errors, $lmember->errors);
1597  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1598  $error++;
1599  }
1600  } elseif ($result < 0) {
1601  $this->error = $lmember->error;
1602  $error++;
1603  }
1604  }
1605  }
1606 
1607  $action = 'update';
1608 
1609  // update accountancy for this entity
1610  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1611  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1612 
1613  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1614  $sql .= " fk_soc";
1615  $sql .= ", entity";
1616  $sql .= ", accountancy_code_customer";
1617  $sql .= ", accountancy_code_supplier";
1618  $sql .= ", accountancy_code_buy";
1619  $sql .= ", accountancy_code_sell";
1620  $sql .= ") VALUES (";
1621  $sql .= $this->id;
1622  $sql .= ", ".$conf->entity;
1623  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1624  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1625  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1626  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1627  $sql .= ")";
1628  $result = $this->db->query($sql);
1629  if (!$result) {
1630  $error++;
1631  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1632  }
1633  }
1634 
1635  // Actions on extra fields
1636  if (!$error) {
1637  $result = $this->insertExtraFields();
1638  if ($result < 0) {
1639  $error++;
1640  }
1641  }
1642  // Actions on extra languages
1643  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1644  $result = $this->insertExtraLanguages();
1645  if ($result < 0) {
1646  $error++;
1647  }
1648  }
1649 
1650  if (!$error && $call_trigger) {
1651  // Call trigger
1652  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1653  if ($result < 0) {
1654  $error++;
1655  }
1656  // End call triggers
1657  }
1658 
1659  if (!$error) {
1660  dol_syslog(get_class($this)."::Update success");
1661  $this->db->commit();
1662  return 1;
1663  } else {
1664  $this->db->rollback();
1665  return -1;
1666  }
1667  } else {
1668  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1669  // Doublon
1670  $this->error = $langs->trans("ErrorDuplicateField");
1671  $result = -1;
1672  } else {
1673  $this->error = $this->db->lasterror();
1674  $result = -2;
1675  }
1676  $this->db->rollback();
1677  return $result;
1678  }
1679  } else {
1680  $this->db->rollback();
1681  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1682  return -3;
1683  }
1684  }
1685 
1703  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1704  {
1705  global $langs;
1706  global $conf;
1707 
1708  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1709  return -1;
1710  }
1711 
1712  $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';
1713  $sql .= ', s.status, s.fk_warehouse';
1714  $sql .= ', s.price_level';
1715  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1716  $sql .= ', s.phone, s.fax, s.email';
1717  $sql .= ', s.socialnetworks';
1718  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1719  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1720  $sql .= ', s.capital, s.tva_intra';
1721  $sql .= ', s.fk_typent as typent_id';
1722  $sql .= ', s.fk_effectif as effectif_id';
1723  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1724  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1725  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1726  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1727  } else {
1728  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1729  }
1730  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1731  $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.mode_reglement, s.cond_reglement, s.deposit_percent, s.transport_mode';
1732  $sql .= ', s.fk_account, s.tva_assuj';
1733  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1734  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1735  $sql .= ', s.fk_shipping_method';
1736  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1737  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1738  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1739  $sql .= ', fj.libelle as forme_juridique';
1740  $sql .= ', e.libelle as effectif';
1741  $sql .= ', c.code as country_code, c.label as country';
1742  $sql .= ', d.code_departement as state_code, d.nom as state';
1743  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1744  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1745  $sql .= ', te.code as typent_code';
1746  $sql .= ', i.libelle as label_incoterms';
1747  if (!isModEnabled('multicompany')) {
1748  $sql .= ', s.remise_client, s.remise_supplier';
1749  } else {
1750  $sql .= ', sr.remise_client, sr2.remise_supplier';
1751  }
1752  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1753  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1754  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1755  }
1756  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1757  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1758  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1759  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1760  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1761  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1762  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1763  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1764  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1765  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1766  if (isModEnabled('multicompany')) {
1767  $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').'))';
1768  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise_supplier as sr2 ON sr2.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise_supplier WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))';
1769  }
1770  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1771  if ($rowid) {
1772  $sql .= ' AND s.rowid = '.((int) $rowid);
1773  }
1774  if ($ref) {
1775  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1776  }
1777  if ($ref_alias) {
1778  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1779  }
1780  if ($ref_ext) {
1781  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1782  }
1783  if ($barcode) {
1784  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1785  }
1786  if ($idprof1) {
1787  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1788  }
1789  if ($idprof2) {
1790  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1791  }
1792  if ($idprof3) {
1793  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1794  }
1795  if ($idprof4) {
1796  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1797  }
1798  if ($idprof5) {
1799  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1800  }
1801  if ($idprof6) {
1802  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1803  }
1804  if ($email) {
1805  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1806  }
1807 
1808  $resql = $this->db->query($sql);
1809  if ($resql) {
1810  $num = $this->db->num_rows($resql);
1811  if ($num > 1) {
1812  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1813  dol_syslog($this->error, LOG_ERR);
1814  $result = -2;
1815  } elseif ($num) { // $num = 1
1816  $obj = $this->db->fetch_object($resql);
1817 
1818  $this->id = $obj->rowid;
1819  $this->entity = $obj->entity;
1820  $this->canvas = $obj->canvas;
1821 
1822  $this->ref = $obj->rowid;
1823  $this->name = $obj->name;
1824  $this->nom = $obj->name; // deprecated
1825  $this->name_alias = $obj->name_alias;
1826  $this->ref_ext = $obj->ref_ext;
1827 
1828  $this->date_creation = $this->db->jdate($obj->date_creation);
1829  $this->date_modification = $this->db->jdate($obj->date_modification);
1830  $this->user_creation = $obj->fk_user_creat;
1831  $this->user_modification = $obj->fk_user_modif;
1832 
1833  $this->address = $obj->address;
1834  $this->zip = $obj->zip;
1835  $this->town = $obj->town;
1836 
1837  $this->country_id = $obj->country_id;
1838  $this->country_code = $obj->country_id ? $obj->country_code : '';
1839  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1840 
1841  $this->state_id = $obj->state_id;
1842  $this->state_code = $obj->state_code;
1843  $this->region_id = $obj->region_id;
1844  $this->region_code = $obj->region_code;
1845  $this->state = ($obj->state != '-' ? $obj->state : '');
1846 
1847  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1848  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1849  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1850  $this->status_prospect_label = $label; // label status prospect
1851  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1852 
1853  $this->email = $obj->email;
1854  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1855 
1856  $this->url = $obj->url;
1857  $this->phone = $obj->phone;
1858  $this->fax = $obj->fax;
1859 
1860  $this->parent = $obj->parent;
1861 
1862  $this->idprof1 = $obj->idprof1;
1863  $this->idprof2 = $obj->idprof2;
1864  $this->idprof3 = $obj->idprof3;
1865  $this->idprof4 = $obj->idprof4;
1866  $this->idprof5 = $obj->idprof5;
1867  $this->idprof6 = $obj->idprof6;
1868 
1869  $this->capital = $obj->capital;
1870 
1871  $this->code_client = $obj->code_client;
1872  $this->code_fournisseur = $obj->code_fournisseur;
1873 
1874  $this->code_compta = $obj->code_compta; // For backward compatibility
1875  $this->code_compta_client = $obj->code_compta;
1876  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1877 
1878  $this->barcode = $obj->barcode;
1879 
1880  $this->tva_assuj = $obj->tva_assuj;
1881  $this->tva_intra = $obj->tva_intra;
1882  $this->status = $obj->status;
1883 
1884  // Local Taxes
1885  $this->localtax1_assuj = $obj->localtax1_assuj;
1886  $this->localtax2_assuj = $obj->localtax2_assuj;
1887 
1888  $this->localtax1_value = $obj->localtax1_value;
1889  $this->localtax2_value = $obj->localtax2_value;
1890 
1891  $this->typent_id = $obj->typent_id;
1892  $this->typent_code = $obj->typent_code;
1893 
1894  $this->effectif_id = $obj->effectif_id;
1895  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1896 
1897  $this->forme_juridique_code = $obj->forme_juridique_code;
1898  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1899 
1900  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1901 
1902  $this->prefix_comm = $obj->prefix_comm;
1903 
1904  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1905  $this->remise_supplier_percent = $obj->remise_supplier;
1906 
1907  $this->mode_reglement_id = $obj->mode_reglement;
1908  $this->cond_reglement_id = $obj->cond_reglement;
1909  $this->deposit_percent = $obj->deposit_percent;
1910  $this->transport_mode_id = $obj->transport_mode;
1911  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1912  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1913  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1914  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1915  $this->fk_account = $obj->fk_account;
1916 
1917  $this->client = $obj->client;
1918  $this->fournisseur = $obj->fournisseur;
1919 
1920  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1921  $this->note_private = $obj->note_private;
1922  $this->note_public = $obj->note_public;
1923  $this->model_pdf = $obj->model_pdf;
1924  $this->modelpdf = $obj->model_pdf; // deprecated
1925  $this->default_lang = $obj->default_lang;
1926  $this->logo = $obj->logo;
1927  $this->logo_squarred = $obj->logo_squarred;
1928 
1929  $this->webservices_url = $obj->webservices_url;
1930  $this->webservices_key = $obj->webservices_key;
1931 
1932  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1933  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1934 
1935  $this->outstanding_limit = $obj->outstanding_limit;
1936  $this->order_min_amount = $obj->order_min_amount;
1937  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1938 
1939  // multiprix
1940  $this->price_level = $obj->price_level;
1941 
1942  // warehouse
1943  $this->fk_warehouse = $obj->fk_warehouse;
1944 
1945  $this->import_key = $obj->import_key;
1946 
1947  //Incoterms
1948  $this->fk_incoterms = $obj->fk_incoterms;
1949  $this->location_incoterms = $obj->location_incoterms;
1950  $this->label_incoterms = $obj->label_incoterms;
1951 
1952  // multicurrency
1953  $this->fk_multicurrency = $obj->fk_multicurrency;
1954  $this->multicurrency_code = $obj->multicurrency_code;
1955 
1956  // pdf
1957  $this->model_pdf = $obj->model_pdf;
1958  $this->last_main_doc = $obj->last_main_doc;
1959 
1960  $result = 1;
1961 
1962  // fetch optionals attributes and labels
1963  $this->fetch_optionals();
1964  } else {
1965  $result = 0;
1966  }
1967 
1968  $this->db->free($resql);
1969  } else {
1970  $this->error = $this->db->lasterror();
1971  $this->errors[] = $this->db->lasterror();
1972  $result = -3;
1973  }
1974 
1975  // Use first price level if level not defined for third party
1976  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1977  $this->price_level = 1;
1978  }
1979 
1980  return $result;
1981  }
1982 
1991  public function delete($id, User $fuser = null, $call_trigger = 1)
1992  {
1993  global $langs, $conf, $user;
1994 
1995  if (empty($fuser)) {
1996  $fuser = $user;
1997  }
1998 
1999  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2000 
2001  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2002 
2003  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2004  $error = 0;
2005 
2006  // Test if child exists
2007  $objectisused = $this->isObjectUsed($id);
2008  if (empty($objectisused)) {
2009  $this->db->begin();
2010 
2011  // User is mandatory for trigger call
2012  if (!$error && $call_trigger) {
2013  // Call trigger
2014  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2015  if ($result < 0) {
2016  $error++;
2017  }
2018  // End call triggers
2019  }
2020 
2021  if (!$error) {
2022  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2023  $static_cat = new Categorie($this->db);
2024  $toute_categs = array();
2025 
2026  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2027  if ($this->client || $this->prospect) {
2028  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2029  }
2030  if ($this->fournisseur) {
2031  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2032  }
2033 
2034  // Remove each "Categorie"
2035  foreach ($toute_categs as $type => $categs_type) {
2036  foreach ($categs_type as $cat) {
2037  $cat->del_type($this, $type);
2038  }
2039  }
2040  }
2041 
2042  if (!$error) {
2043  foreach ($this->childtablesoncascade as $tabletodelete) {
2044  $deleteFromObject = explode(':', $tabletodelete);
2045  if (count($deleteFromObject) >= 2) {
2046  $className = str_replace('@', '', $deleteFromObject[0]);
2047  $filepath = $deleteFromObject[1];
2048  $columnName = $deleteFromObject[2];
2049  if (dol_include_once($filepath)) {
2050  $child_object = new $className($this->db);
2051  $result = $child_object->deleteByParentField($id, $columnName);
2052  if ($result < 0) {
2053  $error++;
2054  $this->errors[] = $child_object->error;
2055  break;
2056  }
2057  } else {
2058  $error++;
2059  $this->errors[] = 'Cannot include child class file '.$filepath;
2060  break;
2061  }
2062  } else {
2063  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2064  $sql .= " WHERE fk_soc = ".((int) $id);
2065  if (!$this->db->query($sql)) {
2066  $error++;
2067  $this->errors[] = $this->db->lasterror();
2068  break;
2069  }
2070  }
2071  }
2072  }
2073 
2074  // Removed extrafields
2075  if (!$error) {
2076  $result = $this->deleteExtraFields();
2077  if ($result < 0) {
2078  $error++;
2079  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2080  }
2081  }
2082 
2083  // Remove links to subsidiaries companies
2084  if (!$error) {
2085  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2086  $sql .= " SET parent = NULL";
2087  $sql .= " WHERE parent = ".((int) $id);
2088  if (!$this->db->query($sql)) {
2089  $error++;
2090  $this->errors[] = $this->db->lasterror();
2091  }
2092  }
2093 
2094  // Remove third party
2095  if (!$error) {
2096  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2097  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2098  $sql .= " WHERE fk_soc = ".((int) $id);
2099  if (!$this->db->query($sql)) {
2100  $error++;
2101  $this->errors[] = $this->db->lasterror();
2102  }
2103  }
2104 
2105  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2106  $sql .= " WHERE rowid = ".((int) $id);
2107  if (!$this->db->query($sql)) {
2108  $error++;
2109  $this->errors[] = $this->db->lasterror();
2110  }
2111  }
2112 
2113  if (!$error) {
2114  $this->db->commit();
2115 
2116  // Delete directory
2117  if (!empty($conf->societe->multidir_output[$entity])) {
2118  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2119  if (dol_is_dir($docdir)) {
2120  dol_delete_dir_recursive($docdir);
2121  }
2122  }
2123 
2124  return 1;
2125  } else {
2126  dol_syslog($this->error, LOG_ERR);
2127  $this->db->rollback();
2128  return -1;
2129  }
2130  } else {
2131  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2132  }
2133  return 0;
2134  }
2135 
2136  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2142  public function set_as_client()
2143  {
2144  // phpcs:enable
2145  if ($this->id) {
2146  $newclient = 1;
2147  if ($this->client == 2 || $this->client == 3) {
2148  $newclient = 3; //If prospect, we keep prospect tag
2149  }
2150  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2151  $sql .= " SET client = ".((int) $newclient);
2152  $sql .= " WHERE rowid = ".((int) $this->id);
2153 
2154  $resql = $this->db->query($sql);
2155  if ($resql) {
2156  $this->client = $newclient;
2157  return 1;
2158  } else {
2159  return -1;
2160  }
2161  }
2162  return 0;
2163  }
2164 
2165  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2174  public function set_remise_client($remise, $note, User $user)
2175  {
2176  // phpcs:enable
2177  global $conf, $langs;
2178 
2179  // Parameter cleaning
2180  $note = trim($note);
2181  if (!$note) {
2182  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2183  return -2;
2184  }
2185 
2186  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2187 
2188  if ($this->id) {
2189  $this->db->begin();
2190 
2191  $now = dol_now();
2192 
2193  // Position current discount
2194  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2195  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2196  $sql .= " WHERE rowid = ".((int) $this->id);
2197  $resql = $this->db->query($sql);
2198  if (!$resql) {
2199  $this->db->rollback();
2200  $this->error = $this->db->error();
2201  return -1;
2202  }
2203 
2204  // Writes trace in discount history
2205  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2206  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2207  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2208  $sql .= " '".$this->db->escape($note)."',";
2209  $sql .= " ".((int) $user->id);
2210  $sql .= ")";
2211 
2212  $resql = $this->db->query($sql);
2213  if (!$resql) {
2214  $this->db->rollback();
2215  $this->error = $this->db->lasterror();
2216  return -1;
2217  }
2218 
2219  $this->db->commit();
2220  return 1;
2221  }
2222  }
2223 
2224  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2233  public function set_remise_supplier($remise, $note, User $user)
2234  {
2235  // phpcs:enable
2236  global $conf, $langs;
2237 
2238  // Parameter cleaning
2239  $note = trim($note);
2240  if (!$note) {
2241  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2242  return -2;
2243  }
2244 
2245  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2246 
2247  if ($this->id) {
2248  $this->db->begin();
2249 
2250  $now = dol_now();
2251 
2252  // Position current discount
2253  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2254  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2255  $sql .= " WHERE rowid = ".((int) $this->id);
2256  $resql = $this->db->query($sql);
2257  if (!$resql) {
2258  $this->db->rollback();
2259  $this->error = $this->db->error();
2260  return -1;
2261  }
2262 
2263  // Writes trace in discount history
2264  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2265  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2266  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2267  $sql .= " '".$this->db->escape($note)."',";
2268  $sql .= " ".((int) $user->id);
2269  $sql .= ")";
2270 
2271  $resql = $this->db->query($sql);
2272  if (!$resql) {
2273  $this->db->rollback();
2274  $this->error = $this->db->lasterror();
2275  return -1;
2276  }
2277 
2278  $this->db->commit();
2279  return 1;
2280  }
2281  }
2282 
2283  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2295  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2296  {
2297  // phpcs:enable
2298  global $langs;
2299 
2300  // Clean parameters
2301  $remise = price2num($remise);
2302  $desc = trim($desc);
2303 
2304  // Check parameters
2305  if (!($remise > 0)) {
2306  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2307  return -1;
2308  }
2309  if (!$desc) {
2310  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2311  return -2;
2312  }
2313 
2314  if ($this->id > 0) {
2315  // Clean vat code
2316  $reg = array();
2317  $vat_src_code = '';
2318  if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2319  $vat_src_code = $reg[1];
2320  $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2321  }
2322 
2323  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2324 
2325  $discount = new DiscountAbsolute($this->db);
2326  $discount->fk_soc = $this->id;
2327 
2328  $discount->discount_type = $discount_type;
2329 
2330  if ($price_base_type == 'TTC') {
2331  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2332  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2333  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2334  } else {
2335  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2336  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2337  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2338  }
2339 
2340  $discount->tva_tx = price2num($vatrate);
2341  $discount->vat_src_code = $vat_src_code;
2342 
2343  $discount->description = $desc;
2344 
2345  $result = $discount->create($user);
2346  if ($result > 0) {
2347  return $result;
2348  } else {
2349  $this->error = $discount->error;
2350  return -3;
2351  }
2352  } else {
2353  return 0;
2354  }
2355  }
2356 
2366  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2367  {
2368  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2369 
2370  $discountstatic = new DiscountAbsolute($this->db);
2371  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2372  if ($result >= 0) {
2373  return $result;
2374  } else {
2375  $this->error = $discountstatic->error;
2376  return -1;
2377  }
2378  }
2379 
2389  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2390  {
2391  global $conf;
2392 
2393  $reparray = array();
2394 
2395  $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, u.gender";
2396  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2397  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2398  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2399  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2400  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2401  $sql .= " AND ug.entity = ".$conf->entity.")";
2402  $sql .= " OR u.admin = 1)";
2403  } else {
2404  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2405  }
2406 
2407  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2408  if (empty($sortfield) && empty($sortorder)) {
2409  $sortfield = 'u.lastname,u.firstname';
2410  $sortorder = 'ASC,ASC';
2411  }
2412  $sql .= $this->db->order($sortfield, $sortorder);
2413 
2414  $resql = $this->db->query($sql);
2415  if ($resql) {
2416  $num = $this->db->num_rows($resql);
2417  $i = 0;
2418  while ($i < $num) {
2419  $obj = $this->db->fetch_object($resql);
2420 
2421  if (empty($mode)) {
2422  $reparray[$i]['id'] = $obj->rowid;
2423  $reparray[$i]['lastname'] = $obj->lastname;
2424  $reparray[$i]['firstname'] = $obj->firstname;
2425  $reparray[$i]['email'] = $obj->email;
2426  $reparray[$i]['phone'] = $obj->office_phone;
2427  $reparray[$i]['office_phone'] = $obj->office_phone;
2428  $reparray[$i]['office_fax'] = $obj->office_fax;
2429  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2430  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2431  $reparray[$i]['job'] = $obj->job;
2432  $reparray[$i]['statut'] = $obj->status; // deprecated
2433  $reparray[$i]['status'] = $obj->status;
2434  $reparray[$i]['entity'] = $obj->entity;
2435  $reparray[$i]['login'] = $obj->login;
2436  $reparray[$i]['photo'] = $obj->photo;
2437  $reparray[$i]['gender'] = $obj->gender;
2438  } else {
2439  $reparray[] = $obj->rowid;
2440  }
2441  $i++;
2442  }
2443  return $reparray;
2444  } else {
2445  dol_print_error($this->db);
2446  return -1;
2447  }
2448  }
2449 
2457  public function setPriceLevel($price_level, User $user)
2458  {
2459  if ($this->id) {
2460  $now = dol_now();
2461 
2462  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2463  $sql .= " SET price_level = ".((int) $price_level);
2464  $sql .= " WHERE rowid = ".((int) $this->id);
2465 
2466  if (!$this->db->query($sql)) {
2467  dol_print_error($this->db);
2468  return -1;
2469  }
2470 
2471  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2472  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2473  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2474 
2475  if (!$this->db->query($sql)) {
2476  dol_print_error($this->db);
2477  return -1;
2478  }
2479  return 1;
2480  }
2481  return -1;
2482  }
2483 
2484  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2492  public function add_commercial(User $user, $commid)
2493  {
2494  // phpcs:enable
2495  $error = 0;
2496 
2497  if ($this->id > 0 && $commid > 0) {
2498  $this->db->begin();
2499 
2500  if (!$error) {
2501  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2502  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2503 
2504  $resql = $this->db->query($sql);
2505  if (!$resql) {
2506  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2507  $error++;
2508  }
2509  }
2510 
2511  if (!$error) {
2512  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2513  $sql .= " (fk_soc, fk_user)";
2514  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2515 
2516  $resql = $this->db->query($sql);
2517  if (!$resql) {
2518  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2519  $error++;
2520  }
2521  }
2522 
2523  if (!$error) {
2524  $this->context = array('commercial_modified' => $commid);
2525 
2526  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2527  if ($result < 0) {
2528  $error++;
2529  }
2530  }
2531 
2532  if (!$error) {
2533  $this->db->commit();
2534  return 1;
2535  } else {
2536  $this->db->rollback();
2537  return -1;
2538  }
2539  }
2540 
2541  return 0;
2542  }
2543 
2544  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2552  public function del_commercial(User $user, $commid)
2553  {
2554  // phpcs:enable
2555  $error = 0;
2556  $this->context = array('commercial_modified'=>$commid);
2557 
2558  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2559  if ($result < 0) {
2560  $error++;
2561  }
2562 
2563  if ($this->id > 0 && $commid > 0) {
2564  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2565  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2566 
2567  if (!$this->db->query($sql)) {
2568  dol_syslog(get_class($this)."::del_commercial Erreur");
2569  }
2570  }
2571  }
2572 
2573 
2586  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2587  {
2588  global $conf, $langs, $hookmanager;
2589 
2590  if (!empty($conf->dol_no_mouse_hover)) {
2591  $notooltip = 1; // Force disable tooltips
2592  }
2593 
2594  $name = $this->name ? $this->name : $this->nom;
2595 
2596  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2597  if (empty($option) && $this->client > 0) {
2598  $option = 'customer';
2599  }
2600  if (empty($option) && $this->fournisseur > 0) {
2601  $option = 'supplier';
2602  }
2603  }
2604 
2605  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2606  $code = '';
2607  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2608  $code = $this->code_client.' - ';
2609  }
2610 
2611  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2612  $code .= $this->code_fournisseur.' - ';
2613  }
2614 
2615  if ($code) {
2616  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2617  $name = $code.' '.$name;
2618  } else {
2619  $name = $code;
2620  }
2621  }
2622  }
2623 
2624  if (!empty($this->name_alias) && empty($noaliasinname)) {
2625  $name .= ' ('.$this->name_alias.')';
2626  }
2627 
2628  $result = ''; $label = ''; $label2 = '';
2629  $linkstart = ''; $linkend = '';
2630 
2631  if (!empty($this->logo) && class_exists('Form')) {
2632  $label .= '<div class="photointooltip floatright">';
2633  $label .= Form::showphoto('societe', $this, 0, 40, 0, 'photoref', '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.
2634  $label .= '</div>';
2635  //$label .= '<div style="clear: both;"></div>';
2636  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2637  /*$label.= '<div class="photointooltip">';
2638  $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.
2639  $label.= '</div><div style="clear: both;"></div>';*/
2640  }
2641 
2642  $label .= '<div class="centpercent">';
2643 
2644  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2645  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2646  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2647  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2648  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2649  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2650  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2651  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2652  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2653  } elseif ($option == 'agenda') {
2654  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2655  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2656  } elseif ($option == 'project') {
2657  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2658  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2659  } elseif ($option == 'margin') {
2660  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2661  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2662  } elseif ($option == 'contact') {
2663  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2664  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2665  } elseif ($option == 'ban') {
2666  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2667  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2668  }
2669 
2670  // By default
2671  if (empty($linkstart)) {
2672  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2673  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2674  }
2675  if (isset($this->status)) {
2676  $label .= ' '.$this->getLibStatut(5);
2677  }
2678  if (isset($this->client) && isset($this->fournisseur)) {
2679  $label .= ' &nbsp; ';
2680  $label .= $this->getTypeUrl(1);
2681  }
2682 
2683  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag($this->name);
2684  if (!empty($this->name_alias)) {
2685  $label .= ' ('.dol_escape_htmltag($this->name_alias).')';
2686  }
2687 
2688  if ($this->email) {
2689  $label .= '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2690  }
2691  if (!empty($this->phone) || !empty($this->fax)) {
2692  $phonelist = array();
2693  if ($this->phone) {
2694  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2695  }
2696  if ($this->fax) {
2697  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2698  }
2699  $label .= '<br>'.implode('&nbsp;', $phonelist);
2700  }
2701 
2702  if (!empty($this->address)) {
2703  $label2 .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2704  } elseif (!empty($this->country_code)) {
2705  $label2 .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2706  }
2707  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2708  $label2 .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2709  }
2710 
2711  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2712  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2713  $label2 .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2714  }
2715  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2716  $label2 .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2717  }
2718  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2719  $label2 .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2720  }
2721  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2722  $label2 .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2723  }
2724  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2725  $label2 .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2726  }
2727  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2728  $label2 .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2729  }
2730  }
2731  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2732  $label2 .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2733  }
2734  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2735  $label2 .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2736  }
2737  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2738  $label2 .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2739  }
2740  if (isModEnabled('accounting') && $this->fournisseur) {
2741  $label2 .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2742  }
2743  $label .= ($label2 ? '<br>'.$label2 : '').'</div>';
2744 
2745  // Add type of canvas
2746  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2747  // Add param to save lastsearch_values or not
2748  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2749  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2750  $add_save_lastsearch_values = 1;
2751  }
2752  if ($add_save_lastsearch_values) {
2753  $linkstart .= '&save_lastsearch_values=1';
2754  }
2755  $linkstart .= '"';
2756 
2757  $linkclose = '';
2758  if (empty($notooltip)) {
2759  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2760  $label = $langs->trans("ShowCompany");
2761  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2762  }
2763  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2764  $linkclose .= ' class="classfortooltip refurl"';
2765  $target_value = array('_self', '_blank', '_parent', '_top');
2766  if (in_array($target, $target_value)) {
2767  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2768  }
2769  }
2770  $linkstart .= $linkclose.'>';
2771  $linkend = '</a>';
2772 
2773  global $user;
2774  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2775  $linkstart = '';
2776  $linkend = '';
2777  }
2778 
2779  $result .= $linkstart;
2780  if ($withpicto) {
2781  $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);
2782  }
2783  if ($withpicto != 2) {
2784  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2785  }
2786  $result .= $linkend;
2787 
2788  global $action;
2789  $hookmanager->initHooks(array('thirdpartydao'));
2790  $parameters = array(
2791  'id'=>$this->id,
2792  'getnomurl' => &$result,
2793  'withpicto '=> $withpicto,
2794  'option'=> $option,
2795  'maxlen'=> $maxlen,
2796  'notooltip'=> $notooltip,
2797  'save_lastsearch_value'=> $save_lastsearch_value
2798  );
2799  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2800  if ($reshook > 0) {
2801  $result = $hookmanager->resPrint;
2802  } else {
2803  $result .= $hookmanager->resPrint;
2804  }
2805 
2806  return $result;
2807  }
2808 
2818  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2819  {
2820  global $conf, $langs;
2821 
2822  $s = '';
2823  if (empty($option) || preg_match('/prospect/', $option)) {
2824  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2825  $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
2826  }
2827  }
2828  if (empty($option) || preg_match('/customer/', $option)) {
2829  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2830  $s .= '<'.$tag.' class="customer-back" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
2831  }
2832  }
2833  if (empty($option) || preg_match('/supplier/', $option)) {
2834  if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2835  $s .= '<'.$tag.' class="vendor-back" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
2836  }
2837  }
2838  return $s;
2839  }
2840 
2841 
2848  public function getLibStatut($mode = 0)
2849  {
2850  return $this->LibStatut($this->status, $mode);
2851  }
2852 
2853  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2861  public function LibStatut($status, $mode = 0)
2862  {
2863  // phpcs:enable
2864  global $langs;
2865  $langs->load('companies');
2866 
2867  $statusType = 'status4';
2868  if ($status == 0) {
2869  $statusType = 'status6';
2870  }
2871 
2872  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2873  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2874  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2875  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2876  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2877  }
2878 
2879  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2880  }
2881 
2882  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2889  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2890  {
2891  // phpcs:enable
2892  global $langs;
2893 
2894  $contact_emails = $this->contact_property_array('email', 1);
2895  if ($this->email && $addthirdparty) {
2896  if (empty($this->name)) {
2897  $this->name = $this->nom;
2898  }
2899  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2900  }
2901  //var_dump($contact_emails)
2902  return $contact_emails;
2903  }
2904 
2905  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2912  {
2913  // phpcs:enable
2914  global $langs;
2915 
2916  $contact_phone = $this->contact_property_array('mobile');
2917 
2918  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2919  if (empty($this->name)) {
2920  $this->name = $this->nom;
2921  }
2922  // TODO: Tester si tel non deja present dans tableau contact
2923  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2924  }
2925  return $contact_phone;
2926  }
2927 
2928  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2936  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2937  {
2938  // phpcs:enable
2939  global $langs;
2940 
2941  $contact_property = array();
2942 
2943 
2944  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2945  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2946  $sql .= " WHERE fk_soc = ".((int) $this->id);
2947  $sql .= " ORDER BY lastname, firstname";
2948 
2949  $resql = $this->db->query($sql);
2950  if ($resql) {
2951  $nump = $this->db->num_rows($resql);
2952  if ($nump) {
2953  $sepa = "("; $sepb = ")";
2954  if ($mode == 'email') {
2955  //$sepa="&lt;"; $sepb="&gt;";
2956  $sepa = "<"; $sepb = ">";
2957  }
2958  $i = 0;
2959  while ($i < $nump) {
2960  $obj = $this->db->fetch_object($resql);
2961  if ($mode == 'email') {
2962  $property = $obj->email;
2963  } elseif ($mode == 'mobile') {
2964  $property = $obj->phone_mobile;
2965  } else {
2966  $property = $obj->$mode;
2967  }
2968 
2969  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2970  if ($obj->status == 1 || empty($hidedisabled)) {
2971  if (empty($property)) {
2972  if ($mode == 'email') {
2973  $property = $langs->transnoentitiesnoconv("NoEMail");
2974  } elseif ($mode == 'mobile') {
2975  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2976  }
2977  }
2978 
2979  if (!empty($obj->poste)) {
2980  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2981  } else {
2982  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2983  }
2984  }
2985  $i++;
2986  }
2987  }
2988  } else {
2989  dol_print_error($this->db);
2990  }
2991  return $contact_property;
2992  }
2993 
2994 
2995  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3001  public function contact_array()
3002  {
3003  // phpcs:enable
3004  $contacts = array();
3005 
3006  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3007  $resql = $this->db->query($sql);
3008  if ($resql) {
3009  $nump = $this->db->num_rows($resql);
3010  if ($nump) {
3011  $i = 0;
3012  while ($i < $nump) {
3013  $obj = $this->db->fetch_object($resql);
3014  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3015  $i++;
3016  }
3017  }
3018  } else {
3019  dol_print_error($this->db);
3020  }
3021  return $contacts;
3022  }
3023 
3024  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3030  public function contact_array_objects()
3031  {
3032  // phpcs:enable
3033  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3034  $contacts = array();
3035 
3036  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3037  $resql = $this->db->query($sql);
3038  if ($resql) {
3039  $nump = $this->db->num_rows($resql);
3040  if ($nump) {
3041  $i = 0;
3042  while ($i < $nump) {
3043  $obj = $this->db->fetch_object($resql);
3044  $contact = new Contact($this->db);
3045  $contact->fetch($obj->rowid);
3046  $contacts[] = $contact;
3047  $i++;
3048  }
3049  }
3050  } else {
3051  dol_print_error($this->db);
3052  }
3053  return $contacts;
3054  }
3055 
3056  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3064  public function contact_get_property($rowid, $mode)
3065  {
3066  // phpcs:enable
3067  $contact_property = '';
3068 
3069  if (empty($rowid)) {
3070  return '';
3071  }
3072 
3073  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3074  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3075  $sql .= " WHERE rowid = ".((int) $rowid);
3076 
3077  $resql = $this->db->query($sql);
3078  if ($resql) {
3079  $nump = $this->db->num_rows($resql);
3080 
3081  if ($nump) {
3082  $obj = $this->db->fetch_object($resql);
3083 
3084  if ($mode == 'email') {
3085  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3086  } elseif ($mode == 'mobile') {
3087  $contact_property = $obj->phone_mobile;
3088  }
3089  }
3090  return $contact_property;
3091  } else {
3092  dol_print_error($this->db);
3093  }
3094  }
3095 
3096 
3097  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3104  public function display_rib($mode = 'label')
3105  {
3106  // phpcs:enable
3107  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3108 
3109  $bac = new CompanyBankAccount($this->db);
3110  $bac->fetch(0, $this->id);
3111 
3112  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3113  if ($mode == 'label') {
3114  return $bac->getRibLabel(true);
3115  } elseif ($mode == 'rum') {
3116  if (empty($bac->rum)) {
3117  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3118  $prelevement = new BonPrelevement($this->db);
3119  $bac->fetch_thirdparty();
3120  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3121  }
3122  return $bac->rum;
3123  } elseif ($mode == 'format') {
3124  return $bac->frstrecur;
3125  } else {
3126  return 'BadParameterToFunctionDisplayRib';
3127  }
3128  } else {
3129  return '';
3130  }
3131  }
3132 
3133  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3139  public function get_all_rib()
3140  {
3141  // phpcs:enable
3142  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3143  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3144  $result = $this->db->query($sql);
3145  if (!$result) {
3146  $this->error++;
3147  $this->errors[] = $this->db->lasterror;
3148  return 0;
3149  } else {
3150  $num_rows = $this->db->num_rows($result);
3151  $rib_array = array();
3152  if ($num_rows) {
3153  while ($obj = $this->db->fetch_object($result)) {
3154  $rib = new CompanyBankAccount($this->db);
3155  $rib->fetch($obj->rowid);
3156  $rib_array[] = $rib;
3157  }
3158  }
3159  return $rib_array;
3160  }
3161  }
3162 
3163  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3172  public function get_codeclient($objsoc = 0, $type = 0)
3173  {
3174  // phpcs:enable
3175  global $conf;
3176  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3177  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3178 
3179  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3180  foreach ($dirsociete as $dirroot) {
3181  $res = dol_include_once($dirroot.$module.'.php');
3182  if ($res) {
3183  break;
3184  }
3185  }
3186  $mod = new $module();
3187 
3188  $this->code_client = $mod->getNextValue($objsoc, $type);
3189  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3190 
3191  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3192  }
3193  }
3194 
3195  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3204  public function get_codefournisseur($objsoc = 0, $type = 1)
3205  {
3206  // phpcs:enable
3207  global $conf;
3208  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3209  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3210 
3211  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3212  foreach ($dirsociete as $dirroot) {
3213  $res = dol_include_once($dirroot.$module.'.php');
3214  if ($res) {
3215  break;
3216  }
3217  }
3218  $mod = new $module();
3219 
3220  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3221 
3222  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3223  }
3224  }
3225 
3226  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3233  public function codeclient_modifiable()
3234  {
3235  // phpcs:enable
3236  global $conf;
3237  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3238  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3239 
3240  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3241  foreach ($dirsociete as $dirroot) {
3242  $res = dol_include_once($dirroot.$module.'.php');
3243  if ($res) {
3244  break;
3245  }
3246  }
3247 
3248  $mod = new $module();
3249 
3250  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3251  if ($mod->code_modifiable_null && !$this->code_client) {
3252  return 1;
3253  }
3254  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3255  return 1;
3256  }
3257  if ($mod->code_modifiable) {
3258  return 1; // A mettre en dernier
3259  }
3260  return 0;
3261  } else {
3262  return 0;
3263  }
3264  }
3265 
3266 
3267  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3273  public function codefournisseur_modifiable()
3274  {
3275  // phpcs:enable
3276  global $conf;
3277  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3278  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3279 
3280  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3281  foreach ($dirsociete as $dirroot) {
3282  $res = dol_include_once($dirroot.$module.'.php');
3283  if ($res) {
3284  break;
3285  }
3286  }
3287 
3288  $mod = new $module();
3289 
3290  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3291  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3292  return 1;
3293  }
3294  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3295  return 1;
3296  }
3297  if ($mod->code_modifiable) {
3298  return 1; // A mettre en dernier
3299  }
3300  return 0;
3301  } else {
3302  return 0;
3303  }
3304  }
3305 
3306 
3307  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3319  public function check_codeclient()
3320  {
3321  // phpcs:enable
3322  global $conf;
3323  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3324  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3325 
3326  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3327  foreach ($dirsociete as $dirroot) {
3328  $res = dol_include_once($dirroot.$module.'.php');
3329  if ($res) {
3330  break;
3331  }
3332  }
3333 
3334  $mod = new $module();
3335 
3336  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3337  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3338  if ($result) { // If error
3339  $this->error = $mod->error;
3340  $this->errors = $mod->errors;
3341  }
3342  return $result;
3343  } else {
3344  return 0;
3345  }
3346  }
3347 
3348  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3360  public function check_codefournisseur()
3361  {
3362  // phpcs:enable
3363  global $conf;
3364  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3365  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3366 
3367  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3368  foreach ($dirsociete as $dirroot) {
3369  $res = dol_include_once($dirroot.$module.'.php');
3370  if ($res) {
3371  break;
3372  }
3373  }
3374 
3375  $mod = new $module();
3376 
3377  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3378  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3379  if ($result) { // If error
3380  $this->error = $mod->error;
3381  $this->errors = $mod->errors;
3382  }
3383  return $result;
3384  } else {
3385  return 0;
3386  }
3387  }
3388 
3389  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3398  public function get_codecompta($type)
3399  {
3400  // phpcs:enable
3401  global $conf;
3402 
3403  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3404  $res = false;
3405  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3406  foreach ($dirsociete as $dirroot) {
3407  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3408  if ($res) {
3409  break;
3410  }
3411  }
3412 
3413  if ($res) {
3414  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3415  $mod = new $classname;
3416 
3417  // Set code count in $mod->code
3418  $result = $mod->get_code($this->db, $this, $type);
3419 
3420  if ($type == 'customer') {
3421  $this->code_compta_client = $mod->code;
3422  $this->code_compta = $this->code_compta_client; // For backward compatibility
3423  } elseif ($type == 'supplier') {
3424  $this->code_compta_fournisseur = $mod->code;
3425  }
3426 
3427  return $result;
3428  } else {
3429  $this->error = 'ErrorAccountancyCodeNotDefined';
3430  return -1;
3431  }
3432  } else {
3433  if ($type == 'customer') {
3434  $this->code_compta_client = '';
3435  $this->code_compta = '';
3436  } elseif ($type == 'supplier') {
3437  $this->code_compta_fournisseur = '';
3438  }
3439 
3440  return 0;
3441  }
3442  }
3443 
3450  public function setParent($id)
3451  {
3452  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3453 
3454  if ($this->id) {
3455  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3456  if ($id > 0) {
3457  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3458  if ($sameparent < 0) {
3459  return -1;
3460  }
3461  if ($sameparent == 1) {
3462  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3463  return -1;
3464  }
3465  }
3466 
3467  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3468 
3469  $resql = $this->db->query($sql);
3470  if ($resql) {
3471  $this->parent = $id;
3472  return 1;
3473  } else {
3474  return -1;
3475  }
3476  } else {
3477  return -1;
3478  }
3479  }
3480 
3489  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3490  {
3491  if ($counter > 100) {
3492  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3493  }
3494 
3495  $sql = 'SELECT s.parent';
3496  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3497  $sql .= ' WHERE rowid = '.((int) $idparent);
3498  $resql = $this->db->query($sql);
3499  if ($resql) {
3500  $obj = $this->db->fetch_object($resql);
3501 
3502  if ($obj->parent == '') {
3503  return 0;
3504  } elseif ($obj->parent == $idchild) {
3505  return 1;
3506  } else {
3507  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3508  }
3509  return $sameparent;
3510  } else {
3511  return -1;
3512  }
3513  }
3514 
3522  public function getParentsForCompany($company_id, $parents = [])
3523  {
3524  global $langs;
3525 
3526  if ($company_id > 0) {
3527  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3528  $resql = $this->db->query($sql);
3529  if ($resql) {
3530  if ($obj = $this->db->fetch_object($resql)) {
3531  $parent = $obj->parent;
3532  if ($parent > 0 && !in_array($parent, $parents)) {
3533  $parents[] = $parent;
3534  return $this->getParentsForCompany($parent, $parents);
3535  } else {
3536  return $parents;
3537  }
3538  }
3539  $this->db->free($resql);
3540  } else {
3541  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3542  }
3543  }
3544  }
3545 
3546  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3553  public function id_prof_verifiable($idprof)
3554  {
3555  // phpcs:enable
3556  global $conf;
3557 
3558  switch ($idprof) {
3559  case 1:
3560  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3561  break;
3562  case 2:
3563  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3564  break;
3565  case 3:
3566  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3567  break;
3568  case 4:
3569  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3570  break;
3571  case 5:
3572  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3573  break;
3574  case 6:
3575  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3576  break;
3577  default:
3578  $ret = false;
3579  }
3580 
3581  return $ret;
3582  }
3583 
3584  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3593  public function id_prof_exists($idprof, $value, $socid = 0)
3594  {
3595  // phpcs:enable
3596  $field = $idprof;
3597 
3598  switch ($idprof) { // For backward compatibility
3599  case '1':
3600  case 'idprof1':
3601  $field = "siren";
3602  break;
3603  case '2':
3604  case 'idprof2':
3605  $field = "siret";
3606  break;
3607  case '3':
3608  case 'idprof3':
3609  $field = "ape";
3610  break;
3611  case '4':
3612  case 'idprof4':
3613  $field = "idprof4";
3614  break;
3615  case '5':
3616  $field = "idprof5";
3617  break;
3618  case '6':
3619  $field = "idprof6";
3620  break;
3621  }
3622 
3623  //Verify duplicate entries
3624  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3625  if ($socid) {
3626  $sql .= " AND rowid <> ".$socid;
3627  }
3628  $resql = $this->db->query($sql);
3629  if ($resql) {
3630  $obj = $this->db->fetch_object($resql);
3631  $count = $obj->nb;
3632  } else {
3633  $count = 0;
3634  print $this->db->error();
3635  }
3636  $this->db->free($resql);
3637 
3638  if ($count > 0) {
3639  return true;
3640  } else {
3641  return false;
3642  }
3643  }
3644 
3645  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3654  public function id_prof_check($idprof, $soc)
3655  {
3656  // phpcs:enable
3657  global $conf;
3658 
3659  $ok = 1;
3660 
3661  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3662  return 1;
3663  }
3664 
3665  // Check SIREN if country FR
3666  if ($idprof == 1 && $soc->country_code == 'FR') {
3667  $chaine = trim($this->idprof1);
3668  $chaine = preg_replace('/(\s)/', '', $chaine);
3669 
3670  if (!is_numeric($chaine)) {
3671  return -1;
3672  }
3673  if (dol_strlen($chaine) != 9) {
3674  return -1;
3675  }
3676 
3677  // on prend chaque chiffre un par un
3678  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3679  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3680  // on ajoute cette valeur à la somme totale
3681  $sum = 0;
3682  for ($index = 0; $index < 9; $index++) {
3683  $number = (int) $chaine[$index];
3684  if (($index % 2) != 0) {
3685  if (($number *= 2) > 9) {
3686  $number -= 9;
3687  }
3688  }
3689  $sum += $number;
3690  }
3691 
3692  // le numéro est valide si la somme des chiffres est multiple de 10
3693  if (($sum % 10) != 0) {
3694  return -1;
3695  }
3696  }
3697 
3698  // Verifie SIRET si pays FR
3699  if ($idprof == 2 && $soc->country_code == 'FR') {
3700  $chaine = trim($this->idprof2);
3701  $chaine = preg_replace('/(\s)/', '', $chaine);
3702 
3703  if (!is_numeric($chaine)) {
3704  return -1;
3705  }
3706  if (dol_strlen($chaine) != 14) {
3707  return -1;
3708  }
3709 
3710  // on prend chaque chiffre un par un
3711  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3712  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3713  // on ajoute cette valeur à la somme totale
3714  $sum = 0;
3715  for ($index = 0; $index < 14; $index++) {
3716  $number = (int) $chaine[$index];
3717  if (($index % 2) == 0) {
3718  if (($number *= 2) > 9) {
3719  $number -= 9;
3720  }
3721  }
3722  $sum += $number;
3723  }
3724 
3725  // le numéro est valide si la somme des chiffres est multiple de 10
3726  if (($sum % 10) != 0) {
3727  return -1;
3728  }
3729  }
3730 
3731  //Verify CIF/NIF/NIE if pays ES
3732  //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
3733  if ($idprof == 1 && $soc->country_code == 'ES') {
3734  $string = trim($this->idprof1);
3735  $string = preg_replace('/(\s)/', '', $string);
3736  $string = strtoupper($string);
3737 
3738  //Check format
3739  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)) {
3740  return 0;
3741  }
3742 
3743  $num = array();
3744  for ($i = 0; $i < 9; $i++) {
3745  $num[$i] = substr($string, $i, 1);
3746  }
3747 
3748  //Check NIF
3749  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3750  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3751  return 1;
3752  } else {
3753  return -1;
3754  }
3755  }
3756 
3757  //algorithm checking type code CIF
3758  $sum = $num[2] + $num[4] + $num[6];
3759  for ($i = 1; $i < 8; $i += 2) {
3760  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3761  }
3762  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3763 
3764  //Chek special NIF
3765  if (preg_match('/^[KLM]{1}/', $string)) {
3766  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3767  return 1;
3768  } else {
3769  return -1;
3770  }
3771  }
3772 
3773  //Check CIF
3774  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3775  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3776  return 2;
3777  } else {
3778  return -2;
3779  }
3780  }
3781 
3782  //Check NIE T
3783  if (preg_match('/^[T]{1}/', $string)) {
3784  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3785  return 3;
3786  } else {
3787  return -3;
3788  }
3789  }
3790 
3791  //Check NIE XYZ
3792  if (preg_match('/^[XYZ]{1}/', $string)) {
3793  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3794  return 3;
3795  } else {
3796  return -3;
3797  }
3798  }
3799 
3800  //Can not be verified
3801  return -4;
3802  }
3803 
3804  //Verify NIF if country is PT
3805  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3806  if ($idprof == 1 && $soc->country_code == 'PT') {
3807  $string = trim($this->idprof1);
3808  $string = preg_replace('/(\s)/', '', $string);
3809 
3810  //Check NIF
3811  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3812  return 1;
3813  } else {
3814  return -1;
3815  }
3816  }
3817 
3818  //Verify NIF if country is DZ
3819  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3820  if ($idprof == 1 && $soc->country_code == 'DZ') {
3821  $string = trim($this->idprof1);
3822  $string = preg_replace('/(\s)/', '', $string);
3823 
3824  //Check NIF
3825  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3826  return 1;
3827  } else {
3828  return -1;
3829  }
3830  }
3831 
3832  return $ok;
3833  }
3834 
3835  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3844  public function id_prof_url($idprof, $thirdparty)
3845  {
3846  // phpcs:enable
3847  global $conf, $langs, $hookmanager;
3848 
3849  $url = '';
3850  $action = '';
3851 
3852  $hookmanager->initHooks(array('idprofurl'));
3853  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3854  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3855  if (empty($reshook)) {
3856  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3857  return '';
3858  }
3859 
3860  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3861  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3862  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3863  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3864  }
3865  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3866  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3867  }
3868  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3869  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3870  }
3871  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3872  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3873  }
3874  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3875  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3876  }
3877  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3878  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3879  }
3880 
3881  if ($url) {
3882  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3883  }
3884  } else {
3885  return $hookmanager->resPrint;
3886  }
3887 
3888  return '';
3889  }
3890 
3891  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3897  public function has_projects()
3898  {
3899  // phpcs:enable
3900  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3901  $resql = $this->db->query($sql);
3902  if ($resql) {
3903  $obj = $this->db->fetch_object($resql);
3904  $count = $obj->numproj;
3905  } else {
3906  $count = 0;
3907  print $this->db->error();
3908  }
3909  $this->db->free($resql);
3910  return ($count > 0);
3911  }
3912 
3913 
3920  public function info($id)
3921  {
3922  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
3923  $sql .= " fk_user_creat, fk_user_modif";
3924  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3925  $sql .= " WHERE s.rowid = ".((int) $id);
3926 
3927  $result = $this->db->query($sql);
3928  if ($result) {
3929  if ($this->db->num_rows($result)) {
3930  $obj = $this->db->fetch_object($result);
3931 
3932  $this->id = $obj->rowid;
3933 
3934  $this->user_creation_id = $obj->fk_user_creat;
3935  $this->user_modification_id = $obj->fk_user_modif;
3936  $this->date_creation = $this->db->jdate($obj->datec);
3937  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
3938 
3939  $this->ref = $obj->name;
3940  }
3941 
3942  $this->db->free($result);
3943  } else {
3944  dol_print_error($this->db);
3945  }
3946  }
3947 
3953  public function isACompany()
3954  {
3955  global $conf;
3956 
3957  // Define if third party is treated as company (or not) when nature is unknown
3958  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3959  if (!empty($this->tva_intra)) {
3960  $isacompany = 1;
3961  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3962  $isacompany = 1;
3963  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3964  // TODO Add a field is_a_company into dictionary
3965  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3966  $isacompany = 0;
3967  } else {
3968  $isacompany = 1;
3969  }
3970  }
3971 
3972  return $isacompany;
3973  }
3974 
3980  public function isInEEC()
3981  {
3982  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3983  return isInEEC($this);
3984  }
3985 
3986  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3992  public function LoadSupplierCateg()
3993  {
3994  // phpcs:enable
3995  $this->SupplierCategories = array();
3996  $sql = "SELECT rowid, label";
3997  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
3998  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3999 
4000  $resql = $this->db->query($sql);
4001  if ($resql) {
4002  while ($obj = $this->db->fetch_object($resql)) {
4003  $this->SupplierCategories[$obj->rowid] = $obj->label;
4004  }
4005  return 0;
4006  } else {
4007  return -1;
4008  }
4009  }
4010 
4011  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4018  public function AddFournisseurInCategory($categorie_id)
4019  {
4020  // phpcs:enable
4021  if ($categorie_id > 0 && $this->id > 0) {
4022  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4023  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4024 
4025  if ($resql = $this->db->query($sql)) {
4026  return 0;
4027  }
4028  } else {
4029  return 0;
4030  }
4031  return -1;
4032  }
4033 
4039  public function getNbOfEMailings()
4040  {
4041  $sql = "SELECT count(mc.email) as nb";
4042  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4043  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4044  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4045 
4046  $resql = $this->db->query($sql);
4047  if ($resql) {
4048  $obj = $this->db->fetch_object($resql);
4049  $nb = $obj->nb;
4050 
4051  $this->db->free($resql);
4052  return $nb;
4053  } else {
4054  $this->error = $this->db->error();
4055  return -1;
4056  }
4057  }
4058 
4065  public function setNoEmail($no_email)
4066  {
4067  $error = 0;
4068 
4069  // Update mass emailing flag into table mailing_unsubscribe
4070  if ($this->email) {
4071  $this->db->begin();
4072 
4073  if ($no_email) {
4074  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'";
4075  $resql = $this->db->query($sql);
4076  if ($resql) {
4077  $obj = $this->db->fetch_object($resql);
4078  $noemail = $obj->nb;
4079  if (empty($noemail)) {
4080  $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".getEntity('mailing', 0).", '".$this->db->idate(dol_now())."')";
4081  $resql = $this->db->query($sql);
4082  if (!$resql) {
4083  $error++;
4084  $this->error = $this->db->lasterror();
4085  $this->errors[] = $this->error;
4086  }
4087  }
4088  } else {
4089  $error++;
4090  $this->error = $this->db->lasterror();
4091  $this->errors[] = $this->error;
4092  }
4093  } else {
4094  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4095  $resql = $this->db->query($sql);
4096  if (!$resql) {
4097  $error++;
4098  $this->error = $this->db->lasterror();
4099  $this->errors[] = $this->error;
4100  }
4101  }
4102 
4103  if (empty($error)) {
4104  $this->no_email = $no_email;
4105  $this->db->commit();
4106  return 1;
4107  } else {
4108  $this->db->rollback();
4109  return $error * -1;
4110  }
4111  }
4112 
4113  return 0;
4114  }
4115 
4122  public function getNoEmail()
4123  {
4124  if ($this->email) {
4125  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4126  $resql = $this->db->query($sql);
4127  if ($resql) {
4128  $obj = $this->db->fetch_object($resql);
4129  $this->no_email = $obj->nb;
4130  return 1;
4131  } else {
4132  $this->error = $this->db->lasterror();
4133  $this->errors[] = $this->error;
4134  return -1;
4135  }
4136  }
4137  return 0;
4138  }
4139 
4140  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4150  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4151  {
4152  // phpcs:enable
4153  global $conf, $user, $langs;
4154 
4155  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4156  $fullname = $member->getFullName($langs);
4157 
4158  if ($member->morphy == 'mor') {
4159  if (empty($socname)) {
4160  $socname = $member->company? $member->company : $member->societe;
4161  }
4162  if (!empty($fullname) && empty($socalias)) {
4163  $socalias = $fullname;
4164  }
4165  } elseif (empty($socname) && $member->morphy == 'phy') {
4166  if (empty($socname)) {
4167  $socname = $fullname;
4168  }
4169  if (!empty($member->company) && empty($socalias)) {
4170  $socalias = $member->company;
4171  }
4172  }
4173 
4174  $name = $socname;
4175  $alias = $socalias ? $socalias : '';
4176 
4177  // Positionne parametres
4178  $this->nom = $name; // TODO deprecated
4179  $this->name = $name;
4180  $this->name_alias = $alias;
4181  $this->address = $member->address;
4182  $this->zip = $member->zip;
4183  $this->town = $member->town;
4184  $this->country_code = $member->country_code;
4185  $this->country_id = $member->country_id;
4186  $this->phone = $member->phone; // Prof phone
4187  $this->email = $member->email;
4188  $this->socialnetworks = $member->socialnetworks;
4189  $this->entity = $member->entity;
4190 
4191  $this->client = 1; // A member is a customer by default
4192  $this->code_client = ($customercode ? $customercode : -1);
4193  $this->code_fournisseur = -1;
4194  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4195  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4196 
4197  $this->db->begin();
4198 
4199  // Cree et positionne $this->id
4200  $result = $this->create($user);
4201 
4202  if ($result >= 0) {
4203  // Auto-create contact on thirdparty creation
4204  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4205  // Fill fields needed by contact
4206  $this->name_bis = $member->lastname;
4207  $this->firstname = $member->firstname;
4208  $this->civility_id = $member->civility_id;
4209 
4210  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4211  $result = $this->create_individual($user);
4212 
4213  if ($result < 0) {
4214  setEventMessages($this->error, $this->errors, 'errors');
4215  $this->db->rollback();
4216  return -1;
4217  }
4218  }
4219 
4220  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4221  $sql .= " SET fk_soc = ".((int) $this->id);
4222  $sql .= " WHERE rowid = ".((int) $member->id);
4223 
4224  $resql = $this->db->query($sql);
4225  if ($resql) {
4226  $this->db->commit();
4227  return $this->id;
4228  } else {
4229  $this->error = $this->db->error();
4230 
4231  $this->db->rollback();
4232  return -1;
4233  }
4234  } else {
4235  // $this->error deja positionne
4236  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4237 
4238  $this->db->rollback();
4239  return $result;
4240  }
4241  }
4242 
4249  public function setMysoc(Conf $conf)
4250  {
4251  global $langs;
4252 
4253  $this->id = 0;
4254  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
4255  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
4256  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
4257  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
4258  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
4259  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
4260 
4261  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
4262 
4263  $this->nom = $this->name; // deprecated
4264 
4265  // We define country_id, country_code and country
4266  $country_id = $country_code = $country_label = '';
4267  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4268  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4269  $country_id = $tmp[0];
4270  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4271  $country_code = $tmp[1];
4272  $country_label = $tmp[2];
4273  } else // For backward compatibility
4274  {
4275  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4276  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4277  $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
4278  $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
4279  }
4280  }
4281  $this->country_id = $country_id;
4282  $this->country_code = $country_code;
4283  $this->country = $country_label;
4284  if (is_object($langs)) {
4285  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4286  }
4287 
4288  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4289  // We define state_id, state_code and state
4290  $state_id = 0; $state_code = $state_label = '';
4291  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4292  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4293  $state_id = $tmp[0];
4294  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4295  $state_code = $tmp[1];
4296  $state_label = $tmp[2];
4297  } else { // For backward compatibility
4298  dol_syslog("Your setup of State has an old syntax (entity=".$conf->entity."). Go in Home - Setup - Organization then Save should remove this error.", LOG_ERR);
4299  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4300  $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
4301  $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
4302  }
4303  }
4304  $this->state_id = $state_id;
4305  $this->state_code = $state_code;
4306  $this->state = $state_label;
4307  if (is_object($langs)) {
4308  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4309  }
4310 
4311  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
4312  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
4313  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
4314 
4315  // Social networks
4316  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
4317  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
4318  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
4319  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
4320  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
4321  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
4322  $this->socialnetworks = array();
4323  if (!empty($this->facebook_url)) {
4324  $this->socialnetworks['facebook'] = $this->facebook_url;
4325  }
4326  if (!empty($this->twitter_url)) {
4327  $this->socialnetworks['twitter'] = $this->twitter_url;
4328  }
4329  if (!empty($this->linkedin_url)) {
4330  $this->socialnetworks['linkedin'] = $this->linkedin_url;
4331  }
4332  if (!empty($this->instagram_url)) {
4333  $this->socialnetworks['instagram'] = $this->instagram_url;
4334  }
4335  if (!empty($this->youtube_url)) {
4336  $this->socialnetworks['youtube'] = $this->youtube_url;
4337  }
4338  if (!empty($this->github_url)) {
4339  $this->socialnetworks['github'] = $this->github_url;
4340  }
4341 
4342  // Id prof generiques
4343  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
4344  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
4345  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
4346  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
4347  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
4348  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
4349  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
4350  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
4351  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
4352  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
4353  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
4354  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
4355  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
4356  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
4357  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
4358  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
4359  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
4360  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
4361 
4362  // Define if company use vat or not
4363  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4364 
4365  // Define if company use local taxes
4366  $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);
4367  $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);
4368  }
4369 
4377  public function initAsSpecimen()
4378  {
4379  $now = dol_now();
4380 
4381  // Initialize parameters
4382  $this->id = 0;
4383  $this->entity = 1;
4384  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4385  $this->nom = $this->name; // For backward compatibility
4386  $this->ref_ext = 'Ref ext';
4387  $this->specimen = 1;
4388  $this->address = '21 jump street';
4389  $this->zip = '99999';
4390  $this->town = 'MyTown';
4391  $this->state_id = 1;
4392  $this->state_code = 'AA';
4393  $this->state = 'MyState';
4394  $this->country_id = 1;
4395  $this->country_code = 'FR';
4396  $this->email = 'specimen@specimen.com';
4397  $this->socialnetworks = array(
4398  'skype' => 'tom.hanson',
4399  'twitter' => 'tomhanson',
4400  'facebook' => 'tomhanson',
4401  'linkedin' => 'tomhanson',
4402  );
4403  $this->url = 'http://www.specimen.com';
4404 
4405  $this->phone = '0909090901';
4406  $this->fax = '0909090909';
4407 
4408  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4409  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4410  $this->capital = 10000;
4411  $this->client = 1;
4412  $this->prospect = 1;
4413  $this->fournisseur = 1;
4414  $this->tva_assuj = 1;
4415  $this->tva_intra = 'EU1234567';
4416  $this->note_public = 'This is a comment (public)';
4417  $this->note_private = 'This is a comment (private)';
4418 
4419  $this->idprof1 = 'idprof1';
4420  $this->idprof2 = 'idprof2';
4421  $this->idprof3 = 'idprof3';
4422  $this->idprof4 = 'idprof4';
4423  $this->idprof5 = 'idprof5';
4424  $this->idprof6 = 'idprof6';
4425  return 1;
4426  }
4427 
4434  public function useLocalTax($localTaxNum = 0)
4435  {
4436  $sql = "SELECT t.localtax1, t.localtax2";
4437  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4438  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4439  $sql .= " AND t.active = 1";
4440  if (empty($localTaxNum)) {
4441  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4442  } elseif ($localTaxNum == 1) {
4443  $sql .= " AND t.localtax1_type <> '0'";
4444  } elseif ($localTaxNum == 2) {
4445  $sql .= " AND t.localtax2_type <> '0'";
4446  }
4447 
4448  $resql = $this->db->query($sql);
4449  if ($resql) {
4450  return ($this->db->num_rows($resql) > 0);
4451  } else {
4452  return false;
4453  }
4454  }
4455 
4461  public function useNPR()
4462  {
4463  $sql = "SELECT t.rowid";
4464  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4465  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4466  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4467 
4468  dol_syslog("useNPR", LOG_DEBUG);
4469  $resql = $this->db->query($sql);
4470  if ($resql) {
4471  return ($this->db->num_rows($resql) > 0);
4472  } else {
4473  return false;
4474  }
4475  }
4476 
4483  public function useRevenueStamp()
4484  {
4485  $sql = "SELECT COUNT(*) as nb";
4486  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4487  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4488  $sql .= " AND r.active = 1";
4489 
4490  dol_syslog("useRevenueStamp", LOG_DEBUG);
4491  $resql = $this->db->query($sql);
4492  if ($resql) {
4493  $obj = $this->db->fetch_object($resql);
4494  return (($obj->nb > 0) ?true:false);
4495  } else {
4496  $this->error = $this->db->lasterror();
4497  return false;
4498  }
4499  }
4500 
4506  public function getLibProspLevel()
4507  {
4508  return $this->LibProspLevel($this->fk_prospectlevel);
4509  }
4510 
4511  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4518  public function LibProspLevel($fk_prospectlevel)
4519  {
4520  // phpcs:enable
4521  global $langs;
4522 
4523  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4524  // If lib not found in language file, we get label from cache/databse
4525  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4526  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4527  }
4528  return $lib;
4529  }
4530 
4538  public function getLibProspCommStatut($mode = 0, $label = '')
4539  {
4540  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4541  }
4542 
4543  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4557  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4558  {
4559  // phpcs:enable
4560  global $langs;
4561  $langs->load('customers');
4562 
4563  if ($mode == 2) {
4564  if ($status == '-1' || $status == 'ST_NO') {
4565  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4566  } elseif ($status == '0' || $status == 'ST_NEVER') {
4567  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4568  } elseif ($status == '1' || $status == 'ST_TODO') {
4569  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4570  } elseif ($status == '2' || $status == 'ST_PEND') {
4571  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4572  } elseif ($status == '3' || $status == 'ST_DONE') {
4573  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4574  } else {
4575  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);
4576  }
4577  } elseif ($mode == 3) {
4578  if ($status == '-1' || $status == 'ST_NO') {
4579  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4580  } elseif ($status == '0' || $status == 'ST_NEVER') {
4581  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4582  } elseif ($status == '1' || $status == 'ST_TODO') {
4583  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4584  } elseif ($status == '2' || $status == 'ST_PEND') {
4585  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4586  } elseif ($status == '3' || $status == 'ST_DONE') {
4587  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4588  } else {
4589  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4590  }
4591  } elseif ($mode == 4) {
4592  if ($status == '-1' || $status == 'ST_NO') {
4593  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4594  } elseif ($status == '0' || $status == 'ST_NEVER') {
4595  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4596  } elseif ($status == '1' || $status == 'ST_TODO') {
4597  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4598  } elseif ($status == '2' || $status == 'ST_PEND') {
4599  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4600  } elseif ($status == '3' || $status == 'ST_DONE') {
4601  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4602  } else {
4603  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);
4604  }
4605  }
4606 
4607  return "Error, mode/status not found";
4608  }
4609 
4616  public function getOutstandingProposals($mode = 'customer')
4617  {
4618  $table = 'propal';
4619  if ($mode == 'supplier') {
4620  $table = 'supplier_proposal';
4621  }
4622 
4623  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4624  $sql .= " WHERE fk_soc = ".((int) $this->id);
4625  if ($mode == 'supplier') {
4626  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4627  } else {
4628  $sql .= " AND entity IN (".getEntity('propal').")";
4629  }
4630 
4631  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4632 
4633  $resql = $this->db->query($sql);
4634  if ($resql) {
4635  $outstandingOpened = 0;
4636  $outstandingTotal = 0;
4637  $outstandingTotalIncTax = 0;
4638  $arrayofref = array();
4639  while ($obj = $this->db->fetch_object($resql)) {
4640  $arrayofref[$obj->rowid] = $obj->ref;
4641  $outstandingTotal += $obj->total_ht;
4642  $outstandingTotalIncTax += $obj->total_ttc;
4643  if ($obj->status != 0) {
4644  // Not a draft
4645  $outstandingOpened += $obj->total_ttc;
4646  }
4647  }
4648  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4649  } else {
4650  return array();
4651  }
4652  }
4653 
4660  public function getOutstandingOrders($mode = 'customer')
4661  {
4662  $table = 'commande';
4663  if ($mode == 'supplier') {
4664  $table = 'commande_fournisseur';
4665  }
4666 
4667  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4668  $sql .= " WHERE fk_soc = ".((int) $this->id);
4669  if ($mode == 'supplier') {
4670  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4671  } else {
4672  $sql .= " AND entity IN (".getEntity('commande').")";
4673  }
4674 
4675  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4676  $resql = $this->db->query($sql);
4677  if ($resql) {
4678  $outstandingOpened = 0;
4679  $outstandingTotal = 0;
4680  $outstandingTotalIncTax = 0;
4681  $arrayofref = array();
4682  while ($obj = $this->db->fetch_object($resql)) {
4683  $arrayofref[$obj->rowid] = $obj->ref;
4684  $outstandingTotal += $obj->total_ht;
4685  $outstandingTotalIncTax += $obj->total_ttc;
4686  if ($obj->status != 0) {
4687  // Not a draft
4688  $outstandingOpened += $obj->total_ttc;
4689  }
4690  }
4691  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4692  } else {
4693  return array();
4694  }
4695  }
4696 
4704  public function getOutstandingBills($mode = 'customer', $late = 0)
4705  {
4706  $table = 'facture';
4707  if ($mode == 'supplier') {
4708  $table = 'facture_fourn';
4709  }
4710 
4711  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4712  $paiement = $invoice->getSommePaiement();
4713  $creditnotes=$invoice->getSumCreditNotesUsed();
4714  $deposits=$invoice->getSumDepositsUsed();
4715  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4716  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4717  */
4718  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4719  $sql .= " WHERE fk_soc = ".((int) $this->id);
4720  if (!empty($late)) {
4721  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4722  }
4723  if ($mode == 'supplier') {
4724  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4725  } else {
4726  $sql .= " AND entity IN (".getEntity('invoice').")";
4727  }
4728 
4729  dol_syslog("getOutstandingBills", LOG_DEBUG);
4730  $resql = $this->db->query($sql);
4731  if ($resql) {
4732  $outstandingOpened = 0;
4733  $outstandingTotal = 0;
4734  $outstandingTotalIncTax = 0;
4735  $arrayofref = array();
4736  $arrayofrefopened = array();
4737  if ($mode == 'supplier') {
4738  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4739  $tmpobject = new FactureFournisseur($this->db);
4740  } else {
4741  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4742  $tmpobject = new Facture($this->db);
4743  }
4744  while ($obj = $this->db->fetch_object($resql)) {
4745  $arrayofref[$obj->rowid] = $obj->ref;
4746  $tmpobject->id = $obj->rowid;
4747 
4748  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4749  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4750  ) {
4751  $outstandingTotal += $obj->total_ht;
4752  $outstandingTotalIncTax += $obj->total_ttc;
4753  }
4754 
4755  $remaintopay = 0;
4756 
4757  if ($obj->paye == 0
4758  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4759  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4760  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4761  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4762  $paiement = $tmpobject->getSommePaiement();
4763  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4764  $deposits = $tmpobject->getSumDepositsUsed();
4765 
4766  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4767  $outstandingOpened += $remaintopay;
4768  }
4769 
4770  //if credit note is converted but not used
4771  // TODO Do this also for customer ?
4772  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4773  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4774  $remaintopay -= $remainingcreditnote;
4775  $outstandingOpened -= $remainingcreditnote;
4776  }
4777 
4778  if ($remaintopay) {
4779  $arrayofrefopened[$obj->rowid] = $obj->ref;
4780  }
4781  }
4782  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4783  } else {
4784  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4785  return array();
4786  }
4787  }
4788 
4795  public function getLibCustProspStatut()
4796  {
4797  return $this->LibCustProspStatut($this->client);
4798  }
4799 
4800  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4807  public function LibCustProspStatut($status)
4808  {
4809  // phpcs:enable
4810  global $langs;
4811  $langs->load('companies');
4812 
4813  if ($status == 0) {
4814  return $langs->trans("NorProspectNorCustomer");
4815  } elseif ($status == 1) {
4816  return $langs->trans("Customer");
4817  } elseif ($status == 2) {
4818  return $langs->trans("Prospect");
4819  } elseif ($status == 3) {
4820  return $langs->trans("ProspectCustomer");
4821  }
4822  }
4823 
4824 
4836  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4837  {
4838  global $conf, $user, $langs;
4839 
4840  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4841  $modelpath = "core/modules/bank/doc/";
4842 
4843  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4844  $companybankaccount = new CompanyBankAccount($this->db);
4845  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4846  if (!$result) {
4847  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4848  }
4849  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4850  } else {
4851  // Positionne le modele sur le nom du modele a utiliser
4852  if (!dol_strlen($modele)) {
4853  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4854  $modele = $conf->global->COMPANY_ADDON_PDF;
4855  } else {
4856  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4857  return 0;
4858  }
4859  }
4860 
4861  if (!isset($this->bank_account)) {
4862  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4863  $bac = new CompanyBankAccount($this->db);
4864  $result = $bac->fetch(0, $this->id);
4865  if ($result > 0) {
4866  $this->bank_account = $bac;
4867  } else {
4868  $this->bank_account = '';
4869  }
4870  }
4871 
4872  $modelpath = "core/modules/societe/doc/";
4873 
4874  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4875  }
4876 
4877  return $result;
4878  }
4879 
4880 
4892  public function setCategories($categories, $type_categ)
4893  {
4894  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4895 
4896  // Decode type
4897  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4898  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4899  return -1;
4900  }
4901 
4902  return parent::setCategoriesCommon($categories, $type_categ);
4903  }
4904 
4912  public function setSalesRep($salesrep, $onlyAdd = false)
4913  {
4914  global $user;
4915 
4916  // Handle single user
4917  if (!is_array($salesrep)) {
4918  $salesrep = array($salesrep);
4919  }
4920 
4921  $to_del = array(); // Nothing to delete
4922  $to_add = $salesrep;
4923  if ($onlyAdd === false) {
4924  // Get current users
4925  $existing = $this->getSalesRepresentatives($user, 1);
4926 
4927  // Diff
4928  if (is_array($existing)) {
4929  $to_del = array_diff($existing, $salesrep);
4930  $to_add = array_diff($salesrep, $existing);
4931  }
4932  }
4933 
4934  $error = 0;
4935 
4936  // Process
4937  foreach ($to_del as $del) {
4938  $this->del_commercial($user, $del);
4939  }
4940  foreach ($to_add as $add) {
4941  $result = $this->add_commercial($user, $add);
4942  if ($result < 0) {
4943  $error++;
4944  break;
4945  }
4946  }
4947 
4948  return $error ? -1 : 1;
4949  }
4950 
4957  public function setThirdpartyType($typent_id)
4958  {
4959  global $user;
4960 
4961  dol_syslog(__METHOD__, LOG_DEBUG);
4962 
4963  if ($this->id) {
4964  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
4965 
4966  if ($result > 0) {
4967  $this->typent_id = $typent_id;
4968  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
4969  return 1;
4970  } else {
4971  return -1;
4972  }
4973  } else {
4974  return -1;
4975  }
4976  }
4977 
4987  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4988  {
4989  if ($origin_id == $dest_id) {
4990  dol_syslog('Error: Try to merge a thirdparty into itself');
4991  return false;
4992  }
4993 
4998  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4999  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5000  $sql .= ' SELECT fk_user ';
5001  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5002  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5003 
5004  $resql = $dbs->query($sql);
5005  while ($obj = $dbs->fetch_object($resql)) {
5006  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5007  }
5008 
5013  $tables = array(
5014  'societe_address',
5015  'societe_commerciaux',
5016  'societe_prices',
5017  'societe_remise',
5018  'societe_remise_except',
5019  'societe_rib'
5020  );
5021 
5022  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5023  }
5024 
5033  public function setAccountancyCode($type, $value)
5034  {
5035  global $user, $langs, $conf;
5036 
5037  $this->db->begin();
5038 
5039  $field = 'accountancy_code_sell';
5040  if ($type == 'buy') {
5041  $field = 'accountancy_code_buy';
5042  } elseif ($type == 'sell') {
5043  $field = 'accountancy_code_sell';
5044  } else {
5045  return -1;
5046  }
5047 
5048  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5049  $sql .= $field." = '".$this->db->escape($value)."'";
5050  $sql .= " WHERE rowid = ".((int) $this->id);
5051 
5052  dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5053  $resql = $this->db->query($sql);
5054 
5055  if ($resql) {
5056  // Call triggers
5057  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5058  $interface = new Interfaces($this->db);
5059  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5060  if ($result < 0) {
5061  $this->errors = $interface->errors;
5062  $this->db->rollback();
5063  return -1;
5064  }
5065  // End call triggers
5066 
5067  $this->$field = $value;
5068 
5069  $this->db->commit();
5070  return 1;
5071  } else {
5072  $this->error = $this->db->lasterror();
5073  $this->db->rollback();
5074  return -1;
5075  }
5076  }
5077 
5084  public function fetchPartnerships($mode)
5085  {
5086  global $langs;
5087 
5088  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5089 
5090 
5091  $this->partnerships[] = array();
5092 
5093  return 1;
5094  }
5095 }
$object ref
Definition: info.php:78
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage bank accounts description of third parties.
Class to stock current configuration.
Definition: conf.class.php:34
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoices.
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.
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
getParentsForCompany($company_id, $parents=[])
Get parents for company.
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Load a third party from database into memory.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
const PROSPECT
Third party type is a prospect.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='')
Return a link on thirdparty (with picto)
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
setCategories($categories, $type_categ)
Sets object to supplied categories.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
setNoEmail($no_email)
Set "blacklist" mailing status.
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
create_individual(User $user, $no_email=0, $tags=array())
Create a contact/address from thirdparty.
update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Returns the contact list of this company.
getAvailableDiscounts($user='', $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
create(User $user)
Create third party in database.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
getNoEmail()
get "blacklist" mailing status set no_email attribut to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Returns the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
Definition: user.class.php:45
trait CommonIncoterm
Superclass for incoterm classes.
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1401
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:450
clean_url($url, $http=1)
Clean an url string.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0, $extralangcode='')
Return a formated address (part address/zip/town/state) according to country rules.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='')
Show logo action.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
Make a substring.
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:122
$conf db
API class for accounts.
Definition: inc.php:41