dolibarr  18.0.6
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-2023 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-2023 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.'/core/class/commonsocialnetworks.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
46 
47 
51 class Societe extends CommonObject
52 {
53  use CommonIncoterm;
55  use CommonPeople;
56 
60  public $module = 'societe';
61 
65  public $element = 'societe';
66 
70  public $table_element = 'societe';
71 
75  public $fk_element = 'fk_soc';
76 
80  public $fieldsforcombobox = 'nom,name_alias';
81 
85  protected $childtables = array(
86  'supplier_proposal' => array('name' => 'SupplierProposal'),
87  'propal' => array('name' => 'Proposal'),
88  'commande' => array('name' => 'Order'),
89  'facture' => array('name' => 'Invoice'),
90  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
91  'contrat' => array('name' => 'Contract'),
92  'fichinter' => array('name' => 'Fichinter'),
93  'facture_fourn' => array('name' => 'SupplierInvoice'),
94  'commande_fournisseur' => array('name' => 'SupplierOrder'),
95  'projet' => array('name' => 'Project'),
96  'expedition' => array('name' => 'Shipment'),
97  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
98  );
99 
104  protected $childtablesoncascade = array(
105  'societe_prices',
106  'societe_address',
107  'product_fournisseur_price',
108  'product_customer_price_log',
109  'product_customer_price',
110  '@Contact:/contact/class/contact.class.php:fk_soc',
111  'adherent',
112  'societe_account',
113  'societe_rib',
114  'societe_remise',
115  'societe_remise_except',
116  'societe_commerciaux',
117  'categorie',
118  'notify',
119  'notify_def',
120  'actioncomm',
121  );
122 
126  public $picto = 'company';
127 
132  public $ismultientitymanaged = 1;
133 
137  public $isextrafieldmanaged = 1;
138 
143  public $restrictiononfksoc = 1;
144 
148  public $oldcopy;
149 
154  public $SupplierCategories = array();
155 
160  public $prefixCustomerIsRequired;
161 
191  public $fields = array(
192  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
193  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
194  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
195  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
196  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
197  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
198  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
199  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
200  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
201  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
202  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CustomerAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
203  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
204  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
205  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
206  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
207  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
208  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
209  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
210  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
211  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
212  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
213  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
214  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
215  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
216  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
217  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
218  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
219  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
220  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
221  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
222  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
223  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
224  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
225  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
226  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
227  'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
228  'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
229  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>"getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible'=>-1, 'position'=>235),
230  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
231  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
232  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
233  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
234  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
235  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
236  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
237  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
238  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
239  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
240  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
241  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
242  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
243  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
244  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
245  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
246  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
247  '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),
248  '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),
249  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
250  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
251  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
252  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
253  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
254  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
255  'vat_reverse_charge' =>array('type'=>'tinyint(4)', 'label'=>'Vat reverse charge', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
256  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
257  '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),
258  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
259  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
260  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
261  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
262  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
263  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
264  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
265  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
266  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
267  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
268  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
269  'fk_account' =>array('type'=>'integer', 'label'=>'PaymentBankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
270  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
271  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
272  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
273  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
274  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
275  );
276 
280  public $entity;
281 
288  public $nom;
289 
293  public $name;
294 
299  public $name_alias;
300 
304  public $particulier;
305 
310  public $status = 1;
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;
354 
359  public $email;
360 
365  public $no_email;
366 
372  public $skype;
373 
379  public $twitter;
380 
386  public $facebook;
387 
393  public $linkedin;
394 
399  public $url;
400 
405  public $barcode;
406 
407  // 6 professional id (usage depends on country)
408 
413  public $idprof1;
414 
420  public $siren;
421 
422 
427  public $idprof2;
428 
434  public $siret;
435 
440  public $idprof3;
441 
447  public $ape;
448 
453  public $idprof4;
454 
459  public $idprof5;
460 
465  public $idprof6;
466 
471  public $socialobject;
472 
476  public $prefix_comm;
477 
481  public $tva_assuj = 1;
482 
487  public $tva_intra;
488 
492  public $vat_reverse_charge = 0;
493 
494  // Local taxes
495  public $localtax1_assuj;
496  public $localtax1_value;
497  public $localtax2_assuj;
498  public $localtax2_value;
499 
503  public $managers;
504 
508  public $capital;
509 
513  public $typent_id = 0;
514  public $typent_code;
515  public $effectif;
516  public $effectif_id = 0;
517  public $forme_juridique_code;
518  public $forme_juridique = 0;
519 
520  public $remise_percent;
521  public $remise_supplier_percent;
522 
523  public $mode_reglement_id;
524  public $cond_reglement_id;
525  public $deposit_percent;
526  public $mode_reglement_supplier_id;
527  public $cond_reglement_supplier_id;
528  public $transport_mode_supplier_id;
529 
533  public $fk_prospectlevel;
534 
538  public $name_bis;
539 
540  //Log data
541 
546  public $date_modification;
547 
552  public $user_modification;
553 
558  public $date_creation;
559 
564  public $user_creation;
565 
570  public $client = 0;
571 
576  public $prospect = 0;
577 
582  public $fournisseur;
583 
588  public $code_client;
589 
594  public $code_fournisseur;
595 
600  public $code_compta_client;
601 
608  public $code_compta;
609 
614  public $accountancy_code_customer;
615 
620  public $code_compta_fournisseur;
621 
626  public $accountancy_code_supplier;
627 
632  public $code_compta_product;
633 
639  public $note;
640 
645  public $note_private;
646 
651  public $note_public;
652 
657  public $stcomm_id;
658 
663  public $stcomm_picto;
664 
669  public $status_prospect_label;
670 
675  public $price_level;
676 
680  public $outstanding_limit;
681 
685  public $order_min_amount;
686 
690  public $supplier_order_min_amount;
691 
696  public $commercial_id;
697 
702  public $parent;
703 
708  public $default_lang;
709 
713  public $ref;
714 
720  public $ref_ext;
721 
728  public $import_key;
729 
734  public $webservices_url;
735 
740  public $webservices_key;
741 
745  public $logo;
746 
750  public $logo_small;
751 
755  public $logo_mini;
756 
760  public $logo_squarred;
761 
765  public $logo_squarred_small;
766 
770  public $logo_squarred_mini;
771 
775  public $accountancy_code_sell;
776 
780  public $accountancy_code_buy;
781 
782  // Multicurrency
786  public $fk_multicurrency;
787 
788  // Warehouse
792  public $fk_warehouse;
793 
797  public $multicurrency_code;
798 
799  // Fields loaded by fetchPartnerships()
800 
801  public $partnerships = array();
802 
803 
807  public $bank_account;
808 
809 
810  const STATUS_CEASED = 0;
811  const STATUS_INACTIVITY = 1;
812 
816  const NO_CUSTOMER = 0;
817 
821  const CUSTOMER = 1;
822 
826  const PROSPECT = 2;
827 
832 
836  const NO_SUPPLIER = 0;
837 
841  const SUPPLIER = 1;
842 
843 
849  public function __construct($db)
850  {
851  global $conf;
852 
853  $this->db = $db;
854 
855  $this->client = 0;
856  $this->prospect = 0;
857  $this->fournisseur = 0;
858  $this->typent_id = 0;
859  $this->effectif_id = 0;
860  $this->forme_juridique_code = 0;
861  $this->tva_assuj = 1;
862  $this->vat_reverse_charge = 0;
863  $this->status = 1;
864 
865  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
866  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
867  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
868  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
869  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
870  }
871  }
872 
873 
882  public function create(User $user, $notrigger = 0)
883  {
884  global $langs, $conf, $mysoc;
885 
886  $error = 0;
887 
888  // Clean parameters
889  if (empty($this->status)) {
890  $this->status = 0;
891  }
892  $this->name = $this->name ?trim($this->name) : trim($this->nom);
893  $this->setUpperOrLowerCase();
894  $this->nom = $this->name; // For backward compatibility
895  if (empty($this->client)) {
896  $this->client = 0;
897  }
898  if (empty($this->fournisseur)) {
899  $this->fournisseur = 0;
900  }
901  $this->import_key = trim($this->import_key);
902 
903  $this->accountancy_code_customer = trim($this->code_compta);
904  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
905  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
906  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
907 
908  if (!empty($this->multicurrency_code)) {
909  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
910  }
911  if (empty($this->fk_multicurrency)) {
912  $this->multicurrency_code = '';
913  $this->fk_multicurrency = 0;
914  }
915 
916  dol_syslog(get_class($this)."::create ".$this->name);
917 
918  $now = dol_now();
919 
920  $this->db->begin();
921 
922  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
923  if ($this->code_client == -1 || $this->code_client === 'auto') {
924  $this->get_codeclient($this, 0);
925  }
926  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
927  $this->get_codefournisseur($this, 1);
928  }
929 
930  // Check more parameters (including mandatory setup
931  // If error, this->errors[] is filled
932  $result = $this->verify();
933 
934  if ($result >= 0) {
935  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
936 
937  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
938  $sql .= "nom";
939  $sql .= ", name_alias";
940  $sql .= ", entity";
941  $sql .= ", datec";
942  $sql .= ", fk_user_creat";
943  $sql .= ", fk_typent";
944  $sql .= ", canvas";
945  $sql .= ", status";
946  $sql .= ", ref_ext";
947  $sql .= ", fk_stcomm";
948  $sql .= ", fk_incoterms";
949  $sql .= ", location_incoterms";
950  $sql .= ", import_key";
951  $sql .= ", fk_multicurrency";
952  $sql .= ", multicurrency_code";
953  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
954  $sql .= ", vat_reverse_charge";
955  $sql .= ", accountancy_code_buy";
956  $sql .= ", accountancy_code_sell";
957  }
958  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
959  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
960  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
961  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
962  $sql .= ", ".((int) $this->status);
963  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
964  $sql .= ", 0";
965  $sql .= ", ".(int) $this->fk_incoterms;
966  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
967  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
968  $sql .= ", ".(int) $this->fk_multicurrency;
969  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
970  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
971  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
972  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
973  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
974  }
975  $sql .= ")";
976 
977  dol_syslog(get_class($this)."::create", LOG_DEBUG);
978  $result = $this->db->query($sql);
979  if ($result) {
980  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
981 
982  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
983 
984  // update accountancy for this entity
985  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
986  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
987 
988  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
989  $sql .= " fk_soc";
990  $sql .= ", entity";
991  $sql .= ", vat_reverse_charge";
992  $sql .= ", accountancy_code_customer";
993  $sql .= ", accountancy_code_supplier";
994  $sql .= ", accountancy_code_buy";
995  $sql .= ", accountancy_code_sell";
996  $sql .= ") VALUES (";
997  $sql .= $this->id;
998  $sql .= ", ".((int) $conf->entity);
999  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1000  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1001  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1002  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1003  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1004  $sql .= ")";
1005  $result = $this->db->query($sql);
1006  if (!$result) {
1007  $error++;
1008  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1009  }
1010  }
1011 
1012  // Ajout du commercial affecte
1013  if ($this->commercial_id != '' && $this->commercial_id != -1) {
1014  $this->add_commercial($user, $this->commercial_id);
1015  } elseif (empty($user->rights->societe->client->voir)) {
1016  // si un commercial cree un client il lui est affecte automatiquement
1017  $this->add_commercial($user, $user->id);
1018  }
1019 
1020  if ($ret >= 0) {
1021  if (! $notrigger) {
1022  // Call trigger
1023  $result = $this->call_trigger('COMPANY_CREATE', $user);
1024  if ($result < 0) {
1025  $error++;
1026  }
1027  // End call triggers
1028  }
1029  } else {
1030  $error++;
1031  }
1032 
1033  if (!$error) {
1034  dol_syslog(get_class($this)."::Create success id=".$this->id);
1035  $this->db->commit();
1036  return $this->id;
1037  } else {
1038  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1039  $this->db->rollback();
1040  return -4;
1041  }
1042  } else {
1043  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1044  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1045  $result = -1;
1046  } else {
1047  $this->error = $this->db->lasterror();
1048  $result = -2;
1049  }
1050  $this->db->rollback();
1051  return $result;
1052  }
1053  } else {
1054  $this->db->rollback();
1055  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1056  return -3;
1057  }
1058  }
1059 
1060 
1061  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1071  public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1072  {
1073  global $conf;
1074 
1075  $error = 0;
1076 
1077  $this->db->begin();
1078 
1079  // phpcs:enable
1080  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1081  $contact = new Contact($this->db);
1082 
1083  $contact->name = $this->name_bis;
1084  $contact->firstname = $this->firstname;
1085  $contact->civility_id = $this->civility_id;
1086  $contact->socid = $this->id; // fk_soc
1087  $contact->statut = 1; // deprecated
1088  $contact->status = 1;
1089  $contact->priv = 0;
1090  $contact->country_id = $this->country_id;
1091  $contact->state_id = $this->state_id;
1092  $contact->address = $this->address;
1093  $contact->email = $this->email;
1094  $contact->zip = $this->zip;
1095  $contact->town = $this->town;
1096  $this->setUpperOrLowerCase();
1097  $contact->phone_pro = $this->phone;
1098 
1099  $contactId = $contact->create($user, $notrigger);
1100  if ($contactId < 0) {
1101  $error++;
1102  $this->error = $contact->error;
1103  $this->errors = $contact->errors;
1104  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1105  }
1106 
1107  if (empty($error) && is_array($tags) && !empty($tags)) {
1108  $result = $contact->setCategories($tags);
1109  if ($result < 0) {
1110  $error++;
1111  $this->error = $contact->error;
1112  $this->errors = array_merge($this->errors, $contact->errors);
1113  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1114  $contactId = $result;
1115  }
1116  }
1117 
1118  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1119  $result = $contact->setNoEmail($no_email);
1120  if ($result < 0) {
1121  $this->error = $contact->error;
1122  $this->errors = array_merge($this->errors, $contact->errors);
1123  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1124  $contactId = $result;
1125  }
1126  }
1127 
1128  if (empty($error)) {
1129  dol_syslog(get_class($this)."::create_individual success");
1130  $this->db->commit();
1131  } else {
1132  $this->db->rollback();
1133  }
1134 
1135  return $contactId;
1136  }
1137 
1144  public function verify()
1145  {
1146  global $conf, $langs, $mysoc;
1147 
1148  $error = 0;
1149  $this->errors = array();
1150 
1151  $result = 0;
1152  $this->name = trim($this->name);
1153  $this->nom = $this->name; // For backward compatibility
1154 
1155  if (!$this->name) {
1156  $this->errors[] = 'ErrorBadThirdPartyName';
1157  $result = -2;
1158  }
1159 
1160  if ($this->client) {
1161  $rescode = $this->check_codeclient();
1162  if ($rescode != 0 && $rescode != -5) {
1163  if ($rescode == -1) {
1164  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1165  } elseif ($rescode == -2) {
1166  $this->errors[] = 'ErrorCustomerCodeRequired';
1167  } elseif ($rescode == -3) {
1168  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1169  } elseif ($rescode == -4) {
1170  $this->errors[] = 'ErrorPrefixRequired';
1171  } else {
1172  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1173  }
1174 
1175  $result = -3;
1176  }
1177  }
1178 
1179  if ($this->fournisseur) {
1180  $rescode = $this->check_codefournisseur();
1181  if ($rescode != 0 && $rescode != -5) {
1182  if ($rescode == -1) {
1183  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1184  } elseif ($rescode == -2) {
1185  $this->errors[] = 'ErrorSupplierCodeRequired';
1186  } elseif ($rescode == -3) {
1187  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1188  } elseif ($rescode == -4) {
1189  $this->errors[] = 'ErrorPrefixRequired';
1190  } else {
1191  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1192  }
1193  $result = -3;
1194  }
1195  }
1196 
1197  // Check for duplicate or mandatory fields defined into setup
1198  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1199  foreach ($array_to_check as $key) {
1200  $keymin = strtolower($key);
1201  $i = (int) preg_replace('/[^0-9]/', '', $key);
1202  $vallabel = $this->$keymin;
1203 
1204  if ($i > 0) {
1205  if ($this->isACompany()) {
1206  // Check for mandatory prof id (but only if country is same than ours)
1207  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1208  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1209  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1210  $langs->load("errors");
1211  $error++;
1212  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1213  }
1214  }
1215  }
1216 
1217  // Check for unicity on profid
1218  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1219  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1220  $langs->load("errors");
1221  $error++;
1222  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1223  }
1224  }
1225  } else {
1226  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1227  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1228  if ($key == 'EMAIL') {
1229  // Check for mandatory
1230  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1231  $langs->load("errors");
1232  $error++;
1233  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1234  }
1235 
1236  // Check for unicity
1237  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1238  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1239  $langs->load("errors");
1240  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1241  }
1242  }
1243  } elseif ($key == 'TVA_INTRA') {
1244  // Check for unicity
1245  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1246  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1247  $langs->load("errors");
1248  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1249  }
1250  }
1251  }
1252  }
1253  }
1254 
1255  if ($error) {
1256  $result = -4;
1257  }
1258 
1259  return $result;
1260  }
1261 
1274  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1275  {
1276  global $langs, $conf, $hookmanager;
1277 
1278  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1279 
1280  if (empty($id)) {
1281  $id = $this->id;
1282  }
1283 
1284  $error = 0;
1285 
1286  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1287 
1288  $now = dol_now();
1289 
1290  // Clean parameters
1291  $this->id = $id;
1292  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1293  $this->name = $this->name ? trim($this->name) : trim($this->nom);
1294  $this->nom = $this->name; // For backward compatibility
1295  $this->name_alias = trim($this->name_alias);
1296  $this->ref_ext = trim($this->ref_ext);
1297  $this->address = $this->address ?trim($this->address) : trim($this->address);
1298  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1299  $this->town = $this->town ?trim($this->town) : trim($this->town);
1300  $this->state_id = trim($this->state_id);
1301  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1302  $this->phone = trim($this->phone);
1303  $this->phone = preg_replace("/\s/", "", $this->phone);
1304  $this->phone = preg_replace("/\./", "", $this->phone);
1305  $this->fax = trim($this->fax);
1306  $this->fax = preg_replace("/\s/", "", $this->fax);
1307  $this->fax = preg_replace("/\./", "", $this->fax);
1308  $this->email = trim($this->email);
1309  $this->url = $this->url ?clean_url($this->url, 0) : '';
1310  $this->note_private = trim($this->note_private);
1311  $this->note_public = trim($this->note_public);
1312  $this->idprof1 = trim($this->idprof1);
1313  $this->idprof2 = trim($this->idprof2);
1314  $this->idprof3 = trim($this->idprof3);
1315  $this->idprof4 = trim($this->idprof4);
1316  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1317  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1318  $this->prefix_comm = trim($this->prefix_comm);
1319  $this->outstanding_limit = price2num($this->outstanding_limit);
1320  $this->order_min_amount = price2num($this->order_min_amount);
1321  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1322 
1323  $this->tva_assuj = trim($this->tva_assuj);
1324  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1325  $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? '0' : '1';
1326  if (empty($this->status)) {
1327  $this->status = 0;
1328  }
1329 
1330  if (!empty($this->multicurrency_code)) {
1331  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1332  }
1333  if (empty($this->fk_multicurrency)) {
1334  $this->multicurrency_code = '';
1335  $this->fk_multicurrency = 0;
1336  }
1337 
1338  // Local taxes
1339  $this->localtax1_assuj = trim($this->localtax1_assuj);
1340  $this->localtax2_assuj = trim($this->localtax2_assuj);
1341 
1342  $this->localtax1_value = trim($this->localtax1_value);
1343  $this->localtax2_value = trim($this->localtax2_value);
1344 
1345  if ($this->capital != '') {
1346  $this->capital = price2num(trim($this->capital));
1347  }
1348  if (!is_numeric($this->capital)) {
1349  $this->capital = ''; // '' = undef
1350  }
1351 
1352  $this->effectif_id = trim($this->effectif_id);
1353  $this->forme_juridique_code = trim($this->forme_juridique_code);
1354 
1355  //Gencod
1356  $this->barcode = trim($this->barcode);
1357 
1358  // For automatic creation
1359  if ($this->code_client == -1 || $this->code_client === 'auto') {
1360  $this->get_codeclient($this, 0);
1361  }
1362  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1363  $this->get_codefournisseur($this, 1);
1364  }
1365 
1366  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1367  $this->code_compta = $this->code_compta_client; // for backward compatibility
1368  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1369 
1370  // Check parameters. More tests are done later in the ->verify()
1371  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1372  $langs->load("errors");
1373  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1374  return -1;
1375  }
1376 
1377  $customer = false;
1378  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1379  // If $allowmodcodeclient is set and value is not set, we generate it
1380  if (empty($this->code_compta_client)) {
1381  $ret = $this->get_codecompta('customer');
1382  if ($ret < 0) {
1383  return -1;
1384  }
1385  }
1386 
1387  $customer = true;
1388  }
1389 
1390  $supplier = false;
1391  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1392  // If $allowmodcodefournisseur is set and value is not set, we generate it
1393  if (empty($this->code_compta_fournisseur)) {
1394  $ret = $this->get_codecompta('supplier');
1395  if ($ret < 0) {
1396  return -1;
1397  }
1398  }
1399 
1400  $supplier = true;
1401  }
1402 
1403  //Web services
1404  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1405  $this->webservices_key = trim($this->webservices_key);
1406 
1407  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1408  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1409 
1410  //Incoterms
1411  $this->fk_incoterms = (int) $this->fk_incoterms;
1412  $this->location_incoterms = trim($this->location_incoterms);
1413 
1414  $this->db->begin();
1415 
1416  // Check name is required and codes are ok or unique.
1417  // If error, this->errors[] is filled
1418  $result = 0;
1419  if ($action != 'add' && $action != 'merge') {
1420  // We don't check when update called during a create because verify was already done.
1421  // 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
1422  $result = $this->verify();
1423 
1424  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1425  // So we can update record that were using and old numbering rule.
1426  if (is_array($this->errors)) {
1427  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1428  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1429  unset($this->errors[$key]); // Remove error message
1430  }
1431  }
1432  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1433  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1434  unset($this->errors[$key]); // Remove error message
1435  }
1436  }
1437  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1438  $result = 0;
1439  }
1440  }
1441  }
1442  $this->setUpperOrLowerCase();
1443  if ($result >= 0) {
1444  dol_syslog(get_class($this)."::update verify ok or not done");
1445 
1446  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1447  $sql .= "entity = ".$this->db->escape($this->entity);
1448  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1449  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1450  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1451  $sql .= ",address = '".$this->db->escape($this->address)."'";
1452 
1453  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1454  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1455 
1456  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1457  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1458 
1459  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1460  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1461  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1462  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1463  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1464 
1465  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1466 
1467  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1468  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1469 
1470  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1471  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1472  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1473  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1474  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1475  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1476 
1477  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1478  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1479  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1480  $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1481  }
1482  $sql .= ",status = ".((int) $this->status);
1483 
1484  // Local taxes
1485  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1486  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1487  if ($this->localtax1_assuj == 1) {
1488  if ($this->localtax1_value != '') {
1489  $sql .= ",localtax1_value =".$this->localtax1_value;
1490  } else {
1491  $sql .= ",localtax1_value =0.000";
1492  }
1493  } else {
1494  $sql .= ",localtax1_value =0.000";
1495  }
1496 
1497  if ($this->localtax2_assuj == 1) {
1498  if ($this->localtax2_value != '') {
1499  $sql .= ",localtax2_value =".$this->localtax2_value;
1500  } else {
1501  $sql .= ",localtax2_value =0.000";
1502  }
1503  } else {
1504  $sql .= ",localtax2_value =0.000";
1505  }
1506 
1507  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1508 
1509  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1510 
1511  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1512  if (isset($this->stcomm_id)) {
1513  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1514  }
1515  if (isset($this->typent_id)) {
1516  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1517  }
1518 
1519  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1520 
1521  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1522  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1523  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1524  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1525  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1526  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1527  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1528  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1529 
1530  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1531  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1532  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1533  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1534  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1535  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1536  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1537  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1538  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1539  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1540  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1541  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1542  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1543  if ($customer) {
1544  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1545  }
1546 
1547  if ($supplier) {
1548  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1549  }
1550  }
1551  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1552  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1553 
1554  //Incoterms
1555  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1556  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1557 
1558  if ($customer) {
1559  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1560  }
1561 
1562  if ($supplier) {
1563  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1564  }
1565  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1566  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1567  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1568  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1569  $sql .= " WHERE rowid = ".(int) $id;
1570 
1571  $resql = $this->db->query($sql);
1572  if ($resql) {
1573  if (is_object($this->oldcopy)) { // If we have information on old values
1574  if ($this->oldcopy->country_id != $this->country_id) {
1575  unset($this->country_code);
1576  unset($this->country);
1577  }
1578  if ($this->oldcopy->state_id != $this->state_id) {
1579  unset($this->state_code);
1580  unset($this->state);
1581  }
1582  } else {
1583  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1584  unset($this->country);
1585  unset($this->state_code);
1586  unset($this->state);
1587  }
1588 
1589  $nbrowsaffected = $this->db->affected_rows($resql);
1590 
1591  if (!$error && $nbrowsaffected) {
1592  // Update information on linked member if it is an update
1593  if (!$nosyncmember && isModEnabled('adherent')) {
1594  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1595 
1596  dol_syslog(get_class($this)."::update update linked member");
1597 
1598  $lmember = new Adherent($this->db);
1599  $result = $lmember->fetch(0, 0, $this->id);
1600 
1601  if ($result > 0) {
1602  $lmember->company = $this->name;
1603  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1604  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1605  $lmember->address = $this->address;
1606  $lmember->zip = $this->zip;
1607  $lmember->town = $this->town;
1608  $lmember->email = $this->email;
1609  $lmember->socialnetworks = $this->socialnetworks;
1610  $lmember->phone = $this->phone;
1611  $lmember->state_id = $this->state_id;
1612  $lmember->country_id = $this->country_id;
1613  $lmember->default_lang = $this->default_lang;
1614 
1615  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1616  if ($result < 0) {
1617  $this->error = $lmember->error;
1618  $this->errors = array_merge($this->errors, $lmember->errors);
1619  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1620  $error++;
1621  }
1622  } elseif ($result < 0) {
1623  $this->error = $lmember->error;
1624  $error++;
1625  }
1626  }
1627  }
1628 
1629  $action = 'update';
1630 
1631  // update accountancy for this entity
1632  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1633  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1634 
1635  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1636  $sql .= " fk_soc";
1637  $sql .= ", entity";
1638  $sql .= ", vat_reverse_charge";
1639  $sql .= ", accountancy_code_customer";
1640  $sql .= ", accountancy_code_supplier";
1641  $sql .= ", accountancy_code_buy";
1642  $sql .= ", accountancy_code_sell";
1643  $sql .= ") VALUES (";
1644  $sql .= $this->id;
1645  $sql .= ", ".$conf->entity;
1646  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1647  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1648  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1649  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1650  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1651  $sql .= ")";
1652  $result = $this->db->query($sql);
1653  if (!$result) {
1654  $error++;
1655  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1656  }
1657  }
1658 
1659  // Actions on extra fields
1660  if (!$error) {
1661  $result = $this->insertExtraFields();
1662  if ($result < 0) {
1663  $error++;
1664  }
1665  }
1666  // Actions on extra languages
1667  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1668  $result = $this->insertExtraLanguages();
1669  if ($result < 0) {
1670  $error++;
1671  }
1672  }
1673 
1674  if (!$error && $call_trigger) {
1675  // Call trigger
1676  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1677  if ($result < 0) {
1678  $error++;
1679  }
1680  // End call triggers
1681  }
1682 
1683  if (!$error) {
1684  dol_syslog(get_class($this)."::Update success");
1685  $this->db->commit();
1686  return 1;
1687  } else {
1688  $this->db->rollback();
1689  return -1;
1690  }
1691  } else {
1692  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1693  // Doublon
1694  $this->error = $langs->trans("ErrorDuplicateField");
1695  $result = -1;
1696  } else {
1697  $this->error = $this->db->lasterror();
1698  $result = -2;
1699  }
1700  $this->db->rollback();
1701  return $result;
1702  }
1703  } else {
1704  $this->db->rollback();
1705  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1706  return -3;
1707  }
1708  }
1709 
1727  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1728  {
1729  global $langs;
1730  global $conf;
1731 
1732  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email) && empty($ref_alias)) {
1733  return -1;
1734  }
1735 
1736  $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';
1737  $sql .= ', s.status, s.fk_warehouse';
1738  $sql .= ', s.price_level';
1739  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1740  $sql .= ', s.phone, s.fax, s.email';
1741  $sql .= ', s.socialnetworks';
1742  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1743  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1744  $sql .= ', s.capital, s.tva_intra';
1745  $sql .= ', s.fk_typent as typent_id';
1746  $sql .= ', s.fk_effectif as effectif_id';
1747  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1748  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1749  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1750  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1751  $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1752  } else {
1753  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1754  $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1755  }
1756  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1757  $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';
1758  $sql .= ', s.fk_account, s.tva_assuj';
1759  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1760  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1761  $sql .= ', s.fk_shipping_method';
1762  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1763  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1764  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1765  $sql .= ', fj.libelle as forme_juridique';
1766  $sql .= ', e.libelle as effectif';
1767  $sql .= ', c.code as country_code, c.label as country';
1768  $sql .= ', d.code_departement as state_code, d.nom as state';
1769  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1770  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1771  $sql .= ', te.code as typent_code';
1772  $sql .= ', i.libelle as label_incoterms';
1773  if (!isModEnabled('multicompany')) {
1774  $sql .= ', s.remise_client, s.remise_supplier';
1775  } else {
1776  $sql .= ', sr.remise_client, sr2.remise_supplier';
1777  }
1778  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1779  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1780  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1781  }
1782  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1783  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1784  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1785  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1786  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1787  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1788  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1789  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1790  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1791  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1792  if (isModEnabled('multicompany')) {
1793  $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').'))';
1794  $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').'))';
1795  }
1796  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1797  if ($rowid) {
1798  $sql .= ' AND s.rowid = '.((int) $rowid);
1799  }
1800  if ($ref) {
1801  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1802  }
1803  if ($ref_alias) {
1804  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1805  }
1806  if ($ref_ext) {
1807  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1808  }
1809  if ($barcode) {
1810  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1811  }
1812  if ($idprof1) {
1813  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1814  }
1815  if ($idprof2) {
1816  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1817  }
1818  if ($idprof3) {
1819  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1820  }
1821  if ($idprof4) {
1822  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1823  }
1824  if ($idprof5) {
1825  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1826  }
1827  if ($idprof6) {
1828  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1829  }
1830  if ($email) {
1831  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1832  }
1833 
1834  $resql = $this->db->query($sql);
1835  if ($resql) {
1836  $num = $this->db->num_rows($resql);
1837  if ($num > 1) {
1838  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1839  dol_syslog($this->error, LOG_ERR);
1840  $result = -2;
1841  } elseif ($num) { // $num = 1
1842  $obj = $this->db->fetch_object($resql);
1843 
1844  $this->id = $obj->rowid;
1845  $this->entity = $obj->entity;
1846  $this->canvas = $obj->canvas;
1847 
1848  $this->ref = $obj->rowid;
1849  $this->name = $obj->name;
1850  $this->nom = $obj->name; // deprecated
1851  $this->name_alias = $obj->name_alias;
1852  $this->ref_ext = $obj->ref_ext;
1853 
1854  $this->date_creation = $this->db->jdate($obj->date_creation);
1855  $this->date_modification = $this->db->jdate($obj->date_modification);
1856  $this->user_creation = $obj->fk_user_creat;
1857  $this->user_modification = $obj->fk_user_modif;
1858 
1859  $this->address = $obj->address;
1860  $this->zip = $obj->zip;
1861  $this->town = $obj->town;
1862 
1863  $this->country_id = $obj->country_id;
1864  $this->country_code = $obj->country_id ? $obj->country_code : '';
1865  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1866 
1867  $this->state_id = $obj->state_id;
1868  $this->state_code = $obj->state_code;
1869  $this->region_id = $obj->region_id;
1870  $this->region_code = $obj->region_code;
1871  $this->state = ($obj->state != '-' ? $obj->state : '');
1872 
1873  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1874  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1875  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1876  $this->status_prospect_label = $label; // label status prospect
1877  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1878 
1879  $this->email = $obj->email;
1880  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1881 
1882  $this->url = $obj->url;
1883  $this->phone = $obj->phone;
1884  $this->fax = $obj->fax;
1885 
1886  $this->parent = $obj->parent;
1887 
1888  $this->idprof1 = $obj->idprof1;
1889  $this->idprof2 = $obj->idprof2;
1890  $this->idprof3 = $obj->idprof3;
1891  $this->idprof4 = $obj->idprof4;
1892  $this->idprof5 = $obj->idprof5;
1893  $this->idprof6 = $obj->idprof6;
1894 
1895  $this->capital = $obj->capital;
1896 
1897  $this->code_client = $obj->code_client;
1898  $this->code_fournisseur = $obj->code_fournisseur;
1899 
1900  $this->code_compta = $obj->code_compta; // For backward compatibility
1901  $this->code_compta_client = $obj->code_compta;
1902  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1903 
1904  $this->barcode = $obj->barcode;
1905 
1906  $this->tva_assuj = $obj->tva_assuj;
1907  $this->tva_intra = $obj->tva_intra;
1908 
1909  if (!empty($obj->spe_vat_reverse_charge)) {
1910  $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1911  } elseif (!empty($obj->soc_vat_reverse_charge)) {
1912  $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1913  } else {
1914  $this->vat_reverse_charge = 0;
1915  }
1916 
1917  $this->status = $obj->status;
1918 
1919  // Local Taxes
1920  $this->localtax1_assuj = $obj->localtax1_assuj;
1921  $this->localtax2_assuj = $obj->localtax2_assuj;
1922 
1923  $this->localtax1_value = $obj->localtax1_value;
1924  $this->localtax2_value = $obj->localtax2_value;
1925 
1926  $this->typent_id = $obj->typent_id;
1927  $this->typent_code = $obj->typent_code;
1928 
1929  $this->effectif_id = $obj->effectif_id;
1930  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1931 
1932  $this->forme_juridique_code = $obj->forme_juridique_code;
1933  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1934 
1935  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1936 
1937  $this->prefix_comm = $obj->prefix_comm;
1938 
1939  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1940  $this->remise_supplier_percent = $obj->remise_supplier;
1941 
1942  $this->mode_reglement_id = $obj->mode_reglement;
1943  $this->cond_reglement_id = $obj->cond_reglement;
1944  $this->deposit_percent = $obj->deposit_percent;
1945  $this->transport_mode_id = $obj->transport_mode;
1946  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1947  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1948  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1949  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1950  $this->fk_account = $obj->fk_account;
1951 
1952  $this->client = $obj->client;
1953  $this->fournisseur = $obj->fournisseur;
1954 
1955  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1956  $this->note_private = $obj->note_private;
1957  $this->note_public = $obj->note_public;
1958  $this->model_pdf = $obj->model_pdf;
1959  $this->modelpdf = $obj->model_pdf; // deprecated
1960  $this->default_lang = $obj->default_lang;
1961  $this->logo = $obj->logo;
1962  $this->logo_squarred = $obj->logo_squarred;
1963 
1964  $this->webservices_url = $obj->webservices_url;
1965  $this->webservices_key = $obj->webservices_key;
1966 
1967  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1968  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1969 
1970  $this->outstanding_limit = $obj->outstanding_limit;
1971  $this->order_min_amount = $obj->order_min_amount;
1972  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1973 
1974  // multiprix
1975  $this->price_level = $obj->price_level;
1976 
1977  // warehouse
1978  $this->fk_warehouse = $obj->fk_warehouse;
1979 
1980  $this->import_key = $obj->import_key;
1981 
1982  //Incoterms
1983  $this->fk_incoterms = $obj->fk_incoterms;
1984  $this->location_incoterms = $obj->location_incoterms;
1985  $this->label_incoterms = $obj->label_incoterms;
1986 
1987  // multicurrency
1988  $this->fk_multicurrency = $obj->fk_multicurrency;
1989  $this->multicurrency_code = $obj->multicurrency_code;
1990 
1991  // pdf
1992  $this->model_pdf = $obj->model_pdf;
1993  $this->last_main_doc = $obj->last_main_doc;
1994 
1995  $result = 1;
1996 
1997  // fetch optionals attributes and labels
1998  $this->fetch_optionals();
1999  } else {
2000  $result = 0;
2001  }
2002 
2003  $this->db->free($resql);
2004  } else {
2005  $this->error = $this->db->lasterror();
2006  $this->errors[] = $this->db->lasterror();
2007  $result = -3;
2008  }
2009 
2010  // Use first price level if level not defined for third party
2011  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
2012  $this->price_level = 1;
2013  }
2014 
2015  return $result;
2016  }
2017 
2026  public function delete($id, User $fuser = null, $call_trigger = 1)
2027  {
2028  global $langs, $conf, $user;
2029 
2030  if (empty($fuser)) {
2031  $fuser = $user;
2032  }
2033 
2034  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2035 
2036  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2037 
2038  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2039  $error = 0;
2040 
2041  // Test if child exists
2042  $objectisused = $this->isObjectUsed($id);
2043  if (empty($objectisused)) {
2044  $this->db->begin();
2045 
2046  // User is mandatory for trigger call
2047  if (!$error && $call_trigger) {
2048  // Call trigger
2049  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2050  if ($result < 0) {
2051  $error++;
2052  }
2053  // End call triggers
2054  }
2055 
2056  if (!$error) {
2057  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2058  $static_cat = new Categorie($this->db);
2059  $toute_categs = array();
2060 
2061  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2062  if ($this->client || $this->prospect) {
2063  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2064  }
2065  if ($this->fournisseur) {
2066  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2067  }
2068 
2069  // Remove each "Categorie"
2070  foreach ($toute_categs as $type => $categs_type) {
2071  foreach ($categs_type as $cat) {
2072  $cat->del_type($this, $type);
2073  }
2074  }
2075  }
2076 
2077  if (!$error) {
2078  foreach ($this->childtablesoncascade as $tabletodelete) {
2079  $deleteFromObject = explode(':', $tabletodelete);
2080  if (count($deleteFromObject) >= 2) {
2081  $className = str_replace('@', '', $deleteFromObject[0]);
2082  $filepath = $deleteFromObject[1];
2083  $columnName = $deleteFromObject[2];
2084  if (dol_include_once($filepath)) {
2085  $child_object = new $className($this->db);
2086  $result = $child_object->deleteByParentField($id, $columnName);
2087  if ($result < 0) {
2088  $error++;
2089  $this->errors[] = $child_object->error;
2090  break;
2091  }
2092  } else {
2093  $error++;
2094  $this->errors[] = 'Cannot include child class file '.$filepath;
2095  break;
2096  }
2097  } else {
2098  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2099  $sql .= " WHERE fk_soc = ".((int) $id);
2100  if (!$this->db->query($sql)) {
2101  $error++;
2102  $this->errors[] = $this->db->lasterror();
2103  break;
2104  }
2105  }
2106  }
2107  }
2108 
2109  // Removed extrafields
2110  if (!$error) {
2111  $result = $this->deleteExtraFields();
2112  if ($result < 0) {
2113  $error++;
2114  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2115  }
2116  }
2117 
2118  // Remove links to subsidiaries companies
2119  if (!$error) {
2120  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2121  $sql .= " SET parent = NULL";
2122  $sql .= " WHERE parent = ".((int) $id);
2123  if (!$this->db->query($sql)) {
2124  $error++;
2125  $this->errors[] = $this->db->lasterror();
2126  }
2127  }
2128 
2129  // Remove third party
2130  if (!$error) {
2131  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2132  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2133  $sql .= " WHERE fk_soc = ".((int) $id);
2134  if (!$this->db->query($sql)) {
2135  $error++;
2136  $this->errors[] = $this->db->lasterror();
2137  }
2138  }
2139 
2140  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2141  $sql .= " WHERE rowid = ".((int) $id);
2142  if (!$this->db->query($sql)) {
2143  $error++;
2144  $this->errors[] = $this->db->lasterror();
2145  }
2146  }
2147 
2148  if (!$error) {
2149  $this->db->commit();
2150 
2151  // Delete directory
2152  if (!empty($conf->societe->multidir_output[$entity])) {
2153  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2154  if (dol_is_dir($docdir)) {
2155  dol_delete_dir_recursive($docdir);
2156  }
2157  }
2158 
2159  return 1;
2160  } else {
2161  dol_syslog($this->error, LOG_ERR);
2162  $this->db->rollback();
2163  return -1;
2164  }
2165  } else {
2166  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2167  }
2168  return 0;
2169  }
2170 
2171  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2177  public function set_as_client()
2178  {
2179  global $conf;
2180  // phpcs:enable
2181  if ($this->id) {
2182  $newclient = 1;
2183  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
2184  $newclient = 3; //If prospect, we keep prospect tag
2185  }
2186  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2187  $sql .= " SET client = ".((int) $newclient);
2188  $sql .= " WHERE rowid = ".((int) $this->id);
2189 
2190  $resql = $this->db->query($sql);
2191  if ($resql) {
2192  $this->client = $newclient;
2193  return 1;
2194  } else {
2195  return -1;
2196  }
2197  }
2198  return 0;
2199  }
2200 
2201  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2210  public function set_remise_client($remise, $note, User $user)
2211  {
2212  // phpcs:enable
2213  global $conf, $langs;
2214 
2215  // Parameter cleaning
2216  $note = trim($note);
2217  if (!$note) {
2218  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2219  return -2;
2220  }
2221 
2222  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2223 
2224  if ($this->id) {
2225  $this->db->begin();
2226 
2227  $now = dol_now();
2228 
2229  // Position current discount
2230  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2231  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2232  $sql .= " WHERE rowid = ".((int) $this->id);
2233  $resql = $this->db->query($sql);
2234  if (!$resql) {
2235  $this->db->rollback();
2236  $this->error = $this->db->error();
2237  return -1;
2238  }
2239 
2240  // Writes trace in discount history
2241  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2242  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2243  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2244  $sql .= " '".$this->db->escape($note)."',";
2245  $sql .= " ".((int) $user->id);
2246  $sql .= ")";
2247 
2248  $resql = $this->db->query($sql);
2249  if (!$resql) {
2250  $this->db->rollback();
2251  $this->error = $this->db->lasterror();
2252  return -1;
2253  }
2254 
2255  $this->db->commit();
2256 
2257  return 1;
2258  }
2259  return -1;
2260  }
2261 
2262  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2271  public function set_remise_supplier($remise, $note, User $user)
2272  {
2273  // phpcs:enable
2274  global $conf, $langs;
2275 
2276  // Parameter cleaning
2277  $note = trim($note);
2278  if (!$note) {
2279  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2280  return -2;
2281  }
2282 
2283  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2284 
2285  if ($this->id) {
2286  $this->db->begin();
2287 
2288  $now = dol_now();
2289 
2290  // Position current discount
2291  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2292  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2293  $sql .= " WHERE rowid = ".((int) $this->id);
2294  $resql = $this->db->query($sql);
2295  if (!$resql) {
2296  $this->db->rollback();
2297  $this->error = $this->db->error();
2298  return -1;
2299  }
2300 
2301  // Writes trace in discount history
2302  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2303  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2304  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2305  $sql .= " '".$this->db->escape($note)."',";
2306  $sql .= " ".((int) $user->id);
2307  $sql .= ")";
2308 
2309  $resql = $this->db->query($sql);
2310  if (!$resql) {
2311  $this->db->rollback();
2312  $this->error = $this->db->lasterror();
2313  return -1;
2314  }
2315 
2316  $this->db->commit();
2317  return 1;
2318  }
2319 
2320  return -1;
2321  }
2322 
2323  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2335  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2336  {
2337  // phpcs:enable
2338  global $langs;
2339 
2340  // Clean parameters
2341  $remise = price2num($remise);
2342  $desc = trim($desc);
2343 
2344  // Check parameters
2345  if (!($remise > 0)) {
2346  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2347  return -1;
2348  }
2349  if (!$desc) {
2350  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2351  return -2;
2352  }
2353 
2354  if ($this->id > 0) {
2355  // Clean vat code
2356  $reg = array();
2357  $vat_src_code = '';
2358  if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2359  $vat_src_code = $reg[1];
2360  $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2361  }
2362 
2363  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2364 
2365  $discount = new DiscountAbsolute($this->db);
2366  $discount->fk_soc = $this->id;
2367 
2368  $discount->discount_type = $discount_type;
2369 
2370  if ($price_base_type == 'TTC') {
2371  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2372  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2373  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2374  } else {
2375  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2376  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2377  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2378  }
2379 
2380  $discount->tva_tx = price2num($vatrate);
2381  $discount->vat_src_code = $vat_src_code;
2382 
2383  $discount->description = $desc;
2384 
2385  $result = $discount->create($user);
2386  if ($result > 0) {
2387  return $result;
2388  } else {
2389  $this->error = $discount->error;
2390  return -3;
2391  }
2392  } else {
2393  return 0;
2394  }
2395  }
2396 
2406  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2407  {
2408  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2409 
2410  $discountstatic = new DiscountAbsolute($this->db);
2411  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2412  if ($result >= 0) {
2413  return $result;
2414  } else {
2415  $this->error = $discountstatic->error;
2416  return -1;
2417  }
2418  }
2419 
2429  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2430  {
2431  global $conf;
2432 
2433  $reparray = array();
2434 
2435  $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";
2436  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2437  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2438  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2439  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2440  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2441  $sql .= " AND ug.entity = ".$conf->entity.")";
2442  $sql .= " OR u.admin = 1)";
2443  } else {
2444  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2445  }
2446 
2447  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2448  if (empty($sortfield) && empty($sortorder)) {
2449  $sortfield = 'u.lastname,u.firstname';
2450  $sortorder = 'ASC,ASC';
2451  }
2452  $sql .= $this->db->order($sortfield, $sortorder);
2453 
2454  $resql = $this->db->query($sql);
2455  if ($resql) {
2456  $num = $this->db->num_rows($resql);
2457  $i = 0;
2458  while ($i < $num) {
2459  $obj = $this->db->fetch_object($resql);
2460 
2461  if (empty($mode)) {
2462  $reparray[$i]['id'] = $obj->rowid;
2463  $reparray[$i]['lastname'] = $obj->lastname;
2464  $reparray[$i]['firstname'] = $obj->firstname;
2465  $reparray[$i]['email'] = $obj->email;
2466  $reparray[$i]['phone'] = $obj->office_phone;
2467  $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2468  $reparray[$i]['office_fax'] = $obj->office_fax;
2469  $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2470  $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2471  $reparray[$i]['job'] = $obj->job;
2472  $reparray[$i]['statut'] = $obj->status; // deprecated
2473  $reparray[$i]['status'] = $obj->status;
2474  $reparray[$i]['entity'] = $obj->entity;
2475  $reparray[$i]['login'] = $obj->login;
2476  $reparray[$i]['photo'] = $obj->photo;
2477  $reparray[$i]['gender'] = $obj->gender;
2478  } else {
2479  $reparray[] = $obj->rowid;
2480  }
2481  $i++;
2482  }
2483  return $reparray;
2484  } else {
2485  dol_print_error($this->db);
2486  return -1;
2487  }
2488  }
2489 
2497  public function setPriceLevel($price_level, User $user)
2498  {
2499  if ($this->id) {
2500  $now = dol_now();
2501 
2502  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2503  $sql .= " SET price_level = ".((int) $price_level);
2504  $sql .= " WHERE rowid = ".((int) $this->id);
2505 
2506  if (!$this->db->query($sql)) {
2507  dol_print_error($this->db);
2508  return -1;
2509  }
2510 
2511  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2512  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2513  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2514 
2515  if (!$this->db->query($sql)) {
2516  dol_print_error($this->db);
2517  return -1;
2518  }
2519  return 1;
2520  }
2521  return -1;
2522  }
2523 
2524  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2532  public function add_commercial(User $user, $commid)
2533  {
2534  // phpcs:enable
2535  $error = 0;
2536 
2537  if ($this->id > 0 && $commid > 0) {
2538  $this->db->begin();
2539 
2540  if (!$error) {
2541  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2542  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2543 
2544  $resql = $this->db->query($sql);
2545  if (!$resql) {
2546  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2547  $error++;
2548  }
2549  }
2550 
2551  if (!$error) {
2552  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2553  $sql .= " (fk_soc, fk_user)";
2554  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2555 
2556  $resql = $this->db->query($sql);
2557  if (!$resql) {
2558  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2559  $error++;
2560  }
2561  }
2562 
2563  if (!$error) {
2564  $this->context = array('commercial_modified' => $commid);
2565 
2566  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2567  if ($result < 0) {
2568  $error++;
2569  }
2570  }
2571 
2572  if (!$error) {
2573  $this->db->commit();
2574  return 1;
2575  } else {
2576  $this->db->rollback();
2577  return -1;
2578  }
2579  }
2580 
2581  return 0;
2582  }
2583 
2584  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2592  public function del_commercial(User $user, $commid)
2593  {
2594  // phpcs:enable
2595  $error = 0;
2596  $this->context = array('commercial_modified'=>$commid);
2597 
2598  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2599  if ($result < 0) {
2600  $error++;
2601  }
2602 
2603  if ($this->id > 0 && $commid > 0) {
2604  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2605  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2606 
2607  if (!$this->db->query($sql)) {
2608  dol_syslog(get_class($this)."::del_commercial Erreur");
2609  }
2610  }
2611  }
2612 
2620  public function getTooltipContentArray($params)
2621  {
2622  global $conf, $langs, $user;
2623 
2624  $langs->loadLangs(['companies', 'commercial']);
2625 
2626  $datas = array();
2627 
2628  $option = $params['option'] ?? '';
2629  $nofetch = !empty($params['nofetch']);
2630 
2631  $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2632 
2633  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2634  return ['optimize' => $langs->trans("ShowCompany")];
2635  }
2636 
2637  if (!empty($this->logo) && class_exists('Form')) {
2638  $photo = '<div class="photointooltip floatright">';
2639  $photo .= 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.
2640  $photo .= '</div>';
2641  $datas['photo'] = $photo;
2642  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2643  /*$label.= '<div class="photointooltip">';
2644  $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.
2645  $label.= '</div><div style="clear: both;"></div>';*/
2646  }
2647 
2648  $datas['divopen'] = '<div class="centpercent">';
2649 
2650  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2651  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2652  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2653  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2654  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2655  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2656  } elseif ($option == 'agenda') {
2657  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2658  } elseif ($option == 'project') {
2659  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2660  } elseif ($option == 'margin') {
2661  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2662  } elseif ($option == 'contact') {
2663  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2664  } elseif ($option == 'ban') {
2665  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2666  }
2667 
2668  // By default
2669  if (empty($datas['picto'])) {
2670  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2671  }
2672  if (isset($this->status)) {
2673  $datas['status'] = ' '.$this->getLibStatut(5);
2674  }
2675  if (isset($this->client) && isset($this->fournisseur)) {
2676  $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2677  }
2678  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2679  if (!empty($this->name_alias) && empty($noaliasinname)) {
2680  $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2681  }
2682  if (!empty($this->email)) {
2683  $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2684  }
2685  if (!empty($this->url)) {
2686  $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2687  }
2688  if (!empty($this->phone) || !empty($this->fax)) {
2689  $phonelist = array();
2690  if ($this->phone) {
2691  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2692  }
2693  if ($this->fax) {
2694  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2695  }
2696  $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2697  }
2698 
2699  if (!empty($this->address)) {
2700  $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2701  } elseif (!empty($this->country_code)) {
2702  $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2703  }
2704  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2705  $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2706  }
2707 
2708  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2709  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2710  $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2711  }
2712  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2713  $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2714  }
2715  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2716  $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2717  }
2718  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2719  $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2720  }
2721  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2722  $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2723  }
2724  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2725  $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2726  }
2727  }
2728 
2729  $datas['separator'] = '<br>';
2730 
2731  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2732  $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2733  }
2734  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2735  $langs->load('compta');
2736  $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2737  }
2738  // show categories for this record only in ajax to not overload lists
2739  if (!$nofetch && isModEnabled('categorie') && $this->client) {
2740  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2741  $form = new Form($this->db);
2742  $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2743  }
2744  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2745  $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2746  }
2747  if (isModEnabled('accounting') && $this->fournisseur) {
2748  $langs->load('compta');
2749  $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2750  }
2751  // show categories for this record only in ajax to not overload lists
2752  if (!$nofetch && isModEnabled('categorie') && $this->fournisseur) {
2753  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2754  $form = new Form($this->db);
2755  $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2756  }
2757 
2758  $datas['divclose'] = '</div>';
2759 
2760  return $datas;
2761  }
2762 
2775  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2776  {
2777  global $conf, $langs, $hookmanager;
2778 
2779  if (!empty($conf->dol_no_mouse_hover)) {
2780  $notooltip = 1; // Force disable tooltips
2781  }
2782 
2783  $name = $this->name ? $this->name : $this->nom;
2784 
2785  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2786  if (empty($option) && $this->client > 0) {
2787  $option = 'customer';
2788  }
2789  if (empty($option) && $this->fournisseur > 0) {
2790  $option = 'supplier';
2791  }
2792  }
2793 
2794  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2795  $code = '';
2796  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2797  $code = $this->code_client.' - ';
2798  }
2799 
2800  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2801  $code .= $this->code_fournisseur.' - ';
2802  }
2803 
2804  if ($code) {
2805  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2806  $name = $code.' '.$name;
2807  } else {
2808  $name = $code;
2809  }
2810  }
2811  }
2812 
2813  if (!empty($this->name_alias) && empty($noaliasinname)) {
2814  $name .= ' ('.$this->name_alias.')';
2815  }
2816 
2817  $result = '';
2818  $params = [
2819  'id' => $this->id,
2820  'objecttype' => $this->element,
2821  'option' => $option,
2822  'nofetch' => 1,
2823  ];
2824  $classfortooltip = 'classfortooltip';
2825  $dataparams = '';
2826  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2827  $classfortooltip = 'classforajaxtooltip';
2828  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2829  $label = '';
2830  } else {
2831  $label = implode($this->getTooltipContentArray($params));
2832  }
2833 
2834  $linkstart = '';
2835  $linkend = '';
2836 
2837  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2838  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2839  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2840  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2841  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2842  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2843  } elseif ($option == 'agenda') {
2844  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2845  } elseif ($option == 'project') {
2846  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2847  } elseif ($option == 'margin') {
2848  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2849  } elseif ($option == 'contact') {
2850  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2851  } elseif ($option == 'ban') {
2852  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2853  }
2854 
2855  // By default
2856  if (empty($linkstart)) {
2857  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2858  }
2859 
2860  // Add type of canvas
2861  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2862  // Add param to save lastsearch_values or not
2863  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2864  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2865  $add_save_lastsearch_values = 1;
2866  }
2867  if ($add_save_lastsearch_values) {
2868  $linkstart .= '&save_lastsearch_values=1';
2869  }
2870  $linkstart .= '"';
2871 
2872  $linkclose = '';
2873  if (empty($notooltip)) {
2874  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2875  $label = $langs->trans("ShowCompany");
2876  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2877  }
2878  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2879  $linkclose .= $dataparams.' class="'.$classfortooltip.' refurl valignmiddle"';
2880  $target_value = array('_self', '_blank', '_parent', '_top');
2881  if (in_array($target, $target_value)) {
2882  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2883  }
2884  } else {
2885  $linkclose .= ' class="valignmiddle"';
2886  }
2887  $linkstart .= $linkclose.'>';
2888  $linkend = '</a>';
2889 
2890  global $user;
2891  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2892  $linkstart = '';
2893  $linkend = '';
2894  }
2895 
2896  $result .= $linkstart;
2897  if ($withpicto) {
2898  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2899  }
2900  if ($withpicto != 2) {
2901  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2902  }
2903  $result .= $linkend;
2904 
2905  global $action;
2906  $hookmanager->initHooks(array('thirdpartydao'));
2907  $parameters = array(
2908  'id'=>$this->id,
2909  'getnomurl' => &$result,
2910  'withpicto '=> $withpicto,
2911  'option'=> $option,
2912  'maxlen'=> $maxlen,
2913  'notooltip'=> $notooltip,
2914  'save_lastsearch_value'=> $save_lastsearch_value
2915  );
2916  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2917  if ($reshook > 0) {
2918  $result = $hookmanager->resPrint;
2919  } else {
2920  $result .= $hookmanager->resPrint;
2921  }
2922 
2923  return $result;
2924  }
2925 
2935  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2936  {
2937  global $conf, $langs;
2938 
2939  $s = '';
2940  if (empty($option) || preg_match('/prospect/', $option)) {
2941  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2942  $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.'>';
2943  }
2944  }
2945  if (empty($option) || preg_match('/customer/', $option)) {
2946  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2947  $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.'>';
2948  }
2949  }
2950  if (empty($option) || preg_match('/supplier/', $option)) {
2951  if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2952  $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.'>';
2953  }
2954  }
2955  return $s;
2956  }
2957 
2958 
2965  public function getLibStatut($mode = 0)
2966  {
2967  return $this->LibStatut($this->status, $mode);
2968  }
2969 
2970  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2978  public function LibStatut($status, $mode = 0)
2979  {
2980  // phpcs:enable
2981  global $langs;
2982  $langs->load('companies');
2983 
2984  $statusType = 'status4';
2985  if ($status == 0) {
2986  $statusType = 'status6';
2987  }
2988 
2989  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2990  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2991  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2992  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2993  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2994  }
2995 
2996  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2997  }
2998 
2999  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3006  public function thirdparty_and_contact_email_array($addthirdparty = 0)
3007  {
3008  // phpcs:enable
3009  global $langs;
3010 
3011  $contact_emails = $this->contact_property_array('email', 1);
3012  if ($this->email && $addthirdparty) {
3013  if (empty($this->name)) {
3014  $this->name = $this->nom;
3015  }
3016  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
3017  }
3018  //var_dump($contact_emails)
3019  return $contact_emails;
3020  }
3021 
3022  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3029  {
3030  // phpcs:enable
3031  global $langs;
3032 
3033  $contact_phone = $this->contact_property_array('mobile');
3034 
3035  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
3036  if (empty($this->name)) {
3037  $this->name = $this->nom;
3038  }
3039  // TODO: Tester si tel non deja present dans tableau contact
3040  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3041  }
3042  return $contact_phone;
3043  }
3044 
3045  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3053  public function contact_property_array($mode = 'email', $hidedisabled = 0)
3054  {
3055  // phpcs:enable
3056  global $langs;
3057 
3058  $contact_property = array();
3059 
3060 
3061  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3062  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3063  $sql .= " WHERE fk_soc = ".((int) $this->id);
3064  $sql .= " AND entity IN (".getEntity($this->element).")";
3065  $sql .= " ORDER BY lastname, firstname";
3066 
3067  $resql = $this->db->query($sql);
3068  if ($resql) {
3069  $nump = $this->db->num_rows($resql);
3070  if ($nump) {
3071  $sepa = "("; $sepb = ")";
3072  if ($mode == 'email') {
3073  //$sepa="&lt;"; $sepb="&gt;";
3074  $sepa = "<"; $sepb = ">";
3075  }
3076  $i = 0;
3077  while ($i < $nump) {
3078  $obj = $this->db->fetch_object($resql);
3079  if ($mode == 'email') {
3080  $property = $obj->email;
3081  } elseif ($mode == 'mobile') {
3082  $property = $obj->phone_mobile;
3083  } else {
3084  $property = $obj->$mode;
3085  }
3086 
3087  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3088  if ($obj->status == 1 || empty($hidedisabled)) {
3089  if (empty($property)) {
3090  if ($mode == 'email') {
3091  $property = $langs->transnoentitiesnoconv("NoEMail");
3092  } elseif ($mode == 'mobile') {
3093  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3094  }
3095  }
3096 
3097  if (!empty($obj->poste)) {
3098  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3099  } else {
3100  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3101  }
3102  }
3103  $i++;
3104  }
3105  }
3106  } else {
3107  dol_print_error($this->db);
3108  }
3109  return $contact_property;
3110  }
3111 
3112 
3113  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3119  public function contact_array()
3120  {
3121  // phpcs:enable
3122  $contacts = array();
3123 
3124  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3125  $resql = $this->db->query($sql);
3126  if ($resql) {
3127  $nump = $this->db->num_rows($resql);
3128  if ($nump) {
3129  $i = 0;
3130  while ($i < $nump) {
3131  $obj = $this->db->fetch_object($resql);
3132  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3133  $i++;
3134  }
3135  }
3136  } else {
3137  dol_print_error($this->db);
3138  }
3139  return $contacts;
3140  }
3141 
3142  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3148  public function contact_array_objects()
3149  {
3150  // phpcs:enable
3151  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3152  $contacts = array();
3153 
3154  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3155  $resql = $this->db->query($sql);
3156  if ($resql) {
3157  $nump = $this->db->num_rows($resql);
3158  if ($nump) {
3159  $i = 0;
3160  while ($i < $nump) {
3161  $obj = $this->db->fetch_object($resql);
3162  $contact = new Contact($this->db);
3163  $contact->fetch($obj->rowid);
3164  $contacts[] = $contact;
3165  $i++;
3166  }
3167  }
3168  } else {
3169  dol_print_error($this->db);
3170  }
3171  return $contacts;
3172  }
3173 
3174  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3182  public function contact_get_property($rowid, $mode)
3183  {
3184  // phpcs:enable
3185  $contact_property = '';
3186 
3187  if (empty($rowid)) {
3188  return '';
3189  }
3190 
3191  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3192  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3193  $sql .= " WHERE rowid = ".((int) $rowid);
3194 
3195  $resql = $this->db->query($sql);
3196  if ($resql) {
3197  $nump = $this->db->num_rows($resql);
3198 
3199  if ($nump) {
3200  $obj = $this->db->fetch_object($resql);
3201 
3202  if ($mode == 'email') {
3203  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3204  } elseif ($mode == 'mobile') {
3205  $contact_property = $obj->phone_mobile;
3206  }
3207  }
3208  return $contact_property;
3209  } else {
3210  dol_print_error($this->db);
3211  }
3212 
3213  return '';
3214  }
3215 
3216 
3217  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3224  public function display_rib($mode = 'label')
3225  {
3226  // phpcs:enable
3227  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3228 
3229  $bac = new CompanyBankAccount($this->db);
3230  $bac->fetch(0, $this->id);
3231 
3232  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3233  if ($mode == 'label') {
3234  return $bac->getRibLabel(true);
3235  } elseif ($mode == 'rum') {
3236  if (empty($bac->rum)) {
3237  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3238  $prelevement = new BonPrelevement($this->db);
3239  $bac->fetch_thirdparty();
3240  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3241  }
3242  return $bac->rum;
3243  } elseif ($mode == 'format') {
3244  return $bac->frstrecur;
3245  } else {
3246  return 'BadParameterToFunctionDisplayRib';
3247  }
3248  } else {
3249  return '';
3250  }
3251  }
3252 
3253  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3259  public function get_all_rib()
3260  {
3261  // phpcs:enable
3262  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3263  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3264  $result = $this->db->query($sql);
3265  if (!$result) {
3266  $this->error++;
3267  $this->errors[] = $this->db->lasterror;
3268  return 0;
3269  } else {
3270  $num_rows = $this->db->num_rows($result);
3271  $rib_array = array();
3272  if ($num_rows) {
3273  while ($obj = $this->db->fetch_object($result)) {
3274  $rib = new CompanyBankAccount($this->db);
3275  $rib->fetch($obj->rowid);
3276  $rib_array[] = $rib;
3277  }
3278  }
3279  return $rib_array;
3280  }
3281  }
3282 
3283  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3292  public function get_codeclient($objsoc = 0, $type = 0)
3293  {
3294  // phpcs:enable
3295  global $conf;
3296  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3297  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3298 
3299  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3300  foreach ($dirsociete as $dirroot) {
3301  $res = dol_include_once($dirroot.$module.'.php');
3302  if ($res) {
3303  break;
3304  }
3305  }
3306  $mod = new $module();
3307 
3308  $this->code_client = $mod->getNextValue($objsoc, $type);
3309  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3310 
3311  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3312  }
3313  }
3314 
3315  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3324  public function get_codefournisseur($objsoc = 0, $type = 1)
3325  {
3326  // phpcs:enable
3327  global $conf;
3328  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3329  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3330 
3331  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3332  foreach ($dirsociete as $dirroot) {
3333  $res = dol_include_once($dirroot.$module.'.php');
3334  if ($res) {
3335  break;
3336  }
3337  }
3338  $mod = new $module();
3339 
3340  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3341 
3342  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3343  }
3344  }
3345 
3346  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3353  public function codeclient_modifiable()
3354  {
3355  // phpcs:enable
3356  global $conf;
3357  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3358  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3359 
3360  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3361  foreach ($dirsociete as $dirroot) {
3362  $res = dol_include_once($dirroot.$module.'.php');
3363  if ($res) {
3364  break;
3365  }
3366  }
3367 
3368  $mod = new $module();
3369 
3370  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3371  if ($mod->code_modifiable_null && !$this->code_client) {
3372  return 1;
3373  }
3374  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3375  return 1;
3376  }
3377  if ($mod->code_modifiable) {
3378  return 1; // A mettre en dernier
3379  }
3380  return 0;
3381  } else {
3382  return 0;
3383  }
3384  }
3385 
3386 
3387  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3393  public function codefournisseur_modifiable()
3394  {
3395  // phpcs:enable
3396  global $conf;
3397  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3398  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3399 
3400  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3401  foreach ($dirsociete as $dirroot) {
3402  $res = dol_include_once($dirroot.$module.'.php');
3403  if ($res) {
3404  break;
3405  }
3406  }
3407 
3408  $mod = new $module();
3409 
3410  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3411  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3412  return 1;
3413  }
3414  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3415  return 1;
3416  }
3417  if ($mod->code_modifiable) {
3418  return 1; // A mettre en dernier
3419  }
3420  return 0;
3421  } else {
3422  return 0;
3423  }
3424  }
3425 
3426 
3427  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3439  public function check_codeclient()
3440  {
3441  // phpcs:enable
3442  global $conf;
3443  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3444  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3445 
3446  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3447  foreach ($dirsociete as $dirroot) {
3448  $res = dol_include_once($dirroot.$module.'.php');
3449  if ($res) {
3450  break;
3451  }
3452  }
3453 
3454  $mod = new $module();
3455 
3456  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3457  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3458  if ($result) { // If error
3459  $this->error = $mod->error;
3460  $this->errors = $mod->errors;
3461  }
3462  return $result;
3463  } else {
3464  return 0;
3465  }
3466  }
3467 
3468  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3480  public function check_codefournisseur()
3481  {
3482  // phpcs:enable
3483  global $conf;
3484  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3485  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3486 
3487  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3488  foreach ($dirsociete as $dirroot) {
3489  $res = dol_include_once($dirroot.$module.'.php');
3490  if ($res) {
3491  break;
3492  }
3493  }
3494 
3495  $mod = new $module();
3496 
3497  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3498  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3499  if ($result) { // If error
3500  $this->error = $mod->error;
3501  $this->errors = $mod->errors;
3502  }
3503  return $result;
3504  } else {
3505  return 0;
3506  }
3507  }
3508 
3509  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3518  public function get_codecompta($type)
3519  {
3520  // phpcs:enable
3521  global $conf;
3522 
3523  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3524  $res = false;
3525  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3526  foreach ($dirsociete as $dirroot) {
3527  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3528  if ($res) {
3529  break;
3530  }
3531  }
3532 
3533  if ($res) {
3534  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3535  $mod = new $classname;
3536 
3537  // Set code count in $mod->code
3538  $result = $mod->get_code($this->db, $this, $type);
3539 
3540  if ($type == 'customer') {
3541  $this->code_compta_client = $mod->code;
3542  $this->code_compta = $this->code_compta_client; // For backward compatibility
3543  } elseif ($type == 'supplier') {
3544  $this->code_compta_fournisseur = $mod->code;
3545  }
3546 
3547  return $result;
3548  } else {
3549  $this->error = 'ErrorAccountancyCodeNotDefined';
3550  return -1;
3551  }
3552  } else {
3553  if ($type == 'customer') {
3554  $this->code_compta_client = '';
3555  $this->code_compta = '';
3556  } elseif ($type == 'supplier') {
3557  $this->code_compta_fournisseur = '';
3558  }
3559 
3560  return 0;
3561  }
3562  }
3563 
3570  public function setParent($id)
3571  {
3572  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3573 
3574  if ($this->id) {
3575  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3576  if ($id > 0) {
3577  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3578  if ($sameparent < 0) {
3579  return -1;
3580  }
3581  if ($sameparent == 1) {
3582  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3583  return -1;
3584  }
3585  }
3586 
3587  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3588 
3589  $resql = $this->db->query($sql);
3590  if ($resql) {
3591  $this->parent = $id;
3592  return 1;
3593  } else {
3594  return -1;
3595  }
3596  }
3597 
3598  return -1;
3599  }
3600 
3609  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3610  {
3611  if ($counter > 100) {
3612  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3613  }
3614 
3615  $sql = 'SELECT s.parent';
3616  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3617  $sql .= ' WHERE rowid = '.((int) $idparent);
3618  $resql = $this->db->query($sql);
3619  if ($resql) {
3620  $obj = $this->db->fetch_object($resql);
3621 
3622  if ($obj->parent == '') {
3623  return 0;
3624  } elseif ($obj->parent == $idchild) {
3625  return 1;
3626  } else {
3627  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3628  }
3629  return $sameparent;
3630  } else {
3631  return -1;
3632  }
3633  }
3634 
3642  public function getParentsForCompany($company_id, $parents = array())
3643  {
3644  global $langs;
3645 
3646  if ($company_id > 0) {
3647  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3648  $resql = $this->db->query($sql);
3649  if ($resql) {
3650  if ($obj = $this->db->fetch_object($resql)) {
3651  $parent = $obj->parent;
3652  if ($parent > 0 && !in_array($parent, $parents)) {
3653  $parents[] = $parent;
3654  return $this->getParentsForCompany($parent, $parents);
3655  } else {
3656  return $parents;
3657  }
3658  }
3659  $this->db->free($resql);
3660  } else {
3661  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3662  }
3663  }
3664  // Return a default value when $company_id is not greater than 0
3665  return array();
3666  }
3667 
3668  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3675  public function id_prof_verifiable($idprof)
3676  {
3677  // phpcs:enable
3678  global $conf;
3679 
3680  switch ($idprof) {
3681  case 1:
3682  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3683  break;
3684  case 2:
3685  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3686  break;
3687  case 3:
3688  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3689  break;
3690  case 4:
3691  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3692  break;
3693  case 5:
3694  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3695  break;
3696  case 6:
3697  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3698  break;
3699  default:
3700  $ret = false;
3701  }
3702 
3703  return $ret;
3704  }
3705 
3706  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3715  public function id_prof_exists($idprof, $value, $socid = 0)
3716  {
3717  // phpcs:enable
3718  $field = $idprof;
3719 
3720  switch ($idprof) { // For backward compatibility
3721  case '1':
3722  case 'idprof1':
3723  $field = "siren";
3724  break;
3725  case '2':
3726  case 'idprof2':
3727  $field = "siret";
3728  break;
3729  case '3':
3730  case 'idprof3':
3731  $field = "ape";
3732  break;
3733  case '4':
3734  case 'idprof4':
3735  $field = "idprof4";
3736  break;
3737  case '5':
3738  $field = "idprof5";
3739  break;
3740  case '6':
3741  $field = "idprof6";
3742  break;
3743  }
3744 
3745  //Verify duplicate entries
3746  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3747  if ($socid) {
3748  $sql .= " AND rowid <> ".$socid;
3749  }
3750  $resql = $this->db->query($sql);
3751  if ($resql) {
3752  $obj = $this->db->fetch_object($resql);
3753  $count = $obj->nb;
3754  } else {
3755  $count = 0;
3756  print $this->db->error();
3757  }
3758  $this->db->free($resql);
3759 
3760  if ($count > 0) {
3761  return true;
3762  } else {
3763  return false;
3764  }
3765  }
3766 
3767  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3776  public function id_prof_check($idprof, $soc)
3777  {
3778  // phpcs:enable
3779  global $conf;
3780 
3781  $ok = 1;
3782 
3783  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3784  return 1;
3785  }
3786 
3787  // Check SIREN if country FR
3788  if ($idprof == 1 && $soc->country_code == 'FR') {
3789  $chaine = trim($this->idprof1);
3790  $chaine = preg_replace('/(\s)/', '', $chaine);
3791 
3792  if (!is_numeric($chaine)) {
3793  return -1;
3794  }
3795  if (dol_strlen($chaine) != 9) {
3796  return -1;
3797  }
3798 
3799  // on prend chaque chiffre un par un
3800  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3801  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3802  // on ajoute cette valeur à la somme totale
3803  $sum = 0;
3804  for ($index = 0; $index < 9; $index++) {
3805  $number = (int) $chaine[$index];
3806  if (($index % 2) != 0) {
3807  if (($number *= 2) > 9) {
3808  $number -= 9;
3809  }
3810  }
3811  $sum += $number;
3812  }
3813 
3814  // le numéro est valide si la somme des chiffres est multiple de 10
3815  if (($sum % 10) != 0) {
3816  return -1;
3817  }
3818  }
3819 
3820  // Verifie SIRET si pays FR
3821  if ($idprof == 2 && $soc->country_code == 'FR') {
3822  $chaine = trim($this->idprof2);
3823  $chaine = preg_replace('/(\s)/', '', $chaine);
3824 
3825  if (!is_numeric($chaine)) {
3826  return -1;
3827  }
3828  if (dol_strlen($chaine) != 14) {
3829  return -1;
3830  }
3831 
3832  // on prend chaque chiffre un par un
3833  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3834  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3835  // on ajoute cette valeur à la somme totale
3836  $sum = 0;
3837  for ($index = 0; $index < 14; $index++) {
3838  $number = (int) $chaine[$index];
3839  if (($index % 2) == 0) {
3840  if (($number *= 2) > 9) {
3841  $number -= 9;
3842  }
3843  }
3844  $sum += $number;
3845  }
3846 
3847  // le numéro est valide si la somme des chiffres est multiple de 10
3848  if (($sum % 10) != 0) {
3849  return -1;
3850  }
3851  }
3852 
3853  //Verify CIF/NIF/NIE if pays ES
3854  //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
3855  if ($idprof == 1 && $soc->country_code == 'ES') {
3856  $string = trim($this->idprof1);
3857  $string = preg_replace('/(\s)/', '', $string);
3858  $string = strtoupper($string);
3859 
3860  //Check format
3861  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)) {
3862  return 0;
3863  }
3864 
3865  $num = array();
3866  for ($i = 0; $i < 9; $i++) {
3867  $num[$i] = substr($string, $i, 1);
3868  }
3869 
3870  //Check NIF
3871  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3872  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3873  return 1;
3874  } else {
3875  return -1;
3876  }
3877  }
3878 
3879  //algorithm checking type code CIF
3880  $sum = $num[2] + $num[4] + $num[6];
3881  for ($i = 1; $i < 8; $i += 2) {
3882  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3883  }
3884  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3885 
3886  //Chek special NIF
3887  if (preg_match('/^[KLM]{1}/', $string)) {
3888  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3889  return 1;
3890  } else {
3891  return -1;
3892  }
3893  }
3894 
3895  //Check CIF
3896  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3897  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3898  return 2;
3899  } else {
3900  return -2;
3901  }
3902  }
3903 
3904  //Check NIE T
3905  if (preg_match('/^[T]{1}/', $string)) {
3906  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3907  return 3;
3908  } else {
3909  return -3;
3910  }
3911  }
3912 
3913  //Check NIE XYZ
3914  if (preg_match('/^[XYZ]{1}/', $string)) {
3915  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3916  return 3;
3917  } else {
3918  return -3;
3919  }
3920  }
3921 
3922  //Can not be verified
3923  return -4;
3924  }
3925 
3926  //Verify NIF if country is PT
3927  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3928  if ($idprof == 1 && $soc->country_code == 'PT') {
3929  $string = trim($this->idprof1);
3930  $string = preg_replace('/(\s)/', '', $string);
3931 
3932  //Check NIF
3933  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3934  return 1;
3935  } else {
3936  return -1;
3937  }
3938  }
3939 
3940  //Verify NIF if country is DZ
3941  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3942  if ($idprof == 1 && $soc->country_code == 'DZ') {
3943  $string = trim($this->idprof1);
3944  $string = preg_replace('/(\s)/', '', $string);
3945 
3946  //Check NIF
3947  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3948  return 1;
3949  } else {
3950  return -1;
3951  }
3952  }
3953 
3954  return $ok;
3955  }
3956 
3957  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3966  public function id_prof_url($idprof, $thirdparty)
3967  {
3968  // phpcs:enable
3969  global $conf, $langs, $hookmanager;
3970 
3971  $url = '';
3972  $action = '';
3973 
3974  $hookmanager->initHooks(array('idprofurl'));
3975  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3976  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3977  if (empty($reshook)) {
3978  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3979  return '';
3980  }
3981 
3982  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3983  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3984  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3985  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3986  }
3987  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3988  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3989  }
3990  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3991  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3992  }
3993  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3994  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3995  }
3996  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3997  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3998  }
3999  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4000  $url = 'http://www.nif.pt/'.$strippedIdProf1;
4001  }
4002 
4003  if ($url) {
4004  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4005  }
4006  } else {
4007  return $hookmanager->resPrint;
4008  }
4009 
4010  return '';
4011  }
4012 
4013  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4019  public function has_projects()
4020  {
4021  // phpcs:enable
4022  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4023  $resql = $this->db->query($sql);
4024  if ($resql) {
4025  $obj = $this->db->fetch_object($resql);
4026  $count = $obj->numproj;
4027  } else {
4028  $count = 0;
4029  print $this->db->error();
4030  }
4031  $this->db->free($resql);
4032  return ($count > 0);
4033  }
4034 
4035 
4042  public function info($id)
4043  {
4044  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4045  $sql .= " fk_user_creat, fk_user_modif";
4046  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4047  $sql .= " WHERE s.rowid = ".((int) $id);
4048 
4049  $result = $this->db->query($sql);
4050  if ($result) {
4051  if ($this->db->num_rows($result)) {
4052  $obj = $this->db->fetch_object($result);
4053 
4054  $this->id = $obj->rowid;
4055 
4056  $this->user_creation_id = $obj->fk_user_creat;
4057  $this->user_modification_id = $obj->fk_user_modif;
4058  $this->date_creation = $this->db->jdate($obj->datec);
4059  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4060 
4061  $this->ref = $obj->name;
4062  }
4063 
4064  $this->db->free($result);
4065  } else {
4066  dol_print_error($this->db);
4067  }
4068  }
4069 
4075  public function isACompany()
4076  {
4077  global $conf;
4078 
4079  // Define if third party is treated as company (or not) when nature is unknown
4080  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
4081  if (!empty($this->tva_intra)) {
4082  $isacompany = 1;
4083  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4084  $isacompany = 1;
4085  } else {
4086  if (getDolGlobalString('DEFINE_CUSTOMERS_ARE_COMPANIES_BY_TYPE_COMPANY')) {
4087  // TODO Add a field is_a_company into dictionary
4088  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4089  $isacompany = 0;
4090  } else {
4091  $isacompany = 1;
4092  }
4093  } else {
4094  $isacompany = 0;
4095  }
4096  }
4097 
4098  return $isacompany;
4099  }
4100 
4106  public function isInEEC()
4107  {
4108  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4109  return isInEEC($this);
4110  }
4111 
4112  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4118  public function LoadSupplierCateg()
4119  {
4120  // phpcs:enable
4121  $this->SupplierCategories = array();
4122  $sql = "SELECT rowid, label";
4123  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4124  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4125 
4126  $resql = $this->db->query($sql);
4127  if ($resql) {
4128  while ($obj = $this->db->fetch_object($resql)) {
4129  $this->SupplierCategories[$obj->rowid] = $obj->label;
4130  }
4131  return 0;
4132  } else {
4133  return -1;
4134  }
4135  }
4136 
4137  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4144  public function AddFournisseurInCategory($categorie_id)
4145  {
4146  // phpcs:enable
4147  if ($categorie_id > 0 && $this->id > 0) {
4148  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4149  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4150 
4151  if ($resql = $this->db->query($sql)) {
4152  return 0;
4153  }
4154  } else {
4155  return 0;
4156  }
4157  return -1;
4158  }
4159 
4165  public function getNbOfEMailings()
4166  {
4167  $sql = "SELECT count(mc.email) as nb";
4168  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4169  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4170  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4171 
4172  $resql = $this->db->query($sql);
4173  if ($resql) {
4174  $obj = $this->db->fetch_object($resql);
4175  $nb = $obj->nb;
4176 
4177  $this->db->free($resql);
4178  return $nb;
4179  } else {
4180  $this->error = $this->db->error();
4181  return -1;
4182  }
4183  }
4184 
4191  public function setNoEmail($no_email)
4192  {
4193  $error = 0;
4194 
4195  // Update mass emailing flag into table mailing_unsubscribe
4196  if ($this->email) {
4197  $this->db->begin();
4198 
4199  if ($no_email) {
4200  $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)."'";
4201  $resql = $this->db->query($sql);
4202  if ($resql) {
4203  $obj = $this->db->fetch_object($resql);
4204  $noemail = $obj->nb;
4205  if (empty($noemail)) {
4206  $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())."')";
4207  $resql = $this->db->query($sql);
4208  if (!$resql) {
4209  $error++;
4210  $this->error = $this->db->lasterror();
4211  $this->errors[] = $this->error;
4212  }
4213  }
4214  } else {
4215  $error++;
4216  $this->error = $this->db->lasterror();
4217  $this->errors[] = $this->error;
4218  }
4219  } else {
4220  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4221  $resql = $this->db->query($sql);
4222  if (!$resql) {
4223  $error++;
4224  $this->error = $this->db->lasterror();
4225  $this->errors[] = $this->error;
4226  }
4227  }
4228 
4229  if (empty($error)) {
4230  $this->no_email = $no_email;
4231  $this->db->commit();
4232  return 1;
4233  } else {
4234  $this->db->rollback();
4235  return $error * -1;
4236  }
4237  }
4238 
4239  return 0;
4240  }
4241 
4248  public function getNoEmail()
4249  {
4250  if ($this->email) {
4251  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4252  $resql = $this->db->query($sql);
4253  if ($resql) {
4254  $obj = $this->db->fetch_object($resql);
4255  $this->no_email = $obj->nb;
4256  return 1;
4257  } else {
4258  $this->error = $this->db->lasterror();
4259  $this->errors[] = $this->error;
4260  return -1;
4261  }
4262  }
4263  return 0;
4264  }
4265 
4266  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4276  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4277  {
4278  // phpcs:enable
4279  global $conf, $user, $langs;
4280 
4281  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4282  $fullname = $member->getFullName($langs);
4283 
4284  if ($member->morphy == 'mor') {
4285  if (empty($socname)) {
4286  $socname = $member->company? $member->company : $member->societe;
4287  }
4288  if (!empty($fullname) && empty($socalias)) {
4289  $socalias = $fullname;
4290  }
4291  } elseif (empty($socname) && $member->morphy == 'phy') {
4292  if (empty($socname)) {
4293  $socname = $fullname;
4294  }
4295  if (!empty($member->company) && empty($socalias)) {
4296  $socalias = $member->company;
4297  }
4298  }
4299 
4300  $name = $socname;
4301  $alias = $socalias ? $socalias : '';
4302 
4303  // Positionne parametres
4304  $this->nom = $name; // TODO deprecated
4305  $this->name = $name;
4306  $this->name_alias = $alias;
4307  $this->address = $member->address;
4308  $this->zip = $member->zip;
4309  $this->town = $member->town;
4310  $this->country_code = $member->country_code;
4311  $this->country_id = $member->country_id;
4312  $this->phone = $member->phone; // Prof phone
4313  $this->email = $member->email;
4314  $this->socialnetworks = $member->socialnetworks;
4315  $this->entity = $member->entity;
4316 
4317  $this->client = 1; // A member is a customer by default
4318  $this->code_client = ($customercode ? $customercode : -1);
4319  $this->code_fournisseur = -1;
4320  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4321  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4322 
4323  $this->db->begin();
4324 
4325  // Cree et positionne $this->id
4326  $result = $this->create($user);
4327 
4328  if ($result >= 0) {
4329  // Auto-create contact on thirdparty creation
4330  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4331  // Fill fields needed by contact
4332  $this->name_bis = $member->lastname;
4333  $this->firstname = $member->firstname;
4334  $this->civility_id = $member->civility_id;
4335 
4336  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4337  $result = $this->create_individual($user);
4338 
4339  if ($result < 0) {
4340  setEventMessages($this->error, $this->errors, 'errors');
4341  $this->db->rollback();
4342  return -1;
4343  }
4344  }
4345 
4346  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4347  $sql .= " SET fk_soc = ".((int) $this->id);
4348  $sql .= " WHERE rowid = ".((int) $member->id);
4349 
4350  $resql = $this->db->query($sql);
4351  if ($resql) {
4352  $this->db->commit();
4353  return $this->id;
4354  } else {
4355  $this->error = $this->db->error();
4356 
4357  $this->db->rollback();
4358  return -1;
4359  }
4360  } else {
4361  // $this->error deja positionne
4362  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4363 
4364  $this->db->rollback();
4365  return $result;
4366  }
4367  }
4368 
4375  public function setMysoc(Conf $conf)
4376  {
4377  global $langs;
4378 
4379  $this->id = 0;
4380  $this->entity = $conf->entity;
4381  $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4382  $this->nom = $this->name; // deprecated
4383  $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4384  $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4385  $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4386  $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4387 
4388  $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4389 
4390  $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4391 
4392  // We define country_id, country_code and country
4393  $country_id = $country_code = $country_label = '';
4394  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4395  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4396  $country_id = $tmp[0];
4397  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4398  $country_code = $tmp[1];
4399  $country_label = $tmp[2];
4400  } else {
4401  // For backward compatibility
4402  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4403  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4404  $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
4405  $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
4406  }
4407  }
4408  $this->country_id = $country_id;
4409  $this->country_code = $country_code;
4410  $this->country = $country_label;
4411  if (is_object($langs)) {
4412  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4413  }
4414 
4415  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4416  // We define state_id, state_code and state
4417  $state_id = 0; $state_code = $state_label = '';
4418  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4419  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4420  $state_id = $tmp[0];
4421  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4422  $state_code = $tmp[1];
4423  $state_label = $tmp[2];
4424  } else { // For backward compatibility
4425  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);
4426  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4427  $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
4428  $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
4429  }
4430  }
4431  $this->state_id = $state_id;
4432  $this->state_code = $state_code;
4433  $this->state = $state_label;
4434  if (is_object($langs)) {
4435  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4436  }
4437 
4438  $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4439  $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4440  $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4441 
4442  // Social networks
4443  $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4444  $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4445  $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4446  $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4447  $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4448  $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4449  $this->socialnetworks = array();
4450  if (!empty($facebook_url)) {
4451  $this->socialnetworks['facebook'] = $facebook_url;
4452  }
4453  if (!empty($twitter_url)) {
4454  $this->socialnetworks['twitter'] = $twitter_url;
4455  }
4456  if (!empty($linkedin_url)) {
4457  $this->socialnetworks['linkedin'] = $linkedin_url;
4458  }
4459  if (!empty($instagram_url)) {
4460  $this->socialnetworks['instagram'] = $instagram_url;
4461  }
4462  if (!empty($youtube_url)) {
4463  $this->socialnetworks['youtube'] = $youtube_url;
4464  }
4465  if (!empty($github_url)) {
4466  $this->socialnetworks['github'] = $github_url;
4467  }
4468 
4469  // Id prof generiques
4470  $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4471  $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4472  $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4473  $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4474  $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4475  $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4476  $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarly INTRA.
4477  $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4478  $this->capital = getDolGlobalString('MAIN_INFO_CAPITAL');
4479  $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4480  $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4481  $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4482  $this->logo =getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4483  $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4484  $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4485  $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4486  $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4487  $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4488 
4489  // Define if company use vat or not
4490  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4491 
4492  // Define if company use local taxes
4493  $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);
4494  $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);
4495  }
4496 
4504  public function initAsSpecimen()
4505  {
4506  $now = dol_now();
4507 
4508  // Initialize parameters
4509  $this->id = 0;
4510  $this->entity = 1;
4511  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4512  $this->nom = $this->name; // For backward compatibility
4513  $this->ref_ext = 'Ref ext';
4514  $this->specimen = 1;
4515  $this->address = '21 jump street';
4516  $this->zip = '99999';
4517  $this->town = 'MyTown';
4518  $this->state_id = 1;
4519  $this->state_code = 'AA';
4520  $this->state = 'MyState';
4521  $this->country_id = 1;
4522  $this->country_code = 'FR';
4523  $this->email = 'specimen@specimen.com';
4524  $this->socialnetworks = array(
4525  'skype' => 'tom.hanson',
4526  'twitter' => 'tomhanson',
4527  'facebook' => 'tomhanson',
4528  'linkedin' => 'tomhanson',
4529  );
4530  $this->url = 'http://www.specimen.com';
4531 
4532  $this->phone = '0909090901';
4533  $this->fax = '0909090909';
4534 
4535  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4536  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4537  $this->capital = 10000;
4538  $this->client = 1;
4539  $this->prospect = 1;
4540  $this->fournisseur = 1;
4541  $this->tva_assuj = 1;
4542  $this->tva_intra = 'EU1234567';
4543  $this->note_public = 'This is a comment (public)';
4544  $this->note_private = 'This is a comment (private)';
4545 
4546  $this->idprof1 = 'idprof1';
4547  $this->idprof2 = 'idprof2';
4548  $this->idprof3 = 'idprof3';
4549  $this->idprof4 = 'idprof4';
4550  $this->idprof5 = 'idprof5';
4551  $this->idprof6 = 'idprof6';
4552  return 1;
4553  }
4554 
4561  public function useLocalTax($localTaxNum = 0)
4562  {
4563  $sql = "SELECT t.localtax1, t.localtax2";
4564  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4565  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4566  $sql .= " AND t.active = 1";
4567  if (empty($localTaxNum)) {
4568  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4569  } elseif ($localTaxNum == 1) {
4570  $sql .= " AND t.localtax1_type <> '0'";
4571  } elseif ($localTaxNum == 2) {
4572  $sql .= " AND t.localtax2_type <> '0'";
4573  }
4574 
4575  $resql = $this->db->query($sql);
4576  if ($resql) {
4577  return ($this->db->num_rows($resql) > 0);
4578  } else {
4579  return false;
4580  }
4581  }
4582 
4588  public function useNPR()
4589  {
4590  $sql = "SELECT t.rowid";
4591  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4592  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4593  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4594 
4595  dol_syslog("useNPR", LOG_DEBUG);
4596  $resql = $this->db->query($sql);
4597  if ($resql) {
4598  return ($this->db->num_rows($resql) > 0);
4599  } else {
4600  return false;
4601  }
4602  }
4603 
4610  public function useRevenueStamp()
4611  {
4612  $sql = "SELECT COUNT(*) as nb";
4613  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4614  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4615  $sql .= " AND r.active = 1";
4616 
4617  dol_syslog("useRevenueStamp", LOG_DEBUG);
4618  $resql = $this->db->query($sql);
4619  if ($resql) {
4620  $obj = $this->db->fetch_object($resql);
4621  return (($obj->nb > 0) ?true:false);
4622  } else {
4623  $this->error = $this->db->lasterror();
4624  return false;
4625  }
4626  }
4627 
4633  public function getLibProspLevel()
4634  {
4635  return $this->LibProspLevel($this->fk_prospectlevel);
4636  }
4637 
4638  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4645  public function LibProspLevel($fk_prospectlevel)
4646  {
4647  // phpcs:enable
4648  global $langs;
4649 
4650  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4651  // If lib not found in language file, we get label from cache/databse
4652  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4653  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4654  }
4655  return $lib;
4656  }
4657 
4665  public function getLibProspCommStatut($mode = 0, $label = '')
4666  {
4667  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4668  }
4669 
4670  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4684  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4685  {
4686  // phpcs:enable
4687  global $langs;
4688 
4689  $langs->load('customers');
4690 
4691  if ($mode == 2) {
4692  if ($status == '-1' || $status == 'ST_NO') {
4693  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4694  } elseif ($status == '0' || $status == 'ST_NEVER') {
4695  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4696  } elseif ($status == '1' || $status == 'ST_TODO') {
4697  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4698  } elseif ($status == '2' || $status == 'ST_PEND') {
4699  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4700  } elseif ($status == '3' || $status == 'ST_DONE') {
4701  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4702  } else {
4703  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4704  }
4705  } elseif ($mode == 3) {
4706  if ($status == '-1' || $status == 'ST_NO') {
4707  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4708  } elseif ($status == '0' || $status == 'ST_NEVER') {
4709  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4710  } elseif ($status == '1' || $status == 'ST_TODO') {
4711  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4712  } elseif ($status == '2' || $status == 'ST_PEND') {
4713  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4714  } elseif ($status == '3' || $status == 'ST_DONE') {
4715  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4716  } else {
4717  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4718  }
4719  } elseif ($mode == 4) {
4720  if ($status == '-1' || $status == 'ST_NO') {
4721  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4722  } elseif ($status == '0' || $status == 'ST_NEVER') {
4723  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4724  } elseif ($status == '1' || $status == 'ST_TODO') {
4725  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4726  } elseif ($status == '2' || $status == 'ST_PEND') {
4727  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4728  } elseif ($status == '3' || $status == 'ST_DONE') {
4729  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4730  } else {
4731  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4732  }
4733  }
4734 
4735  return "Error, mode/status not found";
4736  }
4737 
4744  public function getOutstandingProposals($mode = 'customer')
4745  {
4746  $table = 'propal';
4747  if ($mode == 'supplier') {
4748  $table = 'supplier_proposal';
4749  }
4750 
4751  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4752  $sql .= " WHERE fk_soc = ".((int) $this->id);
4753  if ($mode == 'supplier') {
4754  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4755  } else {
4756  $sql .= " AND entity IN (".getEntity('propal').")";
4757  }
4758 
4759  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4760 
4761  $resql = $this->db->query($sql);
4762  if ($resql) {
4763  $outstandingOpened = 0;
4764  $outstandingTotal = 0;
4765  $outstandingTotalIncTax = 0;
4766  $arrayofref = array();
4767  while ($obj = $this->db->fetch_object($resql)) {
4768  $arrayofref[$obj->rowid] = $obj->ref;
4769  $outstandingTotal += $obj->total_ht;
4770  $outstandingTotalIncTax += $obj->total_ttc;
4771  if ($obj->status != 0) {
4772  // Not a draft
4773  $outstandingOpened += $obj->total_ttc;
4774  }
4775  }
4776  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4777  } else {
4778  return array();
4779  }
4780  }
4781 
4788  public function getOutstandingOrders($mode = 'customer')
4789  {
4790  $table = 'commande';
4791  if ($mode == 'supplier') {
4792  $table = 'commande_fournisseur';
4793  }
4794 
4795  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4796  $sql .= " WHERE fk_soc = ".((int) $this->id);
4797  if ($mode == 'supplier') {
4798  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4799  } else {
4800  $sql .= " AND entity IN (".getEntity('commande').")";
4801  }
4802 
4803  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4804  $resql = $this->db->query($sql);
4805  if ($resql) {
4806  $outstandingOpened = 0;
4807  $outstandingTotal = 0;
4808  $outstandingTotalIncTax = 0;
4809  $arrayofref = array();
4810  while ($obj = $this->db->fetch_object($resql)) {
4811  $arrayofref[$obj->rowid] = $obj->ref;
4812  $outstandingTotal += $obj->total_ht;
4813  $outstandingTotalIncTax += $obj->total_ttc;
4814  if ($obj->status != 0) {
4815  // Not a draft
4816  $outstandingOpened += $obj->total_ttc;
4817  }
4818  }
4819  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4820  } else {
4821  return array();
4822  }
4823  }
4824 
4832  public function getOutstandingBills($mode = 'customer', $late = 0)
4833  {
4834  $table = 'facture';
4835  if ($mode == 'supplier') {
4836  $table = 'facture_fourn';
4837  }
4838 
4839  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4840  $paiement = $invoice->getSommePaiement();
4841  $creditnotes=$invoice->getSumCreditNotesUsed();
4842  $deposits=$invoice->getSumDepositsUsed();
4843  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4844  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4845  */
4846  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4847  $sql .= " WHERE fk_soc = ".((int) $this->id);
4848  if (!empty($late)) {
4849  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4850  }
4851  if ($mode == 'supplier') {
4852  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4853  } else {
4854  $sql .= " AND entity IN (".getEntity('invoice').")";
4855  }
4856 
4857  dol_syslog("getOutstandingBills", LOG_DEBUG);
4858  $resql = $this->db->query($sql);
4859  if ($resql) {
4860  $outstandingOpened = 0;
4861  $outstandingTotal = 0;
4862  $outstandingTotalIncTax = 0;
4863  $arrayofref = array();
4864  $arrayofrefopened = array();
4865  if ($mode == 'supplier') {
4866  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4867  $tmpobject = new FactureFournisseur($this->db);
4868  } else {
4869  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4870  $tmpobject = new Facture($this->db);
4871  }
4872  while ($obj = $this->db->fetch_object($resql)) {
4873  $arrayofref[$obj->rowid] = $obj->ref;
4874  $tmpobject->id = $obj->rowid;
4875 
4876  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4877  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4878  ) {
4879  $outstandingTotal += $obj->total_ht;
4880  $outstandingTotalIncTax += $obj->total_ttc;
4881  }
4882 
4883  $remaintopay = 0;
4884 
4885  if ($obj->paye == 0
4886  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4887  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4888  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4889  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4890  $paiement = $tmpobject->getSommePaiement();
4891  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4892  $deposits = $tmpobject->getSumDepositsUsed();
4893 
4894  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4895  $outstandingOpened += $remaintopay;
4896  }
4897 
4898  //if credit note is converted but not used
4899  // TODO Do this also for customer ?
4900  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4901  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4902  $remaintopay -= $remainingcreditnote;
4903  $outstandingOpened -= $remainingcreditnote;
4904  }
4905 
4906  if ($remaintopay) {
4907  $arrayofrefopened[$obj->rowid] = $obj->ref;
4908  }
4909  }
4910  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4911  } else {
4912  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4913  return array();
4914  }
4915  }
4916 
4923  public function getLibCustProspStatut()
4924  {
4925  return $this->LibCustProspStatut($this->client);
4926  }
4927 
4928  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4935  public function LibCustProspStatut($status)
4936  {
4937  // phpcs:enable
4938  global $langs;
4939  $langs->load('companies');
4940 
4941  if ($status == 0) {
4942  return $langs->trans("NorProspectNorCustomer");
4943  } elseif ($status == 1) {
4944  return $langs->trans("Customer");
4945  } elseif ($status == 2) {
4946  return $langs->trans("Prospect");
4947  } elseif ($status == 3) {
4948  return $langs->trans("ProspectCustomer");
4949  }
4950 
4951  return '';
4952  }
4953 
4954 
4966  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4967  {
4968  global $conf, $user, $langs;
4969 
4970  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4971  $modelpath = "core/modules/bank/doc/";
4972 
4973  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4974  $companybankaccount = new CompanyBankAccount($this->db);
4975  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4976  if (!$result) {
4977  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4978  }
4979  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4980  } else {
4981  // Positionne le modele sur le nom du modele a utiliser
4982  if (!dol_strlen($modele)) {
4983  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4984  $modele = $conf->global->COMPANY_ADDON_PDF;
4985  } else {
4986  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4987  return 0;
4988  }
4989  }
4990 
4991  if (!isset($this->bank_account)) {
4992  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4993  $bac = new CompanyBankAccount($this->db);
4994  $result = $bac->fetch(0, $this->id);
4995  if ($result > 0) {
4996  $this->bank_account = $bac;
4997  } else {
4998  $this->bank_account = '';
4999  }
5000  }
5001 
5002  $modelpath = "core/modules/societe/doc/";
5003 
5004  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5005  }
5006 
5007  return $result;
5008  }
5009 
5010 
5022  public function setCategories($categories, $type_categ)
5023  {
5024  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5025 
5026  // Decode type
5027  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5028  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5029  return -1;
5030  }
5031 
5032  return parent::setCategoriesCommon($categories, $type_categ);
5033  }
5034 
5042  public function setSalesRep($salesrep, $onlyAdd = false)
5043  {
5044  global $user;
5045 
5046  // Handle single user
5047  if (!is_array($salesrep)) {
5048  $salesrep = array($salesrep);
5049  }
5050 
5051  $to_del = array(); // Nothing to delete
5052  $to_add = $salesrep;
5053  if ($onlyAdd === false) {
5054  // Get current users
5055  $existing = $this->getSalesRepresentatives($user, 1);
5056 
5057  // Diff
5058  if (is_array($existing)) {
5059  $to_del = array_diff($existing, $salesrep);
5060  $to_add = array_diff($salesrep, $existing);
5061  }
5062  }
5063 
5064  $error = 0;
5065 
5066  // Process
5067  foreach ($to_del as $del) {
5068  $this->del_commercial($user, $del);
5069  }
5070  foreach ($to_add as $add) {
5071  $result = $this->add_commercial($user, $add);
5072  if ($result < 0) {
5073  $error++;
5074  break;
5075  }
5076  }
5077 
5078  return $error ? -1 : 1;
5079  }
5080 
5087  public function setThirdpartyType($typent_id)
5088  {
5089  global $user;
5090 
5091  dol_syslog(__METHOD__, LOG_DEBUG);
5092 
5093  if ($this->id) {
5094  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5095 
5096  if ($result > 0) {
5097  $this->typent_id = $typent_id;
5098  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5099  return 1;
5100  } else {
5101  return -1;
5102  }
5103  } else {
5104  return -1;
5105  }
5106  }
5107 
5117  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5118  {
5119  global $conf;
5120 
5121  if ($origin_id == $dest_id) {
5122  dol_syslog('Error: Try to merge a thirdparty into itself');
5123  return false;
5124  }
5125 
5130  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5131  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5132  $sql .= ' SELECT fk_user ';
5133  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5134  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5135 
5136  $resql = $dbs->query($sql);
5137  while ($obj = $dbs->fetch_object($resql)) {
5138  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5139  }
5140 
5145  $tables = array(
5146  'societe_address',
5147  'societe_commerciaux',
5148  'societe_prices',
5149  'societe_remise',
5150  'societe_remise_except',
5151  'societe_rib'
5152  );
5153 
5154 
5155  // Move files from the dir of the third party to delete into the dir of the third party to keep
5156  if (!empty($conf->societe->multidir_output[$conf->entity])) {
5157  $srcdir = $conf->societe->multidir_output[$conf->entity]."/".$origin_id;
5158  $destdir = $conf->societe->multidir_output[$conf->entity]."/".$dest_id;
5159 
5160  if (dol_is_dir($srcdir)) {
5161  $dirlist = dol_dir_list($srcdir, 'files', 1);
5162  foreach ($dirlist as $filetomove) {
5163  $destfile = $destdir.'/'.$filetomove['relativename'];
5164  //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5165  dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5166  }
5167  //exit;
5168  }
5169  }
5170 
5171  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5172  }
5173 
5182  public function setAccountancyCode($type, $value)
5183  {
5184  global $user, $langs, $conf;
5185 
5186  $this->db->begin();
5187 
5188  $field = 'accountancy_code_sell';
5189  if ($type == 'buy') {
5190  $field = 'accountancy_code_buy';
5191  } elseif ($type == 'sell') {
5192  $field = 'accountancy_code_sell';
5193  } else {
5194  return -1;
5195  }
5196 
5197  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5198  $sql .= $field." = '".$this->db->escape($value)."'";
5199  $sql .= " WHERE rowid = ".((int) $this->id);
5200 
5201  dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5202  $resql = $this->db->query($sql);
5203 
5204  if ($resql) {
5205  // Call triggers
5206  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5207  $interface = new Interfaces($this->db);
5208  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5209  if ($result < 0) {
5210  $this->errors = $interface->errors;
5211  $this->db->rollback();
5212  return -1;
5213  }
5214  // End call triggers
5215 
5216  $this->$field = $value;
5217 
5218  $this->db->commit();
5219  return 1;
5220  } else {
5221  $this->error = $this->db->lasterror();
5222  $this->db->rollback();
5223  return -1;
5224  }
5225  }
5226 
5233  public function fetchPartnerships($mode)
5234  {
5235  global $langs;
5236 
5237  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5238 
5239 
5240  $this->partnerships[] = array();
5241 
5242  return 1;
5243  }
5244 
5252  public function getKanbanView($option = '', $arraydata = null)
5253  {
5254  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5255 
5256  $return = '<div class="box-flex-item box-flex-grow-zero">';
5257  $return .= '<div class="info-box info-box-sm">';
5258  $return .= '<span class="info-box-icon bg-infobox-action">';
5259  $return .= img_picto('', $this->picto);
5260  $return .= '</span>';
5261  $return .= '<div class="info-box-content">';
5262  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5263  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5264  if (property_exists($this, 'code_client')) {
5265  $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5266  }
5267 
5268  if (method_exists($this, 'getLibStatut')) {
5269  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
5270  }
5271  $return .= '</div>';
5272  $return .= '</div>';
5273  $return .= '</div>';
5274 
5275  return $return;
5276  }
5277 
5287  public function getContacts($list = 0, $code = '', $element = '')
5288  {
5289  // phpcs:enable
5290  global $langs;
5291 
5292  $tab = array();
5293 
5294  $sql = "SELECT sc.rowid, sc.fk_socpeople as id, sc.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
5295 
5296  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5297 
5298  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5299  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
5300  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5301  $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5302 
5303  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5304 
5305  $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5306  $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5307  if (!empty($element)) {
5308  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5309  }
5310  if ($code) {
5311  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5312  }
5313  $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5314  $sql .= " AND tc.source = 'external'";
5315  $sql .= " AND tc.active=1";
5316 
5317  $sql .= " ORDER BY t.lastname ASC";
5318 
5319  dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5320  $resql = $this->db->query($sql);
5321  if ($resql) {
5322  $num = $this->db->num_rows($resql);
5323  $i = 0;
5324  while ($i < $num) {
5325  $obj = $this->db->fetch_object($resql);
5326 
5327  if (!$list) {
5328  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5329  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
5330  $tab[$i] = array(
5331  'source' => $obj->source,
5332  'socid' => $obj->socid,
5333  'id' => $obj->id,
5334  'nom' => $obj->lastname, // For backward compatibility
5335  'civility' => $obj->civility,
5336  'lastname' => $obj->lastname,
5337  'firstname' => $obj->firstname,
5338  'email'=>$obj->email,
5339  'login'=> (empty($obj->login) ? '' : $obj->login),
5340  'photo' => (empty($obj->photo) ? '' : $obj->photo),
5341  'statuscontact' => $obj->statuscontact,
5342  'rowid' => $obj->rowid,
5343  'code' => $obj->code,
5344  'element' => $obj->element,
5345  'libelle' => $libelle_type,
5346  'status' => $obj->statuslink,
5347  'fk_c_type_contact' => $obj->fk_c_type_contact
5348  );
5349  } else {
5350  $tab[$i] = $obj->id;
5351  }
5352 
5353  $i++;
5354  }
5355 
5356  return $tab;
5357  } else {
5358  $this->error = $this->db->lasterror();
5359  dol_print_error($this->db);
5360  return -1;
5361  }
5362  }
5363 }
$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,...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
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.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
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...
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
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.
create(User $user, $notrigger=0)
Create third party in database.
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.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
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.
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.
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).
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
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.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
getTooltipContentArray($params)
getTooltipContentArray
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:48
trait CommonIncoterm
Superclass for incoterm classes.
trait CommonPeople
Superclass for thirdparties, contacts, members or users.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
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') && $user->hasRight('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') && $user->hasRight('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)) $sql
Social contributions to pay.
Definition: index.php:746
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
Definition: files.lib.php:948
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:1507
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:62
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:453
clean_url($url, $http=1)
Clean an url string.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
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.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message 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.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
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.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages 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.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
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:123