dolibarr  19.0.0-dev
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 && !$notrigger) {
1021  // Call trigger
1022  $result = $this->call_trigger('COMPANY_CREATE', $user);
1023  if ($result < 0) {
1024  $error++;
1025  }
1026  // End call triggers
1027  } else {
1028  $error++;
1029  }
1030 
1031  if (!$error) {
1032  dol_syslog(get_class($this)."::Create success id=".$this->id);
1033  $this->db->commit();
1034  return $this->id;
1035  } else {
1036  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1037  $this->db->rollback();
1038  return -4;
1039  }
1040  } else {
1041  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1042  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1043  $result = -1;
1044  } else {
1045  $this->error = $this->db->lasterror();
1046  $result = -2;
1047  }
1048  $this->db->rollback();
1049  return $result;
1050  }
1051  } else {
1052  $this->db->rollback();
1053  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1054  return -3;
1055  }
1056  }
1057 
1058 
1059  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1069  public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1070  {
1071  global $conf;
1072 
1073  $error = 0;
1074 
1075  $this->db->begin();
1076 
1077  // phpcs:enable
1078  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1079  $contact = new Contact($this->db);
1080 
1081  $contact->name = $this->name_bis;
1082  $contact->firstname = $this->firstname;
1083  $contact->civility_id = $this->civility_id;
1084  $contact->socid = $this->id; // fk_soc
1085  $contact->statut = 1; // deprecated
1086  $contact->status = 1;
1087  $contact->priv = 0;
1088  $contact->country_id = $this->country_id;
1089  $contact->state_id = $this->state_id;
1090  $contact->address = $this->address;
1091  $contact->email = $this->email;
1092  $contact->zip = $this->zip;
1093  $contact->town = $this->town;
1094  $this->setUpperOrLowerCase();
1095  $contact->phone_pro = $this->phone;
1096 
1097  $contactId = $contact->create($user, $notrigger);
1098  if ($contactId < 0) {
1099  $error++;
1100  $this->error = $contact->error;
1101  $this->errors = $contact->errors;
1102  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1103  }
1104 
1105  if (empty($error) && is_array($tags) && !empty($tags)) {
1106  $result = $contact->setCategories($tags);
1107  if ($result < 0) {
1108  $error++;
1109  $this->error = $contact->error;
1110  $this->errors = array_merge($this->errors, $contact->errors);
1111  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1112  $contactId = $result;
1113  }
1114  }
1115 
1116  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1117  $result = $contact->setNoEmail($no_email);
1118  if ($result < 0) {
1119  $this->error = $contact->error;
1120  $this->errors = array_merge($this->errors, $contact->errors);
1121  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1122  $contactId = $result;
1123  }
1124  }
1125 
1126  if (empty($error)) {
1127  dol_syslog(get_class($this)."::create_individual success");
1128  $this->db->commit();
1129  } else {
1130  $this->db->rollback();
1131  }
1132 
1133  return $contactId;
1134  }
1135 
1142  public function verify()
1143  {
1144  global $conf, $langs, $mysoc;
1145 
1146  $error = 0;
1147  $this->errors = array();
1148 
1149  $result = 0;
1150  $this->name = trim($this->name);
1151  $this->nom = $this->name; // For backward compatibility
1152 
1153  if (!$this->name) {
1154  $this->errors[] = 'ErrorBadThirdPartyName';
1155  $result = -2;
1156  }
1157 
1158  if ($this->client) {
1159  $rescode = $this->check_codeclient();
1160  if ($rescode != 0 && $rescode != -5) {
1161  if ($rescode == -1) {
1162  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1163  } elseif ($rescode == -2) {
1164  $this->errors[] = 'ErrorCustomerCodeRequired';
1165  } elseif ($rescode == -3) {
1166  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1167  } elseif ($rescode == -4) {
1168  $this->errors[] = 'ErrorPrefixRequired';
1169  } else {
1170  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1171  }
1172 
1173  $result = -3;
1174  }
1175  }
1176 
1177  if ($this->fournisseur) {
1178  $rescode = $this->check_codefournisseur();
1179  if ($rescode != 0 && $rescode != -5) {
1180  if ($rescode == -1) {
1181  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1182  } elseif ($rescode == -2) {
1183  $this->errors[] = 'ErrorSupplierCodeRequired';
1184  } elseif ($rescode == -3) {
1185  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1186  } elseif ($rescode == -4) {
1187  $this->errors[] = 'ErrorPrefixRequired';
1188  } else {
1189  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1190  }
1191  $result = -3;
1192  }
1193  }
1194 
1195  // Check for duplicate or mandatory fields defined into setup
1196  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1197  foreach ($array_to_check as $key) {
1198  $keymin = strtolower($key);
1199  $i = (int) preg_replace('/[^0-9]/', '', $key);
1200  $vallabel = $this->$keymin;
1201 
1202  if ($i > 0) {
1203  if ($this->isACompany()) {
1204  // Check for mandatory prof id (but only if country is same than ours)
1205  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1206  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1207  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1208  $langs->load("errors");
1209  $error++;
1210  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1211  }
1212  }
1213  }
1214 
1215  // Check for unicity on profid
1216  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1217  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1218  $langs->load("errors");
1219  $error++;
1220  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1221  }
1222  }
1223  } else {
1224  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1225  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1226  if ($key == 'EMAIL') {
1227  // Check for mandatory
1228  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1229  $langs->load("errors");
1230  $error++;
1231  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1232  }
1233 
1234  // Check for unicity
1235  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1236  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1237  $langs->load("errors");
1238  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1239  }
1240  }
1241  } elseif ($key == 'TVA_INTRA') {
1242  // Check for unicity
1243  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1244  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1245  $langs->load("errors");
1246  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1247  }
1248  }
1249  }
1250  }
1251  }
1252 
1253  if ($error) {
1254  $result = -4;
1255  }
1256 
1257  return $result;
1258  }
1259 
1272  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1273  {
1274  global $langs, $conf, $hookmanager;
1275 
1276  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1277 
1278  if (empty($id)) {
1279  $id = $this->id;
1280  }
1281 
1282  $error = 0;
1283 
1284  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1285 
1286  $now = dol_now();
1287 
1288  // Clean parameters
1289  $this->id = $id;
1290  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1291  $this->name = $this->name ? trim($this->name) : trim($this->nom);
1292  $this->nom = $this->name; // For backward compatibility
1293  $this->name_alias = trim($this->name_alias);
1294  $this->ref_ext = trim($this->ref_ext);
1295  $this->address = $this->address ?trim($this->address) : trim($this->address);
1296  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1297  $this->town = $this->town ?trim($this->town) : trim($this->town);
1298  $this->state_id = trim($this->state_id);
1299  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1300  $this->phone = trim($this->phone);
1301  $this->phone = preg_replace("/\s/", "", $this->phone);
1302  $this->phone = preg_replace("/\./", "", $this->phone);
1303  $this->fax = trim($this->fax);
1304  $this->fax = preg_replace("/\s/", "", $this->fax);
1305  $this->fax = preg_replace("/\./", "", $this->fax);
1306  $this->email = trim($this->email);
1307  $this->url = $this->url ?clean_url($this->url, 0) : '';
1308  $this->note_private = trim($this->note_private);
1309  $this->note_public = trim($this->note_public);
1310  $this->idprof1 = trim($this->idprof1);
1311  $this->idprof2 = trim($this->idprof2);
1312  $this->idprof3 = trim($this->idprof3);
1313  $this->idprof4 = trim($this->idprof4);
1314  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1315  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1316  $this->prefix_comm = trim($this->prefix_comm);
1317  $this->outstanding_limit = price2num($this->outstanding_limit);
1318  $this->order_min_amount = price2num($this->order_min_amount);
1319  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1320 
1321  $this->tva_assuj = trim($this->tva_assuj);
1322  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1323  $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? '0' : '1';
1324  if (empty($this->status)) {
1325  $this->status = 0;
1326  }
1327 
1328  if (!empty($this->multicurrency_code)) {
1329  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1330  }
1331  if (empty($this->fk_multicurrency)) {
1332  $this->multicurrency_code = '';
1333  $this->fk_multicurrency = 0;
1334  }
1335 
1336  // Local taxes
1337  $this->localtax1_assuj = trim($this->localtax1_assuj);
1338  $this->localtax2_assuj = trim($this->localtax2_assuj);
1339 
1340  $this->localtax1_value = trim($this->localtax1_value);
1341  $this->localtax2_value = trim($this->localtax2_value);
1342 
1343  if ($this->capital != '') {
1344  $this->capital = price2num(trim($this->capital));
1345  }
1346  if (!is_numeric($this->capital)) {
1347  $this->capital = ''; // '' = undef
1348  }
1349 
1350  $this->effectif_id = trim($this->effectif_id);
1351  $this->forme_juridique_code = trim($this->forme_juridique_code);
1352 
1353  //Gencod
1354  $this->barcode = trim($this->barcode);
1355 
1356  // For automatic creation
1357  if ($this->code_client == -1 || $this->code_client === 'auto') {
1358  $this->get_codeclient($this, 0);
1359  }
1360  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1361  $this->get_codefournisseur($this, 1);
1362  }
1363 
1364  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1365  $this->code_compta = $this->code_compta_client; // for backward compatibility
1366  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1367 
1368  // Check parameters. More tests are done later in the ->verify()
1369  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1370  $langs->load("errors");
1371  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1372  return -1;
1373  }
1374 
1375  $customer = false;
1376  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1377  // If $allowmodcodeclient is set and value is not set, we generate it
1378  if (empty($this->code_compta_client)) {
1379  $ret = $this->get_codecompta('customer');
1380  if ($ret < 0) {
1381  return -1;
1382  }
1383  }
1384 
1385  $customer = true;
1386  }
1387 
1388  $supplier = false;
1389  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1390  // If $allowmodcodefournisseur is set and value is not set, we generate it
1391  if (empty($this->code_compta_fournisseur)) {
1392  $ret = $this->get_codecompta('supplier');
1393  if ($ret < 0) {
1394  return -1;
1395  }
1396  }
1397 
1398  $supplier = true;
1399  }
1400 
1401  //Web services
1402  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1403  $this->webservices_key = trim($this->webservices_key);
1404 
1405  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1406  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1407 
1408  //Incoterms
1409  $this->fk_incoterms = (int) $this->fk_incoterms;
1410  $this->location_incoterms = trim($this->location_incoterms);
1411 
1412  $this->db->begin();
1413 
1414  // Check name is required and codes are ok or unique.
1415  // If error, this->errors[] is filled
1416  $result = 0;
1417  if ($action != 'add' && $action != 'merge') {
1418  // We don't check when update called during a create because verify was already done.
1419  // 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
1420  $result = $this->verify();
1421 
1422  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1423  // So we can update record that were using and old numbering rule.
1424  if (is_array($this->errors)) {
1425  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1426  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1427  unset($this->errors[$key]); // Remove error message
1428  }
1429  }
1430  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1431  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1432  unset($this->errors[$key]); // Remove error message
1433  }
1434  }
1435  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1436  $result = 0;
1437  }
1438  }
1439  }
1440  $this->setUpperOrLowerCase();
1441  if ($result >= 0) {
1442  dol_syslog(get_class($this)."::update verify ok or not done");
1443 
1444  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1445  $sql .= "entity = ".$this->db->escape($this->entity);
1446  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1447  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1448  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1449  $sql .= ",address = '".$this->db->escape($this->address)."'";
1450 
1451  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1452  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1453 
1454  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1455  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1456 
1457  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1458  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1459  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1460  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1461  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1462 
1463  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1464 
1465  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1466  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1467 
1468  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1469  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1470  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1471  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1472  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1473  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1474 
1475  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1476  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1477  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1478  $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1479  }
1480  $sql .= ",status = ".((int) $this->status);
1481 
1482  // Local taxes
1483  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1484  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1485  if ($this->localtax1_assuj == 1) {
1486  if ($this->localtax1_value != '') {
1487  $sql .= ",localtax1_value =".$this->localtax1_value;
1488  } else {
1489  $sql .= ",localtax1_value =0.000";
1490  }
1491  } else {
1492  $sql .= ",localtax1_value =0.000";
1493  }
1494 
1495  if ($this->localtax2_assuj == 1) {
1496  if ($this->localtax2_value != '') {
1497  $sql .= ",localtax2_value =".$this->localtax2_value;
1498  } else {
1499  $sql .= ",localtax2_value =0.000";
1500  }
1501  } else {
1502  $sql .= ",localtax2_value =0.000";
1503  }
1504 
1505  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1506 
1507  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1508 
1509  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1510  if (isset($this->stcomm_id)) {
1511  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1512  }
1513  if (isset($this->typent_id)) {
1514  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1515  }
1516 
1517  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1518 
1519  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1520  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1521  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1522  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1523  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1524  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1525  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1526  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1527 
1528  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1529  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1530  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1531  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1532  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1533  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1534  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1535  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1536  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1537  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1538  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1539  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1540  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1541  if ($customer) {
1542  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1543  }
1544 
1545  if ($supplier) {
1546  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1547  }
1548  }
1549  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1550  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1551 
1552  //Incoterms
1553  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1554  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1555 
1556  if ($customer) {
1557  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1558  }
1559 
1560  if ($supplier) {
1561  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1562  }
1563  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1564  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1565  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1566  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1567  $sql .= " WHERE rowid = ".(int) $id;
1568 
1569  $resql = $this->db->query($sql);
1570  if ($resql) {
1571  if (is_object($this->oldcopy)) { // If we have information on old values
1572  if ($this->oldcopy->country_id != $this->country_id) {
1573  unset($this->country_code);
1574  unset($this->country);
1575  }
1576  if ($this->oldcopy->state_id != $this->state_id) {
1577  unset($this->state_code);
1578  unset($this->state);
1579  }
1580  } else {
1581  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1582  unset($this->country);
1583  unset($this->state_code);
1584  unset($this->state);
1585  }
1586 
1587  $nbrowsaffected = $this->db->affected_rows($resql);
1588 
1589  if (!$error && $nbrowsaffected) {
1590  // Update information on linked member if it is an update
1591  if (!$nosyncmember && isModEnabled('adherent')) {
1592  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1593 
1594  dol_syslog(get_class($this)."::update update linked member");
1595 
1596  $lmember = new Adherent($this->db);
1597  $result = $lmember->fetch(0, 0, $this->id);
1598 
1599  if ($result > 0) {
1600  $lmember->company = $this->name;
1601  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1602  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1603  $lmember->address = $this->address;
1604  $lmember->zip = $this->zip;
1605  $lmember->town = $this->town;
1606  $lmember->email = $this->email;
1607  $lmember->socialnetworks = $this->socialnetworks;
1608  $lmember->phone = $this->phone;
1609  $lmember->state_id = $this->state_id;
1610  $lmember->country_id = $this->country_id;
1611  $lmember->default_lang = $this->default_lang;
1612 
1613  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1614  if ($result < 0) {
1615  $this->error = $lmember->error;
1616  $this->errors = array_merge($this->errors, $lmember->errors);
1617  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1618  $error++;
1619  }
1620  } elseif ($result < 0) {
1621  $this->error = $lmember->error;
1622  $error++;
1623  }
1624  }
1625  }
1626 
1627  $action = 'update';
1628 
1629  // update accountancy for this entity
1630  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1631  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1632 
1633  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1634  $sql .= " fk_soc";
1635  $sql .= ", entity";
1636  $sql .= ", vat_reverse_charge";
1637  $sql .= ", accountancy_code_customer";
1638  $sql .= ", accountancy_code_supplier";
1639  $sql .= ", accountancy_code_buy";
1640  $sql .= ", accountancy_code_sell";
1641  $sql .= ") VALUES (";
1642  $sql .= $this->id;
1643  $sql .= ", ".$conf->entity;
1644  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1645  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1646  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1647  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1648  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1649  $sql .= ")";
1650  $result = $this->db->query($sql);
1651  if (!$result) {
1652  $error++;
1653  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1654  }
1655  }
1656 
1657  // Actions on extra fields
1658  if (!$error) {
1659  $result = $this->insertExtraFields();
1660  if ($result < 0) {
1661  $error++;
1662  }
1663  }
1664  // Actions on extra languages
1665  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1666  $result = $this->insertExtraLanguages();
1667  if ($result < 0) {
1668  $error++;
1669  }
1670  }
1671 
1672  if (!$error && $call_trigger) {
1673  // Call trigger
1674  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1675  if ($result < 0) {
1676  $error++;
1677  }
1678  // End call triggers
1679  }
1680 
1681  if (!$error) {
1682  dol_syslog(get_class($this)."::Update success");
1683  $this->db->commit();
1684  return 1;
1685  } else {
1686  $this->db->rollback();
1687  return -1;
1688  }
1689  } else {
1690  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1691  // Doublon
1692  $this->error = $langs->trans("ErrorDuplicateField");
1693  $result = -1;
1694  } else {
1695  $this->error = $this->db->lasterror();
1696  $result = -2;
1697  }
1698  $this->db->rollback();
1699  return $result;
1700  }
1701  } else {
1702  $this->db->rollback();
1703  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1704  return -3;
1705  }
1706  }
1707 
1725  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1726  {
1727  global $langs;
1728  global $conf;
1729 
1730  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1731  return -1;
1732  }
1733 
1734  $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';
1735  $sql .= ', s.status, s.fk_warehouse';
1736  $sql .= ', s.price_level';
1737  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1738  $sql .= ', s.phone, s.fax, s.email';
1739  $sql .= ', s.socialnetworks';
1740  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1741  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1742  $sql .= ', s.capital, s.tva_intra';
1743  $sql .= ', s.fk_typent as typent_id';
1744  $sql .= ', s.fk_effectif as effectif_id';
1745  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1746  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1747  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1748  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1749  $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1750  } else {
1751  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1752  $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1753  }
1754  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1755  $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';
1756  $sql .= ', s.fk_account, s.tva_assuj';
1757  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1758  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1759  $sql .= ', s.fk_shipping_method';
1760  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1761  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1762  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1763  $sql .= ', fj.libelle as forme_juridique';
1764  $sql .= ', e.libelle as effectif';
1765  $sql .= ', c.code as country_code, c.label as country';
1766  $sql .= ', d.code_departement as state_code, d.nom as state';
1767  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1768  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1769  $sql .= ', te.code as typent_code';
1770  $sql .= ', i.libelle as label_incoterms';
1771  if (!isModEnabled('multicompany')) {
1772  $sql .= ', s.remise_client, s.remise_supplier';
1773  } else {
1774  $sql .= ', sr.remise_client, sr2.remise_supplier';
1775  }
1776  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1777  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1778  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1779  }
1780  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1781  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1782  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1783  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1784  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1785  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1786  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1787  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1788  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1789  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1790  if (isModEnabled('multicompany')) {
1791  $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').'))';
1792  $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').'))';
1793  }
1794  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1795  if ($rowid) {
1796  $sql .= ' AND s.rowid = '.((int) $rowid);
1797  }
1798  if ($ref) {
1799  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1800  }
1801  if ($ref_alias) {
1802  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1803  }
1804  if ($ref_ext) {
1805  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1806  }
1807  if ($barcode) {
1808  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1809  }
1810  if ($idprof1) {
1811  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1812  }
1813  if ($idprof2) {
1814  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1815  }
1816  if ($idprof3) {
1817  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1818  }
1819  if ($idprof4) {
1820  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1821  }
1822  if ($idprof5) {
1823  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1824  }
1825  if ($idprof6) {
1826  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1827  }
1828  if ($email) {
1829  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1830  }
1831 
1832  $resql = $this->db->query($sql);
1833  if ($resql) {
1834  $num = $this->db->num_rows($resql);
1835  if ($num > 1) {
1836  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1837  dol_syslog($this->error, LOG_ERR);
1838  $result = -2;
1839  } elseif ($num) { // $num = 1
1840  $obj = $this->db->fetch_object($resql);
1841 
1842  $this->id = $obj->rowid;
1843  $this->entity = $obj->entity;
1844  $this->canvas = $obj->canvas;
1845 
1846  $this->ref = $obj->rowid;
1847  $this->name = $obj->name;
1848  $this->nom = $obj->name; // deprecated
1849  $this->name_alias = $obj->name_alias;
1850  $this->ref_ext = $obj->ref_ext;
1851 
1852  $this->date_creation = $this->db->jdate($obj->date_creation);
1853  $this->date_modification = $this->db->jdate($obj->date_modification);
1854  $this->user_creation = $obj->fk_user_creat;
1855  $this->user_modification = $obj->fk_user_modif;
1856 
1857  $this->address = $obj->address;
1858  $this->zip = $obj->zip;
1859  $this->town = $obj->town;
1860 
1861  $this->country_id = $obj->country_id;
1862  $this->country_code = $obj->country_id ? $obj->country_code : '';
1863  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1864 
1865  $this->state_id = $obj->state_id;
1866  $this->state_code = $obj->state_code;
1867  $this->region_id = $obj->region_id;
1868  $this->region_code = $obj->region_code;
1869  $this->state = ($obj->state != '-' ? $obj->state : '');
1870 
1871  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1872  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1873  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1874  $this->status_prospect_label = $label; // label status prospect
1875  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1876 
1877  $this->email = $obj->email;
1878  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1879 
1880  $this->url = $obj->url;
1881  $this->phone = $obj->phone;
1882  $this->fax = $obj->fax;
1883 
1884  $this->parent = $obj->parent;
1885 
1886  $this->idprof1 = $obj->idprof1;
1887  $this->idprof2 = $obj->idprof2;
1888  $this->idprof3 = $obj->idprof3;
1889  $this->idprof4 = $obj->idprof4;
1890  $this->idprof5 = $obj->idprof5;
1891  $this->idprof6 = $obj->idprof6;
1892 
1893  $this->capital = $obj->capital;
1894 
1895  $this->code_client = $obj->code_client;
1896  $this->code_fournisseur = $obj->code_fournisseur;
1897 
1898  $this->code_compta = $obj->code_compta; // For backward compatibility
1899  $this->code_compta_client = $obj->code_compta;
1900  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1901 
1902  $this->barcode = $obj->barcode;
1903 
1904  $this->tva_assuj = $obj->tva_assuj;
1905  $this->tva_intra = $obj->tva_intra;
1906 
1907  if (!empty($obj->spe_vat_reverse_charge)) {
1908  $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1909  } elseif (!empty($obj->soc_vat_reverse_charge)) {
1910  $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1911  } else {
1912  $this->vat_reverse_charge = 0;
1913  }
1914 
1915  $this->status = $obj->status;
1916 
1917  // Local Taxes
1918  $this->localtax1_assuj = $obj->localtax1_assuj;
1919  $this->localtax2_assuj = $obj->localtax2_assuj;
1920 
1921  $this->localtax1_value = $obj->localtax1_value;
1922  $this->localtax2_value = $obj->localtax2_value;
1923 
1924  $this->typent_id = $obj->typent_id;
1925  $this->typent_code = $obj->typent_code;
1926 
1927  $this->effectif_id = $obj->effectif_id;
1928  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1929 
1930  $this->forme_juridique_code = $obj->forme_juridique_code;
1931  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1932 
1933  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1934 
1935  $this->prefix_comm = $obj->prefix_comm;
1936 
1937  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1938  $this->remise_supplier_percent = $obj->remise_supplier;
1939 
1940  $this->mode_reglement_id = $obj->mode_reglement;
1941  $this->cond_reglement_id = $obj->cond_reglement;
1942  $this->deposit_percent = $obj->deposit_percent;
1943  $this->transport_mode_id = $obj->transport_mode;
1944  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1945  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1946  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1947  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1948  $this->fk_account = $obj->fk_account;
1949 
1950  $this->client = $obj->client;
1951  $this->fournisseur = $obj->fournisseur;
1952 
1953  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1954  $this->note_private = $obj->note_private;
1955  $this->note_public = $obj->note_public;
1956  $this->model_pdf = $obj->model_pdf;
1957  $this->modelpdf = $obj->model_pdf; // deprecated
1958  $this->default_lang = $obj->default_lang;
1959  $this->logo = $obj->logo;
1960  $this->logo_squarred = $obj->logo_squarred;
1961 
1962  $this->webservices_url = $obj->webservices_url;
1963  $this->webservices_key = $obj->webservices_key;
1964 
1965  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1966  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1967 
1968  $this->outstanding_limit = $obj->outstanding_limit;
1969  $this->order_min_amount = $obj->order_min_amount;
1970  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1971 
1972  // multiprix
1973  $this->price_level = $obj->price_level;
1974 
1975  // warehouse
1976  $this->fk_warehouse = $obj->fk_warehouse;
1977 
1978  $this->import_key = $obj->import_key;
1979 
1980  //Incoterms
1981  $this->fk_incoterms = $obj->fk_incoterms;
1982  $this->location_incoterms = $obj->location_incoterms;
1983  $this->label_incoterms = $obj->label_incoterms;
1984 
1985  // multicurrency
1986  $this->fk_multicurrency = $obj->fk_multicurrency;
1987  $this->multicurrency_code = $obj->multicurrency_code;
1988 
1989  // pdf
1990  $this->model_pdf = $obj->model_pdf;
1991  $this->last_main_doc = $obj->last_main_doc;
1992 
1993  $result = 1;
1994 
1995  // fetch optionals attributes and labels
1996  $this->fetch_optionals();
1997  } else {
1998  $result = 0;
1999  }
2000 
2001  $this->db->free($resql);
2002  } else {
2003  $this->error = $this->db->lasterror();
2004  $this->errors[] = $this->db->lasterror();
2005  $result = -3;
2006  }
2007 
2008  // Use first price level if level not defined for third party
2009  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
2010  $this->price_level = 1;
2011  }
2012 
2013  return $result;
2014  }
2015 
2024  public function delete($id, User $fuser = null, $call_trigger = 1)
2025  {
2026  global $langs, $conf, $user;
2027 
2028  if (empty($fuser)) {
2029  $fuser = $user;
2030  }
2031 
2032  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2033 
2034  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2035 
2036  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2037  $error = 0;
2038 
2039  // Test if child exists
2040  $objectisused = $this->isObjectUsed($id);
2041  if (empty($objectisused)) {
2042  $this->db->begin();
2043 
2044  // User is mandatory for trigger call
2045  if (!$error && $call_trigger) {
2046  // Call trigger
2047  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2048  if ($result < 0) {
2049  $error++;
2050  }
2051  // End call triggers
2052  }
2053 
2054  if (!$error) {
2055  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2056  $static_cat = new Categorie($this->db);
2057  $toute_categs = array();
2058 
2059  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2060  if ($this->client || $this->prospect) {
2061  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2062  }
2063  if ($this->fournisseur) {
2064  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2065  }
2066 
2067  // Remove each "Categorie"
2068  foreach ($toute_categs as $type => $categs_type) {
2069  foreach ($categs_type as $cat) {
2070  $cat->del_type($this, $type);
2071  }
2072  }
2073  }
2074 
2075  if (!$error) {
2076  foreach ($this->childtablesoncascade as $tabletodelete) {
2077  $deleteFromObject = explode(':', $tabletodelete);
2078  if (count($deleteFromObject) >= 2) {
2079  $className = str_replace('@', '', $deleteFromObject[0]);
2080  $filepath = $deleteFromObject[1];
2081  $columnName = $deleteFromObject[2];
2082  if (dol_include_once($filepath)) {
2083  $child_object = new $className($this->db);
2084  $result = $child_object->deleteByParentField($id, $columnName);
2085  if ($result < 0) {
2086  $error++;
2087  $this->errors[] = $child_object->error;
2088  break;
2089  }
2090  } else {
2091  $error++;
2092  $this->errors[] = 'Cannot include child class file '.$filepath;
2093  break;
2094  }
2095  } else {
2096  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2097  $sql .= " WHERE fk_soc = ".((int) $id);
2098  if (!$this->db->query($sql)) {
2099  $error++;
2100  $this->errors[] = $this->db->lasterror();
2101  break;
2102  }
2103  }
2104  }
2105  }
2106 
2107  // Removed extrafields
2108  if (!$error) {
2109  $result = $this->deleteExtraFields();
2110  if ($result < 0) {
2111  $error++;
2112  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2113  }
2114  }
2115 
2116  // Remove links to subsidiaries companies
2117  if (!$error) {
2118  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2119  $sql .= " SET parent = NULL";
2120  $sql .= " WHERE parent = ".((int) $id);
2121  if (!$this->db->query($sql)) {
2122  $error++;
2123  $this->errors[] = $this->db->lasterror();
2124  }
2125  }
2126 
2127  // Remove third party
2128  if (!$error) {
2129  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2130  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2131  $sql .= " WHERE fk_soc = ".((int) $id);
2132  if (!$this->db->query($sql)) {
2133  $error++;
2134  $this->errors[] = $this->db->lasterror();
2135  }
2136  }
2137 
2138  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2139  $sql .= " WHERE rowid = ".((int) $id);
2140  if (!$this->db->query($sql)) {
2141  $error++;
2142  $this->errors[] = $this->db->lasterror();
2143  }
2144  }
2145 
2146  if (!$error) {
2147  $this->db->commit();
2148 
2149  // Delete directory
2150  if (!empty($conf->societe->multidir_output[$entity])) {
2151  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2152  if (dol_is_dir($docdir)) {
2153  dol_delete_dir_recursive($docdir);
2154  }
2155  }
2156 
2157  return 1;
2158  } else {
2159  dol_syslog($this->error, LOG_ERR);
2160  $this->db->rollback();
2161  return -1;
2162  }
2163  } else {
2164  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2165  }
2166  return 0;
2167  }
2168 
2169  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2175  public function set_as_client()
2176  {
2177  // phpcs:enable
2178  if ($this->id) {
2179  $newclient = 1;
2180  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
2181  $newclient = 3; //If prospect, we keep prospect tag
2182  }
2183  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2184  $sql .= " SET client = ".((int) $newclient);
2185  $sql .= " WHERE rowid = ".((int) $this->id);
2186 
2187  $resql = $this->db->query($sql);
2188  if ($resql) {
2189  $this->client = $newclient;
2190  return 1;
2191  } else {
2192  return -1;
2193  }
2194  }
2195  return 0;
2196  }
2197 
2198  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2207  public function set_remise_client($remise, $note, User $user)
2208  {
2209  // phpcs:enable
2210  global $conf, $langs;
2211 
2212  // Parameter cleaning
2213  $note = trim($note);
2214  if (!$note) {
2215  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2216  return -2;
2217  }
2218 
2219  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2220 
2221  if ($this->id) {
2222  $this->db->begin();
2223 
2224  $now = dol_now();
2225 
2226  // Position current discount
2227  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2228  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2229  $sql .= " WHERE rowid = ".((int) $this->id);
2230  $resql = $this->db->query($sql);
2231  if (!$resql) {
2232  $this->db->rollback();
2233  $this->error = $this->db->error();
2234  return -1;
2235  }
2236 
2237  // Writes trace in discount history
2238  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2239  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2240  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2241  $sql .= " '".$this->db->escape($note)."',";
2242  $sql .= " ".((int) $user->id);
2243  $sql .= ")";
2244 
2245  $resql = $this->db->query($sql);
2246  if (!$resql) {
2247  $this->db->rollback();
2248  $this->error = $this->db->lasterror();
2249  return -1;
2250  }
2251 
2252  $this->db->commit();
2253 
2254  return 1;
2255  }
2256  return -1;
2257  }
2258 
2259  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2268  public function set_remise_supplier($remise, $note, User $user)
2269  {
2270  // phpcs:enable
2271  global $conf, $langs;
2272 
2273  // Parameter cleaning
2274  $note = trim($note);
2275  if (!$note) {
2276  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2277  return -2;
2278  }
2279 
2280  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2281 
2282  if ($this->id) {
2283  $this->db->begin();
2284 
2285  $now = dol_now();
2286 
2287  // Position current discount
2288  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2289  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2290  $sql .= " WHERE rowid = ".((int) $this->id);
2291  $resql = $this->db->query($sql);
2292  if (!$resql) {
2293  $this->db->rollback();
2294  $this->error = $this->db->error();
2295  return -1;
2296  }
2297 
2298  // Writes trace in discount history
2299  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2300  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2301  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2302  $sql .= " '".$this->db->escape($note)."',";
2303  $sql .= " ".((int) $user->id);
2304  $sql .= ")";
2305 
2306  $resql = $this->db->query($sql);
2307  if (!$resql) {
2308  $this->db->rollback();
2309  $this->error = $this->db->lasterror();
2310  return -1;
2311  }
2312 
2313  $this->db->commit();
2314  return 1;
2315  }
2316 
2317  return -1;
2318  }
2319 
2320  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2332  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2333  {
2334  // phpcs:enable
2335  global $langs;
2336 
2337  // Clean parameters
2338  $remise = price2num($remise);
2339  $desc = trim($desc);
2340 
2341  // Check parameters
2342  if (!($remise > 0)) {
2343  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2344  return -1;
2345  }
2346  if (!$desc) {
2347  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2348  return -2;
2349  }
2350 
2351  if ($this->id > 0) {
2352  // Clean vat code
2353  $reg = array();
2354  $vat_src_code = '';
2355  if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2356  $vat_src_code = $reg[1];
2357  $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2358  }
2359 
2360  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2361 
2362  $discount = new DiscountAbsolute($this->db);
2363  $discount->fk_soc = $this->id;
2364 
2365  $discount->discount_type = $discount_type;
2366 
2367  if ($price_base_type == 'TTC') {
2368  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2369  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2370  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2371  } else {
2372  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2373  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2374  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2375  }
2376 
2377  $discount->tva_tx = price2num($vatrate);
2378  $discount->vat_src_code = $vat_src_code;
2379 
2380  $discount->description = $desc;
2381 
2382  $result = $discount->create($user);
2383  if ($result > 0) {
2384  return $result;
2385  } else {
2386  $this->error = $discount->error;
2387  return -3;
2388  }
2389  } else {
2390  return 0;
2391  }
2392  }
2393 
2403  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2404  {
2405  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2406 
2407  $discountstatic = new DiscountAbsolute($this->db);
2408  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2409  if ($result >= 0) {
2410  return $result;
2411  } else {
2412  $this->error = $discountstatic->error;
2413  return -1;
2414  }
2415  }
2416 
2426  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2427  {
2428  global $conf;
2429 
2430  $reparray = array();
2431 
2432  $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";
2433  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2434  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2435  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2436  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2437  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2438  $sql .= " AND ug.entity = ".$conf->entity.")";
2439  $sql .= " OR u.admin = 1)";
2440  } else {
2441  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2442  }
2443 
2444  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2445  if (empty($sortfield) && empty($sortorder)) {
2446  $sortfield = 'u.lastname,u.firstname';
2447  $sortorder = 'ASC,ASC';
2448  }
2449  $sql .= $this->db->order($sortfield, $sortorder);
2450 
2451  $resql = $this->db->query($sql);
2452  if ($resql) {
2453  $num = $this->db->num_rows($resql);
2454  $i = 0;
2455  while ($i < $num) {
2456  $obj = $this->db->fetch_object($resql);
2457 
2458  if (empty($mode)) {
2459  $reparray[$i]['id'] = $obj->rowid;
2460  $reparray[$i]['lastname'] = $obj->lastname;
2461  $reparray[$i]['firstname'] = $obj->firstname;
2462  $reparray[$i]['email'] = $obj->email;
2463  $reparray[$i]['phone'] = $obj->office_phone;
2464  $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2465  $reparray[$i]['office_fax'] = $obj->office_fax;
2466  $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2467  $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2468  $reparray[$i]['job'] = $obj->job;
2469  $reparray[$i]['statut'] = $obj->status; // deprecated
2470  $reparray[$i]['status'] = $obj->status;
2471  $reparray[$i]['entity'] = $obj->entity;
2472  $reparray[$i]['login'] = $obj->login;
2473  $reparray[$i]['photo'] = $obj->photo;
2474  $reparray[$i]['gender'] = $obj->gender;
2475  } else {
2476  $reparray[] = $obj->rowid;
2477  }
2478  $i++;
2479  }
2480  return $reparray;
2481  } else {
2482  dol_print_error($this->db);
2483  return -1;
2484  }
2485  }
2486 
2494  public function setPriceLevel($price_level, User $user)
2495  {
2496  if ($this->id) {
2497  $now = dol_now();
2498 
2499  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2500  $sql .= " SET price_level = ".((int) $price_level);
2501  $sql .= " WHERE rowid = ".((int) $this->id);
2502 
2503  if (!$this->db->query($sql)) {
2504  dol_print_error($this->db);
2505  return -1;
2506  }
2507 
2508  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2509  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2510  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2511 
2512  if (!$this->db->query($sql)) {
2513  dol_print_error($this->db);
2514  return -1;
2515  }
2516  return 1;
2517  }
2518  return -1;
2519  }
2520 
2521  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2529  public function add_commercial(User $user, $commid)
2530  {
2531  // phpcs:enable
2532  $error = 0;
2533 
2534  if ($this->id > 0 && $commid > 0) {
2535  $this->db->begin();
2536 
2537  if (!$error) {
2538  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2539  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2540 
2541  $resql = $this->db->query($sql);
2542  if (!$resql) {
2543  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2544  $error++;
2545  }
2546  }
2547 
2548  if (!$error) {
2549  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2550  $sql .= " (fk_soc, fk_user)";
2551  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2552 
2553  $resql = $this->db->query($sql);
2554  if (!$resql) {
2555  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2556  $error++;
2557  }
2558  }
2559 
2560  if (!$error) {
2561  $this->context = array('commercial_modified' => $commid);
2562 
2563  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2564  if ($result < 0) {
2565  $error++;
2566  }
2567  }
2568 
2569  if (!$error) {
2570  $this->db->commit();
2571  return 1;
2572  } else {
2573  $this->db->rollback();
2574  return -1;
2575  }
2576  }
2577 
2578  return 0;
2579  }
2580 
2581  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2589  public function del_commercial(User $user, $commid)
2590  {
2591  // phpcs:enable
2592  $error = 0;
2593  $this->context = array('commercial_modified'=>$commid);
2594 
2595  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2596  if ($result < 0) {
2597  $error++;
2598  }
2599 
2600  if ($this->id > 0 && $commid > 0) {
2601  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2602  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2603 
2604  if (!$this->db->query($sql)) {
2605  dol_syslog(get_class($this)."::del_commercial Erreur");
2606  }
2607  }
2608  }
2609 
2617  public function getTooltipContentArray($params)
2618  {
2619  global $conf, $langs, $user;
2620 
2621  $langs->loadLangs(['companies', 'commercial']);
2622 
2623  $datas = array();
2624 
2625  $option = $params['option'] ?? '';
2626  $nofetch = !empty($params['nofetch']);
2627 
2628  $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2629 
2630  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2631  return ['optimize' => $langs->trans("ShowCompany")];
2632  }
2633 
2634  if (!empty($this->logo) && class_exists('Form')) {
2635  $photo = '<div class="photointooltip floatright">';
2636  $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.
2637  $photo .= '</div>';
2638  $datas['photo'] = $photo;
2639  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2640  /*$label.= '<div class="photointooltip">';
2641  $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.
2642  $label.= '</div><div style="clear: both;"></div>';*/
2643  }
2644 
2645  $datas['divopen'] = '<div class="centpercent">';
2646 
2647  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2648  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2649  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2650  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2651  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2652  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2653  } elseif ($option == 'agenda') {
2654  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2655  } elseif ($option == 'project') {
2656  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2657  } elseif ($option == 'margin') {
2658  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2659  } elseif ($option == 'contact') {
2660  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2661  } elseif ($option == 'ban') {
2662  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2663  }
2664 
2665  // By default
2666  if (empty($datas['picto'])) {
2667  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2668  }
2669  if (isset($this->status)) {
2670  $datas['status'] = ' '.$this->getLibStatut(5);
2671  }
2672  if (isset($this->client) && isset($this->fournisseur)) {
2673  $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2674  }
2675  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2676  if (!empty($this->name_alias) && empty($noaliasinname)) {
2677  $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2678  }
2679  if (!empty($this->email)) {
2680  $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2681  }
2682  if (!empty($this->url)) {
2683  $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2684  }
2685  if (!empty($this->phone) || !empty($this->fax)) {
2686  $phonelist = array();
2687  if ($this->phone) {
2688  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2689  }
2690  if ($this->fax) {
2691  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2692  }
2693  $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2694  }
2695 
2696  if (!empty($this->address)) {
2697  $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2698  } elseif (!empty($this->country_code)) {
2699  $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2700  }
2701  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2702  $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2703  }
2704 
2705  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2706  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2707  $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2708  }
2709  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2710  $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2711  }
2712  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2713  $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2714  }
2715  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2716  $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2717  }
2718  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2719  $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2720  }
2721  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2722  $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2723  }
2724  }
2725 
2726  $datas['separator'] = '<br>';
2727 
2728  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2729  $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2730  }
2731  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2732  $langs->load('compta');
2733  $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2734  }
2735  // show categories for this record only in ajax to not overload lists
2736  if (!$nofetch && isModEnabled('categorie') && $this->client) {
2737  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2738  $form = new Form($this->db);
2739  $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2740  }
2741  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2742  $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2743  }
2744  if (isModEnabled('accounting') && $this->fournisseur) {
2745  $langs->load('compta');
2746  $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2747  }
2748  // show categories for this record only in ajax to not overload lists
2749  if (!$nofetch && isModEnabled('categorie') && $this->fournisseur) {
2750  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2751  $form = new Form($this->db);
2752  $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2753  }
2754 
2755  $datas['divclose'] = '</div>';
2756 
2757  return $datas;
2758  }
2759 
2772  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2773  {
2774  global $conf, $langs, $hookmanager;
2775 
2776  if (!empty($conf->dol_no_mouse_hover)) {
2777  $notooltip = 1; // Force disable tooltips
2778  }
2779 
2780  $name = $this->name ? $this->name : $this->nom;
2781 
2782  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2783  if (empty($option) && $this->client > 0) {
2784  $option = 'customer';
2785  }
2786  if (empty($option) && $this->fournisseur > 0) {
2787  $option = 'supplier';
2788  }
2789  }
2790 
2791  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2792  $code = '';
2793  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2794  $code = $this->code_client.' - ';
2795  }
2796 
2797  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2798  $code .= $this->code_fournisseur.' - ';
2799  }
2800 
2801  if ($code) {
2802  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2803  $name = $code.' '.$name;
2804  } else {
2805  $name = $code;
2806  }
2807  }
2808  }
2809 
2810  if (!empty($this->name_alias) && empty($noaliasinname)) {
2811  $name .= ' ('.$this->name_alias.')';
2812  }
2813 
2814  $result = '';
2815  $params = [
2816  'id' => $this->id,
2817  'objecttype' => $this->element,
2818  'option' => $option,
2819  'nofetch' => 1,
2820  ];
2821  $classfortooltip = 'classfortooltip';
2822  $dataparams = '';
2823  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2824  $classfortooltip = 'classforajaxtooltip';
2825  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2826  $label = '';
2827  } else {
2828  $label = implode($this->getTooltipContentArray($params));
2829  }
2830 
2831  $linkstart = '';
2832  $linkend = '';
2833 
2834  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2835  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2836  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2837  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2838  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2839  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2840  } elseif ($option == 'agenda') {
2841  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2842  } elseif ($option == 'project') {
2843  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2844  } elseif ($option == 'margin') {
2845  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2846  } elseif ($option == 'contact') {
2847  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2848  } elseif ($option == 'ban') {
2849  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2850  }
2851 
2852  // By default
2853  if (empty($linkstart)) {
2854  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2855  }
2856 
2857  // Add type of canvas
2858  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2859  // Add param to save lastsearch_values or not
2860  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2861  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2862  $add_save_lastsearch_values = 1;
2863  }
2864  if ($add_save_lastsearch_values) {
2865  $linkstart .= '&save_lastsearch_values=1';
2866  }
2867  $linkstart .= '"';
2868 
2869  $linkclose = '';
2870  if (empty($notooltip)) {
2871  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2872  $label = $langs->trans("ShowCompany");
2873  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2874  }
2875  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2876  $linkclose .= $dataparams.' class="'.$classfortooltip.' refurl valignmiddle"';
2877  $target_value = array('_self', '_blank', '_parent', '_top');
2878  if (in_array($target, $target_value)) {
2879  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2880  }
2881  } else {
2882  $linkclose .= ' class="valignmiddle"';
2883  }
2884  $linkstart .= $linkclose.'>';
2885  $linkend = '</a>';
2886 
2887  global $user;
2888  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2889  $linkstart = '';
2890  $linkend = '';
2891  }
2892 
2893  $result .= $linkstart;
2894  if ($withpicto) {
2895  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2896  }
2897  if ($withpicto != 2) {
2898  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2899  }
2900  $result .= $linkend;
2901 
2902  global $action;
2903  $hookmanager->initHooks(array('thirdpartydao'));
2904  $parameters = array(
2905  'id'=>$this->id,
2906  'getnomurl' => &$result,
2907  'withpicto '=> $withpicto,
2908  'option'=> $option,
2909  'maxlen'=> $maxlen,
2910  'notooltip'=> $notooltip,
2911  'save_lastsearch_value'=> $save_lastsearch_value
2912  );
2913  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2914  if ($reshook > 0) {
2915  $result = $hookmanager->resPrint;
2916  } else {
2917  $result .= $hookmanager->resPrint;
2918  }
2919 
2920  return $result;
2921  }
2922 
2932  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2933  {
2934  global $conf, $langs;
2935 
2936  $s = '';
2937  if (empty($option) || preg_match('/prospect/', $option)) {
2938  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2939  $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.'>';
2940  }
2941  }
2942  if (empty($option) || preg_match('/customer/', $option)) {
2943  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2944  $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.'>';
2945  }
2946  }
2947  if (empty($option) || preg_match('/supplier/', $option)) {
2948  if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2949  $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.'>';
2950  }
2951  }
2952  return $s;
2953  }
2954 
2955 
2962  public function getLibStatut($mode = 0)
2963  {
2964  return $this->LibStatut($this->status, $mode);
2965  }
2966 
2967  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2975  public function LibStatut($status, $mode = 0)
2976  {
2977  // phpcs:enable
2978  global $langs;
2979  $langs->load('companies');
2980 
2981  $statusType = 'status4';
2982  if ($status == 0) {
2983  $statusType = 'status6';
2984  }
2985 
2986  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2987  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2988  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2989  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2990  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2991  }
2992 
2993  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2994  }
2995 
2996  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3003  public function thirdparty_and_contact_email_array($addthirdparty = 0)
3004  {
3005  // phpcs:enable
3006  global $langs;
3007 
3008  $contact_emails = $this->contact_property_array('email', 1);
3009  if ($this->email && $addthirdparty) {
3010  if (empty($this->name)) {
3011  $this->name = $this->nom;
3012  }
3013  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
3014  }
3015  //var_dump($contact_emails)
3016  return $contact_emails;
3017  }
3018 
3019  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3026  {
3027  // phpcs:enable
3028  global $langs;
3029 
3030  $contact_phone = $this->contact_property_array('mobile');
3031 
3032  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
3033  if (empty($this->name)) {
3034  $this->name = $this->nom;
3035  }
3036  // TODO: Tester si tel non deja present dans tableau contact
3037  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3038  }
3039  return $contact_phone;
3040  }
3041 
3042  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3050  public function contact_property_array($mode = 'email', $hidedisabled = 0)
3051  {
3052  // phpcs:enable
3053  global $langs;
3054 
3055  $contact_property = array();
3056 
3057 
3058  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3059  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3060  $sql .= " WHERE fk_soc = ".((int) $this->id);
3061  $sql .= " ORDER BY lastname, firstname";
3062 
3063  $resql = $this->db->query($sql);
3064  if ($resql) {
3065  $nump = $this->db->num_rows($resql);
3066  if ($nump) {
3067  $sepa = "("; $sepb = ")";
3068  if ($mode == 'email') {
3069  //$sepa="&lt;"; $sepb="&gt;";
3070  $sepa = "<"; $sepb = ">";
3071  }
3072  $i = 0;
3073  while ($i < $nump) {
3074  $obj = $this->db->fetch_object($resql);
3075  if ($mode == 'email') {
3076  $property = $obj->email;
3077  } elseif ($mode == 'mobile') {
3078  $property = $obj->phone_mobile;
3079  } else {
3080  $property = $obj->$mode;
3081  }
3082 
3083  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3084  if ($obj->status == 1 || empty($hidedisabled)) {
3085  if (empty($property)) {
3086  if ($mode == 'email') {
3087  $property = $langs->transnoentitiesnoconv("NoEMail");
3088  } elseif ($mode == 'mobile') {
3089  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3090  }
3091  }
3092 
3093  if (!empty($obj->poste)) {
3094  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3095  } else {
3096  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3097  }
3098  }
3099  $i++;
3100  }
3101  }
3102  } else {
3103  dol_print_error($this->db);
3104  }
3105  return $contact_property;
3106  }
3107 
3108 
3109  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3115  public function contact_array()
3116  {
3117  // phpcs:enable
3118  $contacts = array();
3119 
3120  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3121  $resql = $this->db->query($sql);
3122  if ($resql) {
3123  $nump = $this->db->num_rows($resql);
3124  if ($nump) {
3125  $i = 0;
3126  while ($i < $nump) {
3127  $obj = $this->db->fetch_object($resql);
3128  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3129  $i++;
3130  }
3131  }
3132  } else {
3133  dol_print_error($this->db);
3134  }
3135  return $contacts;
3136  }
3137 
3138  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3144  public function contact_array_objects()
3145  {
3146  // phpcs:enable
3147  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3148  $contacts = array();
3149 
3150  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3151  $resql = $this->db->query($sql);
3152  if ($resql) {
3153  $nump = $this->db->num_rows($resql);
3154  if ($nump) {
3155  $i = 0;
3156  while ($i < $nump) {
3157  $obj = $this->db->fetch_object($resql);
3158  $contact = new Contact($this->db);
3159  $contact->fetch($obj->rowid);
3160  $contacts[] = $contact;
3161  $i++;
3162  }
3163  }
3164  } else {
3165  dol_print_error($this->db);
3166  }
3167  return $contacts;
3168  }
3169 
3170  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3178  public function contact_get_property($rowid, $mode)
3179  {
3180  // phpcs:enable
3181  $contact_property = '';
3182 
3183  if (empty($rowid)) {
3184  return '';
3185  }
3186 
3187  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3188  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3189  $sql .= " WHERE rowid = ".((int) $rowid);
3190 
3191  $resql = $this->db->query($sql);
3192  if ($resql) {
3193  $nump = $this->db->num_rows($resql);
3194 
3195  if ($nump) {
3196  $obj = $this->db->fetch_object($resql);
3197 
3198  if ($mode == 'email') {
3199  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3200  } elseif ($mode == 'mobile') {
3201  $contact_property = $obj->phone_mobile;
3202  }
3203  }
3204  return $contact_property;
3205  } else {
3206  dol_print_error($this->db);
3207  }
3208 
3209  return '';
3210  }
3211 
3212 
3213  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3220  public function display_rib($mode = 'label')
3221  {
3222  // phpcs:enable
3223  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3224 
3225  $bac = new CompanyBankAccount($this->db);
3226  $bac->fetch(0, $this->id);
3227 
3228  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3229  if ($mode == 'label') {
3230  return $bac->getRibLabel(true);
3231  } elseif ($mode == 'rum') {
3232  if (empty($bac->rum)) {
3233  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3234  $prelevement = new BonPrelevement($this->db);
3235  $bac->fetch_thirdparty();
3236  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3237  }
3238  return $bac->rum;
3239  } elseif ($mode == 'format') {
3240  return $bac->frstrecur;
3241  } else {
3242  return 'BadParameterToFunctionDisplayRib';
3243  }
3244  } else {
3245  return '';
3246  }
3247  }
3248 
3249  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3255  public function get_all_rib()
3256  {
3257  // phpcs:enable
3258  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3259  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3260  $result = $this->db->query($sql);
3261  if (!$result) {
3262  $this->error++;
3263  $this->errors[] = $this->db->lasterror;
3264  return 0;
3265  } else {
3266  $num_rows = $this->db->num_rows($result);
3267  $rib_array = array();
3268  if ($num_rows) {
3269  while ($obj = $this->db->fetch_object($result)) {
3270  $rib = new CompanyBankAccount($this->db);
3271  $rib->fetch($obj->rowid);
3272  $rib_array[] = $rib;
3273  }
3274  }
3275  return $rib_array;
3276  }
3277  }
3278 
3279  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3288  public function get_codeclient($objsoc = 0, $type = 0)
3289  {
3290  // phpcs:enable
3291  global $conf;
3292  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3293  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3294 
3295  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3296  foreach ($dirsociete as $dirroot) {
3297  $res = dol_include_once($dirroot.$module.'.php');
3298  if ($res) {
3299  break;
3300  }
3301  }
3302  $mod = new $module();
3303 
3304  $this->code_client = $mod->getNextValue($objsoc, $type);
3305  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3306 
3307  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3308  }
3309  }
3310 
3311  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3320  public function get_codefournisseur($objsoc = 0, $type = 1)
3321  {
3322  // phpcs:enable
3323  global $conf;
3324  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3325  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3326 
3327  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3328  foreach ($dirsociete as $dirroot) {
3329  $res = dol_include_once($dirroot.$module.'.php');
3330  if ($res) {
3331  break;
3332  }
3333  }
3334  $mod = new $module();
3335 
3336  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3337 
3338  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3339  }
3340  }
3341 
3342  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3349  public function codeclient_modifiable()
3350  {
3351  // phpcs:enable
3352  global $conf;
3353  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3354  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3355 
3356  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3357  foreach ($dirsociete as $dirroot) {
3358  $res = dol_include_once($dirroot.$module.'.php');
3359  if ($res) {
3360  break;
3361  }
3362  }
3363 
3364  $mod = new $module();
3365 
3366  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3367  if ($mod->code_modifiable_null && !$this->code_client) {
3368  return 1;
3369  }
3370  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3371  return 1;
3372  }
3373  if ($mod->code_modifiable) {
3374  return 1; // A mettre en dernier
3375  }
3376  return 0;
3377  } else {
3378  return 0;
3379  }
3380  }
3381 
3382 
3383  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3389  public function codefournisseur_modifiable()
3390  {
3391  // phpcs:enable
3392  global $conf;
3393  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3394  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3395 
3396  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3397  foreach ($dirsociete as $dirroot) {
3398  $res = dol_include_once($dirroot.$module.'.php');
3399  if ($res) {
3400  break;
3401  }
3402  }
3403 
3404  $mod = new $module();
3405 
3406  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3407  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3408  return 1;
3409  }
3410  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3411  return 1;
3412  }
3413  if ($mod->code_modifiable) {
3414  return 1; // A mettre en dernier
3415  }
3416  return 0;
3417  } else {
3418  return 0;
3419  }
3420  }
3421 
3422 
3423  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3435  public function check_codeclient()
3436  {
3437  // phpcs:enable
3438  global $conf;
3439  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3440  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3441 
3442  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3443  foreach ($dirsociete as $dirroot) {
3444  $res = dol_include_once($dirroot.$module.'.php');
3445  if ($res) {
3446  break;
3447  }
3448  }
3449 
3450  $mod = new $module();
3451 
3452  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3453  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3454  if ($result) { // If error
3455  $this->error = $mod->error;
3456  $this->errors = $mod->errors;
3457  }
3458  return $result;
3459  } else {
3460  return 0;
3461  }
3462  }
3463 
3464  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3476  public function check_codefournisseur()
3477  {
3478  // phpcs:enable
3479  global $conf;
3480  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3481  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3482 
3483  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3484  foreach ($dirsociete as $dirroot) {
3485  $res = dol_include_once($dirroot.$module.'.php');
3486  if ($res) {
3487  break;
3488  }
3489  }
3490 
3491  $mod = new $module();
3492 
3493  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3494  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3495  if ($result) { // If error
3496  $this->error = $mod->error;
3497  $this->errors = $mod->errors;
3498  }
3499  return $result;
3500  } else {
3501  return 0;
3502  }
3503  }
3504 
3505  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3514  public function get_codecompta($type)
3515  {
3516  // phpcs:enable
3517  global $conf;
3518 
3519  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3520  $res = false;
3521  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3522  foreach ($dirsociete as $dirroot) {
3523  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3524  if ($res) {
3525  break;
3526  }
3527  }
3528 
3529  if ($res) {
3530  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3531  $mod = new $classname;
3532 
3533  // Set code count in $mod->code
3534  $result = $mod->get_code($this->db, $this, $type);
3535 
3536  if ($type == 'customer') {
3537  $this->code_compta_client = $mod->code;
3538  $this->code_compta = $this->code_compta_client; // For backward compatibility
3539  } elseif ($type == 'supplier') {
3540  $this->code_compta_fournisseur = $mod->code;
3541  }
3542 
3543  return $result;
3544  } else {
3545  $this->error = 'ErrorAccountancyCodeNotDefined';
3546  return -1;
3547  }
3548  } else {
3549  if ($type == 'customer') {
3550  $this->code_compta_client = '';
3551  $this->code_compta = '';
3552  } elseif ($type == 'supplier') {
3553  $this->code_compta_fournisseur = '';
3554  }
3555 
3556  return 0;
3557  }
3558  }
3559 
3566  public function setParent($id)
3567  {
3568  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3569 
3570  if ($this->id) {
3571  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3572  if ($id > 0) {
3573  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3574  if ($sameparent < 0) {
3575  return -1;
3576  }
3577  if ($sameparent == 1) {
3578  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3579  return -1;
3580  }
3581  }
3582 
3583  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3584 
3585  $resql = $this->db->query($sql);
3586  if ($resql) {
3587  $this->parent = $id;
3588  return 1;
3589  } else {
3590  return -1;
3591  }
3592  }
3593 
3594  return -1;
3595  }
3596 
3605  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3606  {
3607  if ($counter > 100) {
3608  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3609  }
3610 
3611  $sql = 'SELECT s.parent';
3612  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3613  $sql .= ' WHERE rowid = '.((int) $idparent);
3614  $resql = $this->db->query($sql);
3615  if ($resql) {
3616  $obj = $this->db->fetch_object($resql);
3617 
3618  if ($obj->parent == '') {
3619  return 0;
3620  } elseif ($obj->parent == $idchild) {
3621  return 1;
3622  } else {
3623  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3624  }
3625  return $sameparent;
3626  } else {
3627  return -1;
3628  }
3629  }
3630 
3638  public function getParentsForCompany($company_id, $parents = array())
3639  {
3640  global $langs;
3641 
3642  if ($company_id > 0) {
3643  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3644  $resql = $this->db->query($sql);
3645  if ($resql) {
3646  if ($obj = $this->db->fetch_object($resql)) {
3647  $parent = $obj->parent;
3648  if ($parent > 0 && !in_array($parent, $parents)) {
3649  $parents[] = $parent;
3650  return $this->getParentsForCompany($parent, $parents);
3651  } else {
3652  return $parents;
3653  }
3654  }
3655  $this->db->free($resql);
3656  } else {
3657  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3658  }
3659  }
3660  // Return a default value when $company_id is not greater than 0
3661  return array();
3662  }
3663 
3664  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3671  public function id_prof_verifiable($idprof)
3672  {
3673  // phpcs:enable
3674  global $conf;
3675 
3676  switch ($idprof) {
3677  case 1:
3678  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3679  break;
3680  case 2:
3681  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3682  break;
3683  case 3:
3684  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3685  break;
3686  case 4:
3687  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3688  break;
3689  case 5:
3690  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3691  break;
3692  case 6:
3693  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3694  break;
3695  default:
3696  $ret = false;
3697  }
3698 
3699  return $ret;
3700  }
3701 
3702  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3711  public function id_prof_exists($idprof, $value, $socid = 0)
3712  {
3713  // phpcs:enable
3714  $field = $idprof;
3715 
3716  switch ($idprof) { // For backward compatibility
3717  case '1':
3718  case 'idprof1':
3719  $field = "siren";
3720  break;
3721  case '2':
3722  case 'idprof2':
3723  $field = "siret";
3724  break;
3725  case '3':
3726  case 'idprof3':
3727  $field = "ape";
3728  break;
3729  case '4':
3730  case 'idprof4':
3731  $field = "idprof4";
3732  break;
3733  case '5':
3734  $field = "idprof5";
3735  break;
3736  case '6':
3737  $field = "idprof6";
3738  break;
3739  }
3740 
3741  //Verify duplicate entries
3742  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3743  if ($socid) {
3744  $sql .= " AND rowid <> ".$socid;
3745  }
3746  $resql = $this->db->query($sql);
3747  if ($resql) {
3748  $obj = $this->db->fetch_object($resql);
3749  $count = $obj->nb;
3750  } else {
3751  $count = 0;
3752  print $this->db->error();
3753  }
3754  $this->db->free($resql);
3755 
3756  if ($count > 0) {
3757  return true;
3758  } else {
3759  return false;
3760  }
3761  }
3762 
3763  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3772  public function id_prof_check($idprof, $soc)
3773  {
3774  // phpcs:enable
3775  global $conf;
3776 
3777  $ok = 1;
3778 
3779  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3780  return 1;
3781  }
3782 
3783  // Check SIREN if country FR
3784  if ($idprof == 1 && $soc->country_code == 'FR') {
3785  $chaine = trim($this->idprof1);
3786  $chaine = preg_replace('/(\s)/', '', $chaine);
3787 
3788  if (!is_numeric($chaine)) {
3789  return -1;
3790  }
3791  if (dol_strlen($chaine) != 9) {
3792  return -1;
3793  }
3794 
3795  // on prend chaque chiffre un par un
3796  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3797  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3798  // on ajoute cette valeur à la somme totale
3799  $sum = 0;
3800  for ($index = 0; $index < 9; $index++) {
3801  $number = (int) $chaine[$index];
3802  if (($index % 2) != 0) {
3803  if (($number *= 2) > 9) {
3804  $number -= 9;
3805  }
3806  }
3807  $sum += $number;
3808  }
3809 
3810  // le numéro est valide si la somme des chiffres est multiple de 10
3811  if (($sum % 10) != 0) {
3812  return -1;
3813  }
3814  }
3815 
3816  // Verifie SIRET si pays FR
3817  if ($idprof == 2 && $soc->country_code == 'FR') {
3818  $chaine = trim($this->idprof2);
3819  $chaine = preg_replace('/(\s)/', '', $chaine);
3820 
3821  if (!is_numeric($chaine)) {
3822  return -1;
3823  }
3824  if (dol_strlen($chaine) != 14) {
3825  return -1;
3826  }
3827 
3828  // on prend chaque chiffre un par un
3829  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3830  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3831  // on ajoute cette valeur à la somme totale
3832  $sum = 0;
3833  for ($index = 0; $index < 14; $index++) {
3834  $number = (int) $chaine[$index];
3835  if (($index % 2) == 0) {
3836  if (($number *= 2) > 9) {
3837  $number -= 9;
3838  }
3839  }
3840  $sum += $number;
3841  }
3842 
3843  // le numéro est valide si la somme des chiffres est multiple de 10
3844  if (($sum % 10) != 0) {
3845  return -1;
3846  }
3847  }
3848 
3849  //Verify CIF/NIF/NIE if pays ES
3850  //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
3851  if ($idprof == 1 && $soc->country_code == 'ES') {
3852  $string = trim($this->idprof1);
3853  $string = preg_replace('/(\s)/', '', $string);
3854  $string = strtoupper($string);
3855 
3856  //Check format
3857  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)) {
3858  return 0;
3859  }
3860 
3861  $num = array();
3862  for ($i = 0; $i < 9; $i++) {
3863  $num[$i] = substr($string, $i, 1);
3864  }
3865 
3866  //Check NIF
3867  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3868  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3869  return 1;
3870  } else {
3871  return -1;
3872  }
3873  }
3874 
3875  //algorithm checking type code CIF
3876  $sum = $num[2] + $num[4] + $num[6];
3877  for ($i = 1; $i < 8; $i += 2) {
3878  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3879  }
3880  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3881 
3882  //Chek special NIF
3883  if (preg_match('/^[KLM]{1}/', $string)) {
3884  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3885  return 1;
3886  } else {
3887  return -1;
3888  }
3889  }
3890 
3891  //Check CIF
3892  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3893  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3894  return 2;
3895  } else {
3896  return -2;
3897  }
3898  }
3899 
3900  //Check NIE T
3901  if (preg_match('/^[T]{1}/', $string)) {
3902  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3903  return 3;
3904  } else {
3905  return -3;
3906  }
3907  }
3908 
3909  //Check NIE XYZ
3910  if (preg_match('/^[XYZ]{1}/', $string)) {
3911  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3912  return 3;
3913  } else {
3914  return -3;
3915  }
3916  }
3917 
3918  //Can not be verified
3919  return -4;
3920  }
3921 
3922  //Verify NIF if country is PT
3923  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3924  if ($idprof == 1 && $soc->country_code == 'PT') {
3925  $string = trim($this->idprof1);
3926  $string = preg_replace('/(\s)/', '', $string);
3927 
3928  //Check NIF
3929  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3930  return 1;
3931  } else {
3932  return -1;
3933  }
3934  }
3935 
3936  //Verify NIF if country is DZ
3937  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3938  if ($idprof == 1 && $soc->country_code == 'DZ') {
3939  $string = trim($this->idprof1);
3940  $string = preg_replace('/(\s)/', '', $string);
3941 
3942  //Check NIF
3943  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3944  return 1;
3945  } else {
3946  return -1;
3947  }
3948  }
3949 
3950  return $ok;
3951  }
3952 
3953  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3962  public function id_prof_url($idprof, $thirdparty)
3963  {
3964  // phpcs:enable
3965  global $conf, $langs, $hookmanager;
3966 
3967  $url = '';
3968  $action = '';
3969 
3970  $hookmanager->initHooks(array('idprofurl'));
3971  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3972  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3973  if (empty($reshook)) {
3974  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3975  return '';
3976  }
3977 
3978  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3979  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3980  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3981  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3982  }
3983  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3984  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3985  }
3986  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3987  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3988  }
3989  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3990  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3991  }
3992  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3993  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3994  }
3995  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3996  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3997  }
3998 
3999  if ($url) {
4000  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4001  }
4002  } else {
4003  return $hookmanager->resPrint;
4004  }
4005 
4006  return '';
4007  }
4008 
4009  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4015  public function has_projects()
4016  {
4017  // phpcs:enable
4018  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4019  $resql = $this->db->query($sql);
4020  if ($resql) {
4021  $obj = $this->db->fetch_object($resql);
4022  $count = $obj->numproj;
4023  } else {
4024  $count = 0;
4025  print $this->db->error();
4026  }
4027  $this->db->free($resql);
4028  return ($count > 0);
4029  }
4030 
4031 
4038  public function info($id)
4039  {
4040  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4041  $sql .= " fk_user_creat, fk_user_modif";
4042  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4043  $sql .= " WHERE s.rowid = ".((int) $id);
4044 
4045  $result = $this->db->query($sql);
4046  if ($result) {
4047  if ($this->db->num_rows($result)) {
4048  $obj = $this->db->fetch_object($result);
4049 
4050  $this->id = $obj->rowid;
4051 
4052  $this->user_creation_id = $obj->fk_user_creat;
4053  $this->user_modification_id = $obj->fk_user_modif;
4054  $this->date_creation = $this->db->jdate($obj->datec);
4055  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4056 
4057  $this->ref = $obj->name;
4058  }
4059 
4060  $this->db->free($result);
4061  } else {
4062  dol_print_error($this->db);
4063  }
4064  }
4065 
4071  public function isACompany()
4072  {
4073  global $conf;
4074 
4075  // Define if third party is treated as company (or not) when nature is unknown
4076  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
4077  if (!empty($this->tva_intra)) {
4078  $isacompany = 1;
4079  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4080  $isacompany = 1;
4081  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
4082  // TODO Add a field is_a_company into dictionary
4083  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4084  $isacompany = 0;
4085  } else {
4086  $isacompany = 1;
4087  }
4088  }
4089 
4090  return $isacompany;
4091  }
4092 
4098  public function isInEEC()
4099  {
4100  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4101  return isInEEC($this);
4102  }
4103 
4104  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4110  public function LoadSupplierCateg()
4111  {
4112  // phpcs:enable
4113  $this->SupplierCategories = array();
4114  $sql = "SELECT rowid, label";
4115  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4116  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4117 
4118  $resql = $this->db->query($sql);
4119  if ($resql) {
4120  while ($obj = $this->db->fetch_object($resql)) {
4121  $this->SupplierCategories[$obj->rowid] = $obj->label;
4122  }
4123  return 0;
4124  } else {
4125  return -1;
4126  }
4127  }
4128 
4129  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4136  public function AddFournisseurInCategory($categorie_id)
4137  {
4138  // phpcs:enable
4139  if ($categorie_id > 0 && $this->id > 0) {
4140  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4141  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4142 
4143  if ($resql = $this->db->query($sql)) {
4144  return 0;
4145  }
4146  } else {
4147  return 0;
4148  }
4149  return -1;
4150  }
4151 
4157  public function getNbOfEMailings()
4158  {
4159  $sql = "SELECT count(mc.email) as nb";
4160  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4161  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4162  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4163 
4164  $resql = $this->db->query($sql);
4165  if ($resql) {
4166  $obj = $this->db->fetch_object($resql);
4167  $nb = $obj->nb;
4168 
4169  $this->db->free($resql);
4170  return $nb;
4171  } else {
4172  $this->error = $this->db->error();
4173  return -1;
4174  }
4175  }
4176 
4183  public function setNoEmail($no_email)
4184  {
4185  $error = 0;
4186 
4187  // Update mass emailing flag into table mailing_unsubscribe
4188  if ($this->email) {
4189  $this->db->begin();
4190 
4191  if ($no_email) {
4192  $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)."'";
4193  $resql = $this->db->query($sql);
4194  if ($resql) {
4195  $obj = $this->db->fetch_object($resql);
4196  $noemail = $obj->nb;
4197  if (empty($noemail)) {
4198  $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())."')";
4199  $resql = $this->db->query($sql);
4200  if (!$resql) {
4201  $error++;
4202  $this->error = $this->db->lasterror();
4203  $this->errors[] = $this->error;
4204  }
4205  }
4206  } else {
4207  $error++;
4208  $this->error = $this->db->lasterror();
4209  $this->errors[] = $this->error;
4210  }
4211  } else {
4212  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4213  $resql = $this->db->query($sql);
4214  if (!$resql) {
4215  $error++;
4216  $this->error = $this->db->lasterror();
4217  $this->errors[] = $this->error;
4218  }
4219  }
4220 
4221  if (empty($error)) {
4222  $this->no_email = $no_email;
4223  $this->db->commit();
4224  return 1;
4225  } else {
4226  $this->db->rollback();
4227  return $error * -1;
4228  }
4229  }
4230 
4231  return 0;
4232  }
4233 
4240  public function getNoEmail()
4241  {
4242  if ($this->email) {
4243  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4244  $resql = $this->db->query($sql);
4245  if ($resql) {
4246  $obj = $this->db->fetch_object($resql);
4247  $this->no_email = $obj->nb;
4248  return 1;
4249  } else {
4250  $this->error = $this->db->lasterror();
4251  $this->errors[] = $this->error;
4252  return -1;
4253  }
4254  }
4255  return 0;
4256  }
4257 
4258  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4268  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4269  {
4270  // phpcs:enable
4271  global $conf, $user, $langs;
4272 
4273  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4274  $fullname = $member->getFullName($langs);
4275 
4276  if ($member->morphy == 'mor') {
4277  if (empty($socname)) {
4278  $socname = $member->company? $member->company : $member->societe;
4279  }
4280  if (!empty($fullname) && empty($socalias)) {
4281  $socalias = $fullname;
4282  }
4283  } elseif (empty($socname) && $member->morphy == 'phy') {
4284  if (empty($socname)) {
4285  $socname = $fullname;
4286  }
4287  if (!empty($member->company) && empty($socalias)) {
4288  $socalias = $member->company;
4289  }
4290  }
4291 
4292  $name = $socname;
4293  $alias = $socalias ? $socalias : '';
4294 
4295  // Positionne parametres
4296  $this->nom = $name; // TODO deprecated
4297  $this->name = $name;
4298  $this->name_alias = $alias;
4299  $this->address = $member->address;
4300  $this->zip = $member->zip;
4301  $this->town = $member->town;
4302  $this->country_code = $member->country_code;
4303  $this->country_id = $member->country_id;
4304  $this->phone = $member->phone; // Prof phone
4305  $this->email = $member->email;
4306  $this->socialnetworks = $member->socialnetworks;
4307  $this->entity = $member->entity;
4308 
4309  $this->client = 1; // A member is a customer by default
4310  $this->code_client = ($customercode ? $customercode : -1);
4311  $this->code_fournisseur = -1;
4312  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4313  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4314 
4315  $this->db->begin();
4316 
4317  // Cree et positionne $this->id
4318  $result = $this->create($user);
4319 
4320  if ($result >= 0) {
4321  // Auto-create contact on thirdparty creation
4322  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4323  // Fill fields needed by contact
4324  $this->name_bis = $member->lastname;
4325  $this->firstname = $member->firstname;
4326  $this->civility_id = $member->civility_id;
4327 
4328  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4329  $result = $this->create_individual($user);
4330 
4331  if ($result < 0) {
4332  setEventMessages($this->error, $this->errors, 'errors');
4333  $this->db->rollback();
4334  return -1;
4335  }
4336  }
4337 
4338  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4339  $sql .= " SET fk_soc = ".((int) $this->id);
4340  $sql .= " WHERE rowid = ".((int) $member->id);
4341 
4342  $resql = $this->db->query($sql);
4343  if ($resql) {
4344  $this->db->commit();
4345  return $this->id;
4346  } else {
4347  $this->error = $this->db->error();
4348 
4349  $this->db->rollback();
4350  return -1;
4351  }
4352  } else {
4353  // $this->error deja positionne
4354  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4355 
4356  $this->db->rollback();
4357  return $result;
4358  }
4359  }
4360 
4367  public function setMysoc(Conf $conf)
4368  {
4369  global $langs;
4370 
4371  $this->id = 0;
4372  $this->entity = $conf->entity;
4373  $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4374  $this->nom = $this->name; // deprecated
4375  $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4376  $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4377  $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4378  $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4379 
4380  $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4381 
4382  $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4383 
4384  // We define country_id, country_code and country
4385  $country_id = $country_code = $country_label = '';
4386  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4387  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4388  $country_id = $tmp[0];
4389  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4390  $country_code = $tmp[1];
4391  $country_label = $tmp[2];
4392  } else {
4393  // For backward compatibility
4394  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4395  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4396  $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
4397  $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
4398  }
4399  }
4400  $this->country_id = $country_id;
4401  $this->country_code = $country_code;
4402  $this->country = $country_label;
4403  if (is_object($langs)) {
4404  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4405  }
4406 
4407  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4408  // We define state_id, state_code and state
4409  $state_id = 0; $state_code = $state_label = '';
4410  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4411  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4412  $state_id = $tmp[0];
4413  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4414  $state_code = $tmp[1];
4415  $state_label = $tmp[2];
4416  } else { // For backward compatibility
4417  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);
4418  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4419  $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
4420  $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
4421  }
4422  }
4423  $this->state_id = $state_id;
4424  $this->state_code = $state_code;
4425  $this->state = $state_label;
4426  if (is_object($langs)) {
4427  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4428  }
4429 
4430  $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4431  $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4432  $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4433 
4434  // Social networks
4435  $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4436  $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4437  $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4438  $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4439  $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4440  $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4441  $this->socialnetworks = array();
4442  if (!empty($facebook_url)) {
4443  $this->socialnetworks['facebook'] = $facebook_url;
4444  }
4445  if (!empty($twitter_url)) {
4446  $this->socialnetworks['twitter'] = $twitter_url;
4447  }
4448  if (!empty($linkedin_url)) {
4449  $this->socialnetworks['linkedin'] = $linkedin_url;
4450  }
4451  if (!empty($instagram_url)) {
4452  $this->socialnetworks['instagram'] = $instagram_url;
4453  }
4454  if (!empty($youtube_url)) {
4455  $this->socialnetworks['youtube'] = $youtube_url;
4456  }
4457  if (!empty($github_url)) {
4458  $this->socialnetworks['github'] = $github_url;
4459  }
4460 
4461  // Id prof generiques
4462  $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4463  $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4464  $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4465  $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4466  $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4467  $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4468  $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarly INTRA.
4469  $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4470  $this->capital = getDolGlobalString('MAIN_INFO_CAPITAL');
4471  $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4472  $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4473  $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4474  $this->logo =getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4475  $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4476  $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4477  $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4478  $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4479  $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4480 
4481  // Define if company use vat or not
4482  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4483 
4484  // Define if company use local taxes
4485  $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);
4486  $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);
4487  }
4488 
4496  public function initAsSpecimen()
4497  {
4498  $now = dol_now();
4499 
4500  // Initialize parameters
4501  $this->id = 0;
4502  $this->entity = 1;
4503  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4504  $this->nom = $this->name; // For backward compatibility
4505  $this->ref_ext = 'Ref ext';
4506  $this->specimen = 1;
4507  $this->address = '21 jump street';
4508  $this->zip = '99999';
4509  $this->town = 'MyTown';
4510  $this->state_id = 1;
4511  $this->state_code = 'AA';
4512  $this->state = 'MyState';
4513  $this->country_id = 1;
4514  $this->country_code = 'FR';
4515  $this->email = 'specimen@specimen.com';
4516  $this->socialnetworks = array(
4517  'skype' => 'tom.hanson',
4518  'twitter' => 'tomhanson',
4519  'facebook' => 'tomhanson',
4520  'linkedin' => 'tomhanson',
4521  );
4522  $this->url = 'http://www.specimen.com';
4523 
4524  $this->phone = '0909090901';
4525  $this->fax = '0909090909';
4526 
4527  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4528  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4529  $this->capital = 10000;
4530  $this->client = 1;
4531  $this->prospect = 1;
4532  $this->fournisseur = 1;
4533  $this->tva_assuj = 1;
4534  $this->tva_intra = 'EU1234567';
4535  $this->note_public = 'This is a comment (public)';
4536  $this->note_private = 'This is a comment (private)';
4537 
4538  $this->idprof1 = 'idprof1';
4539  $this->idprof2 = 'idprof2';
4540  $this->idprof3 = 'idprof3';
4541  $this->idprof4 = 'idprof4';
4542  $this->idprof5 = 'idprof5';
4543  $this->idprof6 = 'idprof6';
4544  return 1;
4545  }
4546 
4553  public function useLocalTax($localTaxNum = 0)
4554  {
4555  $sql = "SELECT t.localtax1, t.localtax2";
4556  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4557  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4558  $sql .= " AND t.active = 1";
4559  if (empty($localTaxNum)) {
4560  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4561  } elseif ($localTaxNum == 1) {
4562  $sql .= " AND t.localtax1_type <> '0'";
4563  } elseif ($localTaxNum == 2) {
4564  $sql .= " AND t.localtax2_type <> '0'";
4565  }
4566 
4567  $resql = $this->db->query($sql);
4568  if ($resql) {
4569  return ($this->db->num_rows($resql) > 0);
4570  } else {
4571  return false;
4572  }
4573  }
4574 
4580  public function useNPR()
4581  {
4582  $sql = "SELECT t.rowid";
4583  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4584  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4585  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4586 
4587  dol_syslog("useNPR", LOG_DEBUG);
4588  $resql = $this->db->query($sql);
4589  if ($resql) {
4590  return ($this->db->num_rows($resql) > 0);
4591  } else {
4592  return false;
4593  }
4594  }
4595 
4602  public function useRevenueStamp()
4603  {
4604  $sql = "SELECT COUNT(*) as nb";
4605  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4606  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4607  $sql .= " AND r.active = 1";
4608 
4609  dol_syslog("useRevenueStamp", LOG_DEBUG);
4610  $resql = $this->db->query($sql);
4611  if ($resql) {
4612  $obj = $this->db->fetch_object($resql);
4613  return (($obj->nb > 0) ?true:false);
4614  } else {
4615  $this->error = $this->db->lasterror();
4616  return false;
4617  }
4618  }
4619 
4625  public function getLibProspLevel()
4626  {
4627  return $this->LibProspLevel($this->fk_prospectlevel);
4628  }
4629 
4630  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4637  public function LibProspLevel($fk_prospectlevel)
4638  {
4639  // phpcs:enable
4640  global $langs;
4641 
4642  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4643  // If lib not found in language file, we get label from cache/databse
4644  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4645  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4646  }
4647  return $lib;
4648  }
4649 
4657  public function getLibProspCommStatut($mode = 0, $label = '')
4658  {
4659  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4660  }
4661 
4662  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4676  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4677  {
4678  // phpcs:enable
4679  global $langs;
4680 
4681  $langs->load('customers');
4682 
4683  if ($mode == 2) {
4684  if ($status == '-1' || $status == 'ST_NO') {
4685  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4686  } elseif ($status == '0' || $status == 'ST_NEVER') {
4687  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4688  } elseif ($status == '1' || $status == 'ST_TODO') {
4689  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4690  } elseif ($status == '2' || $status == 'ST_PEND') {
4691  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4692  } elseif ($status == '3' || $status == 'ST_DONE') {
4693  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4694  } else {
4695  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);
4696  }
4697  } elseif ($mode == 3) {
4698  if ($status == '-1' || $status == 'ST_NO') {
4699  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4700  } elseif ($status == '0' || $status == 'ST_NEVER') {
4701  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4702  } elseif ($status == '1' || $status == 'ST_TODO') {
4703  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4704  } elseif ($status == '2' || $status == 'ST_PEND') {
4705  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4706  } elseif ($status == '3' || $status == 'ST_DONE') {
4707  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4708  } else {
4709  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4710  }
4711  } elseif ($mode == 4) {
4712  if ($status == '-1' || $status == 'ST_NO') {
4713  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4714  } elseif ($status == '0' || $status == 'ST_NEVER') {
4715  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4716  } elseif ($status == '1' || $status == 'ST_TODO') {
4717  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4718  } elseif ($status == '2' || $status == 'ST_PEND') {
4719  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4720  } elseif ($status == '3' || $status == 'ST_DONE') {
4721  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4722  } else {
4723  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);
4724  }
4725  }
4726 
4727  return "Error, mode/status not found";
4728  }
4729 
4736  public function getOutstandingProposals($mode = 'customer')
4737  {
4738  $table = 'propal';
4739  if ($mode == 'supplier') {
4740  $table = 'supplier_proposal';
4741  }
4742 
4743  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4744  $sql .= " WHERE fk_soc = ".((int) $this->id);
4745  if ($mode == 'supplier') {
4746  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4747  } else {
4748  $sql .= " AND entity IN (".getEntity('propal').")";
4749  }
4750 
4751  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4752 
4753  $resql = $this->db->query($sql);
4754  if ($resql) {
4755  $outstandingOpened = 0;
4756  $outstandingTotal = 0;
4757  $outstandingTotalIncTax = 0;
4758  $arrayofref = array();
4759  while ($obj = $this->db->fetch_object($resql)) {
4760  $arrayofref[$obj->rowid] = $obj->ref;
4761  $outstandingTotal += $obj->total_ht;
4762  $outstandingTotalIncTax += $obj->total_ttc;
4763  if ($obj->status != 0) {
4764  // Not a draft
4765  $outstandingOpened += $obj->total_ttc;
4766  }
4767  }
4768  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4769  } else {
4770  return array();
4771  }
4772  }
4773 
4780  public function getOutstandingOrders($mode = 'customer')
4781  {
4782  $table = 'commande';
4783  if ($mode == 'supplier') {
4784  $table = 'commande_fournisseur';
4785  }
4786 
4787  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4788  $sql .= " WHERE fk_soc = ".((int) $this->id);
4789  if ($mode == 'supplier') {
4790  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4791  } else {
4792  $sql .= " AND entity IN (".getEntity('commande').")";
4793  }
4794 
4795  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4796  $resql = $this->db->query($sql);
4797  if ($resql) {
4798  $outstandingOpened = 0;
4799  $outstandingTotal = 0;
4800  $outstandingTotalIncTax = 0;
4801  $arrayofref = array();
4802  while ($obj = $this->db->fetch_object($resql)) {
4803  $arrayofref[$obj->rowid] = $obj->ref;
4804  $outstandingTotal += $obj->total_ht;
4805  $outstandingTotalIncTax += $obj->total_ttc;
4806  if ($obj->status != 0) {
4807  // Not a draft
4808  $outstandingOpened += $obj->total_ttc;
4809  }
4810  }
4811  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4812  } else {
4813  return array();
4814  }
4815  }
4816 
4824  public function getOutstandingBills($mode = 'customer', $late = 0)
4825  {
4826  $table = 'facture';
4827  if ($mode == 'supplier') {
4828  $table = 'facture_fourn';
4829  }
4830 
4831  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4832  $paiement = $invoice->getSommePaiement();
4833  $creditnotes=$invoice->getSumCreditNotesUsed();
4834  $deposits=$invoice->getSumDepositsUsed();
4835  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4836  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4837  */
4838  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4839  $sql .= " WHERE fk_soc = ".((int) $this->id);
4840  if (!empty($late)) {
4841  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4842  }
4843  if ($mode == 'supplier') {
4844  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4845  } else {
4846  $sql .= " AND entity IN (".getEntity('invoice').")";
4847  }
4848 
4849  dol_syslog("getOutstandingBills", LOG_DEBUG);
4850  $resql = $this->db->query($sql);
4851  if ($resql) {
4852  $outstandingOpened = 0;
4853  $outstandingTotal = 0;
4854  $outstandingTotalIncTax = 0;
4855  $arrayofref = array();
4856  $arrayofrefopened = array();
4857  if ($mode == 'supplier') {
4858  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4859  $tmpobject = new FactureFournisseur($this->db);
4860  } else {
4861  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4862  $tmpobject = new Facture($this->db);
4863  }
4864  while ($obj = $this->db->fetch_object($resql)) {
4865  $arrayofref[$obj->rowid] = $obj->ref;
4866  $tmpobject->id = $obj->rowid;
4867 
4868  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4869  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4870  ) {
4871  $outstandingTotal += $obj->total_ht;
4872  $outstandingTotalIncTax += $obj->total_ttc;
4873  }
4874 
4875  $remaintopay = 0;
4876 
4877  if ($obj->paye == 0
4878  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4879  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4880  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4881  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4882  $paiement = $tmpobject->getSommePaiement();
4883  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4884  $deposits = $tmpobject->getSumDepositsUsed();
4885 
4886  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4887  $outstandingOpened += $remaintopay;
4888  }
4889 
4890  //if credit note is converted but not used
4891  // TODO Do this also for customer ?
4892  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4893  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4894  $remaintopay -= $remainingcreditnote;
4895  $outstandingOpened -= $remainingcreditnote;
4896  }
4897 
4898  if ($remaintopay) {
4899  $arrayofrefopened[$obj->rowid] = $obj->ref;
4900  }
4901  }
4902  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4903  } else {
4904  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4905  return array();
4906  }
4907  }
4908 
4915  public function getLibCustProspStatut()
4916  {
4917  return $this->LibCustProspStatut($this->client);
4918  }
4919 
4920  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4927  public function LibCustProspStatut($status)
4928  {
4929  // phpcs:enable
4930  global $langs;
4931  $langs->load('companies');
4932 
4933  if ($status == 0) {
4934  return $langs->trans("NorProspectNorCustomer");
4935  } elseif ($status == 1) {
4936  return $langs->trans("Customer");
4937  } elseif ($status == 2) {
4938  return $langs->trans("Prospect");
4939  } elseif ($status == 3) {
4940  return $langs->trans("ProspectCustomer");
4941  }
4942 
4943  return '';
4944  }
4945 
4946 
4958  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4959  {
4960  global $conf, $user, $langs;
4961 
4962  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4963  $modelpath = "core/modules/bank/doc/";
4964 
4965  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4966  $companybankaccount = new CompanyBankAccount($this->db);
4967  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4968  if (!$result) {
4969  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4970  }
4971  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4972  } else {
4973  // Positionne le modele sur le nom du modele a utiliser
4974  if (!dol_strlen($modele)) {
4975  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4976  $modele = $conf->global->COMPANY_ADDON_PDF;
4977  } else {
4978  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4979  return 0;
4980  }
4981  }
4982 
4983  if (!isset($this->bank_account)) {
4984  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4985  $bac = new CompanyBankAccount($this->db);
4986  $result = $bac->fetch(0, $this->id);
4987  if ($result > 0) {
4988  $this->bank_account = $bac;
4989  } else {
4990  $this->bank_account = '';
4991  }
4992  }
4993 
4994  $modelpath = "core/modules/societe/doc/";
4995 
4996  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4997  }
4998 
4999  return $result;
5000  }
5001 
5002 
5014  public function setCategories($categories, $type_categ)
5015  {
5016  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5017 
5018  // Decode type
5019  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5020  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5021  return -1;
5022  }
5023 
5024  return parent::setCategoriesCommon($categories, $type_categ);
5025  }
5026 
5034  public function setSalesRep($salesrep, $onlyAdd = false)
5035  {
5036  global $user;
5037 
5038  // Handle single user
5039  if (!is_array($salesrep)) {
5040  $salesrep = array($salesrep);
5041  }
5042 
5043  $to_del = array(); // Nothing to delete
5044  $to_add = $salesrep;
5045  if ($onlyAdd === false) {
5046  // Get current users
5047  $existing = $this->getSalesRepresentatives($user, 1);
5048 
5049  // Diff
5050  if (is_array($existing)) {
5051  $to_del = array_diff($existing, $salesrep);
5052  $to_add = array_diff($salesrep, $existing);
5053  }
5054  }
5055 
5056  $error = 0;
5057 
5058  // Process
5059  foreach ($to_del as $del) {
5060  $this->del_commercial($user, $del);
5061  }
5062  foreach ($to_add as $add) {
5063  $result = $this->add_commercial($user, $add);
5064  if ($result < 0) {
5065  $error++;
5066  break;
5067  }
5068  }
5069 
5070  return $error ? -1 : 1;
5071  }
5072 
5079  public function setThirdpartyType($typent_id)
5080  {
5081  global $user;
5082 
5083  dol_syslog(__METHOD__, LOG_DEBUG);
5084 
5085  if ($this->id) {
5086  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5087 
5088  if ($result > 0) {
5089  $this->typent_id = $typent_id;
5090  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5091  return 1;
5092  } else {
5093  return -1;
5094  }
5095  } else {
5096  return -1;
5097  }
5098  }
5099 
5109  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5110  {
5111  if ($origin_id == $dest_id) {
5112  dol_syslog('Error: Try to merge a thirdparty into itself');
5113  return false;
5114  }
5115 
5120  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5121  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5122  $sql .= ' SELECT fk_user ';
5123  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5124  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5125 
5126  $resql = $dbs->query($sql);
5127  while ($obj = $dbs->fetch_object($resql)) {
5128  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5129  }
5130 
5135  $tables = array(
5136  'societe_address',
5137  'societe_commerciaux',
5138  'societe_prices',
5139  'societe_remise',
5140  'societe_remise_except',
5141  'societe_rib'
5142  );
5143 
5144  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5145  }
5146 
5155  public function setAccountancyCode($type, $value)
5156  {
5157  global $user, $langs, $conf;
5158 
5159  $this->db->begin();
5160 
5161  $field = 'accountancy_code_sell';
5162  if ($type == 'buy') {
5163  $field = 'accountancy_code_buy';
5164  } elseif ($type == 'sell') {
5165  $field = 'accountancy_code_sell';
5166  } else {
5167  return -1;
5168  }
5169 
5170  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5171  $sql .= $field." = '".$this->db->escape($value)."'";
5172  $sql .= " WHERE rowid = ".((int) $this->id);
5173 
5174  dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5175  $resql = $this->db->query($sql);
5176 
5177  if ($resql) {
5178  // Call triggers
5179  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5180  $interface = new Interfaces($this->db);
5181  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5182  if ($result < 0) {
5183  $this->errors = $interface->errors;
5184  $this->db->rollback();
5185  return -1;
5186  }
5187  // End call triggers
5188 
5189  $this->$field = $value;
5190 
5191  $this->db->commit();
5192  return 1;
5193  } else {
5194  $this->error = $this->db->lasterror();
5195  $this->db->rollback();
5196  return -1;
5197  }
5198  }
5199 
5206  public function fetchPartnerships($mode)
5207  {
5208  global $langs;
5209 
5210  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5211 
5212 
5213  $this->partnerships[] = array();
5214 
5215  return 1;
5216  }
5217 
5225  public function getKanbanView($option = '', $arraydata = null)
5226  {
5227  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5228 
5229  $return = '<div class="box-flex-item box-flex-grow-zero">';
5230  $return .= '<div class="info-box info-box-sm">';
5231  $return .= '<span class="info-box-icon bg-infobox-action">';
5232  $return .= img_picto('', $this->picto);
5233  $return .= '</span>';
5234  $return .= '<div class="info-box-content">';
5235  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5236  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5237  if (property_exists($this, 'code_client')) {
5238  $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5239  }
5240 
5241  if (method_exists($this, 'getLibStatut')) {
5242  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
5243  }
5244  $return .= '</div>';
5245  $return .= '</div>';
5246  $return .= '</div>';
5247 
5248  return $return;
5249  }
5250 
5260  public function getContacts($list = 0, $code = '', $element = '')
5261  {
5262  // phpcs:enable
5263  global $langs;
5264 
5265  $tab = array();
5266 
5267  $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
5268 
5269  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5270 
5271  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5272  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
5273  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5274  $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5275 
5276  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5277 
5278  $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5279  $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5280  if (!empty($element)) {
5281  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5282  }
5283  if ($code) {
5284  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5285  }
5286  $sql .= " AND sc.entity = ".getEntity($this->element);
5287  $sql .= " AND tc.source = 'external'";
5288  $sql .= " AND tc.active=1";
5289 
5290  $sql .= " ORDER BY t.lastname ASC";
5291 
5292  dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5293  $resql = $this->db->query($sql);
5294  if ($resql) {
5295  $num = $this->db->num_rows($resql);
5296  $i = 0;
5297  while ($i < $num) {
5298  $obj = $this->db->fetch_object($resql);
5299 
5300  if (!$list) {
5301  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5302  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
5303  $tab[$i] = array(
5304  'source' => $obj->source,
5305  'socid' => $obj->socid,
5306  'id' => $obj->id,
5307  'nom' => $obj->lastname, // For backward compatibility
5308  'civility' => $obj->civility,
5309  'lastname' => $obj->lastname,
5310  'firstname' => $obj->firstname,
5311  'email'=>$obj->email,
5312  'login'=> (empty($obj->login) ? '' : $obj->login),
5313  'photo' => (empty($obj->photo) ? '' : $obj->photo),
5314  'statuscontact' => $obj->statuscontact,
5315  'rowid' => $obj->rowid,
5316  'code' => $obj->code,
5317  'element' => $obj->element,
5318  'libelle' => $libelle_type,
5319  'status' => $obj->statuslink,
5320  'fk_c_type_contact' => $obj->fk_c_type_contact
5321  );
5322  } else {
5323  $tab[$i] = $obj->id;
5324  }
5325 
5326  $i++;
5327  }
5328 
5329  return $tab;
5330  } else {
5331  $this->error = $this->db->lasterror();
5332  dol_print_error($this->db);
5333  return -1;
5334  }
5335  }
5336 }
$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_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:1485
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