dolibarr  18.0.0-beta
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 
309  public $address;
310 
314  public $zip;
315 
319  public $town;
320 
325  public $status = 1;
326 
331  public $state_id;
332 
336  public $state_code;
337 
341  public $state;
342 
347  public $region_code;
348 
352  public $region;
353 
359  public $departement_code;
360 
366  public $departement;
367 
373  public $pays;
374 
379  public $phone;
384  public $fax;
385 
390  public $email;
391 
396  public $no_email;
397 
403  public $skype;
404 
410  public $twitter;
411 
417  public $facebook;
418 
424  public $linkedin;
425 
430  public $url;
431 
436  public $barcode;
437 
438  // 6 professional id (usage depends on country)
439 
444  public $idprof1;
445 
451  public $siren;
452 
453 
458  public $idprof2;
459 
465  public $siret;
466 
471  public $idprof3;
472 
478  public $ape;
479 
484  public $idprof4;
485 
490  public $idprof5;
491 
496  public $idprof6;
497 
502  public $socialobject;
503 
507  public $prefix_comm;
508 
512  public $tva_assuj = 1;
513 
518  public $tva_intra;
519 
523  public $vat_reverse_charge = 0;
524 
525  // Local taxes
526  public $localtax1_assuj;
527  public $localtax1_value;
528  public $localtax2_assuj;
529  public $localtax2_value;
530 
534  public $managers;
535 
539  public $capital;
540 
544  public $typent_id = 0;
545  public $typent_code;
546  public $effectif;
547  public $effectif_id = 0;
548  public $forme_juridique_code;
549  public $forme_juridique = 0;
550 
551  public $remise_percent;
552  public $remise_supplier_percent;
553 
554  public $mode_reglement_id;
555  public $cond_reglement_id;
556  public $deposit_percent;
557  public $mode_reglement_supplier_id;
558  public $cond_reglement_supplier_id;
559  public $transport_mode_supplier_id;
560 
564  public $fk_prospectlevel;
565 
569  public $name_bis;
570 
571  //Log data
572 
577  public $date_modification;
578 
583  public $user_modification;
584 
589  public $date_creation;
590 
595  public $user_creation;
596 
601  public $client = 0;
602 
607  public $prospect = 0;
608 
613  public $fournisseur;
614 
619  public $code_client;
620 
625  public $code_fournisseur;
626 
631  public $code_compta_client;
632 
639  public $code_compta;
640 
645  public $accountancy_code_customer;
646 
651  public $code_compta_fournisseur;
652 
657  public $accountancy_code_supplier;
658 
663  public $code_compta_product;
664 
670  public $note;
671 
676  public $note_private;
677 
682  public $note_public;
683 
688  public $stcomm_id;
689 
694  public $stcomm_picto;
695 
700  public $status_prospect_label;
701 
706  public $price_level;
707 
711  public $outstanding_limit;
712 
716  public $order_min_amount;
717 
721  public $supplier_order_min_amount;
722 
727  public $commercial_id;
728 
733  public $parent;
734 
739  public $default_lang;
740 
744  public $ref;
745 
751  public $ref_ext;
752 
759  public $import_key;
760 
765  public $webservices_url;
766 
771  public $webservices_key;
772 
776  public $logo;
777 
781  public $logo_small;
782 
786  public $logo_mini;
787 
791  public $logo_squarred;
792 
796  public $logo_squarred_small;
797 
801  public $logo_squarred_mini;
802 
806  public $accountancy_code_sell;
807 
811  public $accountancy_code_buy;
812 
813  // Multicurrency
817  public $fk_multicurrency;
818 
819  // Warehouse
823  public $fk_warehouse;
824 
828  public $multicurrency_code;
829 
830  // Fields loaded by fetchPartnerships()
831 
832  public $partnerships = array();
833 
834 
838  public $bank_account;
839 
840 
841  const STATUS_CEASED = 0;
842  const STATUS_INACTIVITY = 1;
843 
847  const NO_CUSTOMER = 0;
848 
852  const CUSTOMER = 1;
853 
857  const PROSPECT = 2;
858 
863 
867  const NO_SUPPLIER = 0;
868 
872  const SUPPLIER = 1;
873 
874 
880  public function __construct($db)
881  {
882  global $conf;
883 
884  $this->db = $db;
885 
886  $this->client = 0;
887  $this->prospect = 0;
888  $this->fournisseur = 0;
889  $this->typent_id = 0;
890  $this->effectif_id = 0;
891  $this->forme_juridique_code = 0;
892  $this->tva_assuj = 1;
893  $this->vat_reverse_charge = 0;
894  $this->status = 1;
895 
896  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
897  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
898  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
899  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
900  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
901  }
902  }
903 
904 
912  public function create(User $user)
913  {
914  global $langs, $conf, $mysoc;
915 
916  $error = 0;
917 
918  // Clean parameters
919  if (empty($this->status)) {
920  $this->status = 0;
921  }
922  $this->name = $this->name ?trim($this->name) : trim($this->nom);
923  $this->setUpperOrLowerCase();
924  $this->nom = $this->name; // For backward compatibility
925  if (empty($this->client)) {
926  $this->client = 0;
927  }
928  if (empty($this->fournisseur)) {
929  $this->fournisseur = 0;
930  }
931  $this->import_key = trim($this->import_key);
932 
933  $this->accountancy_code_customer = trim($this->code_compta);
934  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
935  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
936  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
937 
938  if (!empty($this->multicurrency_code)) {
939  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
940  }
941  if (empty($this->fk_multicurrency)) {
942  $this->multicurrency_code = '';
943  $this->fk_multicurrency = 0;
944  }
945 
946  dol_syslog(get_class($this)."::create ".$this->name);
947 
948  $now = dol_now();
949 
950  $this->db->begin();
951 
952  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
953  if ($this->code_client == -1 || $this->code_client === 'auto') {
954  $this->get_codeclient($this, 0);
955  }
956  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
957  $this->get_codefournisseur($this, 1);
958  }
959 
960  // Check more parameters (including mandatory setup
961  // If error, this->errors[] is filled
962  $result = $this->verify();
963 
964  if ($result >= 0) {
965  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
966 
967  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
968  $sql .= "nom";
969  $sql .= ", name_alias";
970  $sql .= ", entity";
971  $sql .= ", datec";
972  $sql .= ", fk_user_creat";
973  $sql .= ", fk_typent";
974  $sql .= ", canvas";
975  $sql .= ", status";
976  $sql .= ", ref_ext";
977  $sql .= ", fk_stcomm";
978  $sql .= ", fk_incoterms";
979  $sql .= ", location_incoterms";
980  $sql .= ", import_key";
981  $sql .= ", fk_multicurrency";
982  $sql .= ", multicurrency_code";
983  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
984  $sql .= ", vat_reverse_charge";
985  $sql .= ", accountancy_code_buy";
986  $sql .= ", accountancy_code_sell";
987  }
988  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
989  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
990  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
991  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
992  $sql .= ", ".((int) $this->status);
993  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
994  $sql .= ", 0";
995  $sql .= ", ".(int) $this->fk_incoterms;
996  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
997  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
998  $sql .= ", ".(int) $this->fk_multicurrency;
999  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1000  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1001  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1002  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1003  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1004  }
1005  $sql .= ")";
1006 
1007  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1008  $result = $this->db->query($sql);
1009  if ($result) {
1010  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1011 
1012  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1013 
1014  // update accountancy for this entity
1015  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1016  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1017 
1018  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1019  $sql .= " fk_soc";
1020  $sql .= ", entity";
1021  $sql .= ", vat_reverse_charge";
1022  $sql .= ", accountancy_code_customer";
1023  $sql .= ", accountancy_code_supplier";
1024  $sql .= ", accountancy_code_buy";
1025  $sql .= ", accountancy_code_sell";
1026  $sql .= ") VALUES (";
1027  $sql .= $this->id;
1028  $sql .= ", ".((int) $conf->entity);
1029  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1030  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1031  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1032  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1033  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1034  $sql .= ")";
1035  $result = $this->db->query($sql);
1036  if (!$result) {
1037  $error++;
1038  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1039  }
1040  }
1041 
1042  // Ajout du commercial affecte
1043  if ($this->commercial_id != '' && $this->commercial_id != -1) {
1044  $this->add_commercial($user, $this->commercial_id);
1045  } elseif (empty($user->rights->societe->client->voir)) {
1046  // si un commercial cree un client il lui est affecte automatiquement
1047  $this->add_commercial($user, $user->id);
1048  }
1049 
1050  if ($ret >= 0) {
1051  // Call trigger
1052  $result = $this->call_trigger('COMPANY_CREATE', $user);
1053  if ($result < 0) {
1054  $error++;
1055  }
1056  // End call triggers
1057  } else {
1058  $error++;
1059  }
1060 
1061  if (!$error) {
1062  dol_syslog(get_class($this)."::Create success id=".$this->id);
1063  $this->db->commit();
1064  return $this->id;
1065  } else {
1066  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1067  $this->db->rollback();
1068  return -4;
1069  }
1070  } else {
1071  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1072  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1073  $result = -1;
1074  } else {
1075  $this->error = $this->db->lasterror();
1076  $result = -2;
1077  }
1078  $this->db->rollback();
1079  return $result;
1080  }
1081  } else {
1082  $this->db->rollback();
1083  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1084  return -3;
1085  }
1086  }
1087 
1088 
1089  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1098  public function create_individual(User $user, $no_email = 0, $tags = array())
1099  {
1100  global $conf;
1101 
1102  $error = 0;
1103 
1104  $this->db->begin();
1105 
1106  // phpcs:enable
1107  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1108  $contact = new Contact($this->db);
1109 
1110  $contact->name = $this->name_bis;
1111  $contact->firstname = $this->firstname;
1112  $contact->civility_id = $this->civility_id;
1113  $contact->socid = $this->id; // fk_soc
1114  $contact->statut = 1; // deprecated
1115  $contact->status = 1;
1116  $contact->priv = 0;
1117  $contact->country_id = $this->country_id;
1118  $contact->state_id = $this->state_id;
1119  $contact->address = $this->address;
1120  $contact->email = $this->email;
1121  $contact->zip = $this->zip;
1122  $contact->town = $this->town;
1123  $this->setUpperOrLowerCase();
1124  $contact->phone_pro = $this->phone;
1125 
1126  $contactId = $contact->create($user);
1127  if ($contactId < 0) {
1128  $error++;
1129  $this->error = $contact->error;
1130  $this->errors = $contact->errors;
1131  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1132  }
1133 
1134  if (empty($error) && is_array($tags) && !empty($tags)) {
1135  $result = $contact->setCategories($tags);
1136  if ($result < 0) {
1137  $error++;
1138  $this->error = $contact->error;
1139  $this->errors = array_merge($this->errors, $contact->errors);
1140  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1141  $contactId = $result;
1142  }
1143  }
1144 
1145  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1146  $result = $contact->setNoEmail($no_email);
1147  if ($result < 0) {
1148  $this->error = $contact->error;
1149  $this->errors = array_merge($this->errors, $contact->errors);
1150  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1151  $contactId = $result;
1152  }
1153  }
1154 
1155  if (empty($error)) {
1156  dol_syslog(get_class($this)."::create_individual success");
1157  $this->db->commit();
1158  } else {
1159  $this->db->rollback();
1160  }
1161 
1162  return $contactId;
1163  }
1164 
1171  public function verify()
1172  {
1173  global $conf, $langs, $mysoc;
1174 
1175  $error = 0;
1176  $this->errors = array();
1177 
1178  $result = 0;
1179  $this->name = trim($this->name);
1180  $this->nom = $this->name; // For backward compatibility
1181 
1182  if (!$this->name) {
1183  $this->errors[] = 'ErrorBadThirdPartyName';
1184  $result = -2;
1185  }
1186 
1187  if ($this->client) {
1188  $rescode = $this->check_codeclient();
1189  if ($rescode != 0 && $rescode != -5) {
1190  if ($rescode == -1) {
1191  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1192  } elseif ($rescode == -2) {
1193  $this->errors[] = 'ErrorCustomerCodeRequired';
1194  } elseif ($rescode == -3) {
1195  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1196  } elseif ($rescode == -4) {
1197  $this->errors[] = 'ErrorPrefixRequired';
1198  } else {
1199  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1200  }
1201 
1202  $result = -3;
1203  }
1204  }
1205 
1206  if ($this->fournisseur) {
1207  $rescode = $this->check_codefournisseur();
1208  if ($rescode != 0 && $rescode != -5) {
1209  if ($rescode == -1) {
1210  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1211  } elseif ($rescode == -2) {
1212  $this->errors[] = 'ErrorSupplierCodeRequired';
1213  } elseif ($rescode == -3) {
1214  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1215  } elseif ($rescode == -4) {
1216  $this->errors[] = 'ErrorPrefixRequired';
1217  } else {
1218  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1219  }
1220  $result = -3;
1221  }
1222  }
1223 
1224  // Check for duplicate or mandatory fields defined into setup
1225  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1226  foreach ($array_to_check as $key) {
1227  $keymin = strtolower($key);
1228  $i = (int) preg_replace('/[^0-9]/', '', $key);
1229  $vallabel = $this->$keymin;
1230 
1231  if ($i > 0) {
1232  if ($this->isACompany()) {
1233  // Check for mandatory prof id (but only if country is same than ours)
1234  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1235  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1236  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1237  $langs->load("errors");
1238  $error++;
1239  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1240  }
1241  }
1242  }
1243 
1244  // Check for unicity on profid
1245  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1246  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1247  $langs->load("errors");
1248  $error++;
1249  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1250  }
1251  }
1252  } else {
1253  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1254  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1255  if ($key == 'EMAIL') {
1256  // Check for mandatory
1257  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1258  $langs->load("errors");
1259  $error++;
1260  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1261  }
1262 
1263  // Check for unicity
1264  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1265  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1266  $langs->load("errors");
1267  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1268  }
1269  }
1270  } elseif ($key == 'TVA_INTRA') {
1271  // Check for unicity
1272  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1273  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1274  $langs->load("errors");
1275  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1276  }
1277  }
1278  }
1279  }
1280  }
1281 
1282  if ($error) {
1283  $result = -4;
1284  }
1285 
1286  return $result;
1287  }
1288 
1301  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1302  {
1303  global $langs, $conf, $hookmanager;
1304 
1305  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1306 
1307  if (empty($id)) {
1308  $id = $this->id;
1309  }
1310 
1311  $error = 0;
1312 
1313  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1314 
1315  $now = dol_now();
1316 
1317  // Clean parameters
1318  $this->id = $id;
1319  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1320  $this->name = $this->name ? trim($this->name) : trim($this->nom);
1321  $this->nom = $this->name; // For backward compatibility
1322  $this->name_alias = trim($this->name_alias);
1323  $this->ref_ext = trim($this->ref_ext);
1324  $this->address = $this->address ?trim($this->address) : trim($this->address);
1325  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1326  $this->town = $this->town ?trim($this->town) : trim($this->town);
1327  $this->state_id = trim($this->state_id);
1328  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1329  $this->phone = trim($this->phone);
1330  $this->phone = preg_replace("/\s/", "", $this->phone);
1331  $this->phone = preg_replace("/\./", "", $this->phone);
1332  $this->fax = trim($this->fax);
1333  $this->fax = preg_replace("/\s/", "", $this->fax);
1334  $this->fax = preg_replace("/\./", "", $this->fax);
1335  $this->email = trim($this->email);
1336  $this->url = $this->url ?clean_url($this->url, 0) : '';
1337  $this->note_private = trim($this->note_private);
1338  $this->note_public = trim($this->note_public);
1339  $this->idprof1 = trim($this->idprof1);
1340  $this->idprof2 = trim($this->idprof2);
1341  $this->idprof3 = trim($this->idprof3);
1342  $this->idprof4 = trim($this->idprof4);
1343  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1344  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1345  $this->prefix_comm = trim($this->prefix_comm);
1346  $this->outstanding_limit = price2num($this->outstanding_limit);
1347  $this->order_min_amount = price2num($this->order_min_amount);
1348  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1349 
1350  $this->tva_assuj = trim($this->tva_assuj);
1351  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1352  $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? '0' : '1';
1353  if (empty($this->status)) {
1354  $this->status = 0;
1355  }
1356 
1357  if (!empty($this->multicurrency_code)) {
1358  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1359  }
1360  if (empty($this->fk_multicurrency)) {
1361  $this->multicurrency_code = '';
1362  $this->fk_multicurrency = 0;
1363  }
1364 
1365  // Local taxes
1366  $this->localtax1_assuj = trim($this->localtax1_assuj);
1367  $this->localtax2_assuj = trim($this->localtax2_assuj);
1368 
1369  $this->localtax1_value = trim($this->localtax1_value);
1370  $this->localtax2_value = trim($this->localtax2_value);
1371 
1372  if ($this->capital != '') {
1373  $this->capital = price2num(trim($this->capital));
1374  }
1375  if (!is_numeric($this->capital)) {
1376  $this->capital = ''; // '' = undef
1377  }
1378 
1379  $this->effectif_id = trim($this->effectif_id);
1380  $this->forme_juridique_code = trim($this->forme_juridique_code);
1381 
1382  //Gencod
1383  $this->barcode = trim($this->barcode);
1384 
1385  // For automatic creation
1386  if ($this->code_client == -1 || $this->code_client === 'auto') {
1387  $this->get_codeclient($this, 0);
1388  }
1389  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1390  $this->get_codefournisseur($this, 1);
1391  }
1392 
1393  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1394  $this->code_compta = $this->code_compta_client; // for backward compatibility
1395  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1396 
1397  // Check parameters. More tests are done later in the ->verify()
1398  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1399  $langs->load("errors");
1400  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1401  return -1;
1402  }
1403 
1404  $customer = false;
1405  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1406  // If $allowmodcodeclient is set and value is not set, we generate it
1407  if (empty($this->code_compta_client)) {
1408  $ret = $this->get_codecompta('customer');
1409  if ($ret < 0) {
1410  return -1;
1411  }
1412  }
1413 
1414  $customer = true;
1415  }
1416 
1417  $supplier = false;
1418  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1419  // If $allowmodcodefournisseur is set and value is not set, we generate it
1420  if (empty($this->code_compta_fournisseur)) {
1421  $ret = $this->get_codecompta('supplier');
1422  if ($ret < 0) {
1423  return -1;
1424  }
1425  }
1426 
1427  $supplier = true;
1428  }
1429 
1430  //Web services
1431  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1432  $this->webservices_key = trim($this->webservices_key);
1433 
1434  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1435  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1436 
1437  //Incoterms
1438  $this->fk_incoterms = (int) $this->fk_incoterms;
1439  $this->location_incoterms = trim($this->location_incoterms);
1440 
1441  $this->db->begin();
1442 
1443  // Check name is required and codes are ok or unique.
1444  // If error, this->errors[] is filled
1445  $result = 0;
1446  if ($action != 'add' && $action != 'merge') {
1447  // We don't check when update called during a create because verify was already done.
1448  // 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
1449  $result = $this->verify();
1450 
1451  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1452  // So we can update record that were using and old numbering rule.
1453  if (is_array($this->errors)) {
1454  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1455  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1456  unset($this->errors[$key]); // Remove error message
1457  }
1458  }
1459  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1460  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1461  unset($this->errors[$key]); // Remove error message
1462  }
1463  }
1464  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1465  $result = 0;
1466  }
1467  }
1468  }
1469  $this->setUpperOrLowerCase();
1470  if ($result >= 0) {
1471  dol_syslog(get_class($this)."::update verify ok or not done");
1472 
1473  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1474  $sql .= "entity = ".$this->db->escape($this->entity);
1475  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1476  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1477  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1478  $sql .= ",address = '".$this->db->escape($this->address)."'";
1479 
1480  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1481  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1482 
1483  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1484  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1485 
1486  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1487  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1488  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1489  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1490  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1491 
1492  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1493 
1494  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1495  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1496 
1497  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1498  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1499  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1500  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1501  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1502  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1503 
1504  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1505  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1506  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1507  $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1508  }
1509  $sql .= ",status = ".((int) $this->status);
1510 
1511  // Local taxes
1512  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1513  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1514  if ($this->localtax1_assuj == 1) {
1515  if ($this->localtax1_value != '') {
1516  $sql .= ",localtax1_value =".$this->localtax1_value;
1517  } else {
1518  $sql .= ",localtax1_value =0.000";
1519  }
1520  } else {
1521  $sql .= ",localtax1_value =0.000";
1522  }
1523 
1524  if ($this->localtax2_assuj == 1) {
1525  if ($this->localtax2_value != '') {
1526  $sql .= ",localtax2_value =".$this->localtax2_value;
1527  } else {
1528  $sql .= ",localtax2_value =0.000";
1529  }
1530  } else {
1531  $sql .= ",localtax2_value =0.000";
1532  }
1533 
1534  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1535 
1536  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1537 
1538  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1539  if (isset($this->stcomm_id)) {
1540  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1541  }
1542  if (isset($this->typent_id)) {
1543  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1544  }
1545 
1546  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1547 
1548  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1549  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1550  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1551  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1552  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1553  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1554  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1555  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1556 
1557  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1558  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1559  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1560  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1561  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1562  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1563  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1564  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1565  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1566  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1567  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1568  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1569  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1570  if ($customer) {
1571  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1572  }
1573 
1574  if ($supplier) {
1575  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1576  }
1577  }
1578  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1579  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1580 
1581  //Incoterms
1582  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1583  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1584 
1585  if ($customer) {
1586  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1587  }
1588 
1589  if ($supplier) {
1590  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1591  }
1592  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1593  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1594  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1595  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1596  $sql .= " WHERE rowid = ".(int) $id;
1597 
1598  $resql = $this->db->query($sql);
1599  if ($resql) {
1600  if (is_object($this->oldcopy)) { // If we have information on old values
1601  if ($this->oldcopy->country_id != $this->country_id) {
1602  unset($this->country_code);
1603  unset($this->country);
1604  }
1605  if ($this->oldcopy->state_id != $this->state_id) {
1606  unset($this->state_code);
1607  unset($this->state);
1608  }
1609  } else {
1610  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1611  unset($this->country);
1612  unset($this->state_code);
1613  unset($this->state);
1614  }
1615 
1616  $nbrowsaffected = $this->db->affected_rows($resql);
1617 
1618  if (!$error && $nbrowsaffected) {
1619  // Update information on linked member if it is an update
1620  if (!$nosyncmember && isModEnabled('adherent')) {
1621  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1622 
1623  dol_syslog(get_class($this)."::update update linked member");
1624 
1625  $lmember = new Adherent($this->db);
1626  $result = $lmember->fetch(0, 0, $this->id);
1627 
1628  if ($result > 0) {
1629  $lmember->company = $this->name;
1630  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1631  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1632  $lmember->address = $this->address;
1633  $lmember->zip = $this->zip;
1634  $lmember->town = $this->town;
1635  $lmember->email = $this->email;
1636  $lmember->socialnetworks = $this->socialnetworks;
1637  $lmember->phone = $this->phone;
1638  $lmember->state_id = $this->state_id;
1639  $lmember->country_id = $this->country_id;
1640  $lmember->default_lang = $this->default_lang;
1641 
1642  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1643  if ($result < 0) {
1644  $this->error = $lmember->error;
1645  $this->errors = array_merge($this->errors, $lmember->errors);
1646  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1647  $error++;
1648  }
1649  } elseif ($result < 0) {
1650  $this->error = $lmember->error;
1651  $error++;
1652  }
1653  }
1654  }
1655 
1656  $action = 'update';
1657 
1658  // update accountancy for this entity
1659  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1660  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1661 
1662  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1663  $sql .= " fk_soc";
1664  $sql .= ", entity";
1665  $sql .= ", vat_reverse_charge";
1666  $sql .= ", accountancy_code_customer";
1667  $sql .= ", accountancy_code_supplier";
1668  $sql .= ", accountancy_code_buy";
1669  $sql .= ", accountancy_code_sell";
1670  $sql .= ") VALUES (";
1671  $sql .= $this->id;
1672  $sql .= ", ".$conf->entity;
1673  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1674  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1675  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1676  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1677  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1678  $sql .= ")";
1679  $result = $this->db->query($sql);
1680  if (!$result) {
1681  $error++;
1682  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1683  }
1684  }
1685 
1686  // Actions on extra fields
1687  if (!$error) {
1688  $result = $this->insertExtraFields();
1689  if ($result < 0) {
1690  $error++;
1691  }
1692  }
1693  // Actions on extra languages
1694  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1695  $result = $this->insertExtraLanguages();
1696  if ($result < 0) {
1697  $error++;
1698  }
1699  }
1700 
1701  if (!$error && $call_trigger) {
1702  // Call trigger
1703  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1704  if ($result < 0) {
1705  $error++;
1706  }
1707  // End call triggers
1708  }
1709 
1710  if (!$error) {
1711  dol_syslog(get_class($this)."::Update success");
1712  $this->db->commit();
1713  return 1;
1714  } else {
1715  $this->db->rollback();
1716  return -1;
1717  }
1718  } else {
1719  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1720  // Doublon
1721  $this->error = $langs->trans("ErrorDuplicateField");
1722  $result = -1;
1723  } else {
1724  $this->error = $this->db->lasterror();
1725  $result = -2;
1726  }
1727  $this->db->rollback();
1728  return $result;
1729  }
1730  } else {
1731  $this->db->rollback();
1732  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1733  return -3;
1734  }
1735  }
1736 
1754  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1755  {
1756  global $langs;
1757  global $conf;
1758 
1759  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1760  return -1;
1761  }
1762 
1763  $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';
1764  $sql .= ', s.status, s.fk_warehouse';
1765  $sql .= ', s.price_level';
1766  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1767  $sql .= ', s.phone, s.fax, s.email';
1768  $sql .= ', s.socialnetworks';
1769  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1770  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1771  $sql .= ', s.capital, s.tva_intra';
1772  $sql .= ', s.fk_typent as typent_id';
1773  $sql .= ', s.fk_effectif as effectif_id';
1774  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1775  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1776  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1777  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1778  $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1779  } else {
1780  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1781  $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1782  }
1783  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1784  $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';
1785  $sql .= ', s.fk_account, s.tva_assuj';
1786  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1787  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1788  $sql .= ', s.fk_shipping_method';
1789  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1790  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1791  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1792  $sql .= ', fj.libelle as forme_juridique';
1793  $sql .= ', e.libelle as effectif';
1794  $sql .= ', c.code as country_code, c.label as country';
1795  $sql .= ', d.code_departement as state_code, d.nom as state';
1796  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1797  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1798  $sql .= ', te.code as typent_code';
1799  $sql .= ', i.libelle as label_incoterms';
1800  if (!isModEnabled('multicompany')) {
1801  $sql .= ', s.remise_client, s.remise_supplier';
1802  } else {
1803  $sql .= ', sr.remise_client, sr2.remise_supplier';
1804  }
1805  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1806  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1807  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1808  }
1809  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1810  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1811  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1812  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1813  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1814  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1815  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1816  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1817  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1818  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1819  if (isModEnabled('multicompany')) {
1820  $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').'))';
1821  $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').'))';
1822  }
1823  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1824  if ($rowid) {
1825  $sql .= ' AND s.rowid = '.((int) $rowid);
1826  }
1827  if ($ref) {
1828  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1829  }
1830  if ($ref_alias) {
1831  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1832  }
1833  if ($ref_ext) {
1834  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1835  }
1836  if ($barcode) {
1837  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1838  }
1839  if ($idprof1) {
1840  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1841  }
1842  if ($idprof2) {
1843  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1844  }
1845  if ($idprof3) {
1846  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1847  }
1848  if ($idprof4) {
1849  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1850  }
1851  if ($idprof5) {
1852  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1853  }
1854  if ($idprof6) {
1855  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1856  }
1857  if ($email) {
1858  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1859  }
1860 
1861  $resql = $this->db->query($sql);
1862  if ($resql) {
1863  $num = $this->db->num_rows($resql);
1864  if ($num > 1) {
1865  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1866  dol_syslog($this->error, LOG_ERR);
1867  $result = -2;
1868  } elseif ($num) { // $num = 1
1869  $obj = $this->db->fetch_object($resql);
1870 
1871  $this->id = $obj->rowid;
1872  $this->entity = $obj->entity;
1873  $this->canvas = $obj->canvas;
1874 
1875  $this->ref = $obj->rowid;
1876  $this->name = $obj->name;
1877  $this->nom = $obj->name; // deprecated
1878  $this->name_alias = $obj->name_alias;
1879  $this->ref_ext = $obj->ref_ext;
1880 
1881  $this->date_creation = $this->db->jdate($obj->date_creation);
1882  $this->date_modification = $this->db->jdate($obj->date_modification);
1883  $this->user_creation = $obj->fk_user_creat;
1884  $this->user_modification = $obj->fk_user_modif;
1885 
1886  $this->address = $obj->address;
1887  $this->zip = $obj->zip;
1888  $this->town = $obj->town;
1889 
1890  $this->country_id = $obj->country_id;
1891  $this->country_code = $obj->country_id ? $obj->country_code : '';
1892  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1893 
1894  $this->state_id = $obj->state_id;
1895  $this->state_code = $obj->state_code;
1896  $this->region_id = $obj->region_id;
1897  $this->region_code = $obj->region_code;
1898  $this->state = ($obj->state != '-' ? $obj->state : '');
1899 
1900  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1901  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1902  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1903  $this->status_prospect_label = $label; // label status prospect
1904  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1905 
1906  $this->email = $obj->email;
1907  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1908 
1909  $this->url = $obj->url;
1910  $this->phone = $obj->phone;
1911  $this->fax = $obj->fax;
1912 
1913  $this->parent = $obj->parent;
1914 
1915  $this->idprof1 = $obj->idprof1;
1916  $this->idprof2 = $obj->idprof2;
1917  $this->idprof3 = $obj->idprof3;
1918  $this->idprof4 = $obj->idprof4;
1919  $this->idprof5 = $obj->idprof5;
1920  $this->idprof6 = $obj->idprof6;
1921 
1922  $this->capital = $obj->capital;
1923 
1924  $this->code_client = $obj->code_client;
1925  $this->code_fournisseur = $obj->code_fournisseur;
1926 
1927  $this->code_compta = $obj->code_compta; // For backward compatibility
1928  $this->code_compta_client = $obj->code_compta;
1929  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1930 
1931  $this->barcode = $obj->barcode;
1932 
1933  $this->tva_assuj = $obj->tva_assuj;
1934  $this->tva_intra = $obj->tva_intra;
1935 
1936  if (!empty($obj->spe_vat_reverse_charge)) {
1937  $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1938  } elseif (!empty($obj->soc_vat_reverse_charge)) {
1939  $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1940  } else {
1941  $this->vat_reverse_charge = 0;
1942  }
1943 
1944  $this->status = $obj->status;
1945 
1946  // Local Taxes
1947  $this->localtax1_assuj = $obj->localtax1_assuj;
1948  $this->localtax2_assuj = $obj->localtax2_assuj;
1949 
1950  $this->localtax1_value = $obj->localtax1_value;
1951  $this->localtax2_value = $obj->localtax2_value;
1952 
1953  $this->typent_id = $obj->typent_id;
1954  $this->typent_code = $obj->typent_code;
1955 
1956  $this->effectif_id = $obj->effectif_id;
1957  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1958 
1959  $this->forme_juridique_code = $obj->forme_juridique_code;
1960  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1961 
1962  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1963 
1964  $this->prefix_comm = $obj->prefix_comm;
1965 
1966  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1967  $this->remise_supplier_percent = $obj->remise_supplier;
1968 
1969  $this->mode_reglement_id = $obj->mode_reglement;
1970  $this->cond_reglement_id = $obj->cond_reglement;
1971  $this->deposit_percent = $obj->deposit_percent;
1972  $this->transport_mode_id = $obj->transport_mode;
1973  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1974  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1975  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1976  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1977  $this->fk_account = $obj->fk_account;
1978 
1979  $this->client = $obj->client;
1980  $this->fournisseur = $obj->fournisseur;
1981 
1982  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1983  $this->note_private = $obj->note_private;
1984  $this->note_public = $obj->note_public;
1985  $this->model_pdf = $obj->model_pdf;
1986  $this->modelpdf = $obj->model_pdf; // deprecated
1987  $this->default_lang = $obj->default_lang;
1988  $this->logo = $obj->logo;
1989  $this->logo_squarred = $obj->logo_squarred;
1990 
1991  $this->webservices_url = $obj->webservices_url;
1992  $this->webservices_key = $obj->webservices_key;
1993 
1994  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1995  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1996 
1997  $this->outstanding_limit = $obj->outstanding_limit;
1998  $this->order_min_amount = $obj->order_min_amount;
1999  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2000 
2001  // multiprix
2002  $this->price_level = $obj->price_level;
2003 
2004  // warehouse
2005  $this->fk_warehouse = $obj->fk_warehouse;
2006 
2007  $this->import_key = $obj->import_key;
2008 
2009  //Incoterms
2010  $this->fk_incoterms = $obj->fk_incoterms;
2011  $this->location_incoterms = $obj->location_incoterms;
2012  $this->label_incoterms = $obj->label_incoterms;
2013 
2014  // multicurrency
2015  $this->fk_multicurrency = $obj->fk_multicurrency;
2016  $this->multicurrency_code = $obj->multicurrency_code;
2017 
2018  // pdf
2019  $this->model_pdf = $obj->model_pdf;
2020  $this->last_main_doc = $obj->last_main_doc;
2021 
2022  $result = 1;
2023 
2024  // fetch optionals attributes and labels
2025  $this->fetch_optionals();
2026  } else {
2027  $result = 0;
2028  }
2029 
2030  $this->db->free($resql);
2031  } else {
2032  $this->error = $this->db->lasterror();
2033  $this->errors[] = $this->db->lasterror();
2034  $result = -3;
2035  }
2036 
2037  // Use first price level if level not defined for third party
2038  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
2039  $this->price_level = 1;
2040  }
2041 
2042  return $result;
2043  }
2044 
2053  public function delete($id, User $fuser = null, $call_trigger = 1)
2054  {
2055  global $langs, $conf, $user;
2056 
2057  if (empty($fuser)) {
2058  $fuser = $user;
2059  }
2060 
2061  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2062 
2063  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2064 
2065  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2066  $error = 0;
2067 
2068  // Test if child exists
2069  $objectisused = $this->isObjectUsed($id);
2070  if (empty($objectisused)) {
2071  $this->db->begin();
2072 
2073  // User is mandatory for trigger call
2074  if (!$error && $call_trigger) {
2075  // Call trigger
2076  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2077  if ($result < 0) {
2078  $error++;
2079  }
2080  // End call triggers
2081  }
2082 
2083  if (!$error) {
2084  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2085  $static_cat = new Categorie($this->db);
2086  $toute_categs = array();
2087 
2088  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2089  if ($this->client || $this->prospect) {
2090  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2091  }
2092  if ($this->fournisseur) {
2093  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2094  }
2095 
2096  // Remove each "Categorie"
2097  foreach ($toute_categs as $type => $categs_type) {
2098  foreach ($categs_type as $cat) {
2099  $cat->del_type($this, $type);
2100  }
2101  }
2102  }
2103 
2104  if (!$error) {
2105  foreach ($this->childtablesoncascade as $tabletodelete) {
2106  $deleteFromObject = explode(':', $tabletodelete);
2107  if (count($deleteFromObject) >= 2) {
2108  $className = str_replace('@', '', $deleteFromObject[0]);
2109  $filepath = $deleteFromObject[1];
2110  $columnName = $deleteFromObject[2];
2111  if (dol_include_once($filepath)) {
2112  $child_object = new $className($this->db);
2113  $result = $child_object->deleteByParentField($id, $columnName);
2114  if ($result < 0) {
2115  $error++;
2116  $this->errors[] = $child_object->error;
2117  break;
2118  }
2119  } else {
2120  $error++;
2121  $this->errors[] = 'Cannot include child class file '.$filepath;
2122  break;
2123  }
2124  } else {
2125  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2126  $sql .= " WHERE fk_soc = ".((int) $id);
2127  if (!$this->db->query($sql)) {
2128  $error++;
2129  $this->errors[] = $this->db->lasterror();
2130  break;
2131  }
2132  }
2133  }
2134  }
2135 
2136  // Removed extrafields
2137  if (!$error) {
2138  $result = $this->deleteExtraFields();
2139  if ($result < 0) {
2140  $error++;
2141  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2142  }
2143  }
2144 
2145  // Remove links to subsidiaries companies
2146  if (!$error) {
2147  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2148  $sql .= " SET parent = NULL";
2149  $sql .= " WHERE parent = ".((int) $id);
2150  if (!$this->db->query($sql)) {
2151  $error++;
2152  $this->errors[] = $this->db->lasterror();
2153  }
2154  }
2155 
2156  // Remove third party
2157  if (!$error) {
2158  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2159  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2160  $sql .= " WHERE fk_soc = ".((int) $id);
2161  if (!$this->db->query($sql)) {
2162  $error++;
2163  $this->errors[] = $this->db->lasterror();
2164  }
2165  }
2166 
2167  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2168  $sql .= " WHERE rowid = ".((int) $id);
2169  if (!$this->db->query($sql)) {
2170  $error++;
2171  $this->errors[] = $this->db->lasterror();
2172  }
2173  }
2174 
2175  if (!$error) {
2176  $this->db->commit();
2177 
2178  // Delete directory
2179  if (!empty($conf->societe->multidir_output[$entity])) {
2180  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2181  if (dol_is_dir($docdir)) {
2182  dol_delete_dir_recursive($docdir);
2183  }
2184  }
2185 
2186  return 1;
2187  } else {
2188  dol_syslog($this->error, LOG_ERR);
2189  $this->db->rollback();
2190  return -1;
2191  }
2192  } else {
2193  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2194  }
2195  return 0;
2196  }
2197 
2198  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2204  public function set_as_client()
2205  {
2206  // phpcs:enable
2207  if ($this->id) {
2208  $newclient = 1;
2209  if ($this->client == 2 || $this->client == 3) {
2210  $newclient = 3; //If prospect, we keep prospect tag
2211  }
2212  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2213  $sql .= " SET client = ".((int) $newclient);
2214  $sql .= " WHERE rowid = ".((int) $this->id);
2215 
2216  $resql = $this->db->query($sql);
2217  if ($resql) {
2218  $this->client = $newclient;
2219  return 1;
2220  } else {
2221  return -1;
2222  }
2223  }
2224  return 0;
2225  }
2226 
2227  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2236  public function set_remise_client($remise, $note, User $user)
2237  {
2238  // phpcs:enable
2239  global $conf, $langs;
2240 
2241  // Parameter cleaning
2242  $note = trim($note);
2243  if (!$note) {
2244  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2245  return -2;
2246  }
2247 
2248  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2249 
2250  if ($this->id) {
2251  $this->db->begin();
2252 
2253  $now = dol_now();
2254 
2255  // Position current discount
2256  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2257  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2258  $sql .= " WHERE rowid = ".((int) $this->id);
2259  $resql = $this->db->query($sql);
2260  if (!$resql) {
2261  $this->db->rollback();
2262  $this->error = $this->db->error();
2263  return -1;
2264  }
2265 
2266  // Writes trace in discount history
2267  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2268  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2269  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2270  $sql .= " '".$this->db->escape($note)."',";
2271  $sql .= " ".((int) $user->id);
2272  $sql .= ")";
2273 
2274  $resql = $this->db->query($sql);
2275  if (!$resql) {
2276  $this->db->rollback();
2277  $this->error = $this->db->lasterror();
2278  return -1;
2279  }
2280 
2281  $this->db->commit();
2282 
2283  return 1;
2284  }
2285  }
2286 
2287  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2296  public function set_remise_supplier($remise, $note, User $user)
2297  {
2298  // phpcs:enable
2299  global $conf, $langs;
2300 
2301  // Parameter cleaning
2302  $note = trim($note);
2303  if (!$note) {
2304  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2305  return -2;
2306  }
2307 
2308  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2309 
2310  if ($this->id) {
2311  $this->db->begin();
2312 
2313  $now = dol_now();
2314 
2315  // Position current discount
2316  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2317  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2318  $sql .= " WHERE rowid = ".((int) $this->id);
2319  $resql = $this->db->query($sql);
2320  if (!$resql) {
2321  $this->db->rollback();
2322  $this->error = $this->db->error();
2323  return -1;
2324  }
2325 
2326  // Writes trace in discount history
2327  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2328  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2329  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2330  $sql .= " '".$this->db->escape($note)."',";
2331  $sql .= " ".((int) $user->id);
2332  $sql .= ")";
2333 
2334  $resql = $this->db->query($sql);
2335  if (!$resql) {
2336  $this->db->rollback();
2337  $this->error = $this->db->lasterror();
2338  return -1;
2339  }
2340 
2341  $this->db->commit();
2342  return 1;
2343  }
2344 
2345  return -1;
2346  }
2347 
2348  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2360  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2361  {
2362  // phpcs:enable
2363  global $langs;
2364 
2365  // Clean parameters
2366  $remise = price2num($remise);
2367  $desc = trim($desc);
2368 
2369  // Check parameters
2370  if (!($remise > 0)) {
2371  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2372  return -1;
2373  }
2374  if (!$desc) {
2375  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2376  return -2;
2377  }
2378 
2379  if ($this->id > 0) {
2380  // Clean vat code
2381  $reg = array();
2382  $vat_src_code = '';
2383  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2384  $vat_src_code = $reg[1];
2385  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2386  }
2387 
2388  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2389 
2390  $discount = new DiscountAbsolute($this->db);
2391  $discount->fk_soc = $this->id;
2392 
2393  $discount->discount_type = $discount_type;
2394 
2395  if ($price_base_type == 'TTC') {
2396  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2397  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2398  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2399  } else {
2400  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2401  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2402  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2403  }
2404 
2405  $discount->tva_tx = price2num($vatrate);
2406  $discount->vat_src_code = $vat_src_code;
2407 
2408  $discount->description = $desc;
2409 
2410  $result = $discount->create($user);
2411  if ($result > 0) {
2412  return $result;
2413  } else {
2414  $this->error = $discount->error;
2415  return -3;
2416  }
2417  } else {
2418  return 0;
2419  }
2420  }
2421 
2431  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2432  {
2433  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2434 
2435  $discountstatic = new DiscountAbsolute($this->db);
2436  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2437  if ($result >= 0) {
2438  return $result;
2439  } else {
2440  $this->error = $discountstatic->error;
2441  return -1;
2442  }
2443  }
2444 
2454  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2455  {
2456  global $conf;
2457 
2458  $reparray = array();
2459 
2460  $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";
2461  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2462  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2463  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2464  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2465  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2466  $sql .= " AND ug.entity = ".$conf->entity.")";
2467  $sql .= " OR u.admin = 1)";
2468  } else {
2469  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2470  }
2471 
2472  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2473  if (empty($sortfield) && empty($sortorder)) {
2474  $sortfield = 'u.lastname,u.firstname';
2475  $sortorder = 'ASC,ASC';
2476  }
2477  $sql .= $this->db->order($sortfield, $sortorder);
2478 
2479  $resql = $this->db->query($sql);
2480  if ($resql) {
2481  $num = $this->db->num_rows($resql);
2482  $i = 0;
2483  while ($i < $num) {
2484  $obj = $this->db->fetch_object($resql);
2485 
2486  if (empty($mode)) {
2487  $reparray[$i]['id'] = $obj->rowid;
2488  $reparray[$i]['lastname'] = $obj->lastname;
2489  $reparray[$i]['firstname'] = $obj->firstname;
2490  $reparray[$i]['email'] = $obj->email;
2491  $reparray[$i]['phone'] = $obj->office_phone;
2492  $reparray[$i]['office_phone'] = $obj->office_phone;
2493  $reparray[$i]['office_fax'] = $obj->office_fax;
2494  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2495  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2496  $reparray[$i]['job'] = $obj->job;
2497  $reparray[$i]['statut'] = $obj->status; // deprecated
2498  $reparray[$i]['status'] = $obj->status;
2499  $reparray[$i]['entity'] = $obj->entity;
2500  $reparray[$i]['login'] = $obj->login;
2501  $reparray[$i]['photo'] = $obj->photo;
2502  $reparray[$i]['gender'] = $obj->gender;
2503  } else {
2504  $reparray[] = $obj->rowid;
2505  }
2506  $i++;
2507  }
2508  return $reparray;
2509  } else {
2510  dol_print_error($this->db);
2511  return -1;
2512  }
2513  }
2514 
2522  public function setPriceLevel($price_level, User $user)
2523  {
2524  if ($this->id) {
2525  $now = dol_now();
2526 
2527  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2528  $sql .= " SET price_level = ".((int) $price_level);
2529  $sql .= " WHERE rowid = ".((int) $this->id);
2530 
2531  if (!$this->db->query($sql)) {
2532  dol_print_error($this->db);
2533  return -1;
2534  }
2535 
2536  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2537  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2538  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2539 
2540  if (!$this->db->query($sql)) {
2541  dol_print_error($this->db);
2542  return -1;
2543  }
2544  return 1;
2545  }
2546  return -1;
2547  }
2548 
2549  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2557  public function add_commercial(User $user, $commid)
2558  {
2559  // phpcs:enable
2560  $error = 0;
2561 
2562  if ($this->id > 0 && $commid > 0) {
2563  $this->db->begin();
2564 
2565  if (!$error) {
2566  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2567  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2568 
2569  $resql = $this->db->query($sql);
2570  if (!$resql) {
2571  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2572  $error++;
2573  }
2574  }
2575 
2576  if (!$error) {
2577  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2578  $sql .= " (fk_soc, fk_user)";
2579  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2580 
2581  $resql = $this->db->query($sql);
2582  if (!$resql) {
2583  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2584  $error++;
2585  }
2586  }
2587 
2588  if (!$error) {
2589  $this->context = array('commercial_modified' => $commid);
2590 
2591  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2592  if ($result < 0) {
2593  $error++;
2594  }
2595  }
2596 
2597  if (!$error) {
2598  $this->db->commit();
2599  return 1;
2600  } else {
2601  $this->db->rollback();
2602  return -1;
2603  }
2604  }
2605 
2606  return 0;
2607  }
2608 
2609  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2617  public function del_commercial(User $user, $commid)
2618  {
2619  // phpcs:enable
2620  $error = 0;
2621  $this->context = array('commercial_modified'=>$commid);
2622 
2623  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2624  if ($result < 0) {
2625  $error++;
2626  }
2627 
2628  if ($this->id > 0 && $commid > 0) {
2629  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2630  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2631 
2632  if (!$this->db->query($sql)) {
2633  dol_syslog(get_class($this)."::del_commercial Erreur");
2634  }
2635  }
2636  }
2637 
2645  public function getTooltipContentArray($params)
2646  {
2647  global $conf, $langs, $user;
2648 
2649  $langs->loadLangs(['companies', 'commercial']);
2650 
2651  $datas = array();
2652 
2653  $option = $params['option'] ?? '';
2654  $nofetch = !empty($params['nofetch']);
2655 
2656  $name = $this->name;
2657  $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2658 
2659  if (!empty($this->name_alias) && empty($noaliasinname)) {
2660  $name .= ' ('.$this->name_alias.')';
2661  }
2662  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2663  return ['optimize' => $langs->trans("ShowCompany")];
2664  }
2665 
2666  if (!empty($this->logo) && class_exists('Form')) {
2667  $photo = '<div class="photointooltip floatright">';
2668  $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.
2669  $photo .= '</div>';
2670  $datas['photo'] = $photo;
2671  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2672  /*$label.= '<div class="photointooltip">';
2673  $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.
2674  $label.= '</div><div style="clear: both;"></div>';*/
2675  }
2676 
2677  $datas['divopen'] = '<div class="centpercent">';
2678 
2679  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2680  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2681  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2682  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2683  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2684  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2685  } elseif ($option == 'agenda') {
2686  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2687  } elseif ($option == 'project') {
2688  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2689  } elseif ($option == 'margin') {
2690  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2691  } elseif ($option == 'contact') {
2692  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2693  } elseif ($option == 'ban') {
2694  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2695  }
2696 
2697  // By default
2698  if (empty($datas['picto'])) {
2699  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2700  }
2701  if (isset($this->status)) {
2702  $datas['status'] = ' '.$this->getLibStatut(5);
2703  }
2704  if (isset($this->client) && isset($this->fournisseur)) {
2705  $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2706  }
2707  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag($this->name);
2708  if (!empty($this->name_alias)) {
2709  $datas['namealias'] = ' ('.dol_escape_htmltag($this->name_alias).')';
2710  }
2711  if (!empty($this->email)) {
2712  $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2713  }
2714  if (!empty($this->url)) {
2715  $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2716  }
2717  if (!empty($this->phone) || !empty($this->fax)) {
2718  $phonelist = array();
2719  if ($this->phone) {
2720  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2721  }
2722  if ($this->fax) {
2723  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2724  }
2725  $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2726  }
2727 
2728  if (!empty($this->address)) {
2729  $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2730  } elseif (!empty($this->country_code)) {
2731  $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2732  }
2733  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2734  $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2735  }
2736 
2737  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2738  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2739  $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2740  }
2741  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2742  $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2743  }
2744  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2745  $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2746  }
2747  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2748  $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2749  }
2750  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2751  $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2752  }
2753  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2754  $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2755  }
2756  }
2757 
2758  $datas['separator'] = '<br>';
2759 
2760  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2761  $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2762  }
2763  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2764  $langs->load('compta');
2765  $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2766  }
2767  // show categories for this record only in ajax to not overload lists
2768  if (!$nofetch && isModEnabled('categorie') && $this->client) {
2769  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2770  $form = new Form($this->db);
2771  $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2772  }
2773  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2774  $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2775  }
2776  if (isModEnabled('accounting') && $this->fournisseur) {
2777  $langs->load('compta');
2778  $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2779  }
2780  // show categories for this record only in ajax to not overload lists
2781  if (!$nofetch && isModEnabled('categorie') && $this->fournisseur) {
2782  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2783  $form = new Form($this->db);
2784  $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2785  }
2786 
2787  $datas['divclose'] = '</div>';
2788 
2789  return $datas;
2790  }
2791 
2804  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2805  {
2806  global $conf, $langs, $hookmanager;
2807 
2808  if (!empty($conf->dol_no_mouse_hover)) {
2809  $notooltip = 1; // Force disable tooltips
2810  }
2811 
2812  $name = $this->name ? $this->name : $this->nom;
2813 
2814  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2815  if (empty($option) && $this->client > 0) {
2816  $option = 'customer';
2817  }
2818  if (empty($option) && $this->fournisseur > 0) {
2819  $option = 'supplier';
2820  }
2821  }
2822 
2823  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2824  $code = '';
2825  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2826  $code = $this->code_client.' - ';
2827  }
2828 
2829  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2830  $code .= $this->code_fournisseur.' - ';
2831  }
2832 
2833  if ($code) {
2834  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2835  $name = $code.' '.$name;
2836  } else {
2837  $name = $code;
2838  }
2839  }
2840  }
2841 
2842  if (!empty($this->name_alias) && empty($noaliasinname)) {
2843  $name .= ' ('.$this->name_alias.')';
2844  }
2845 
2846  $result = '';
2847  $params = [
2848  'id' => $this->id,
2849  'objecttype' => $this->element,
2850  'option' => $option,
2851  'nofetch' => 1,
2852  ];
2853  $classfortooltip = 'classfortooltip';
2854  $dataparams = '';
2855  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2856  $classfortooltip = 'classforajaxtooltip';
2857  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2858  $label = '';
2859  } else {
2860  $label = implode($this->getTooltipContentArray($params));
2861  }
2862 
2863  $linkstart = '';
2864  $linkend = '';
2865 
2866  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2867  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2868  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2869  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2870  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2871  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2872  } elseif ($option == 'agenda') {
2873  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2874  } elseif ($option == 'project') {
2875  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2876  } elseif ($option == 'margin') {
2877  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2878  } elseif ($option == 'contact') {
2879  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2880  } elseif ($option == 'ban') {
2881  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2882  }
2883 
2884  // By default
2885  if (empty($linkstart)) {
2886  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2887  }
2888 
2889  // Add type of canvas
2890  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2891  // Add param to save lastsearch_values or not
2892  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2893  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2894  $add_save_lastsearch_values = 1;
2895  }
2896  if ($add_save_lastsearch_values) {
2897  $linkstart .= '&save_lastsearch_values=1';
2898  }
2899  $linkstart .= '"';
2900 
2901  $linkclose = '';
2902  if (empty($notooltip)) {
2903  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2904  $label = $langs->trans("ShowCompany");
2905  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2906  }
2907  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2908  $linkclose .= $dataparams.' class="'.$classfortooltip.' refurl valignmiddle"';
2909  $target_value = array('_self', '_blank', '_parent', '_top');
2910  if (in_array($target, $target_value)) {
2911  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2912  }
2913  } else {
2914  $linkclose .= ' class="valignmiddle"';
2915  }
2916  $linkstart .= $linkclose.'>';
2917  $linkend = '</a>';
2918 
2919  global $user;
2920  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2921  $linkstart = '';
2922  $linkend = '';
2923  }
2924 
2925  $result .= $linkstart;
2926  if ($withpicto) {
2927  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2928  }
2929  if ($withpicto != 2) {
2930  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2931  }
2932  $result .= $linkend;
2933 
2934  global $action;
2935  $hookmanager->initHooks(array('thirdpartydao'));
2936  $parameters = array(
2937  'id'=>$this->id,
2938  'getnomurl' => &$result,
2939  'withpicto '=> $withpicto,
2940  'option'=> $option,
2941  'maxlen'=> $maxlen,
2942  'notooltip'=> $notooltip,
2943  'save_lastsearch_value'=> $save_lastsearch_value
2944  );
2945  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2946  if ($reshook > 0) {
2947  $result = $hookmanager->resPrint;
2948  } else {
2949  $result .= $hookmanager->resPrint;
2950  }
2951 
2952  return $result;
2953  }
2954 
2964  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2965  {
2966  global $conf, $langs;
2967 
2968  $s = '';
2969  if (empty($option) || preg_match('/prospect/', $option)) {
2970  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2971  $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.'>';
2972  }
2973  }
2974  if (empty($option) || preg_match('/customer/', $option)) {
2975  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2976  $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.'>';
2977  }
2978  }
2979  if (empty($option) || preg_match('/supplier/', $option)) {
2980  if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2981  $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.'>';
2982  }
2983  }
2984  return $s;
2985  }
2986 
2987 
2994  public function getLibStatut($mode = 0)
2995  {
2996  return $this->LibStatut($this->status, $mode);
2997  }
2998 
2999  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3007  public function LibStatut($status, $mode = 0)
3008  {
3009  // phpcs:enable
3010  global $langs;
3011  $langs->load('companies');
3012 
3013  $statusType = 'status4';
3014  if ($status == 0) {
3015  $statusType = 'status6';
3016  }
3017 
3018  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3019  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3020  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3021  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3022  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3023  }
3024 
3025  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3026  }
3027 
3028  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3035  public function thirdparty_and_contact_email_array($addthirdparty = 0)
3036  {
3037  // phpcs:enable
3038  global $langs;
3039 
3040  $contact_emails = $this->contact_property_array('email', 1);
3041  if ($this->email && $addthirdparty) {
3042  if (empty($this->name)) {
3043  $this->name = $this->nom;
3044  }
3045  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
3046  }
3047  //var_dump($contact_emails)
3048  return $contact_emails;
3049  }
3050 
3051  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3058  {
3059  // phpcs:enable
3060  global $langs;
3061 
3062  $contact_phone = $this->contact_property_array('mobile');
3063 
3064  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
3065  if (empty($this->name)) {
3066  $this->name = $this->nom;
3067  }
3068  // TODO: Tester si tel non deja present dans tableau contact
3069  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3070  }
3071  return $contact_phone;
3072  }
3073 
3074  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3082  public function contact_property_array($mode = 'email', $hidedisabled = 0)
3083  {
3084  // phpcs:enable
3085  global $langs;
3086 
3087  $contact_property = array();
3088 
3089 
3090  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3091  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3092  $sql .= " WHERE fk_soc = ".((int) $this->id);
3093  $sql .= " ORDER BY lastname, firstname";
3094 
3095  $resql = $this->db->query($sql);
3096  if ($resql) {
3097  $nump = $this->db->num_rows($resql);
3098  if ($nump) {
3099  $sepa = "("; $sepb = ")";
3100  if ($mode == 'email') {
3101  //$sepa="&lt;"; $sepb="&gt;";
3102  $sepa = "<"; $sepb = ">";
3103  }
3104  $i = 0;
3105  while ($i < $nump) {
3106  $obj = $this->db->fetch_object($resql);
3107  if ($mode == 'email') {
3108  $property = $obj->email;
3109  } elseif ($mode == 'mobile') {
3110  $property = $obj->phone_mobile;
3111  } else {
3112  $property = $obj->$mode;
3113  }
3114 
3115  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3116  if ($obj->status == 1 || empty($hidedisabled)) {
3117  if (empty($property)) {
3118  if ($mode == 'email') {
3119  $property = $langs->transnoentitiesnoconv("NoEMail");
3120  } elseif ($mode == 'mobile') {
3121  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3122  }
3123  }
3124 
3125  if (!empty($obj->poste)) {
3126  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3127  } else {
3128  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3129  }
3130  }
3131  $i++;
3132  }
3133  }
3134  } else {
3135  dol_print_error($this->db);
3136  }
3137  return $contact_property;
3138  }
3139 
3140 
3141  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3147  public function contact_array()
3148  {
3149  // phpcs:enable
3150  $contacts = array();
3151 
3152  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3153  $resql = $this->db->query($sql);
3154  if ($resql) {
3155  $nump = $this->db->num_rows($resql);
3156  if ($nump) {
3157  $i = 0;
3158  while ($i < $nump) {
3159  $obj = $this->db->fetch_object($resql);
3160  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
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
3176  public function contact_array_objects()
3177  {
3178  // phpcs:enable
3179  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3180  $contacts = array();
3181 
3182  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3183  $resql = $this->db->query($sql);
3184  if ($resql) {
3185  $nump = $this->db->num_rows($resql);
3186  if ($nump) {
3187  $i = 0;
3188  while ($i < $nump) {
3189  $obj = $this->db->fetch_object($resql);
3190  $contact = new Contact($this->db);
3191  $contact->fetch($obj->rowid);
3192  $contacts[] = $contact;
3193  $i++;
3194  }
3195  }
3196  } else {
3197  dol_print_error($this->db);
3198  }
3199  return $contacts;
3200  }
3201 
3202  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3210  public function contact_get_property($rowid, $mode)
3211  {
3212  // phpcs:enable
3213  $contact_property = '';
3214 
3215  if (empty($rowid)) {
3216  return '';
3217  }
3218 
3219  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3220  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3221  $sql .= " WHERE rowid = ".((int) $rowid);
3222 
3223  $resql = $this->db->query($sql);
3224  if ($resql) {
3225  $nump = $this->db->num_rows($resql);
3226 
3227  if ($nump) {
3228  $obj = $this->db->fetch_object($resql);
3229 
3230  if ($mode == 'email') {
3231  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3232  } elseif ($mode == 'mobile') {
3233  $contact_property = $obj->phone_mobile;
3234  }
3235  }
3236  return $contact_property;
3237  } else {
3238  dol_print_error($this->db);
3239  }
3240 
3241  return '';
3242  }
3243 
3244 
3245  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3252  public function display_rib($mode = 'label')
3253  {
3254  // phpcs:enable
3255  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3256 
3257  $bac = new CompanyBankAccount($this->db);
3258  $bac->fetch(0, $this->id);
3259 
3260  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3261  if ($mode == 'label') {
3262  return $bac->getRibLabel(true);
3263  } elseif ($mode == 'rum') {
3264  if (empty($bac->rum)) {
3265  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3266  $prelevement = new BonPrelevement($this->db);
3267  $bac->fetch_thirdparty();
3268  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3269  }
3270  return $bac->rum;
3271  } elseif ($mode == 'format') {
3272  return $bac->frstrecur;
3273  } else {
3274  return 'BadParameterToFunctionDisplayRib';
3275  }
3276  } else {
3277  return '';
3278  }
3279  }
3280 
3281  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3287  public function get_all_rib()
3288  {
3289  // phpcs:enable
3290  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3291  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3292  $result = $this->db->query($sql);
3293  if (!$result) {
3294  $this->error++;
3295  $this->errors[] = $this->db->lasterror;
3296  return 0;
3297  } else {
3298  $num_rows = $this->db->num_rows($result);
3299  $rib_array = array();
3300  if ($num_rows) {
3301  while ($obj = $this->db->fetch_object($result)) {
3302  $rib = new CompanyBankAccount($this->db);
3303  $rib->fetch($obj->rowid);
3304  $rib_array[] = $rib;
3305  }
3306  }
3307  return $rib_array;
3308  }
3309  }
3310 
3311  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3320  public function get_codeclient($objsoc = 0, $type = 0)
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_client = $mod->getNextValue($objsoc, $type);
3337  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3338 
3339  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3340  }
3341  }
3342 
3343  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3352  public function get_codefournisseur($objsoc = 0, $type = 1)
3353  {
3354  // phpcs:enable
3355  global $conf;
3356  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3357  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3358 
3359  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3360  foreach ($dirsociete as $dirroot) {
3361  $res = dol_include_once($dirroot.$module.'.php');
3362  if ($res) {
3363  break;
3364  }
3365  }
3366  $mod = new $module();
3367 
3368  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3369 
3370  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3371  }
3372  }
3373 
3374  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3381  public function codeclient_modifiable()
3382  {
3383  // phpcs:enable
3384  global $conf;
3385  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3386  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3387 
3388  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3389  foreach ($dirsociete as $dirroot) {
3390  $res = dol_include_once($dirroot.$module.'.php');
3391  if ($res) {
3392  break;
3393  }
3394  }
3395 
3396  $mod = new $module();
3397 
3398  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3399  if ($mod->code_modifiable_null && !$this->code_client) {
3400  return 1;
3401  }
3402  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3403  return 1;
3404  }
3405  if ($mod->code_modifiable) {
3406  return 1; // A mettre en dernier
3407  }
3408  return 0;
3409  } else {
3410  return 0;
3411  }
3412  }
3413 
3414 
3415  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3421  public function codefournisseur_modifiable()
3422  {
3423  // phpcs:enable
3424  global $conf;
3425  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3426  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3427 
3428  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3429  foreach ($dirsociete as $dirroot) {
3430  $res = dol_include_once($dirroot.$module.'.php');
3431  if ($res) {
3432  break;
3433  }
3434  }
3435 
3436  $mod = new $module();
3437 
3438  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3439  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3440  return 1;
3441  }
3442  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3443  return 1;
3444  }
3445  if ($mod->code_modifiable) {
3446  return 1; // A mettre en dernier
3447  }
3448  return 0;
3449  } else {
3450  return 0;
3451  }
3452  }
3453 
3454 
3455  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3467  public function check_codeclient()
3468  {
3469  // phpcs:enable
3470  global $conf;
3471  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3472  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3473 
3474  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3475  foreach ($dirsociete as $dirroot) {
3476  $res = dol_include_once($dirroot.$module.'.php');
3477  if ($res) {
3478  break;
3479  }
3480  }
3481 
3482  $mod = new $module();
3483 
3484  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3485  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3486  if ($result) { // If error
3487  $this->error = $mod->error;
3488  $this->errors = $mod->errors;
3489  }
3490  return $result;
3491  } else {
3492  return 0;
3493  }
3494  }
3495 
3496  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3508  public function check_codefournisseur()
3509  {
3510  // phpcs:enable
3511  global $conf;
3512  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3513  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3514 
3515  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3516  foreach ($dirsociete as $dirroot) {
3517  $res = dol_include_once($dirroot.$module.'.php');
3518  if ($res) {
3519  break;
3520  }
3521  }
3522 
3523  $mod = new $module();
3524 
3525  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3526  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3527  if ($result) { // If error
3528  $this->error = $mod->error;
3529  $this->errors = $mod->errors;
3530  }
3531  return $result;
3532  } else {
3533  return 0;
3534  }
3535  }
3536 
3537  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3546  public function get_codecompta($type)
3547  {
3548  // phpcs:enable
3549  global $conf;
3550 
3551  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3552  $res = false;
3553  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3554  foreach ($dirsociete as $dirroot) {
3555  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3556  if ($res) {
3557  break;
3558  }
3559  }
3560 
3561  if ($res) {
3562  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3563  $mod = new $classname;
3564 
3565  // Set code count in $mod->code
3566  $result = $mod->get_code($this->db, $this, $type);
3567 
3568  if ($type == 'customer') {
3569  $this->code_compta_client = $mod->code;
3570  $this->code_compta = $this->code_compta_client; // For backward compatibility
3571  } elseif ($type == 'supplier') {
3572  $this->code_compta_fournisseur = $mod->code;
3573  }
3574 
3575  return $result;
3576  } else {
3577  $this->error = 'ErrorAccountancyCodeNotDefined';
3578  return -1;
3579  }
3580  } else {
3581  if ($type == 'customer') {
3582  $this->code_compta_client = '';
3583  $this->code_compta = '';
3584  } elseif ($type == 'supplier') {
3585  $this->code_compta_fournisseur = '';
3586  }
3587 
3588  return 0;
3589  }
3590  }
3591 
3598  public function setParent($id)
3599  {
3600  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3601 
3602  if ($this->id) {
3603  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3604  if ($id > 0) {
3605  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3606  if ($sameparent < 0) {
3607  return -1;
3608  }
3609  if ($sameparent == 1) {
3610  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3611  return -1;
3612  }
3613  }
3614 
3615  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3616 
3617  $resql = $this->db->query($sql);
3618  if ($resql) {
3619  $this->parent = $id;
3620  return 1;
3621  } else {
3622  return -1;
3623  }
3624  }
3625 
3626  return -1;
3627  }
3628 
3637  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3638  {
3639  if ($counter > 100) {
3640  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3641  }
3642 
3643  $sql = 'SELECT s.parent';
3644  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3645  $sql .= ' WHERE rowid = '.((int) $idparent);
3646  $resql = $this->db->query($sql);
3647  if ($resql) {
3648  $obj = $this->db->fetch_object($resql);
3649 
3650  if ($obj->parent == '') {
3651  return 0;
3652  } elseif ($obj->parent == $idchild) {
3653  return 1;
3654  } else {
3655  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3656  }
3657  return $sameparent;
3658  } else {
3659  return -1;
3660  }
3661  }
3662 
3670  public function getParentsForCompany($company_id, $parents = [])
3671  {
3672  global $langs;
3673 
3674  if ($company_id > 0) {
3675  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3676  $resql = $this->db->query($sql);
3677  if ($resql) {
3678  if ($obj = $this->db->fetch_object($resql)) {
3679  $parent = $obj->parent;
3680  if ($parent > 0 && !in_array($parent, $parents)) {
3681  $parents[] = $parent;
3682  return $this->getParentsForCompany($parent, $parents);
3683  } else {
3684  return $parents;
3685  }
3686  }
3687  $this->db->free($resql);
3688  } else {
3689  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3690  }
3691  }
3692  }
3693 
3694  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3701  public function id_prof_verifiable($idprof)
3702  {
3703  // phpcs:enable
3704  global $conf;
3705 
3706  switch ($idprof) {
3707  case 1:
3708  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3709  break;
3710  case 2:
3711  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3712  break;
3713  case 3:
3714  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3715  break;
3716  case 4:
3717  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3718  break;
3719  case 5:
3720  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3721  break;
3722  case 6:
3723  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3724  break;
3725  default:
3726  $ret = false;
3727  }
3728 
3729  return $ret;
3730  }
3731 
3732  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3741  public function id_prof_exists($idprof, $value, $socid = 0)
3742  {
3743  // phpcs:enable
3744  $field = $idprof;
3745 
3746  switch ($idprof) { // For backward compatibility
3747  case '1':
3748  case 'idprof1':
3749  $field = "siren";
3750  break;
3751  case '2':
3752  case 'idprof2':
3753  $field = "siret";
3754  break;
3755  case '3':
3756  case 'idprof3':
3757  $field = "ape";
3758  break;
3759  case '4':
3760  case 'idprof4':
3761  $field = "idprof4";
3762  break;
3763  case '5':
3764  $field = "idprof5";
3765  break;
3766  case '6':
3767  $field = "idprof6";
3768  break;
3769  }
3770 
3771  //Verify duplicate entries
3772  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3773  if ($socid) {
3774  $sql .= " AND rowid <> ".$socid;
3775  }
3776  $resql = $this->db->query($sql);
3777  if ($resql) {
3778  $obj = $this->db->fetch_object($resql);
3779  $count = $obj->nb;
3780  } else {
3781  $count = 0;
3782  print $this->db->error();
3783  }
3784  $this->db->free($resql);
3785 
3786  if ($count > 0) {
3787  return true;
3788  } else {
3789  return false;
3790  }
3791  }
3792 
3793  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3802  public function id_prof_check($idprof, $soc)
3803  {
3804  // phpcs:enable
3805  global $conf;
3806 
3807  $ok = 1;
3808 
3809  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3810  return 1;
3811  }
3812 
3813  // Check SIREN if country FR
3814  if ($idprof == 1 && $soc->country_code == 'FR') {
3815  $chaine = trim($this->idprof1);
3816  $chaine = preg_replace('/(\s)/', '', $chaine);
3817 
3818  if (!is_numeric($chaine)) {
3819  return -1;
3820  }
3821  if (dol_strlen($chaine) != 9) {
3822  return -1;
3823  }
3824 
3825  // on prend chaque chiffre un par un
3826  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3827  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3828  // on ajoute cette valeur à la somme totale
3829  $sum = 0;
3830  for ($index = 0; $index < 9; $index++) {
3831  $number = (int) $chaine[$index];
3832  if (($index % 2) != 0) {
3833  if (($number *= 2) > 9) {
3834  $number -= 9;
3835  }
3836  }
3837  $sum += $number;
3838  }
3839 
3840  // le numéro est valide si la somme des chiffres est multiple de 10
3841  if (($sum % 10) != 0) {
3842  return -1;
3843  }
3844  }
3845 
3846  // Verifie SIRET si pays FR
3847  if ($idprof == 2 && $soc->country_code == 'FR') {
3848  $chaine = trim($this->idprof2);
3849  $chaine = preg_replace('/(\s)/', '', $chaine);
3850 
3851  if (!is_numeric($chaine)) {
3852  return -1;
3853  }
3854  if (dol_strlen($chaine) != 14) {
3855  return -1;
3856  }
3857 
3858  // on prend chaque chiffre un par un
3859  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3860  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3861  // on ajoute cette valeur à la somme totale
3862  $sum = 0;
3863  for ($index = 0; $index < 14; $index++) {
3864  $number = (int) $chaine[$index];
3865  if (($index % 2) == 0) {
3866  if (($number *= 2) > 9) {
3867  $number -= 9;
3868  }
3869  }
3870  $sum += $number;
3871  }
3872 
3873  // le numéro est valide si la somme des chiffres est multiple de 10
3874  if (($sum % 10) != 0) {
3875  return -1;
3876  }
3877  }
3878 
3879  //Verify CIF/NIF/NIE if pays ES
3880  //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
3881  if ($idprof == 1 && $soc->country_code == 'ES') {
3882  $string = trim($this->idprof1);
3883  $string = preg_replace('/(\s)/', '', $string);
3884  $string = strtoupper($string);
3885 
3886  //Check format
3887  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)) {
3888  return 0;
3889  }
3890 
3891  $num = array();
3892  for ($i = 0; $i < 9; $i++) {
3893  $num[$i] = substr($string, $i, 1);
3894  }
3895 
3896  //Check NIF
3897  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3898  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3899  return 1;
3900  } else {
3901  return -1;
3902  }
3903  }
3904 
3905  //algorithm checking type code CIF
3906  $sum = $num[2] + $num[4] + $num[6];
3907  for ($i = 1; $i < 8; $i += 2) {
3908  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3909  }
3910  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3911 
3912  //Chek special NIF
3913  if (preg_match('/^[KLM]{1}/', $string)) {
3914  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3915  return 1;
3916  } else {
3917  return -1;
3918  }
3919  }
3920 
3921  //Check CIF
3922  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3923  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3924  return 2;
3925  } else {
3926  return -2;
3927  }
3928  }
3929 
3930  //Check NIE T
3931  if (preg_match('/^[T]{1}/', $string)) {
3932  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3933  return 3;
3934  } else {
3935  return -3;
3936  }
3937  }
3938 
3939  //Check NIE XYZ
3940  if (preg_match('/^[XYZ]{1}/', $string)) {
3941  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3942  return 3;
3943  } else {
3944  return -3;
3945  }
3946  }
3947 
3948  //Can not be verified
3949  return -4;
3950  }
3951 
3952  //Verify NIF if country is PT
3953  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3954  if ($idprof == 1 && $soc->country_code == 'PT') {
3955  $string = trim($this->idprof1);
3956  $string = preg_replace('/(\s)/', '', $string);
3957 
3958  //Check NIF
3959  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3960  return 1;
3961  } else {
3962  return -1;
3963  }
3964  }
3965 
3966  //Verify NIF if country is DZ
3967  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3968  if ($idprof == 1 && $soc->country_code == 'DZ') {
3969  $string = trim($this->idprof1);
3970  $string = preg_replace('/(\s)/', '', $string);
3971 
3972  //Check NIF
3973  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3974  return 1;
3975  } else {
3976  return -1;
3977  }
3978  }
3979 
3980  return $ok;
3981  }
3982 
3983  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3992  public function id_prof_url($idprof, $thirdparty)
3993  {
3994  // phpcs:enable
3995  global $conf, $langs, $hookmanager;
3996 
3997  $url = '';
3998  $action = '';
3999 
4000  $hookmanager->initHooks(array('idprofurl'));
4001  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
4002  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4003  if (empty($reshook)) {
4004  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
4005  return '';
4006  }
4007 
4008  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4009  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4010  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4011  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4012  }
4013  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4014  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4015  }
4016  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4017  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4018  }
4019  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4020  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4021  }
4022  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4023  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4024  }
4025  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4026  $url = 'http://www.nif.pt/'.$strippedIdProf1;
4027  }
4028 
4029  if ($url) {
4030  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4031  }
4032  } else {
4033  return $hookmanager->resPrint;
4034  }
4035 
4036  return '';
4037  }
4038 
4039  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4045  public function has_projects()
4046  {
4047  // phpcs:enable
4048  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4049  $resql = $this->db->query($sql);
4050  if ($resql) {
4051  $obj = $this->db->fetch_object($resql);
4052  $count = $obj->numproj;
4053  } else {
4054  $count = 0;
4055  print $this->db->error();
4056  }
4057  $this->db->free($resql);
4058  return ($count > 0);
4059  }
4060 
4061 
4068  public function info($id)
4069  {
4070  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4071  $sql .= " fk_user_creat, fk_user_modif";
4072  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4073  $sql .= " WHERE s.rowid = ".((int) $id);
4074 
4075  $result = $this->db->query($sql);
4076  if ($result) {
4077  if ($this->db->num_rows($result)) {
4078  $obj = $this->db->fetch_object($result);
4079 
4080  $this->id = $obj->rowid;
4081 
4082  $this->user_creation_id = $obj->fk_user_creat;
4083  $this->user_modification_id = $obj->fk_user_modif;
4084  $this->date_creation = $this->db->jdate($obj->datec);
4085  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4086 
4087  $this->ref = $obj->name;
4088  }
4089 
4090  $this->db->free($result);
4091  } else {
4092  dol_print_error($this->db);
4093  }
4094  }
4095 
4101  public function isACompany()
4102  {
4103  global $conf;
4104 
4105  // Define if third party is treated as company (or not) when nature is unknown
4106  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
4107  if (!empty($this->tva_intra)) {
4108  $isacompany = 1;
4109  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4110  $isacompany = 1;
4111  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
4112  // TODO Add a field is_a_company into dictionary
4113  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4114  $isacompany = 0;
4115  } else {
4116  $isacompany = 1;
4117  }
4118  }
4119 
4120  return $isacompany;
4121  }
4122 
4128  public function isInEEC()
4129  {
4130  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4131  return isInEEC($this);
4132  }
4133 
4134  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4140  public function LoadSupplierCateg()
4141  {
4142  // phpcs:enable
4143  $this->SupplierCategories = array();
4144  $sql = "SELECT rowid, label";
4145  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4146  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4147 
4148  $resql = $this->db->query($sql);
4149  if ($resql) {
4150  while ($obj = $this->db->fetch_object($resql)) {
4151  $this->SupplierCategories[$obj->rowid] = $obj->label;
4152  }
4153  return 0;
4154  } else {
4155  return -1;
4156  }
4157  }
4158 
4159  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4166  public function AddFournisseurInCategory($categorie_id)
4167  {
4168  // phpcs:enable
4169  if ($categorie_id > 0 && $this->id > 0) {
4170  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4171  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4172 
4173  if ($resql = $this->db->query($sql)) {
4174  return 0;
4175  }
4176  } else {
4177  return 0;
4178  }
4179  return -1;
4180  }
4181 
4187  public function getNbOfEMailings()
4188  {
4189  $sql = "SELECT count(mc.email) as nb";
4190  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4191  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4192  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4193 
4194  $resql = $this->db->query($sql);
4195  if ($resql) {
4196  $obj = $this->db->fetch_object($resql);
4197  $nb = $obj->nb;
4198 
4199  $this->db->free($resql);
4200  return $nb;
4201  } else {
4202  $this->error = $this->db->error();
4203  return -1;
4204  }
4205  }
4206 
4213  public function setNoEmail($no_email)
4214  {
4215  $error = 0;
4216 
4217  // Update mass emailing flag into table mailing_unsubscribe
4218  if ($this->email) {
4219  $this->db->begin();
4220 
4221  if ($no_email) {
4222  $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)."'";
4223  $resql = $this->db->query($sql);
4224  if ($resql) {
4225  $obj = $this->db->fetch_object($resql);
4226  $noemail = $obj->nb;
4227  if (empty($noemail)) {
4228  $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())."')";
4229  $resql = $this->db->query($sql);
4230  if (!$resql) {
4231  $error++;
4232  $this->error = $this->db->lasterror();
4233  $this->errors[] = $this->error;
4234  }
4235  }
4236  } else {
4237  $error++;
4238  $this->error = $this->db->lasterror();
4239  $this->errors[] = $this->error;
4240  }
4241  } else {
4242  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4243  $resql = $this->db->query($sql);
4244  if (!$resql) {
4245  $error++;
4246  $this->error = $this->db->lasterror();
4247  $this->errors[] = $this->error;
4248  }
4249  }
4250 
4251  if (empty($error)) {
4252  $this->no_email = $no_email;
4253  $this->db->commit();
4254  return 1;
4255  } else {
4256  $this->db->rollback();
4257  return $error * -1;
4258  }
4259  }
4260 
4261  return 0;
4262  }
4263 
4270  public function getNoEmail()
4271  {
4272  if ($this->email) {
4273  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4274  $resql = $this->db->query($sql);
4275  if ($resql) {
4276  $obj = $this->db->fetch_object($resql);
4277  $this->no_email = $obj->nb;
4278  return 1;
4279  } else {
4280  $this->error = $this->db->lasterror();
4281  $this->errors[] = $this->error;
4282  return -1;
4283  }
4284  }
4285  return 0;
4286  }
4287 
4288  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4298  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4299  {
4300  // phpcs:enable
4301  global $conf, $user, $langs;
4302 
4303  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4304  $fullname = $member->getFullName($langs);
4305 
4306  if ($member->morphy == 'mor') {
4307  if (empty($socname)) {
4308  $socname = $member->company? $member->company : $member->societe;
4309  }
4310  if (!empty($fullname) && empty($socalias)) {
4311  $socalias = $fullname;
4312  }
4313  } elseif (empty($socname) && $member->morphy == 'phy') {
4314  if (empty($socname)) {
4315  $socname = $fullname;
4316  }
4317  if (!empty($member->company) && empty($socalias)) {
4318  $socalias = $member->company;
4319  }
4320  }
4321 
4322  $name = $socname;
4323  $alias = $socalias ? $socalias : '';
4324 
4325  // Positionne parametres
4326  $this->nom = $name; // TODO deprecated
4327  $this->name = $name;
4328  $this->name_alias = $alias;
4329  $this->address = $member->address;
4330  $this->zip = $member->zip;
4331  $this->town = $member->town;
4332  $this->country_code = $member->country_code;
4333  $this->country_id = $member->country_id;
4334  $this->phone = $member->phone; // Prof phone
4335  $this->email = $member->email;
4336  $this->socialnetworks = $member->socialnetworks;
4337  $this->entity = $member->entity;
4338 
4339  $this->client = 1; // A member is a customer by default
4340  $this->code_client = ($customercode ? $customercode : -1);
4341  $this->code_fournisseur = -1;
4342  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4343  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4344 
4345  $this->db->begin();
4346 
4347  // Cree et positionne $this->id
4348  $result = $this->create($user);
4349 
4350  if ($result >= 0) {
4351  // Auto-create contact on thirdparty creation
4352  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4353  // Fill fields needed by contact
4354  $this->name_bis = $member->lastname;
4355  $this->firstname = $member->firstname;
4356  $this->civility_id = $member->civility_id;
4357 
4358  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4359  $result = $this->create_individual($user);
4360 
4361  if ($result < 0) {
4362  setEventMessages($this->error, $this->errors, 'errors');
4363  $this->db->rollback();
4364  return -1;
4365  }
4366  }
4367 
4368  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4369  $sql .= " SET fk_soc = ".((int) $this->id);
4370  $sql .= " WHERE rowid = ".((int) $member->id);
4371 
4372  $resql = $this->db->query($sql);
4373  if ($resql) {
4374  $this->db->commit();
4375  return $this->id;
4376  } else {
4377  $this->error = $this->db->error();
4378 
4379  $this->db->rollback();
4380  return -1;
4381  }
4382  } else {
4383  // $this->error deja positionne
4384  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4385 
4386  $this->db->rollback();
4387  return $result;
4388  }
4389  }
4390 
4397  public function setMysoc(Conf $conf)
4398  {
4399  global $langs;
4400 
4401  $this->id = 0;
4402  $this->entity = $conf->entity;
4403  $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4404  $this->nom = $this->name; // deprecated
4405  $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4406  $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4407  $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4408  $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4409 
4410  $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4411 
4412  $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4413 
4414  // We define country_id, country_code and country
4415  $country_id = $country_code = $country_label = '';
4416  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4417  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4418  $country_id = $tmp[0];
4419  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4420  $country_code = $tmp[1];
4421  $country_label = $tmp[2];
4422  } else {
4423  // For backward compatibility
4424  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4425  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4426  $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
4427  $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
4428  }
4429  }
4430  $this->country_id = $country_id;
4431  $this->country_code = $country_code;
4432  $this->country = $country_label;
4433  if (is_object($langs)) {
4434  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4435  }
4436 
4437  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4438  // We define state_id, state_code and state
4439  $state_id = 0; $state_code = $state_label = '';
4440  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4441  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4442  $state_id = $tmp[0];
4443  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4444  $state_code = $tmp[1];
4445  $state_label = $tmp[2];
4446  } else { // For backward compatibility
4447  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);
4448  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4449  $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
4450  $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
4451  }
4452  }
4453  $this->state_id = $state_id;
4454  $this->state_code = $state_code;
4455  $this->state = $state_label;
4456  if (is_object($langs)) {
4457  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4458  }
4459 
4460  $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4461  $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4462  $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4463 
4464  // Social networks
4465  $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4466  $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4467  $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4468  $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4469  $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4470  $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4471  $this->socialnetworks = array();
4472  if (!empty($facebook_url)) {
4473  $this->socialnetworks['facebook'] = $facebook_url;
4474  }
4475  if (!empty($twitter_url)) {
4476  $this->socialnetworks['twitter'] = $twitter_url;
4477  }
4478  if (!empty($linkedin_url)) {
4479  $this->socialnetworks['linkedin'] = $linkedin_url;
4480  }
4481  if (!empty($instagram_url)) {
4482  $this->socialnetworks['instagram'] = $instagram_url;
4483  }
4484  if (!empty($youtube_url)) {
4485  $this->socialnetworks['youtube'] = $youtube_url;
4486  }
4487  if (!empty($github_url)) {
4488  $this->socialnetworks['github'] = $github_url;
4489  }
4490 
4491  // Id prof generiques
4492  $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4493  $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4494  $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4495  $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4496  $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4497  $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4498  $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarly INTRA.
4499  $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4500  $this->capital = getDolGlobalString('MAIN_INFO_CAPITAL');
4501  $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4502  $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4503  $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4504  $this->logo =getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4505  $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4506  $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4507  $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4508  $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4509  $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4510 
4511  // Define if company use vat or not
4512  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4513 
4514  // Define if company use local taxes
4515  $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);
4516  $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);
4517  }
4518 
4526  public function initAsSpecimen()
4527  {
4528  $now = dol_now();
4529 
4530  // Initialize parameters
4531  $this->id = 0;
4532  $this->entity = 1;
4533  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4534  $this->nom = $this->name; // For backward compatibility
4535  $this->ref_ext = 'Ref ext';
4536  $this->specimen = 1;
4537  $this->address = '21 jump street';
4538  $this->zip = '99999';
4539  $this->town = 'MyTown';
4540  $this->state_id = 1;
4541  $this->state_code = 'AA';
4542  $this->state = 'MyState';
4543  $this->country_id = 1;
4544  $this->country_code = 'FR';
4545  $this->email = 'specimen@specimen.com';
4546  $this->socialnetworks = array(
4547  'skype' => 'tom.hanson',
4548  'twitter' => 'tomhanson',
4549  'facebook' => 'tomhanson',
4550  'linkedin' => 'tomhanson',
4551  );
4552  $this->url = 'http://www.specimen.com';
4553 
4554  $this->phone = '0909090901';
4555  $this->fax = '0909090909';
4556 
4557  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4558  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4559  $this->capital = 10000;
4560  $this->client = 1;
4561  $this->prospect = 1;
4562  $this->fournisseur = 1;
4563  $this->tva_assuj = 1;
4564  $this->tva_intra = 'EU1234567';
4565  $this->note_public = 'This is a comment (public)';
4566  $this->note_private = 'This is a comment (private)';
4567 
4568  $this->idprof1 = 'idprof1';
4569  $this->idprof2 = 'idprof2';
4570  $this->idprof3 = 'idprof3';
4571  $this->idprof4 = 'idprof4';
4572  $this->idprof5 = 'idprof5';
4573  $this->idprof6 = 'idprof6';
4574  return 1;
4575  }
4576 
4583  public function useLocalTax($localTaxNum = 0)
4584  {
4585  $sql = "SELECT t.localtax1, t.localtax2";
4586  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4587  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4588  $sql .= " AND t.active = 1";
4589  if (empty($localTaxNum)) {
4590  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4591  } elseif ($localTaxNum == 1) {
4592  $sql .= " AND t.localtax1_type <> '0'";
4593  } elseif ($localTaxNum == 2) {
4594  $sql .= " AND t.localtax2_type <> '0'";
4595  }
4596 
4597  $resql = $this->db->query($sql);
4598  if ($resql) {
4599  return ($this->db->num_rows($resql) > 0);
4600  } else {
4601  return false;
4602  }
4603  }
4604 
4610  public function useNPR()
4611  {
4612  $sql = "SELECT t.rowid";
4613  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4614  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4615  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4616 
4617  dol_syslog("useNPR", LOG_DEBUG);
4618  $resql = $this->db->query($sql);
4619  if ($resql) {
4620  return ($this->db->num_rows($resql) > 0);
4621  } else {
4622  return false;
4623  }
4624  }
4625 
4632  public function useRevenueStamp()
4633  {
4634  $sql = "SELECT COUNT(*) as nb";
4635  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4636  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4637  $sql .= " AND r.active = 1";
4638 
4639  dol_syslog("useRevenueStamp", LOG_DEBUG);
4640  $resql = $this->db->query($sql);
4641  if ($resql) {
4642  $obj = $this->db->fetch_object($resql);
4643  return (($obj->nb > 0) ?true:false);
4644  } else {
4645  $this->error = $this->db->lasterror();
4646  return false;
4647  }
4648  }
4649 
4655  public function getLibProspLevel()
4656  {
4657  return $this->LibProspLevel($this->fk_prospectlevel);
4658  }
4659 
4660  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4667  public function LibProspLevel($fk_prospectlevel)
4668  {
4669  // phpcs:enable
4670  global $langs;
4671 
4672  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4673  // If lib not found in language file, we get label from cache/databse
4674  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4675  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4676  }
4677  return $lib;
4678  }
4679 
4687  public function getLibProspCommStatut($mode = 0, $label = '')
4688  {
4689  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4690  }
4691 
4692  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4706  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4707  {
4708  // phpcs:enable
4709  global $langs;
4710 
4711  $langs->load('customers');
4712 
4713  if ($mode == 2) {
4714  if ($status == '-1' || $status == 'ST_NO') {
4715  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4716  } elseif ($status == '0' || $status == 'ST_NEVER') {
4717  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4718  } elseif ($status == '1' || $status == 'ST_TODO') {
4719  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4720  } elseif ($status == '2' || $status == 'ST_PEND') {
4721  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4722  } elseif ($status == '3' || $status == 'ST_DONE') {
4723  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4724  } else {
4725  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);
4726  }
4727  } elseif ($mode == 3) {
4728  if ($status == '-1' || $status == 'ST_NO') {
4729  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4730  } elseif ($status == '0' || $status == 'ST_NEVER') {
4731  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4732  } elseif ($status == '1' || $status == 'ST_TODO') {
4733  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4734  } elseif ($status == '2' || $status == 'ST_PEND') {
4735  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4736  } elseif ($status == '3' || $status == 'ST_DONE') {
4737  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4738  } else {
4739  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4740  }
4741  } elseif ($mode == 4) {
4742  if ($status == '-1' || $status == 'ST_NO') {
4743  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4744  } elseif ($status == '0' || $status == 'ST_NEVER') {
4745  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4746  } elseif ($status == '1' || $status == 'ST_TODO') {
4747  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4748  } elseif ($status == '2' || $status == 'ST_PEND') {
4749  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4750  } elseif ($status == '3' || $status == 'ST_DONE') {
4751  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4752  } else {
4753  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);
4754  }
4755  }
4756 
4757  return "Error, mode/status not found";
4758  }
4759 
4766  public function getOutstandingProposals($mode = 'customer')
4767  {
4768  $table = 'propal';
4769  if ($mode == 'supplier') {
4770  $table = 'supplier_proposal';
4771  }
4772 
4773  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4774  $sql .= " WHERE fk_soc = ".((int) $this->id);
4775  if ($mode == 'supplier') {
4776  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4777  } else {
4778  $sql .= " AND entity IN (".getEntity('propal').")";
4779  }
4780 
4781  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4782 
4783  $resql = $this->db->query($sql);
4784  if ($resql) {
4785  $outstandingOpened = 0;
4786  $outstandingTotal = 0;
4787  $outstandingTotalIncTax = 0;
4788  $arrayofref = array();
4789  while ($obj = $this->db->fetch_object($resql)) {
4790  $arrayofref[$obj->rowid] = $obj->ref;
4791  $outstandingTotal += $obj->total_ht;
4792  $outstandingTotalIncTax += $obj->total_ttc;
4793  if ($obj->status != 0) {
4794  // Not a draft
4795  $outstandingOpened += $obj->total_ttc;
4796  }
4797  }
4798  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4799  } else {
4800  return array();
4801  }
4802  }
4803 
4810  public function getOutstandingOrders($mode = 'customer')
4811  {
4812  $table = 'commande';
4813  if ($mode == 'supplier') {
4814  $table = 'commande_fournisseur';
4815  }
4816 
4817  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4818  $sql .= " WHERE fk_soc = ".((int) $this->id);
4819  if ($mode == 'supplier') {
4820  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4821  } else {
4822  $sql .= " AND entity IN (".getEntity('commande').")";
4823  }
4824 
4825  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4826  $resql = $this->db->query($sql);
4827  if ($resql) {
4828  $outstandingOpened = 0;
4829  $outstandingTotal = 0;
4830  $outstandingTotalIncTax = 0;
4831  $arrayofref = array();
4832  while ($obj = $this->db->fetch_object($resql)) {
4833  $arrayofref[$obj->rowid] = $obj->ref;
4834  $outstandingTotal += $obj->total_ht;
4835  $outstandingTotalIncTax += $obj->total_ttc;
4836  if ($obj->status != 0) {
4837  // Not a draft
4838  $outstandingOpened += $obj->total_ttc;
4839  }
4840  }
4841  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4842  } else {
4843  return array();
4844  }
4845  }
4846 
4854  public function getOutstandingBills($mode = 'customer', $late = 0)
4855  {
4856  $table = 'facture';
4857  if ($mode == 'supplier') {
4858  $table = 'facture_fourn';
4859  }
4860 
4861  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4862  $paiement = $invoice->getSommePaiement();
4863  $creditnotes=$invoice->getSumCreditNotesUsed();
4864  $deposits=$invoice->getSumDepositsUsed();
4865  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4866  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4867  */
4868  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4869  $sql .= " WHERE fk_soc = ".((int) $this->id);
4870  if (!empty($late)) {
4871  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4872  }
4873  if ($mode == 'supplier') {
4874  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4875  } else {
4876  $sql .= " AND entity IN (".getEntity('invoice').")";
4877  }
4878 
4879  dol_syslog("getOutstandingBills", LOG_DEBUG);
4880  $resql = $this->db->query($sql);
4881  if ($resql) {
4882  $outstandingOpened = 0;
4883  $outstandingTotal = 0;
4884  $outstandingTotalIncTax = 0;
4885  $arrayofref = array();
4886  $arrayofrefopened = array();
4887  if ($mode == 'supplier') {
4888  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4889  $tmpobject = new FactureFournisseur($this->db);
4890  } else {
4891  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4892  $tmpobject = new Facture($this->db);
4893  }
4894  while ($obj = $this->db->fetch_object($resql)) {
4895  $arrayofref[$obj->rowid] = $obj->ref;
4896  $tmpobject->id = $obj->rowid;
4897 
4898  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4899  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4900  ) {
4901  $outstandingTotal += $obj->total_ht;
4902  $outstandingTotalIncTax += $obj->total_ttc;
4903  }
4904 
4905  $remaintopay = 0;
4906 
4907  if ($obj->paye == 0
4908  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4909  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4910  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4911  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4912  $paiement = $tmpobject->getSommePaiement();
4913  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4914  $deposits = $tmpobject->getSumDepositsUsed();
4915 
4916  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4917  $outstandingOpened += $remaintopay;
4918  }
4919 
4920  //if credit note is converted but not used
4921  // TODO Do this also for customer ?
4922  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4923  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4924  $remaintopay -= $remainingcreditnote;
4925  $outstandingOpened -= $remainingcreditnote;
4926  }
4927 
4928  if ($remaintopay) {
4929  $arrayofrefopened[$obj->rowid] = $obj->ref;
4930  }
4931  }
4932  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4933  } else {
4934  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4935  return array();
4936  }
4937  }
4938 
4945  public function getLibCustProspStatut()
4946  {
4947  return $this->LibCustProspStatut($this->client);
4948  }
4949 
4950  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4957  public function LibCustProspStatut($status)
4958  {
4959  // phpcs:enable
4960  global $langs;
4961  $langs->load('companies');
4962 
4963  if ($status == 0) {
4964  return $langs->trans("NorProspectNorCustomer");
4965  } elseif ($status == 1) {
4966  return $langs->trans("Customer");
4967  } elseif ($status == 2) {
4968  return $langs->trans("Prospect");
4969  } elseif ($status == 3) {
4970  return $langs->trans("ProspectCustomer");
4971  }
4972 
4973  return '';
4974  }
4975 
4976 
4988  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4989  {
4990  global $conf, $user, $langs;
4991 
4992  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4993  $modelpath = "core/modules/bank/doc/";
4994 
4995  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4996  $companybankaccount = new CompanyBankAccount($this->db);
4997  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4998  if (!$result) {
4999  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5000  }
5001  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5002  } else {
5003  // Positionne le modele sur le nom du modele a utiliser
5004  if (!dol_strlen($modele)) {
5005  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
5006  $modele = $conf->global->COMPANY_ADDON_PDF;
5007  } else {
5008  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5009  return 0;
5010  }
5011  }
5012 
5013  if (!isset($this->bank_account)) {
5014  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5015  $bac = new CompanyBankAccount($this->db);
5016  $result = $bac->fetch(0, $this->id);
5017  if ($result > 0) {
5018  $this->bank_account = $bac;
5019  } else {
5020  $this->bank_account = '';
5021  }
5022  }
5023 
5024  $modelpath = "core/modules/societe/doc/";
5025 
5026  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5027  }
5028 
5029  return $result;
5030  }
5031 
5032 
5044  public function setCategories($categories, $type_categ)
5045  {
5046  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5047 
5048  // Decode type
5049  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5050  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5051  return -1;
5052  }
5053 
5054  return parent::setCategoriesCommon($categories, $type_categ);
5055  }
5056 
5064  public function setSalesRep($salesrep, $onlyAdd = false)
5065  {
5066  global $user;
5067 
5068  // Handle single user
5069  if (!is_array($salesrep)) {
5070  $salesrep = array($salesrep);
5071  }
5072 
5073  $to_del = array(); // Nothing to delete
5074  $to_add = $salesrep;
5075  if ($onlyAdd === false) {
5076  // Get current users
5077  $existing = $this->getSalesRepresentatives($user, 1);
5078 
5079  // Diff
5080  if (is_array($existing)) {
5081  $to_del = array_diff($existing, $salesrep);
5082  $to_add = array_diff($salesrep, $existing);
5083  }
5084  }
5085 
5086  $error = 0;
5087 
5088  // Process
5089  foreach ($to_del as $del) {
5090  $this->del_commercial($user, $del);
5091  }
5092  foreach ($to_add as $add) {
5093  $result = $this->add_commercial($user, $add);
5094  if ($result < 0) {
5095  $error++;
5096  break;
5097  }
5098  }
5099 
5100  return $error ? -1 : 1;
5101  }
5102 
5109  public function setThirdpartyType($typent_id)
5110  {
5111  global $user;
5112 
5113  dol_syslog(__METHOD__, LOG_DEBUG);
5114 
5115  if ($this->id) {
5116  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5117 
5118  if ($result > 0) {
5119  $this->typent_id = $typent_id;
5120  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5121  return 1;
5122  } else {
5123  return -1;
5124  }
5125  } else {
5126  return -1;
5127  }
5128  }
5129 
5139  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5140  {
5141  if ($origin_id == $dest_id) {
5142  dol_syslog('Error: Try to merge a thirdparty into itself');
5143  return false;
5144  }
5145 
5150  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5151  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5152  $sql .= ' SELECT fk_user ';
5153  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5154  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5155 
5156  $resql = $dbs->query($sql);
5157  while ($obj = $dbs->fetch_object($resql)) {
5158  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5159  }
5160 
5165  $tables = array(
5166  'societe_address',
5167  'societe_commerciaux',
5168  'societe_prices',
5169  'societe_remise',
5170  'societe_remise_except',
5171  'societe_rib'
5172  );
5173 
5174  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5175  }
5176 
5185  public function setAccountancyCode($type, $value)
5186  {
5187  global $user, $langs, $conf;
5188 
5189  $this->db->begin();
5190 
5191  $field = 'accountancy_code_sell';
5192  if ($type == 'buy') {
5193  $field = 'accountancy_code_buy';
5194  } elseif ($type == 'sell') {
5195  $field = 'accountancy_code_sell';
5196  } else {
5197  return -1;
5198  }
5199 
5200  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5201  $sql .= $field." = '".$this->db->escape($value)."'";
5202  $sql .= " WHERE rowid = ".((int) $this->id);
5203 
5204  dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5205  $resql = $this->db->query($sql);
5206 
5207  if ($resql) {
5208  // Call triggers
5209  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5210  $interface = new Interfaces($this->db);
5211  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5212  if ($result < 0) {
5213  $this->errors = $interface->errors;
5214  $this->db->rollback();
5215  return -1;
5216  }
5217  // End call triggers
5218 
5219  $this->$field = $value;
5220 
5221  $this->db->commit();
5222  return 1;
5223  } else {
5224  $this->error = $this->db->lasterror();
5225  $this->db->rollback();
5226  return -1;
5227  }
5228  }
5229 
5236  public function fetchPartnerships($mode)
5237  {
5238  global $langs;
5239 
5240  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5241 
5242 
5243  $this->partnerships[] = array();
5244 
5245  return 1;
5246  }
5247 
5255  public function getKanbanView($option = '', $arraydata = null)
5256  {
5257  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5258 
5259  $return = '<div class="box-flex-item box-flex-grow-zero">';
5260  $return .= '<div class="info-box info-box-sm">';
5261  $return .= '<span class="info-box-icon bg-infobox-action">';
5262  $return .= img_picto('', $this->picto);
5263  $return .= '</span>';
5264  $return .= '<div class="info-box-content">';
5265  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5266  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5267  if (property_exists($this, 'code_client')) {
5268  $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5269  }
5270 
5271  if (method_exists($this, 'getLibStatut')) {
5272  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
5273  }
5274  $return .= '</div>';
5275  $return .= '</div>';
5276  $return .= '</div>';
5277  return $return;
5278  }
5279 }
Societe\NO_SUPPLIER
const NO_SUPPLIER
Third party supplier flag is not supplier.
Definition: societe.class.php:867
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:51
Societe\replaceThirdparty
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: societe.class.php:5139
clean_url
clean_url($url, $http=1)
Clean an url string.
Definition: functions2.lib.php:825
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1495
Societe\PROSPECT
const PROSPECT
Third party type is a prospect.
Definition: societe.class.php:857
Societe\create_individual
create_individual(User $user, $no_email=0, $tags=array())
Create a contact/address from thirdparty.
Definition: societe.class.php:1098
Societe\validateFamilyTree
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
Definition: societe.class.php:3637
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
Definition: functions.lib.php:1594
dol_trunc
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.
Definition: functions.lib.php:4049
Societe\LibProspCommStatut
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
Definition: societe.class.php:4706
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1322
FactureFournisseur\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: fournisseur.facture.class.php:341
Societe\get_codefournisseur
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
Definition: societe.class.php:3352
Societe\id_prof_verifiable
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
Definition: societe.class.php:3701
Societe\getParentsForCompany
getParentsForCompany($company_id, $parents=[])
Get parents for company.
Definition: societe.class.php:3670
dol_delete_dir_recursive
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:1483
Societe\codefournisseur_modifiable
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
Definition: societe.class.php:3421
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
Societe\getNbOfEMailings
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
Definition: societe.class.php:4187
Societe\LoadSupplierCateg
LoadSupplierCateg()
Load the list of provider categories.
Definition: societe.class.php:4140
Societe\set_remise_supplier
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2296
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:51
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5096
Societe\CUSTOMER_AND_PROSPECT
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
Definition: societe.class.php:862
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1128
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:503
Societe\getLibStatut
getLibStatut($mode=0)
Return label of status (activity, closed)
Definition: societe.class.php:2994
CommonIncoterm
trait CommonIncoterm
Superclass for incoterm classes.
Definition: commonincoterm.class.php:29
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
Societe\NO_CUSTOMER
const NO_CUSTOMER
Third party type is no customer.
Definition: societe.class.php:847
Societe\codeclient_modifiable
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
Definition: societe.class.php:3381
Societe\create
create(User $user)
Create third party in database.
Definition: societe.class.php:912
Interfaces
Class to manage triggers.
Definition: interfaces.class.php:32
CommonObject\setValueFrom
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
Definition: commonobject.class.php:1903
setEventMessage
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
Definition: functions.lib.php:8608
name
$conf db name
Definition: repair.php:123
Categorie
Class to manage categories.
Definition: categorie.class.php:47
Facture
Class to manage invoices.
Definition: facture.class.php:60
Societe\add_commercial
add_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2557
Societe\useRevenueStamp
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
Definition: societe.class.php:4632
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
Societe\setCategories
setCategories($categories, $type_categ)
Sets object to supplied categories.
Definition: societe.class.php:5044
CommonObject\isObjectUsed
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
Definition: commonobject.class.php:4473
CompanyBankAccount
Class to manage bank accounts description of third parties.
Definition: companybankaccount.class.php:34
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5943
Societe\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: societe.class.php:4526
Societe\setThirdpartyType
setThirdpartyType($typent_id)
Define third-party type of current company.
Definition: societe.class.php:5109
Societe\__construct
__construct($db)
Constructor.
Definition: societe.class.php:880
Societe\get_codecompta
get_codecompta($type)
Assigns a accounting code from the accounting code module.
Definition: societe.class.php:3546
Conf
Class to stock current configuration.
Definition: conf.class.php:33
CommonObject\insertExtraLanguages
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6393
Societe\useNPR
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
Definition: societe.class.php:4610
Societe\get_codeclient
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
Definition: societe.class.php:3320
getState
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
Definition: company.lib.php:595
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:4125
Societe\thirdparty_and_contact_email_array
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
Definition: societe.class.php:3035
Societe\getSalesRepresentatives
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Definition: societe.class.php:2454
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5334
BonPrelevement
Class to manage withdrawal receipts.
Definition: bonprelevement.class.php:43
Societe\setSalesRep
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
Definition: societe.class.php:5064
Societe\AddFournisseurInCategory
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
Definition: societe.class.php:4166
Societe\display_rib
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
Definition: societe.class.php:3252
Societe\setPriceLevel
setPriceLevel($price_level, User $user)
Set the price level.
Definition: societe.class.php:2522
Societe\getNomUrl
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='')
Return a link on thirdparty (with picto)
Definition: societe.class.php:2804
dol_getIdFromCode
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
Definition: functions.lib.php:9062
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:265
Societe\id_prof_check
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
Definition: societe.class.php:3802
Societe\getAvailableDiscounts
getAvailableDiscounts($user='', $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
Definition: societe.class.php:2431
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6110
Societe\isACompany
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
Definition: societe.class.php:4101
Database\fetch_object
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $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
Societe\setNoEmail
setNoEmail($no_email)
Set "blacklist" mailing status.
Definition: societe.class.php:4213
Societe\update
update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
Definition: societe.class.php:1301
Societe\SUPPLIER
const SUPPLIER
Third party supplier flag is a supplier.
Definition: societe.class.php:872
Societe\set_remise_except
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
Definition: societe.class.php:2360
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1732
Societe\getLibProspLevel
getLibProspLevel()
Return prostect level.
Definition: societe.class.php:4655
DiscountAbsolute
Class to manage absolute discounts.
Definition: discount.class.php:29
Societe\LibStatut
LibStatut($status, $mode=0)
Return the label of a given status.
Definition: societe.class.php:3007
Contact
Class to manage contact/addresses.
Definition: contact.class.php:42
Societe\has_projects
has_projects()
Indicates if the company has projects.
Definition: societe.class.php:4045
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
Definition: functions.lib.php:8644
Societe\contact_property_array
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
Definition: societe.class.php:3082
Societe\setMysoc
setMysoc(Conf $conf)
Set properties with value into $conf.
Definition: societe.class.php:4397
dol_format_address
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.
Definition: functions.lib.php:2544
Societe\getOutstandingBills
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
Definition: societe.class.php:4854
Adherent
Class to manage members of a foundation.
Definition: adherent.class.php:47
Societe\create_from_member
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
Definition: societe.class.php:4298
Societe\isInEEC
isInEEC()
Return if a company is inside the EEC (European Economic Community)
Definition: societe.class.php:4128
dol_substr
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
Definition: functions.lib.php:4010
Societe\getLibProspCommStatut
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
Definition: societe.class.php:4687
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3987
Societe\id_prof_exists
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
Definition: societe.class.php:3741
CommonSocialNetworks
trait CommonSocialNetworks
Superclass for social networks.
Definition: commonsocialnetworks.class.php:29
Societe\getNoEmail
getNoEmail()
get "blacklist" mailing status set no_email attribut to 1 or 0
Definition: societe.class.php:4270
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:207
Societe\fetch
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Load a third party from database into memory.
Definition: societe.class.php:1754
Societe\contact_get_property
contact_get_property($rowid, $mode)
Return property of contact from its id.
Definition: societe.class.php:3210
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8561
ref
$object ref
Definition: info.php:78
getDolGlobalString
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:142
Societe\useLocalTax
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
Definition: societe.class.php:4583
User
Class to manage Dolibarr users.
Definition: user.class.php:47
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6070
Societe\set_remise_client
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2236
Societe\getOutstandingProposals
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
Definition: societe.class.php:4766
Societe\setParent
setParent($id)
Define parent company of current company.
Definition: societe.class.php:3598
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10932
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:53
Societe\contact_array_objects
contact_array_objects()
Returns the contact list of this company.
Definition: societe.class.php:3176
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4462
Societe\contact_array
contact_array()
Returns the contact list of this company.
Definition: societe.class.php:3147
img_action
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
Definition: functions.lib.php:4548
Societe\CUSTOMER
const CUSTOMER
Third party type is a customer.
Definition: societe.class.php:852
Societe\thirdparty_and_contact_phone_array
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
Definition: societe.class.php:3057
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3046
Societe\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: societe.class.php:4988
Societe\getOutstandingOrders
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
Definition: societe.class.php:4810
Societe\set_as_client
set_as_client()
Define third party as a customer.
Definition: societe.class.php:2204
Societe\getKanbanView
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
Definition: societe.class.php:5255
Societe\getTooltipContentArray
getTooltipContentArray($params)
getTooltipContentArray
Definition: societe.class.php:2645
dol_print_phone
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
Definition: functions.lib.php:3391
Societe\get_all_rib
get_all_rib()
Return Array of RIB.
Definition: societe.class.php:3287
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:515
Form\showphoto
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Definition: html.form.class.php:9618
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5743
Societe\verify
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
Definition: societe.class.php:1171
Database\query
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
dol_is_dir
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:452
Societe\LibCustProspStatut
LibCustProspStatut($status)
Return the label of the customer/prospect status.
Definition: societe.class.php:4957
Societe\del_commercial
del_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2617
Societe\getTypeUrl
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
Definition: societe.class.php:2964
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
Societe\id_prof_url
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
Definition: societe.class.php:3992
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8469
Societe\check_codefournisseur
check_codefournisseur()
Check supplier code.
Definition: societe.class.php:3508
Societe\LibProspLevel
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
Definition: societe.class.php:4667
Societe\getLibCustProspStatut
getLibCustProspStatut()
Return label of status customer is prospect/customer.
Definition: societe.class.php:4945
Societe\setAccountancyCode
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
Definition: societe.class.php:5185
Societe\check_codeclient
check_codeclient()
Check customer code.
Definition: societe.class.php:3467
Societe\info
info($id)
Load information for tab info.
Definition: societe.class.php:4068
Societe\fetchPartnerships
fetchPartnerships($mode)
Function to get partnerships array.
Definition: societe.class.php:5236