dolibarr  17.0.3
societe.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9  * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
12  * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16  * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17  * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18  * Copyright (C) 2019-2022 Frédéric France <frederic.france@netlogic.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21  *
22  * This program is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as published by
24  * the Free Software Foundation; either version 3 of the License, or
25  * (at your option) any later version.
26  *
27  * This program is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License
33  * along with this program. If not, see <https://www.gnu.org/licenses/>.
34  */
35 
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
44 
45 
49 class Societe extends CommonObject
50 {
51  use CommonIncoterm;
52 
56  public $module = 'societe';
57 
61  public $element = 'societe';
62 
66  public $table_element = 'societe';
67 
71  public $fk_element = 'fk_soc';
72 
76  public $fieldsforcombobox = 'nom,name_alias';
77 
81  protected $childtables = array(
82  'supplier_proposal' => array('name' => 'SupplierProposal'),
83  'propal' => array('name' => 'Proposal'),
84  'commande' => array('name' => 'Order'),
85  'facture' => array('name' => 'Invoice'),
86  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
87  'contrat' => array('name' => 'Contract'),
88  'fichinter' => array('name' => 'Fichinter'),
89  'facture_fourn' => array('name' => 'SupplierInvoice'),
90  'commande_fournisseur' => array('name' => 'SupplierOrder'),
91  'projet' => array('name' => 'Project'),
92  'expedition' => array('name' => 'Shipment'),
93  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
94  );
95 
100  protected $childtablesoncascade = array(
101  'societe_prices',
102  'societe_address',
103  'product_fournisseur_price',
104  'product_customer_price_log',
105  'product_customer_price',
106  '@Contact:/contact/class/contact.class.php:fk_soc',
107  'adherent',
108  'societe_account',
109  'societe_rib',
110  'societe_remise',
111  'societe_remise_except',
112  'societe_commerciaux',
113  'categorie',
114  'notify',
115  'notify_def',
116  'actioncomm',
117  );
118 
122  public $picto = 'company';
123 
128  public $ismultientitymanaged = 1;
129 
134  public $restrictiononfksoc = 1;
135 
136 
166  public $fields = array(
167  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
168  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
169  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
170  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
171  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
172  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
173  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
174  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
175  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
176  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
177  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CodeCompta', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
178  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'CodeComptaSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
179  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
180  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
181  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
182  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
183  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
184  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
185  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
186  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
187  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
188  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
189  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
190  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
191  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
192  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
193  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
194  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
195  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
196  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
197  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
198  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
199  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
200  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
201  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
202  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
203  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
204  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>"getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible'=>-1, 'position'=>235),
205  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
206  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
207  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
208  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
209  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
210  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
211  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
212  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
213  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
214  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
215  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
216  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
217  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
218  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
219  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
220  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
221  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
222  '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),
223  '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),
224  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
225  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
226  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
227  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
228  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
229  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
230  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
231  '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),
232  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
233  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
234  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
235  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
236  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
237  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
238  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
239  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
240  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
241  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
242  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
243  'fk_account' =>array('type'=>'integer', 'label'=>'PaymentBankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
244  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
245  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
246  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
247  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
248  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
249  );
250 
254  public $entity;
255 
262  public $nom;
263 
267  public $name;
268 
273  public $name_alias;
274 
278  public $particulier;
279 
283  public $address;
284 
288  public $zip;
289 
293  public $town;
294 
299  public $status = 1;
300 
305  public $state_id;
306 
310  public $state_code;
311 
315  public $state;
316 
321  public $region_code;
322 
326  public $region;
327 
333  public $departement_code;
334 
340  public $departement;
341 
347  public $pays;
348 
353  public $phone;
358  public $fax;
363  public $email;
364 
368  public $socialnetworks;
369 
375  public $skype;
376 
382  public $twitter;
383 
389  public $facebook;
390 
396  public $linkedin;
397 
402  public $url;
403 
408  public $barcode;
409 
410  // 6 professional id (usage depends on country)
411 
416  public $idprof1;
417 
423  public $siren;
424 
425 
430  public $idprof2;
431 
437  public $siret;
438 
443  public $idprof3;
444 
450  public $ape;
451 
456  public $idprof4;
457 
462  public $idprof5;
463 
468  public $idprof6;
469 
473  public $prefix_comm;
474 
478  public $tva_assuj = 1;
479 
484  public $tva_intra;
485 
486  // Local taxes
487  public $localtax1_assuj;
488  public $localtax1_value;
489  public $localtax2_assuj;
490  public $localtax2_value;
491 
495  public $managers;
496 
500  public $capital;
501 
505  public $typent_id = 0;
506  public $typent_code;
507  public $effectif;
508  public $effectif_id = 0;
509  public $forme_juridique_code;
510  public $forme_juridique = 0;
511 
512  public $remise_percent;
513  public $remise_supplier_percent;
514 
515  public $mode_reglement_id;
516  public $cond_reglement_id;
517  public $deposit_percent;
518  public $mode_reglement_supplier_id;
519  public $cond_reglement_supplier_id;
520  public $transport_mode_supplier_id;
521 
525  public $fk_prospectlevel;
526 
530  public $name_bis;
531 
532  //Log data
533 
538  public $date_modification;
539 
544  public $user_modification;
545 
550  public $date_creation;
551 
556  public $user_creation;
557 
562  public $client = 0;
563 
568  public $prospect = 0;
569 
574  public $fournisseur;
575 
580  public $code_client;
581 
586  public $code_fournisseur;
587 
592  public $code_compta_client;
593 
598  public $code_compta;
599 
600 
605  public $accountancy_code_customer;
606 
611  public $code_compta_fournisseur;
612 
617  public $accountancy_code_supplier;
618 
619 
624  public $code_compta_product;
625 
626 
632  public $note;
633 
638  public $note_private;
639 
644  public $note_public;
645 
650  public $stcomm_id;
651 
656  public $stcomm_picto;
657 
662  public $status_prospect_label;
663 
668  public $price_level;
669 
673  public $outstanding_limit;
674 
678  public $order_min_amount;
679 
683  public $supplier_order_min_amount;
684 
689  public $commercial_id;
690 
695  public $parent;
696 
701  public $default_lang;
702 
706  public $ref;
707 
713  public $ref_ext;
714 
721  public $import_key;
722 
727  public $webservices_url;
728 
733  public $webservices_key;
734 
738  public $logo;
739 
743  public $logo_small;
744 
748  public $logo_mini;
749 
753  public $logo_squarred;
754 
758  public $logo_squarred_small;
759 
763  public $logo_squarred_mini;
764 
768  public $accountancy_code_sell;
769 
773  public $accountancy_code_buy;
774 
775  // Multicurrency
779  public $fk_multicurrency;
780 
781  // Warehouse
785  public $fk_warehouse;
786 
790  public $multicurrency_code;
791 
795  public $no_email;
796 
797  // Fields loaded by fetchPartnerships()
798 
799  public $partnerships = array();
800 
801 
805  public $bank_account;
806 
807 
808  const STATUS_CEASED = 0;
809  const STATUS_INACTIVITY = 1;
810 
814  const NO_CUSTOMER = 0;
815 
819  const CUSTOMER = 1;
820 
824  const PROSPECT = 2;
825 
830 
834  const NO_SUPPLIER = 0;
835 
839  const SUPPLIER = 1;
840 
841 
847  public function __construct($db)
848  {
849  global $conf;
850 
851  $this->db = $db;
852 
853  $this->client = 0;
854  $this->prospect = 0;
855  $this->fournisseur = 0;
856  $this->typent_id = 0;
857  $this->effectif_id = 0;
858  $this->forme_juridique_code = 0;
859  $this->tva_assuj = 1;
860  $this->status = 1;
861 
862  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
863  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
864  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
865  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
866  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
867  }
868  }
869 
870 
879  public function create(User $user, $notrigger = 0)
880  {
881  global $langs, $conf, $mysoc;
882 
883  $error = 0;
884 
885  // Clean parameters
886  if (empty($this->status)) {
887  $this->status = 0;
888  }
889  $this->name = $this->name ?trim($this->name) : trim($this->nom);
890  $this->setUpperOrLowerCase();
891  $this->nom = $this->name; // For backward compatibility
892  if (empty($this->client)) {
893  $this->client = 0;
894  }
895  if (empty($this->fournisseur)) {
896  $this->fournisseur = 0;
897  }
898  $this->import_key = trim($this->import_key);
899 
900  $this->accountancy_code_customer = trim($this->code_compta);
901  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
902  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
903  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
904 
905  if (!empty($this->multicurrency_code)) {
906  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
907  }
908  if (empty($this->fk_multicurrency)) {
909  $this->multicurrency_code = '';
910  $this->fk_multicurrency = 0;
911  }
912 
913  dol_syslog(get_class($this)."::create ".$this->name);
914 
915  $now = dol_now();
916 
917  $this->db->begin();
918 
919  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
920  if ($this->code_client == -1 || $this->code_client === 'auto') {
921  $this->get_codeclient($this, 0);
922  }
923  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
924  $this->get_codefournisseur($this, 1);
925  }
926 
927  // Check more parameters (including mandatory setup
928  // If error, this->errors[] is filled
929  $result = $this->verify();
930 
931  if ($result >= 0) {
932  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
933 
934  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
935  $sql .= "nom";
936  $sql .= ", name_alias";
937  $sql .= ", entity";
938  $sql .= ", datec";
939  $sql .= ", fk_user_creat";
940  $sql .= ", fk_typent";
941  $sql .= ", canvas";
942  $sql .= ", status";
943  $sql .= ", ref_ext";
944  $sql .= ", fk_stcomm";
945  $sql .= ", fk_incoterms";
946  $sql .= ", location_incoterms";
947  $sql .= ", import_key";
948  $sql .= ", fk_multicurrency";
949  $sql .= ", multicurrency_code";
950  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
951  $sql .= ", accountancy_code_buy";
952  $sql .= ", accountancy_code_sell";
953  }
954  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
955  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
956  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
957  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
958  $sql .= ", ".((int) $this->status);
959  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
960  $sql .= ", 0";
961  $sql .= ", ".(int) $this->fk_incoterms;
962  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
963  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
964  $sql .= ", ".(int) $this->fk_multicurrency;
965  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
966  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
967  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
968  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
969  }
970  $sql .= ")";
971 
972  dol_syslog(get_class($this)."::create", LOG_DEBUG);
973  $result = $this->db->query($sql);
974  if ($result) {
975  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
976 
977  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
978 
979  // update accountancy for this entity
980  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
981  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
982 
983  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
984  $sql .= " fk_soc";
985  $sql .= ", entity";
986  $sql .= ", accountancy_code_customer";
987  $sql .= ", accountancy_code_supplier";
988  $sql .= ", accountancy_code_buy";
989  $sql .= ", accountancy_code_sell";
990  $sql .= ") VALUES (";
991  $sql .= $this->id;
992  $sql .= ", ".((int) $conf->entity);
993  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
994  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
995  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
996  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
997  $sql .= ")";
998  $result = $this->db->query($sql);
999  if (!$result) {
1000  $error++;
1001  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1002  }
1003  }
1004 
1005  // Ajout du commercial affecte
1006  if ($this->commercial_id != '' && $this->commercial_id != -1) {
1007  $this->add_commercial($user, $this->commercial_id);
1008  } elseif (empty($user->rights->societe->client->voir)) {
1009  // si un commercial cree un client il lui est affecte automatiquement
1010  $this->add_commercial($user, $user->id);
1011  }
1012 
1013  if ($ret >= 0) {
1014  if (! $notrigger) {
1015  // Call trigger
1016  $result = $this->call_trigger('COMPANY_CREATE', $user);
1017  if ($result < 0) {
1018  $error++;
1019  }
1020  // End call triggers
1021  }
1022  } else {
1023  $error++;
1024  }
1025 
1026  if (!$error) {
1027  dol_syslog(get_class($this)."::Create success id=".$this->id);
1028  $this->db->commit();
1029  return $this->id;
1030  } else {
1031  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1032  $this->db->rollback();
1033  return -4;
1034  }
1035  } else {
1036  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1037  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1038  $result = -1;
1039  } else {
1040  $this->error = $this->db->lasterror();
1041  $result = -2;
1042  }
1043  $this->db->rollback();
1044  return $result;
1045  }
1046  } else {
1047  $this->db->rollback();
1048  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1049  return -3;
1050  }
1051  }
1052 
1053 
1054  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1064  public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1065  {
1066  global $conf;
1067 
1068  $error = 0;
1069 
1070  $this->db->begin();
1071 
1072  // phpcs:enable
1073  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1074  $contact = new Contact($this->db);
1075 
1076  $contact->name = $this->name_bis;
1077  $contact->firstname = $this->firstname;
1078  $contact->civility_id = $this->civility_id;
1079  $contact->socid = $this->id; // fk_soc
1080  $contact->statut = 1; // deprecated
1081  $contact->status = 1;
1082  $contact->priv = 0;
1083  $contact->country_id = $this->country_id;
1084  $contact->state_id = $this->state_id;
1085  $contact->address = $this->address;
1086  $contact->email = $this->email;
1087  $contact->zip = $this->zip;
1088  $contact->town = $this->town;
1089  $this->setUpperOrLowerCase();
1090  $contact->phone_pro = $this->phone;
1091 
1092  $contactId = $contact->create($user, $notrigger);
1093  if ($contactId < 0) {
1094  $error++;
1095  $this->error = $contact->error;
1096  $this->errors = $contact->errors;
1097  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1098  }
1099 
1100  if (empty($error) && is_array($tags) && !empty($tags)) {
1101  $result = $contact->setCategories($tags);
1102  if ($result < 0) {
1103  $error++;
1104  $this->error = $contact->error;
1105  $this->errors = array_merge($this->errors, $contact->errors);
1106  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1107  $contactId = $result;
1108  }
1109  }
1110 
1111  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1112  $result = $contact->setNoEmail($no_email);
1113  if ($result < 0) {
1114  $this->error = $contact->error;
1115  $this->errors = array_merge($this->errors, $contact->errors);
1116  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1117  $contactId = $result;
1118  }
1119  }
1120 
1121  if (empty($error)) {
1122  dol_syslog(get_class($this)."::create_individual success");
1123  $this->db->commit();
1124  } else {
1125  $this->db->rollback();
1126  }
1127 
1128  return $contactId;
1129  }
1130 
1137  public function verify()
1138  {
1139  global $conf, $langs, $mysoc;
1140 
1141  $error = 0;
1142  $this->errors = array();
1143 
1144  $result = 0;
1145  $this->name = trim($this->name);
1146  $this->nom = $this->name; // For backward compatibility
1147 
1148  if (!$this->name) {
1149  $this->errors[] = 'ErrorBadThirdPartyName';
1150  $result = -2;
1151  }
1152 
1153  if ($this->client) {
1154  $rescode = $this->check_codeclient();
1155  if ($rescode != 0 && $rescode != -5) {
1156  if ($rescode == -1) {
1157  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1158  } elseif ($rescode == -2) {
1159  $this->errors[] = 'ErrorCustomerCodeRequired';
1160  } elseif ($rescode == -3) {
1161  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1162  } elseif ($rescode == -4) {
1163  $this->errors[] = 'ErrorPrefixRequired';
1164  } else {
1165  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1166  }
1167 
1168  $result = -3;
1169  }
1170  }
1171 
1172  if ($this->fournisseur) {
1173  $rescode = $this->check_codefournisseur();
1174  if ($rescode != 0 && $rescode != -5) {
1175  if ($rescode == -1) {
1176  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1177  } elseif ($rescode == -2) {
1178  $this->errors[] = 'ErrorSupplierCodeRequired';
1179  } elseif ($rescode == -3) {
1180  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1181  } elseif ($rescode == -4) {
1182  $this->errors[] = 'ErrorPrefixRequired';
1183  } else {
1184  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1185  }
1186  $result = -3;
1187  }
1188  }
1189 
1190  // Check for duplicate or mandatory fields defined into setup
1191  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1192  foreach ($array_to_check as $key) {
1193  $keymin = strtolower($key);
1194  $i = (int) preg_replace('/[^0-9]/', '', $key);
1195  $vallabel = $this->$keymin;
1196 
1197  if ($i > 0) {
1198  if ($this->isACompany()) {
1199  // Check for mandatory prof id (but only if country is same than ours)
1200  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1201  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1202  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1203  $langs->load("errors");
1204  $error++;
1205  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1206  }
1207  }
1208  }
1209 
1210  // Check for unicity on profid
1211  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1212  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1213  $langs->load("errors");
1214  $error++;
1215  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1216  }
1217  }
1218  } else {
1219  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1220  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1221  if ($key == 'EMAIL') {
1222  // Check for mandatory
1223  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1224  $langs->load("errors");
1225  $error++;
1226  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1227  }
1228 
1229  // Check for unicity
1230  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1231  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1232  $langs->load("errors");
1233  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1234  }
1235  }
1236  } elseif ($key == 'TVA_INTRA') {
1237  // Check for unicity
1238  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1239  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1240  $langs->load("errors");
1241  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1242  }
1243  }
1244  }
1245  }
1246  }
1247 
1248  if ($error) {
1249  $result = -4;
1250  }
1251 
1252  return $result;
1253  }
1254 
1267  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1268  {
1269  global $langs, $conf, $hookmanager;
1270 
1271  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1272 
1273  if (empty($id)) {
1274  $id = $this->id;
1275  }
1276 
1277  $error = 0;
1278 
1279  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1280 
1281  $now = dol_now();
1282 
1283  // Clean parameters
1284  $this->id = $id;
1285  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1286  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1287  $this->nom = $this->name; // For backward compatibility
1288  $this->name_alias = trim($this->name_alias);
1289  $this->ref_ext = trim($this->ref_ext);
1290  $this->address = $this->address ?trim($this->address) : trim($this->address);
1291  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1292  $this->town = $this->town ?trim($this->town) : trim($this->town);
1293  $this->state_id = trim($this->state_id);
1294  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1295  $this->phone = trim($this->phone);
1296  $this->phone = preg_replace("/\s/", "", $this->phone);
1297  $this->phone = preg_replace("/\./", "", $this->phone);
1298  $this->fax = trim($this->fax);
1299  $this->fax = preg_replace("/\s/", "", $this->fax);
1300  $this->fax = preg_replace("/\./", "", $this->fax);
1301  $this->email = trim($this->email);
1302  $this->url = $this->url ?clean_url($this->url, 0) : '';
1303  $this->note_private = trim($this->note_private);
1304  $this->note_public = trim($this->note_public);
1305  $this->idprof1 = trim($this->idprof1);
1306  $this->idprof2 = trim($this->idprof2);
1307  $this->idprof3 = trim($this->idprof3);
1308  $this->idprof4 = trim($this->idprof4);
1309  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1310  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1311  $this->prefix_comm = trim($this->prefix_comm);
1312  $this->outstanding_limit = price2num($this->outstanding_limit);
1313  $this->order_min_amount = price2num($this->order_min_amount);
1314  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1315 
1316  $this->tva_assuj = trim($this->tva_assuj);
1317  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1318  if (empty($this->status)) {
1319  $this->status = 0;
1320  }
1321 
1322  if (!empty($this->multicurrency_code)) {
1323  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1324  }
1325  if (empty($this->fk_multicurrency)) {
1326  $this->multicurrency_code = '';
1327  $this->fk_multicurrency = 0;
1328  }
1329 
1330  // Local taxes
1331  $this->localtax1_assuj = trim($this->localtax1_assuj);
1332  $this->localtax2_assuj = trim($this->localtax2_assuj);
1333 
1334  $this->localtax1_value = trim($this->localtax1_value);
1335  $this->localtax2_value = trim($this->localtax2_value);
1336 
1337  if ($this->capital != '') {
1338  $this->capital = price2num(trim($this->capital));
1339  }
1340  if (!is_numeric($this->capital)) {
1341  $this->capital = ''; // '' = undef
1342  }
1343 
1344  $this->effectif_id = trim($this->effectif_id);
1345  $this->forme_juridique_code = trim($this->forme_juridique_code);
1346 
1347  //Gencod
1348  $this->barcode = trim($this->barcode);
1349 
1350  // For automatic creation
1351  if ($this->code_client == -1 || $this->code_client === 'auto') {
1352  $this->get_codeclient($this, 0);
1353  }
1354  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1355  $this->get_codefournisseur($this, 1);
1356  }
1357 
1358  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1359  $this->code_compta = $this->code_compta_client; // for backward compatibility
1360  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1361 
1362  // Check parameters. More tests are done later in the ->verify()
1363  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1364  $langs->load("errors");
1365  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1366  return -1;
1367  }
1368 
1369  $customer = false;
1370  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1371  // If $allowmodcodeclient is set and value is not set, we generate it
1372  if (empty($this->code_compta_client)) {
1373  $ret = $this->get_codecompta('customer');
1374  if ($ret < 0) {
1375  return -1;
1376  }
1377  }
1378 
1379  $customer = true;
1380  }
1381 
1382  $supplier = false;
1383  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1384  // If $allowmodcodefournisseur is set and value is not set, we generate it
1385  if (empty($this->code_compta_fournisseur)) {
1386  $ret = $this->get_codecompta('supplier');
1387  if ($ret < 0) {
1388  return -1;
1389  }
1390  }
1391 
1392  $supplier = true;
1393  }
1394 
1395  //Web services
1396  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1397  $this->webservices_key = trim($this->webservices_key);
1398 
1399  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1400  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1401 
1402  //Incoterms
1403  $this->fk_incoterms = (int) $this->fk_incoterms;
1404  $this->location_incoterms = trim($this->location_incoterms);
1405 
1406  $this->db->begin();
1407 
1408  // Check name is required and codes are ok or unique.
1409  // If error, this->errors[] is filled
1410  $result = 0;
1411  if ($action != 'add' && $action != 'merge') {
1412  // We don't check when update called during a create because verify was already done.
1413  // 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
1414  $result = $this->verify();
1415 
1416  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1417  // So we can update record that were using and old numbering rule.
1418  if (is_array($this->errors)) {
1419  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1420  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1421  unset($this->errors[$key]); // Remove error message
1422  }
1423  }
1424  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1425  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1426  unset($this->errors[$key]); // Remove error message
1427  }
1428  }
1429  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1430  $result = 0;
1431  }
1432  }
1433  }
1434  $this->setUpperOrLowerCase();
1435  if ($result >= 0) {
1436  dol_syslog(get_class($this)."::update verify ok or not done");
1437 
1438  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1439  $sql .= "entity = ".$this->db->escape($this->entity);
1440  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1441  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1442  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1443  $sql .= ",address = '".$this->db->escape($this->address)."'";
1444 
1445  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1446  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1447 
1448  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1449  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1450 
1451  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1452  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1453  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1454  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1455  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1456 
1457  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1458 
1459  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1460  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1461 
1462  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1463  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1464  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1465  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1466  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1467  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1468 
1469  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1470  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1471  $sql .= ",status = ".((int) $this->status);
1472 
1473  // Local taxes
1474  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1475  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1476  if ($this->localtax1_assuj == 1) {
1477  if ($this->localtax1_value != '') {
1478  $sql .= ",localtax1_value =".$this->localtax1_value;
1479  } else {
1480  $sql .= ",localtax1_value =0.000";
1481  }
1482  } else {
1483  $sql .= ",localtax1_value =0.000";
1484  }
1485 
1486  if ($this->localtax2_assuj == 1) {
1487  if ($this->localtax2_value != '') {
1488  $sql .= ",localtax2_value =".$this->localtax2_value;
1489  } else {
1490  $sql .= ",localtax2_value =0.000";
1491  }
1492  } else {
1493  $sql .= ",localtax2_value =0.000";
1494  }
1495 
1496  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1497 
1498  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1499 
1500  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1501  if (isset($this->stcomm_id)) {
1502  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1503  }
1504  if (isset($this->typent_id)) {
1505  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1506  }
1507 
1508  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1509 
1510  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1511  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1512  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1513  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1514  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1515  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1516  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1517  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1518 
1519  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1520  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1521  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1522  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1523  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1524  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1525  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1526  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1527  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1528  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1529  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1530  $sql .= ", accountancy_code_buy = '".$this->db->escape($this->accountancy_code_buy)."'";
1531  $sql .= ", accountancy_code_sell= '".$this->db->escape($this->accountancy_code_sell)."'";
1532 
1533  if ($customer) {
1534  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1535  }
1536 
1537  if ($supplier) {
1538  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1539  }
1540  }
1541  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1542  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1543 
1544  //Incoterms
1545  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1546  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1547 
1548  if ($customer) {
1549  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1550  }
1551 
1552  if ($supplier) {
1553  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1554  }
1555  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1556  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1557  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1558  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1559  $sql .= " WHERE rowid = ".(int) $id;
1560 
1561  $resql = $this->db->query($sql);
1562  if ($resql) {
1563  if (is_object($this->oldcopy)) { // If we have information on old values
1564  if ($this->oldcopy->country_id != $this->country_id) {
1565  unset($this->country_code);
1566  unset($this->country);
1567  }
1568  if ($this->oldcopy->state_id != $this->state_id) {
1569  unset($this->state_code);
1570  unset($this->state);
1571  }
1572  } else {
1573  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1574  unset($this->country);
1575  unset($this->state_code);
1576  unset($this->state);
1577  }
1578 
1579  $nbrowsaffected = $this->db->affected_rows($resql);
1580 
1581  if (!$error && $nbrowsaffected) {
1582  // Update information on linked member if it is an update
1583  if (!$nosyncmember && isModEnabled('adherent')) {
1584  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1585 
1586  dol_syslog(get_class($this)."::update update linked member");
1587 
1588  $lmember = new Adherent($this->db);
1589  $result = $lmember->fetch(0, 0, $this->id);
1590 
1591  if ($result > 0) {
1592  $lmember->company = $this->name;
1593  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1594  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1595  $lmember->address = $this->address;
1596  $lmember->zip = $this->zip;
1597  $lmember->town = $this->town;
1598  $lmember->email = $this->email;
1599  $lmember->socialnetworks = $this->socialnetworks;
1600  $lmember->phone = $this->phone;
1601  $lmember->state_id = $this->state_id;
1602  $lmember->country_id = $this->country_id;
1603  $lmember->default_lang = $this->default_lang;
1604 
1605  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1606  if ($result < 0) {
1607  $this->error = $lmember->error;
1608  $this->errors = array_merge($this->errors, $lmember->errors);
1609  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1610  $error++;
1611  }
1612  } elseif ($result < 0) {
1613  $this->error = $lmember->error;
1614  $error++;
1615  }
1616  }
1617  }
1618 
1619  $action = 'update';
1620 
1621  // update accountancy for this entity
1622  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1623  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1624 
1625  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1626  $sql .= " fk_soc";
1627  $sql .= ", entity";
1628  $sql .= ", accountancy_code_customer";
1629  $sql .= ", accountancy_code_supplier";
1630  $sql .= ", accountancy_code_buy";
1631  $sql .= ", accountancy_code_sell";
1632  $sql .= ") VALUES (";
1633  $sql .= $this->id;
1634  $sql .= ", ".$conf->entity;
1635  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1636  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1637  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1638  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1639  $sql .= ")";
1640  $result = $this->db->query($sql);
1641  if (!$result) {
1642  $error++;
1643  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1644  }
1645  }
1646 
1647  // Actions on extra fields
1648  if (!$error) {
1649  $result = $this->insertExtraFields();
1650  if ($result < 0) {
1651  $error++;
1652  }
1653  }
1654  // Actions on extra languages
1655  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1656  $result = $this->insertExtraLanguages();
1657  if ($result < 0) {
1658  $error++;
1659  }
1660  }
1661 
1662  if (!$error && $call_trigger) {
1663  // Call trigger
1664  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1665  if ($result < 0) {
1666  $error++;
1667  }
1668  // End call triggers
1669  }
1670 
1671  if (!$error) {
1672  dol_syslog(get_class($this)."::Update success");
1673  $this->db->commit();
1674  return 1;
1675  } else {
1676  $this->db->rollback();
1677  return -1;
1678  }
1679  } else {
1680  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1681  // Doublon
1682  $this->error = $langs->trans("ErrorDuplicateField");
1683  $result = -1;
1684  } else {
1685  $this->error = $this->db->lasterror();
1686  $result = -2;
1687  }
1688  $this->db->rollback();
1689  return $result;
1690  }
1691  } else {
1692  $this->db->rollback();
1693  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1694  return -3;
1695  }
1696  }
1697 
1715  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1716  {
1717  global $langs;
1718  global $conf;
1719 
1720  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1721  return -1;
1722  }
1723 
1724  $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';
1725  $sql .= ', s.status, s.fk_warehouse';
1726  $sql .= ', s.price_level';
1727  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1728  $sql .= ', s.phone, s.fax, s.email';
1729  $sql .= ', s.socialnetworks';
1730  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1731  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1732  $sql .= ', s.capital, s.tva_intra';
1733  $sql .= ', s.fk_typent as typent_id';
1734  $sql .= ', s.fk_effectif as effectif_id';
1735  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1736  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1737  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1738  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1739  } else {
1740  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1741  }
1742  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1743  $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';
1744  $sql .= ', s.fk_account, s.tva_assuj';
1745  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1746  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1747  $sql .= ', s.fk_shipping_method';
1748  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1749  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1750  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1751  $sql .= ', fj.libelle as forme_juridique';
1752  $sql .= ', e.libelle as effectif';
1753  $sql .= ', c.code as country_code, c.label as country';
1754  $sql .= ', d.code_departement as state_code, d.nom as state';
1755  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1756  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1757  $sql .= ', te.code as typent_code';
1758  $sql .= ', i.libelle as label_incoterms';
1759  if (!isModEnabled('multicompany')) {
1760  $sql .= ', s.remise_client, s.remise_supplier';
1761  } else {
1762  $sql .= ', sr.remise_client, sr2.remise_supplier';
1763  }
1764  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1765  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1766  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1767  }
1768  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1769  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1770  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1771  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1772  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1773  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1774  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1775  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1776  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1777  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1778  if (isModEnabled('multicompany')) {
1779  $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').'))';
1780  $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').'))';
1781  }
1782  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1783  if ($rowid) {
1784  $sql .= ' AND s.rowid = '.((int) $rowid);
1785  }
1786  if ($ref) {
1787  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1788  }
1789  if ($ref_alias) {
1790  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1791  }
1792  if ($ref_ext) {
1793  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1794  }
1795  if ($barcode) {
1796  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1797  }
1798  if ($idprof1) {
1799  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1800  }
1801  if ($idprof2) {
1802  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1803  }
1804  if ($idprof3) {
1805  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1806  }
1807  if ($idprof4) {
1808  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1809  }
1810  if ($idprof5) {
1811  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1812  }
1813  if ($idprof6) {
1814  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1815  }
1816  if ($email) {
1817  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1818  }
1819 
1820  $resql = $this->db->query($sql);
1821  if ($resql) {
1822  $num = $this->db->num_rows($resql);
1823  if ($num > 1) {
1824  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1825  dol_syslog($this->error, LOG_ERR);
1826  $result = -2;
1827  } elseif ($num) { // $num = 1
1828  $obj = $this->db->fetch_object($resql);
1829 
1830  $this->id = $obj->rowid;
1831  $this->entity = $obj->entity;
1832  $this->canvas = $obj->canvas;
1833 
1834  $this->ref = $obj->rowid;
1835  $this->name = $obj->name;
1836  $this->nom = $obj->name; // deprecated
1837  $this->name_alias = $obj->name_alias;
1838  $this->ref_ext = $obj->ref_ext;
1839 
1840  $this->date_creation = $this->db->jdate($obj->date_creation);
1841  $this->date_modification = $this->db->jdate($obj->date_modification);
1842  $this->user_creation = $obj->fk_user_creat;
1843  $this->user_modification = $obj->fk_user_modif;
1844 
1845  $this->address = $obj->address;
1846  $this->zip = $obj->zip;
1847  $this->town = $obj->town;
1848 
1849  $this->country_id = $obj->country_id;
1850  $this->country_code = $obj->country_id ? $obj->country_code : '';
1851  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1852 
1853  $this->state_id = $obj->state_id;
1854  $this->state_code = $obj->state_code;
1855  $this->region_id = $obj->region_id;
1856  $this->region_code = $obj->region_code;
1857  $this->state = ($obj->state != '-' ? $obj->state : '');
1858 
1859  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1860  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1861  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1862  $this->status_prospect_label = $label; // label status prospect
1863  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1864 
1865  $this->email = $obj->email;
1866  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1867 
1868  $this->url = $obj->url;
1869  $this->phone = $obj->phone;
1870  $this->fax = $obj->fax;
1871 
1872  $this->parent = $obj->parent;
1873 
1874  $this->idprof1 = $obj->idprof1;
1875  $this->idprof2 = $obj->idprof2;
1876  $this->idprof3 = $obj->idprof3;
1877  $this->idprof4 = $obj->idprof4;
1878  $this->idprof5 = $obj->idprof5;
1879  $this->idprof6 = $obj->idprof6;
1880 
1881  $this->capital = $obj->capital;
1882 
1883  $this->code_client = $obj->code_client;
1884  $this->code_fournisseur = $obj->code_fournisseur;
1885 
1886  $this->code_compta = $obj->code_compta; // For backward compatibility
1887  $this->code_compta_client = $obj->code_compta;
1888  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1889 
1890  $this->barcode = $obj->barcode;
1891 
1892  $this->tva_assuj = $obj->tva_assuj;
1893  $this->tva_intra = $obj->tva_intra;
1894  $this->status = $obj->status;
1895 
1896  // Local Taxes
1897  $this->localtax1_assuj = $obj->localtax1_assuj;
1898  $this->localtax2_assuj = $obj->localtax2_assuj;
1899 
1900  $this->localtax1_value = $obj->localtax1_value;
1901  $this->localtax2_value = $obj->localtax2_value;
1902 
1903  $this->typent_id = $obj->typent_id;
1904  $this->typent_code = $obj->typent_code;
1905 
1906  $this->effectif_id = $obj->effectif_id;
1907  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1908 
1909  $this->forme_juridique_code = $obj->forme_juridique_code;
1910  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1911 
1912  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1913 
1914  $this->prefix_comm = $obj->prefix_comm;
1915 
1916  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1917  $this->remise_supplier_percent = $obj->remise_supplier;
1918 
1919  $this->mode_reglement_id = $obj->mode_reglement;
1920  $this->cond_reglement_id = $obj->cond_reglement;
1921  $this->deposit_percent = $obj->deposit_percent;
1922  $this->transport_mode_id = $obj->transport_mode;
1923  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1924  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1925  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1926  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1927  $this->fk_account = $obj->fk_account;
1928 
1929  $this->client = $obj->client;
1930  $this->fournisseur = $obj->fournisseur;
1931 
1932  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1933  $this->note_private = $obj->note_private;
1934  $this->note_public = $obj->note_public;
1935  $this->model_pdf = $obj->model_pdf;
1936  $this->modelpdf = $obj->model_pdf; // deprecated
1937  $this->default_lang = $obj->default_lang;
1938  $this->logo = $obj->logo;
1939  $this->logo_squarred = $obj->logo_squarred;
1940 
1941  $this->webservices_url = $obj->webservices_url;
1942  $this->webservices_key = $obj->webservices_key;
1943 
1944  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1945  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1946 
1947  $this->outstanding_limit = $obj->outstanding_limit;
1948  $this->order_min_amount = $obj->order_min_amount;
1949  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1950 
1951  // multiprix
1952  $this->price_level = $obj->price_level;
1953 
1954  // warehouse
1955  $this->fk_warehouse = $obj->fk_warehouse;
1956 
1957  $this->import_key = $obj->import_key;
1958 
1959  //Incoterms
1960  $this->fk_incoterms = $obj->fk_incoterms;
1961  $this->location_incoterms = $obj->location_incoterms;
1962  $this->label_incoterms = $obj->label_incoterms;
1963 
1964  // multicurrency
1965  $this->fk_multicurrency = $obj->fk_multicurrency;
1966  $this->multicurrency_code = $obj->multicurrency_code;
1967 
1968  // pdf
1969  $this->model_pdf = $obj->model_pdf;
1970  $this->last_main_doc = $obj->last_main_doc;
1971 
1972  $result = 1;
1973 
1974  // fetch optionals attributes and labels
1975  $this->fetch_optionals();
1976  } else {
1977  $result = 0;
1978  }
1979 
1980  $this->db->free($resql);
1981  } else {
1982  $this->error = $this->db->lasterror();
1983  $this->errors[] = $this->db->lasterror();
1984  $result = -3;
1985  }
1986 
1987  // Use first price level if level not defined for third party
1988  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1989  $this->price_level = 1;
1990  }
1991 
1992  return $result;
1993  }
1994 
2003  public function delete($id, User $fuser = null, $call_trigger = 1)
2004  {
2005  global $langs, $conf, $user;
2006 
2007  if (empty($fuser)) {
2008  $fuser = $user;
2009  }
2010 
2011  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2012 
2013  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2014 
2015  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2016  $error = 0;
2017 
2018  // Test if child exists
2019  $objectisused = $this->isObjectUsed($id);
2020  if (empty($objectisused)) {
2021  $this->db->begin();
2022 
2023  // User is mandatory for trigger call
2024  if (!$error && $call_trigger) {
2025  // Call trigger
2026  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2027  if ($result < 0) {
2028  $error++;
2029  }
2030  // End call triggers
2031  }
2032 
2033  if (!$error) {
2034  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2035  $static_cat = new Categorie($this->db);
2036  $toute_categs = array();
2037 
2038  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2039  if ($this->client || $this->prospect) {
2040  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2041  }
2042  if ($this->fournisseur) {
2043  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2044  }
2045 
2046  // Remove each "Categorie"
2047  foreach ($toute_categs as $type => $categs_type) {
2048  foreach ($categs_type as $cat) {
2049  $cat->del_type($this, $type);
2050  }
2051  }
2052  }
2053 
2054  if (!$error) {
2055  foreach ($this->childtablesoncascade as $tabletodelete) {
2056  $deleteFromObject = explode(':', $tabletodelete);
2057  if (count($deleteFromObject) >= 2) {
2058  $className = str_replace('@', '', $deleteFromObject[0]);
2059  $filepath = $deleteFromObject[1];
2060  $columnName = $deleteFromObject[2];
2061  if (dol_include_once($filepath)) {
2062  $child_object = new $className($this->db);
2063  $result = $child_object->deleteByParentField($id, $columnName);
2064  if ($result < 0) {
2065  $error++;
2066  $this->errors[] = $child_object->error;
2067  break;
2068  }
2069  } else {
2070  $error++;
2071  $this->errors[] = 'Cannot include child class file '.$filepath;
2072  break;
2073  }
2074  } else {
2075  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2076  $sql .= " WHERE fk_soc = ".((int) $id);
2077  if (!$this->db->query($sql)) {
2078  $error++;
2079  $this->errors[] = $this->db->lasterror();
2080  break;
2081  }
2082  }
2083  }
2084  }
2085 
2086  // Removed extrafields
2087  if (!$error) {
2088  $result = $this->deleteExtraFields();
2089  if ($result < 0) {
2090  $error++;
2091  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2092  }
2093  }
2094 
2095  // Remove links to subsidiaries companies
2096  if (!$error) {
2097  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2098  $sql .= " SET parent = NULL";
2099  $sql .= " WHERE parent = ".((int) $id);
2100  if (!$this->db->query($sql)) {
2101  $error++;
2102  $this->errors[] = $this->db->lasterror();
2103  }
2104  }
2105 
2106  // Remove third party
2107  if (!$error) {
2108  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2109  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2110  $sql .= " WHERE fk_soc = ".((int) $id);
2111  if (!$this->db->query($sql)) {
2112  $error++;
2113  $this->errors[] = $this->db->lasterror();
2114  }
2115  }
2116 
2117  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2118  $sql .= " WHERE rowid = ".((int) $id);
2119  if (!$this->db->query($sql)) {
2120  $error++;
2121  $this->errors[] = $this->db->lasterror();
2122  }
2123  }
2124 
2125  if (!$error) {
2126  $this->db->commit();
2127 
2128  // Delete directory
2129  if (!empty($conf->societe->multidir_output[$entity])) {
2130  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2131  if (dol_is_dir($docdir)) {
2132  dol_delete_dir_recursive($docdir);
2133  }
2134  }
2135 
2136  return 1;
2137  } else {
2138  dol_syslog($this->error, LOG_ERR);
2139  $this->db->rollback();
2140  return -1;
2141  }
2142  } else {
2143  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2144  }
2145  return 0;
2146  }
2147 
2148  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2154  public function set_as_client()
2155  {
2156  global $conf;
2157  // phpcs:enable
2158  if ($this->id) {
2159  $newclient = 1;
2160  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
2161  $newclient = 3; //If prospect, we keep prospect tag
2162  }
2163  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2164  $sql .= " SET client = ".((int) $newclient);
2165  $sql .= " WHERE rowid = ".((int) $this->id);
2166 
2167  $resql = $this->db->query($sql);
2168  if ($resql) {
2169  $this->client = $newclient;
2170  return 1;
2171  } else {
2172  return -1;
2173  }
2174  }
2175  return 0;
2176  }
2177 
2178  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2187  public function set_remise_client($remise, $note, User $user)
2188  {
2189  // phpcs:enable
2190  global $conf, $langs;
2191 
2192  // Parameter cleaning
2193  $note = trim($note);
2194  if (!$note) {
2195  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2196  return -2;
2197  }
2198 
2199  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2200 
2201  if ($this->id) {
2202  $this->db->begin();
2203 
2204  $now = dol_now();
2205 
2206  // Position current discount
2207  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2208  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2209  $sql .= " WHERE rowid = ".((int) $this->id);
2210  $resql = $this->db->query($sql);
2211  if (!$resql) {
2212  $this->db->rollback();
2213  $this->error = $this->db->error();
2214  return -1;
2215  }
2216 
2217  // Writes trace in discount history
2218  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2219  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2220  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2221  $sql .= " '".$this->db->escape($note)."',";
2222  $sql .= " ".((int) $user->id);
2223  $sql .= ")";
2224 
2225  $resql = $this->db->query($sql);
2226  if (!$resql) {
2227  $this->db->rollback();
2228  $this->error = $this->db->lasterror();
2229  return -1;
2230  }
2231 
2232  $this->db->commit();
2233  return 1;
2234  }
2235  }
2236 
2237  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2246  public function set_remise_supplier($remise, $note, User $user)
2247  {
2248  // phpcs:enable
2249  global $conf, $langs;
2250 
2251  // Parameter cleaning
2252  $note = trim($note);
2253  if (!$note) {
2254  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2255  return -2;
2256  }
2257 
2258  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2259 
2260  if ($this->id) {
2261  $this->db->begin();
2262 
2263  $now = dol_now();
2264 
2265  // Position current discount
2266  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2267  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2268  $sql .= " WHERE rowid = ".((int) $this->id);
2269  $resql = $this->db->query($sql);
2270  if (!$resql) {
2271  $this->db->rollback();
2272  $this->error = $this->db->error();
2273  return -1;
2274  }
2275 
2276  // Writes trace in discount history
2277  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2278  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2279  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2280  $sql .= " '".$this->db->escape($note)."',";
2281  $sql .= " ".((int) $user->id);
2282  $sql .= ")";
2283 
2284  $resql = $this->db->query($sql);
2285  if (!$resql) {
2286  $this->db->rollback();
2287  $this->error = $this->db->lasterror();
2288  return -1;
2289  }
2290 
2291  $this->db->commit();
2292  return 1;
2293  }
2294  }
2295 
2296  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2308  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2309  {
2310  // phpcs:enable
2311  global $langs;
2312 
2313  // Clean parameters
2314  $remise = price2num($remise);
2315  $desc = trim($desc);
2316 
2317  // Check parameters
2318  if (!($remise > 0)) {
2319  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2320  return -1;
2321  }
2322  if (!$desc) {
2323  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2324  return -2;
2325  }
2326 
2327  if ($this->id > 0) {
2328  // Clean vat code
2329  $reg = array();
2330  $vat_src_code = '';
2331  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2332  $vat_src_code = $reg[1];
2333  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2334  }
2335 
2336  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2337 
2338  $discount = new DiscountAbsolute($this->db);
2339  $discount->fk_soc = $this->id;
2340 
2341  $discount->discount_type = $discount_type;
2342 
2343  if ($price_base_type == 'TTC') {
2344  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2345  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2346  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2347  } else {
2348  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2349  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2350  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2351  }
2352 
2353  $discount->tva_tx = price2num($vatrate);
2354  $discount->vat_src_code = $vat_src_code;
2355 
2356  $discount->description = $desc;
2357 
2358  $result = $discount->create($user);
2359  if ($result > 0) {
2360  return $result;
2361  } else {
2362  $this->error = $discount->error;
2363  return -3;
2364  }
2365  } else {
2366  return 0;
2367  }
2368  }
2369 
2379  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2380  {
2381  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2382 
2383  $discountstatic = new DiscountAbsolute($this->db);
2384  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2385  if ($result >= 0) {
2386  return $result;
2387  } else {
2388  $this->error = $discountstatic->error;
2389  return -1;
2390  }
2391  }
2392 
2402  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2403  {
2404  global $conf;
2405 
2406  $reparray = array();
2407 
2408  $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";
2409  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2410  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2411  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2412  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2413  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2414  $sql .= " AND ug.entity = ".$conf->entity.")";
2415  $sql .= " OR u.admin = 1)";
2416  } else {
2417  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2418  }
2419 
2420  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2421  if (empty($sortfield) && empty($sortorder)) {
2422  $sortfield = 'u.lastname,u.firstname';
2423  $sortorder = 'ASC,ASC';
2424  }
2425  $sql .= $this->db->order($sortfield, $sortorder);
2426 
2427  $resql = $this->db->query($sql);
2428  if ($resql) {
2429  $num = $this->db->num_rows($resql);
2430  $i = 0;
2431  while ($i < $num) {
2432  $obj = $this->db->fetch_object($resql);
2433 
2434  if (empty($mode)) {
2435  $reparray[$i]['id'] = $obj->rowid;
2436  $reparray[$i]['lastname'] = $obj->lastname;
2437  $reparray[$i]['firstname'] = $obj->firstname;
2438  $reparray[$i]['email'] = $obj->email;
2439  $reparray[$i]['phone'] = $obj->office_phone;
2440  $reparray[$i]['office_phone'] = $obj->office_phone;
2441  $reparray[$i]['office_fax'] = $obj->office_fax;
2442  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2443  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2444  $reparray[$i]['job'] = $obj->job;
2445  $reparray[$i]['statut'] = $obj->status; // deprecated
2446  $reparray[$i]['status'] = $obj->status;
2447  $reparray[$i]['entity'] = $obj->entity;
2448  $reparray[$i]['login'] = $obj->login;
2449  $reparray[$i]['photo'] = $obj->photo;
2450  $reparray[$i]['gender'] = $obj->gender;
2451  } else {
2452  $reparray[] = $obj->rowid;
2453  }
2454  $i++;
2455  }
2456  return $reparray;
2457  } else {
2458  dol_print_error($this->db);
2459  return -1;
2460  }
2461  }
2462 
2470  public function setPriceLevel($price_level, User $user)
2471  {
2472  if ($this->id) {
2473  $now = dol_now();
2474 
2475  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2476  $sql .= " SET price_level = ".((int) $price_level);
2477  $sql .= " WHERE rowid = ".((int) $this->id);
2478 
2479  if (!$this->db->query($sql)) {
2480  dol_print_error($this->db);
2481  return -1;
2482  }
2483 
2484  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2485  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2486  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2487 
2488  if (!$this->db->query($sql)) {
2489  dol_print_error($this->db);
2490  return -1;
2491  }
2492  return 1;
2493  }
2494  return -1;
2495  }
2496 
2497  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2505  public function add_commercial(User $user, $commid)
2506  {
2507  // phpcs:enable
2508  $error = 0;
2509 
2510  if ($this->id > 0 && $commid > 0) {
2511  $this->db->begin();
2512 
2513  if (!$error) {
2514  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2515  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2516 
2517  $resql = $this->db->query($sql);
2518  if (!$resql) {
2519  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2520  $error++;
2521  }
2522  }
2523 
2524  if (!$error) {
2525  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2526  $sql .= " (fk_soc, fk_user)";
2527  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2528 
2529  $resql = $this->db->query($sql);
2530  if (!$resql) {
2531  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2532  $error++;
2533  }
2534  }
2535 
2536  if (!$error) {
2537  $this->context = array('commercial_modified' => $commid);
2538 
2539  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2540  if ($result < 0) {
2541  $error++;
2542  }
2543  }
2544 
2545  if (!$error) {
2546  $this->db->commit();
2547  return 1;
2548  } else {
2549  $this->db->rollback();
2550  return -1;
2551  }
2552  }
2553 
2554  return 0;
2555  }
2556 
2557  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2565  public function del_commercial(User $user, $commid)
2566  {
2567  // phpcs:enable
2568  $error = 0;
2569  $this->context = array('commercial_modified'=>$commid);
2570 
2571  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2572  if ($result < 0) {
2573  $error++;
2574  }
2575 
2576  if ($this->id > 0 && $commid > 0) {
2577  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2578  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2579 
2580  if (!$this->db->query($sql)) {
2581  dol_syslog(get_class($this)."::del_commercial Erreur");
2582  }
2583  }
2584  }
2585 
2586 
2599  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2600  {
2601  global $conf, $langs, $hookmanager;
2602 
2603  if (!empty($conf->dol_no_mouse_hover)) {
2604  $notooltip = 1; // Force disable tooltips
2605  }
2606 
2607  $name = $this->name ? $this->name : $this->nom;
2608 
2609  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2610  if (empty($option) && $this->client > 0) {
2611  $option = 'customer';
2612  }
2613  if (empty($option) && $this->fournisseur > 0) {
2614  $option = 'supplier';
2615  }
2616  }
2617 
2618  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2619  $code = '';
2620  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2621  $code = $this->code_client.' - ';
2622  }
2623 
2624  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2625  $code .= $this->code_fournisseur.' - ';
2626  }
2627 
2628  if ($code) {
2629  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2630  $name = $code.' '.$name;
2631  } else {
2632  $name = $code;
2633  }
2634  }
2635  }
2636 
2637  if (!empty($this->name_alias) && empty($noaliasinname)) {
2638  $name .= ' ('.$this->name_alias.')';
2639  }
2640 
2641  $result = ''; $label = ''; $label2 = '';
2642  $linkstart = ''; $linkend = '';
2643 
2644  if (!empty($this->logo) && class_exists('Form')) {
2645  $label .= '<div class="photointooltip floatright">';
2646  $label .= Form::showphoto('societe', $this, 0, 40, 0, 'photoref', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
2647  $label .= '</div>';
2648  //$label .= '<div style="clear: both;"></div>';
2649  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2650  /*$label.= '<div class="photointooltip">';
2651  $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.
2652  $label.= '</div><div style="clear: both;"></div>';*/
2653  }
2654 
2655  $label .= '<div class="centpercent">';
2656 
2657  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2658  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2659  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2660  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2661  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2662  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2663  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2664  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2665  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2666  } elseif ($option == 'agenda') {
2667  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2668  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2669  } elseif ($option == 'project') {
2670  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2671  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2672  } elseif ($option == 'margin') {
2673  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2674  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2675  } elseif ($option == 'contact') {
2676  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2677  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2678  } elseif ($option == 'ban') {
2679  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2680  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2681  }
2682 
2683  // By default
2684  if (empty($linkstart)) {
2685  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2686  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2687  }
2688  if (isset($this->status)) {
2689  $label .= ' '.$this->getLibStatut(5);
2690  }
2691  if (isset($this->client) && isset($this->fournisseur)) {
2692  $label .= ' &nbsp; ';
2693  $label .= $this->getTypeUrl(1);
2694  }
2695 
2696  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2697  if (!empty($this->name_alias)) {
2698  $label .= ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2699  }
2700 
2701  if ($this->email) {
2702  $label .= '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2703  }
2704  if (!empty($this->phone) || !empty($this->fax)) {
2705  $phonelist = array();
2706  if ($this->phone) {
2707  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2708  }
2709  if ($this->fax) {
2710  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2711  }
2712  $label .= '<br>'.implode('&nbsp;', $phonelist);
2713  }
2714 
2715  if (!empty($this->address)) {
2716  $label2 .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2717  } elseif (!empty($this->country_code)) {
2718  $label2 .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2719  }
2720  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2721  $label2 .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2722  }
2723 
2724  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2725  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2726  $label2 .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2727  }
2728  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2729  $label2 .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2730  }
2731  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2732  $label2 .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2733  }
2734  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2735  $label2 .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2736  }
2737  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2738  $label2 .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2739  }
2740  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2741  $label2 .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2742  }
2743  }
2744  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2745  $label2 .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2746  }
2747  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2748  $label2 .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2749  }
2750  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2751  $label2 .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2752  }
2753  if (isModEnabled('accounting') && $this->fournisseur) {
2754  $label2 .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2755  }
2756  $label .= ($label2 ? '<br>'.$label2 : '').'</div>';
2757 
2758  // Add type of canvas
2759  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2760  // Add param to save lastsearch_values or not
2761  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2762  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2763  $add_save_lastsearch_values = 1;
2764  }
2765  if ($add_save_lastsearch_values) {
2766  $linkstart .= '&save_lastsearch_values=1';
2767  }
2768  $linkstart .= '"';
2769 
2770  $linkclose = '';
2771  if (empty($notooltip)) {
2772  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2773  $label = $langs->trans("ShowCompany");
2774  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2775  }
2776  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2777  $linkclose .= ' class="classfortooltip refurl"';
2778  $target_value = array('_self', '_blank', '_parent', '_top');
2779  if (in_array($target, $target_value)) {
2780  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2781  }
2782  }
2783  $linkstart .= $linkclose.'>';
2784  $linkend = '</a>';
2785 
2786  global $user;
2787  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2788  $linkstart = '';
2789  $linkend = '';
2790  }
2791 
2792  $result .= $linkstart;
2793  if ($withpicto) {
2794  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
2795  }
2796  if ($withpicto != 2) {
2797  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2798  }
2799  $result .= $linkend;
2800 
2801  global $action;
2802  $hookmanager->initHooks(array('thirdpartydao'));
2803  $parameters = array(
2804  'id'=>$this->id,
2805  'getnomurl' => &$result,
2806  'withpicto '=> $withpicto,
2807  'option'=> $option,
2808  'maxlen'=> $maxlen,
2809  'notooltip'=> $notooltip,
2810  'save_lastsearch_value'=> $save_lastsearch_value
2811  );
2812  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2813  if ($reshook > 0) {
2814  $result = $hookmanager->resPrint;
2815  } else {
2816  $result .= $hookmanager->resPrint;
2817  }
2818 
2819  return $result;
2820  }
2821 
2831  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2832  {
2833  global $conf, $langs;
2834 
2835  $s = '';
2836  if (empty($option) || preg_match('/prospect/', $option)) {
2837  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2838  $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.'>';
2839  }
2840  }
2841  if (empty($option) || preg_match('/customer/', $option)) {
2842  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2843  $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.'>';
2844  }
2845  }
2846  if (empty($option) || preg_match('/supplier/', $option)) {
2847  if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2848  $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.'>';
2849  }
2850  }
2851  return $s;
2852  }
2853 
2854 
2861  public function getLibStatut($mode = 0)
2862  {
2863  return $this->LibStatut($this->status, $mode);
2864  }
2865 
2866  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2874  public function LibStatut($status, $mode = 0)
2875  {
2876  // phpcs:enable
2877  global $langs;
2878  $langs->load('companies');
2879 
2880  $statusType = 'status4';
2881  if ($status == 0) {
2882  $statusType = 'status6';
2883  }
2884 
2885  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2886  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2887  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2888  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2889  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2890  }
2891 
2892  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2893  }
2894 
2895  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2902  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2903  {
2904  // phpcs:enable
2905  global $langs;
2906 
2907  $contact_emails = $this->contact_property_array('email', 1);
2908  if ($this->email && $addthirdparty) {
2909  if (empty($this->name)) {
2910  $this->name = $this->nom;
2911  }
2912  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2913  }
2914  //var_dump($contact_emails)
2915  return $contact_emails;
2916  }
2917 
2918  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2925  {
2926  // phpcs:enable
2927  global $langs;
2928 
2929  $contact_phone = $this->contact_property_array('mobile');
2930 
2931  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2932  if (empty($this->name)) {
2933  $this->name = $this->nom;
2934  }
2935  // TODO: Tester si tel non deja present dans tableau contact
2936  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2937  }
2938  return $contact_phone;
2939  }
2940 
2941  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2949  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2950  {
2951  // phpcs:enable
2952  global $langs;
2953 
2954  $contact_property = array();
2955 
2956 
2957  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2958  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2959  $sql .= " WHERE fk_soc = ".((int) $this->id);
2960  $sql .= " AND entity IN (".getEntity($this->element).")";
2961  $sql .= " ORDER BY lastname, firstname";
2962 
2963  $resql = $this->db->query($sql);
2964  if ($resql) {
2965  $nump = $this->db->num_rows($resql);
2966  if ($nump) {
2967  $sepa = "("; $sepb = ")";
2968  if ($mode == 'email') {
2969  //$sepa="&lt;"; $sepb="&gt;";
2970  $sepa = "<"; $sepb = ">";
2971  }
2972  $i = 0;
2973  while ($i < $nump) {
2974  $obj = $this->db->fetch_object($resql);
2975  if ($mode == 'email') {
2976  $property = $obj->email;
2977  } elseif ($mode == 'mobile') {
2978  $property = $obj->phone_mobile;
2979  } else {
2980  $property = $obj->$mode;
2981  }
2982 
2983  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2984  if ($obj->status == 1 || empty($hidedisabled)) {
2985  if (empty($property)) {
2986  if ($mode == 'email') {
2987  $property = $langs->transnoentitiesnoconv("NoEMail");
2988  } elseif ($mode == 'mobile') {
2989  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2990  }
2991  }
2992 
2993  if (!empty($obj->poste)) {
2994  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2995  } else {
2996  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2997  }
2998  }
2999  $i++;
3000  }
3001  }
3002  } else {
3003  dol_print_error($this->db);
3004  }
3005  return $contact_property;
3006  }
3007 
3008 
3009  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3015  public function contact_array()
3016  {
3017  // phpcs:enable
3018  $contacts = array();
3019 
3020  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3021  $resql = $this->db->query($sql);
3022  if ($resql) {
3023  $nump = $this->db->num_rows($resql);
3024  if ($nump) {
3025  $i = 0;
3026  while ($i < $nump) {
3027  $obj = $this->db->fetch_object($resql);
3028  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3029  $i++;
3030  }
3031  }
3032  } else {
3033  dol_print_error($this->db);
3034  }
3035  return $contacts;
3036  }
3037 
3038  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3044  public function contact_array_objects()
3045  {
3046  // phpcs:enable
3047  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3048  $contacts = array();
3049 
3050  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3051  $resql = $this->db->query($sql);
3052  if ($resql) {
3053  $nump = $this->db->num_rows($resql);
3054  if ($nump) {
3055  $i = 0;
3056  while ($i < $nump) {
3057  $obj = $this->db->fetch_object($resql);
3058  $contact = new Contact($this->db);
3059  $contact->fetch($obj->rowid);
3060  $contacts[] = $contact;
3061  $i++;
3062  }
3063  }
3064  } else {
3065  dol_print_error($this->db);
3066  }
3067  return $contacts;
3068  }
3069 
3070  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3078  public function contact_get_property($rowid, $mode)
3079  {
3080  // phpcs:enable
3081  $contact_property = '';
3082 
3083  if (empty($rowid)) {
3084  return '';
3085  }
3086 
3087  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3088  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3089  $sql .= " WHERE rowid = ".((int) $rowid);
3090 
3091  $resql = $this->db->query($sql);
3092  if ($resql) {
3093  $nump = $this->db->num_rows($resql);
3094 
3095  if ($nump) {
3096  $obj = $this->db->fetch_object($resql);
3097 
3098  if ($mode == 'email') {
3099  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3100  } elseif ($mode == 'mobile') {
3101  $contact_property = $obj->phone_mobile;
3102  }
3103  }
3104  return $contact_property;
3105  } else {
3106  dol_print_error($this->db);
3107  }
3108  }
3109 
3110 
3111  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3118  public function display_rib($mode = 'label')
3119  {
3120  // phpcs:enable
3121  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3122 
3123  $bac = new CompanyBankAccount($this->db);
3124  $bac->fetch(0, $this->id);
3125 
3126  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3127  if ($mode == 'label') {
3128  return $bac->getRibLabel(true);
3129  } elseif ($mode == 'rum') {
3130  if (empty($bac->rum)) {
3131  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3132  $prelevement = new BonPrelevement($this->db);
3133  $bac->fetch_thirdparty();
3134  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3135  }
3136  return $bac->rum;
3137  } elseif ($mode == 'format') {
3138  return $bac->frstrecur;
3139  } else {
3140  return 'BadParameterToFunctionDisplayRib';
3141  }
3142  } else {
3143  return '';
3144  }
3145  }
3146 
3147  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3153  public function get_all_rib()
3154  {
3155  // phpcs:enable
3156  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3157  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3158  $result = $this->db->query($sql);
3159  if (!$result) {
3160  $this->error++;
3161  $this->errors[] = $this->db->lasterror;
3162  return 0;
3163  } else {
3164  $num_rows = $this->db->num_rows($result);
3165  $rib_array = array();
3166  if ($num_rows) {
3167  while ($obj = $this->db->fetch_object($result)) {
3168  $rib = new CompanyBankAccount($this->db);
3169  $rib->fetch($obj->rowid);
3170  $rib_array[] = $rib;
3171  }
3172  }
3173  return $rib_array;
3174  }
3175  }
3176 
3177  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3186  public function get_codeclient($objsoc = 0, $type = 0)
3187  {
3188  // phpcs:enable
3189  global $conf;
3190  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3191  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3192 
3193  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3194  foreach ($dirsociete as $dirroot) {
3195  $res = dol_include_once($dirroot.$module.'.php');
3196  if ($res) {
3197  break;
3198  }
3199  }
3200  $mod = new $module();
3201 
3202  $this->code_client = $mod->getNextValue($objsoc, $type);
3203  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3204 
3205  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3206  }
3207  }
3208 
3209  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3218  public function get_codefournisseur($objsoc = 0, $type = 1)
3219  {
3220  // phpcs:enable
3221  global $conf;
3222  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3223  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3224 
3225  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3226  foreach ($dirsociete as $dirroot) {
3227  $res = dol_include_once($dirroot.$module.'.php');
3228  if ($res) {
3229  break;
3230  }
3231  }
3232  $mod = new $module();
3233 
3234  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3235 
3236  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3237  }
3238  }
3239 
3240  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3247  public function codeclient_modifiable()
3248  {
3249  // phpcs:enable
3250  global $conf;
3251  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3252  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3253 
3254  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3255  foreach ($dirsociete as $dirroot) {
3256  $res = dol_include_once($dirroot.$module.'.php');
3257  if ($res) {
3258  break;
3259  }
3260  }
3261 
3262  $mod = new $module();
3263 
3264  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3265  if ($mod->code_modifiable_null && !$this->code_client) {
3266  return 1;
3267  }
3268  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3269  return 1;
3270  }
3271  if ($mod->code_modifiable) {
3272  return 1; // A mettre en dernier
3273  }
3274  return 0;
3275  } else {
3276  return 0;
3277  }
3278  }
3279 
3280 
3281  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3287  public function codefournisseur_modifiable()
3288  {
3289  // phpcs:enable
3290  global $conf;
3291  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3292  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3293 
3294  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3295  foreach ($dirsociete as $dirroot) {
3296  $res = dol_include_once($dirroot.$module.'.php');
3297  if ($res) {
3298  break;
3299  }
3300  }
3301 
3302  $mod = new $module();
3303 
3304  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3305  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3306  return 1;
3307  }
3308  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3309  return 1;
3310  }
3311  if ($mod->code_modifiable) {
3312  return 1; // A mettre en dernier
3313  }
3314  return 0;
3315  } else {
3316  return 0;
3317  }
3318  }
3319 
3320 
3321  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3333  public function check_codeclient()
3334  {
3335  // phpcs:enable
3336  global $conf;
3337  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3338  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3339 
3340  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3341  foreach ($dirsociete as $dirroot) {
3342  $res = dol_include_once($dirroot.$module.'.php');
3343  if ($res) {
3344  break;
3345  }
3346  }
3347 
3348  $mod = new $module();
3349 
3350  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3351  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3352  if ($result) { // If error
3353  $this->error = $mod->error;
3354  $this->errors = $mod->errors;
3355  }
3356  return $result;
3357  } else {
3358  return 0;
3359  }
3360  }
3361 
3362  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3374  public function check_codefournisseur()
3375  {
3376  // phpcs:enable
3377  global $conf;
3378  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3379  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3380 
3381  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3382  foreach ($dirsociete as $dirroot) {
3383  $res = dol_include_once($dirroot.$module.'.php');
3384  if ($res) {
3385  break;
3386  }
3387  }
3388 
3389  $mod = new $module();
3390 
3391  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3392  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3393  if ($result) { // If error
3394  $this->error = $mod->error;
3395  $this->errors = $mod->errors;
3396  }
3397  return $result;
3398  } else {
3399  return 0;
3400  }
3401  }
3402 
3403  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3412  public function get_codecompta($type)
3413  {
3414  // phpcs:enable
3415  global $conf;
3416 
3417  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3418  $res = false;
3419  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3420  foreach ($dirsociete as $dirroot) {
3421  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3422  if ($res) {
3423  break;
3424  }
3425  }
3426 
3427  if ($res) {
3428  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3429  $mod = new $classname;
3430 
3431  // Set code count in $mod->code
3432  $result = $mod->get_code($this->db, $this, $type);
3433 
3434  if ($type == 'customer') {
3435  $this->code_compta_client = $mod->code;
3436  $this->code_compta = $this->code_compta_client; // For backward compatibility
3437  } elseif ($type == 'supplier') {
3438  $this->code_compta_fournisseur = $mod->code;
3439  }
3440 
3441  return $result;
3442  } else {
3443  $this->error = 'ErrorAccountancyCodeNotDefined';
3444  return -1;
3445  }
3446  } else {
3447  if ($type == 'customer') {
3448  $this->code_compta_client = '';
3449  $this->code_compta = '';
3450  } elseif ($type == 'supplier') {
3451  $this->code_compta_fournisseur = '';
3452  }
3453 
3454  return 0;
3455  }
3456  }
3457 
3464  public function setParent($id)
3465  {
3466  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3467 
3468  if ($this->id) {
3469  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3470  if ($id > 0) {
3471  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3472  if ($sameparent < 0) {
3473  return -1;
3474  }
3475  if ($sameparent == 1) {
3476  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3477  return -1;
3478  }
3479  }
3480 
3481  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3482 
3483  $resql = $this->db->query($sql);
3484  if ($resql) {
3485  $this->parent = $id;
3486  return 1;
3487  } else {
3488  return -1;
3489  }
3490  } else {
3491  return -1;
3492  }
3493  }
3494 
3503  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3504  {
3505  if ($counter > 100) {
3506  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3507  }
3508 
3509  $sql = 'SELECT s.parent';
3510  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3511  $sql .= ' WHERE rowid = '.((int) $idparent);
3512  $resql = $this->db->query($sql);
3513  if ($resql) {
3514  $obj = $this->db->fetch_object($resql);
3515 
3516  if ($obj->parent == '') {
3517  return 0;
3518  } elseif ($obj->parent == $idchild) {
3519  return 1;
3520  } else {
3521  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3522  }
3523  return $sameparent;
3524  } else {
3525  return -1;
3526  }
3527  }
3528 
3536  public function getParentsForCompany($company_id, $parents = [])
3537  {
3538  global $langs;
3539 
3540  if ($company_id > 0) {
3541  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3542  $resql = $this->db->query($sql);
3543  if ($resql) {
3544  if ($obj = $this->db->fetch_object($resql)) {
3545  $parent = $obj->parent;
3546  if ($parent > 0 && !in_array($parent, $parents)) {
3547  $parents[] = $parent;
3548  return $this->getParentsForCompany($parent, $parents);
3549  } else {
3550  return $parents;
3551  }
3552  }
3553  $this->db->free($resql);
3554  } else {
3555  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3556  }
3557  }
3558  }
3559 
3560  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3567  public function id_prof_verifiable($idprof)
3568  {
3569  // phpcs:enable
3570  global $conf;
3571 
3572  switch ($idprof) {
3573  case 1:
3574  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3575  break;
3576  case 2:
3577  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3578  break;
3579  case 3:
3580  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3581  break;
3582  case 4:
3583  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3584  break;
3585  case 5:
3586  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3587  break;
3588  case 6:
3589  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3590  break;
3591  default:
3592  $ret = false;
3593  }
3594 
3595  return $ret;
3596  }
3597 
3598  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3607  public function id_prof_exists($idprof, $value, $socid = 0)
3608  {
3609  // phpcs:enable
3610  $field = $idprof;
3611 
3612  switch ($idprof) { // For backward compatibility
3613  case '1':
3614  case 'idprof1':
3615  $field = "siren";
3616  break;
3617  case '2':
3618  case 'idprof2':
3619  $field = "siret";
3620  break;
3621  case '3':
3622  case 'idprof3':
3623  $field = "ape";
3624  break;
3625  case '4':
3626  case 'idprof4':
3627  $field = "idprof4";
3628  break;
3629  case '5':
3630  $field = "idprof5";
3631  break;
3632  case '6':
3633  $field = "idprof6";
3634  break;
3635  }
3636 
3637  //Verify duplicate entries
3638  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3639  if ($socid) {
3640  $sql .= " AND rowid <> ".$socid;
3641  }
3642  $resql = $this->db->query($sql);
3643  if ($resql) {
3644  $obj = $this->db->fetch_object($resql);
3645  $count = $obj->nb;
3646  } else {
3647  $count = 0;
3648  print $this->db->error();
3649  }
3650  $this->db->free($resql);
3651 
3652  if ($count > 0) {
3653  return true;
3654  } else {
3655  return false;
3656  }
3657  }
3658 
3659  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3668  public function id_prof_check($idprof, $soc)
3669  {
3670  // phpcs:enable
3671  global $conf;
3672 
3673  $ok = 1;
3674 
3675  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3676  return 1;
3677  }
3678 
3679  // Check SIREN if country FR
3680  if ($idprof == 1 && $soc->country_code == 'FR') {
3681  $chaine = trim($this->idprof1);
3682  $chaine = preg_replace('/(\s)/', '', $chaine);
3683 
3684  if (!is_numeric($chaine)) {
3685  return -1;
3686  }
3687  if (dol_strlen($chaine) != 9) {
3688  return -1;
3689  }
3690 
3691  // on prend chaque chiffre un par un
3692  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3693  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3694  // on ajoute cette valeur à la somme totale
3695  $sum = 0;
3696  for ($index = 0; $index < 9; $index++) {
3697  $number = (int) $chaine[$index];
3698  if (($index % 2) != 0) {
3699  if (($number *= 2) > 9) {
3700  $number -= 9;
3701  }
3702  }
3703  $sum += $number;
3704  }
3705 
3706  // le numéro est valide si la somme des chiffres est multiple de 10
3707  if (($sum % 10) != 0) {
3708  return -1;
3709  }
3710  }
3711 
3712  // Verifie SIRET si pays FR
3713  if ($idprof == 2 && $soc->country_code == 'FR') {
3714  $chaine = trim($this->idprof2);
3715  $chaine = preg_replace('/(\s)/', '', $chaine);
3716 
3717  if (!is_numeric($chaine)) {
3718  return -1;
3719  }
3720  if (dol_strlen($chaine) != 14) {
3721  return -1;
3722  }
3723 
3724  // on prend chaque chiffre un par un
3725  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3726  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3727  // on ajoute cette valeur à la somme totale
3728  $sum = 0;
3729  for ($index = 0; $index < 14; $index++) {
3730  $number = (int) $chaine[$index];
3731  if (($index % 2) == 0) {
3732  if (($number *= 2) > 9) {
3733  $number -= 9;
3734  }
3735  }
3736  $sum += $number;
3737  }
3738 
3739  // le numéro est valide si la somme des chiffres est multiple de 10
3740  if (($sum % 10) != 0) {
3741  return -1;
3742  }
3743  }
3744 
3745  //Verify CIF/NIF/NIE if pays ES
3746  //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
3747  if ($idprof == 1 && $soc->country_code == 'ES') {
3748  $string = trim($this->idprof1);
3749  $string = preg_replace('/(\s)/', '', $string);
3750  $string = strtoupper($string);
3751 
3752  //Check format
3753  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)) {
3754  return 0;
3755  }
3756 
3757  $num = array();
3758  for ($i = 0; $i < 9; $i++) {
3759  $num[$i] = substr($string, $i, 1);
3760  }
3761 
3762  //Check NIF
3763  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3764  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3765  return 1;
3766  } else {
3767  return -1;
3768  }
3769  }
3770 
3771  //algorithm checking type code CIF
3772  $sum = $num[2] + $num[4] + $num[6];
3773  for ($i = 1; $i < 8; $i += 2) {
3774  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3775  }
3776  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3777 
3778  //Chek special NIF
3779  if (preg_match('/^[KLM]{1}/', $string)) {
3780  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3781  return 1;
3782  } else {
3783  return -1;
3784  }
3785  }
3786 
3787  //Check CIF
3788  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3789  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3790  return 2;
3791  } else {
3792  return -2;
3793  }
3794  }
3795 
3796  //Check NIE T
3797  if (preg_match('/^[T]{1}/', $string)) {
3798  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3799  return 3;
3800  } else {
3801  return -3;
3802  }
3803  }
3804 
3805  //Check NIE XYZ
3806  if (preg_match('/^[XYZ]{1}/', $string)) {
3807  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3808  return 3;
3809  } else {
3810  return -3;
3811  }
3812  }
3813 
3814  //Can not be verified
3815  return -4;
3816  }
3817 
3818  //Verify NIF if country is PT
3819  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3820  if ($idprof == 1 && $soc->country_code == 'PT') {
3821  $string = trim($this->idprof1);
3822  $string = preg_replace('/(\s)/', '', $string);
3823 
3824  //Check NIF
3825  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3826  return 1;
3827  } else {
3828  return -1;
3829  }
3830  }
3831 
3832  //Verify NIF if country is DZ
3833  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3834  if ($idprof == 1 && $soc->country_code == 'DZ') {
3835  $string = trim($this->idprof1);
3836  $string = preg_replace('/(\s)/', '', $string);
3837 
3838  //Check NIF
3839  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3840  return 1;
3841  } else {
3842  return -1;
3843  }
3844  }
3845 
3846  return $ok;
3847  }
3848 
3849  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3858  public function id_prof_url($idprof, $thirdparty)
3859  {
3860  // phpcs:enable
3861  global $conf, $langs, $hookmanager;
3862 
3863  $url = '';
3864  $action = '';
3865 
3866  $hookmanager->initHooks(array('idprofurl'));
3867  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3868  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3869  if (empty($reshook)) {
3870  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3871  return '';
3872  }
3873 
3874  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3875  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3876  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3877  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3878  }
3879  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3880  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3881  }
3882  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3883  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3884  }
3885  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3886  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3887  }
3888  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3889  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3890  }
3891  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3892  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3893  }
3894 
3895  if ($url) {
3896  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3897  }
3898  } else {
3899  return $hookmanager->resPrint;
3900  }
3901 
3902  return '';
3903  }
3904 
3905  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3911  public function has_projects()
3912  {
3913  // phpcs:enable
3914  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3915  $resql = $this->db->query($sql);
3916  if ($resql) {
3917  $obj = $this->db->fetch_object($resql);
3918  $count = $obj->numproj;
3919  } else {
3920  $count = 0;
3921  print $this->db->error();
3922  }
3923  $this->db->free($resql);
3924  return ($count > 0);
3925  }
3926 
3927 
3934  public function info($id)
3935  {
3936  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
3937  $sql .= " fk_user_creat, fk_user_modif";
3938  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3939  $sql .= " WHERE s.rowid = ".((int) $id);
3940 
3941  $result = $this->db->query($sql);
3942  if ($result) {
3943  if ($this->db->num_rows($result)) {
3944  $obj = $this->db->fetch_object($result);
3945 
3946  $this->id = $obj->rowid;
3947 
3948  $this->user_creation_id = $obj->fk_user_creat;
3949  $this->user_modification_id = $obj->fk_user_modif;
3950  $this->date_creation = $this->db->jdate($obj->datec);
3951  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
3952 
3953  $this->ref = $obj->name;
3954  }
3955 
3956  $this->db->free($result);
3957  } else {
3958  dol_print_error($this->db);
3959  }
3960  }
3961 
3967  public function isACompany()
3968  {
3969  global $conf;
3970 
3971  // Define if third party is treated as company (or not) when nature is unknown
3972  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3973  if (!empty($this->tva_intra)) {
3974  $isacompany = 1;
3975  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3976  $isacompany = 1;
3977  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3978  // TODO Add a field is_a_company into dictionary
3979  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3980  $isacompany = 0;
3981  } else {
3982  $isacompany = 1;
3983  }
3984  }
3985 
3986  return $isacompany;
3987  }
3988 
3994  public function isInEEC()
3995  {
3996  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3997  return isInEEC($this);
3998  }
3999 
4000  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4006  public function LoadSupplierCateg()
4007  {
4008  // phpcs:enable
4009  $this->SupplierCategories = array();
4010  $sql = "SELECT rowid, label";
4011  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4012  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4013 
4014  $resql = $this->db->query($sql);
4015  if ($resql) {
4016  while ($obj = $this->db->fetch_object($resql)) {
4017  $this->SupplierCategories[$obj->rowid] = $obj->label;
4018  }
4019  return 0;
4020  } else {
4021  return -1;
4022  }
4023  }
4024 
4025  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4032  public function AddFournisseurInCategory($categorie_id)
4033  {
4034  // phpcs:enable
4035  if ($categorie_id > 0 && $this->id > 0) {
4036  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4037  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4038 
4039  if ($resql = $this->db->query($sql)) {
4040  return 0;
4041  }
4042  } else {
4043  return 0;
4044  }
4045  return -1;
4046  }
4047 
4053  public function getNbOfEMailings()
4054  {
4055  $sql = "SELECT count(mc.email) as nb";
4056  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4057  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4058  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4059 
4060  $resql = $this->db->query($sql);
4061  if ($resql) {
4062  $obj = $this->db->fetch_object($resql);
4063  $nb = $obj->nb;
4064 
4065  $this->db->free($resql);
4066  return $nb;
4067  } else {
4068  $this->error = $this->db->error();
4069  return -1;
4070  }
4071  }
4072 
4079  public function setNoEmail($no_email)
4080  {
4081  $error = 0;
4082 
4083  // Update mass emailing flag into table mailing_unsubscribe
4084  if ($this->email) {
4085  $this->db->begin();
4086 
4087  if ($no_email) {
4088  $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)."'";
4089  $resql = $this->db->query($sql);
4090  if ($resql) {
4091  $obj = $this->db->fetch_object($resql);
4092  $noemail = $obj->nb;
4093  if (empty($noemail)) {
4094  $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())."')";
4095  $resql = $this->db->query($sql);
4096  if (!$resql) {
4097  $error++;
4098  $this->error = $this->db->lasterror();
4099  $this->errors[] = $this->error;
4100  }
4101  }
4102  } else {
4103  $error++;
4104  $this->error = $this->db->lasterror();
4105  $this->errors[] = $this->error;
4106  }
4107  } else {
4108  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4109  $resql = $this->db->query($sql);
4110  if (!$resql) {
4111  $error++;
4112  $this->error = $this->db->lasterror();
4113  $this->errors[] = $this->error;
4114  }
4115  }
4116 
4117  if (empty($error)) {
4118  $this->no_email = $no_email;
4119  $this->db->commit();
4120  return 1;
4121  } else {
4122  $this->db->rollback();
4123  return $error * -1;
4124  }
4125  }
4126 
4127  return 0;
4128  }
4129 
4136  public function getNoEmail()
4137  {
4138  if ($this->email) {
4139  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4140  $resql = $this->db->query($sql);
4141  if ($resql) {
4142  $obj = $this->db->fetch_object($resql);
4143  $this->no_email = $obj->nb;
4144  return 1;
4145  } else {
4146  $this->error = $this->db->lasterror();
4147  $this->errors[] = $this->error;
4148  return -1;
4149  }
4150  }
4151  return 0;
4152  }
4153 
4154  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4164  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4165  {
4166  // phpcs:enable
4167  global $conf, $user, $langs;
4168 
4169  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4170  $fullname = $member->getFullName($langs);
4171 
4172  if ($member->morphy == 'mor') {
4173  if (empty($socname)) {
4174  $socname = $member->company? $member->company : $member->societe;
4175  }
4176  if (!empty($fullname) && empty($socalias)) {
4177  $socalias = $fullname;
4178  }
4179  } elseif (empty($socname) && $member->morphy == 'phy') {
4180  if (empty($socname)) {
4181  $socname = $fullname;
4182  }
4183  if (!empty($member->company) && empty($socalias)) {
4184  $socalias = $member->company;
4185  }
4186  }
4187 
4188  $name = $socname;
4189  $alias = $socalias ? $socalias : '';
4190 
4191  // Positionne parametres
4192  $this->nom = $name; // TODO deprecated
4193  $this->name = $name;
4194  $this->name_alias = $alias;
4195  $this->address = $member->address;
4196  $this->zip = $member->zip;
4197  $this->town = $member->town;
4198  $this->country_code = $member->country_code;
4199  $this->country_id = $member->country_id;
4200  $this->phone = $member->phone; // Prof phone
4201  $this->email = $member->email;
4202  $this->socialnetworks = $member->socialnetworks;
4203  $this->entity = $member->entity;
4204 
4205  $this->client = 1; // A member is a customer by default
4206  $this->code_client = ($customercode ? $customercode : -1);
4207  $this->code_fournisseur = -1;
4208  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4209  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4210 
4211  $this->db->begin();
4212 
4213  // Cree et positionne $this->id
4214  $result = $this->create($user);
4215 
4216  if ($result >= 0) {
4217  // Auto-create contact on thirdparty creation
4218  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4219  // Fill fields needed by contact
4220  $this->name_bis = $member->lastname;
4221  $this->firstname = $member->firstname;
4222  $this->civility_id = $member->civility_id;
4223 
4224  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4225  $result = $this->create_individual($user);
4226 
4227  if ($result < 0) {
4228  setEventMessages($this->error, $this->errors, 'errors');
4229  $this->db->rollback();
4230  return -1;
4231  }
4232  }
4233 
4234  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4235  $sql .= " SET fk_soc = ".((int) $this->id);
4236  $sql .= " WHERE rowid = ".((int) $member->id);
4237 
4238  $resql = $this->db->query($sql);
4239  if ($resql) {
4240  $this->db->commit();
4241  return $this->id;
4242  } else {
4243  $this->error = $this->db->error();
4244 
4245  $this->db->rollback();
4246  return -1;
4247  }
4248  } else {
4249  // $this->error deja positionne
4250  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4251 
4252  $this->db->rollback();
4253  return $result;
4254  }
4255  }
4256 
4263  public function setMysoc(Conf $conf)
4264  {
4265  global $langs;
4266 
4267  $this->id = 0;
4268  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
4269  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
4270  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
4271  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
4272  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
4273  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
4274 
4275  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
4276 
4277  $this->nom = $this->name; // deprecated
4278 
4279  // We define country_id, country_code and country
4280  $country_id = $country_code = $country_label = '';
4281  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4282  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4283  $country_id = $tmp[0];
4284  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4285  $country_code = $tmp[1];
4286  $country_label = $tmp[2];
4287  } else // For backward compatibility
4288  {
4289  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4290  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4291  $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
4292  $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
4293  }
4294  }
4295  $this->country_id = $country_id;
4296  $this->country_code = $country_code;
4297  $this->country = $country_label;
4298  if (is_object($langs)) {
4299  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4300  }
4301 
4302  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4303  // We define state_id, state_code and state
4304  $state_id = 0; $state_code = $state_label = '';
4305  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4306  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4307  $state_id = $tmp[0];
4308  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4309  $state_code = $tmp[1];
4310  $state_label = $tmp[2];
4311  } else { // For backward compatibility
4312  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);
4313  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4314  $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
4315  $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
4316  }
4317  }
4318  $this->state_id = $state_id;
4319  $this->state_code = $state_code;
4320  $this->state = $state_label;
4321  if (is_object($langs)) {
4322  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4323  }
4324 
4325  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
4326  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
4327  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
4328 
4329  // Social networks
4330  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
4331  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
4332  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
4333  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
4334  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
4335  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
4336  $this->socialnetworks = array();
4337  if (!empty($this->facebook_url)) {
4338  $this->socialnetworks['facebook'] = $this->facebook_url;
4339  }
4340  if (!empty($this->twitter_url)) {
4341  $this->socialnetworks['twitter'] = $this->twitter_url;
4342  }
4343  if (!empty($this->linkedin_url)) {
4344  $this->socialnetworks['linkedin'] = $this->linkedin_url;
4345  }
4346  if (!empty($this->instagram_url)) {
4347  $this->socialnetworks['instagram'] = $this->instagram_url;
4348  }
4349  if (!empty($this->youtube_url)) {
4350  $this->socialnetworks['youtube'] = $this->youtube_url;
4351  }
4352  if (!empty($this->github_url)) {
4353  $this->socialnetworks['github'] = $this->github_url;
4354  }
4355 
4356  // Id prof generiques
4357  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
4358  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
4359  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
4360  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
4361  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
4362  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
4363  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
4364  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
4365  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
4366  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
4367  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
4368  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
4369  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
4370  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
4371  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
4372  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
4373  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
4374  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
4375 
4376  // Define if company use vat or not
4377  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4378 
4379  // Define if company use local taxes
4380  $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);
4381  $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);
4382  }
4383 
4391  public function initAsSpecimen()
4392  {
4393  $now = dol_now();
4394 
4395  // Initialize parameters
4396  $this->id = 0;
4397  $this->entity = 1;
4398  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4399  $this->nom = $this->name; // For backward compatibility
4400  $this->ref_ext = 'Ref ext';
4401  $this->specimen = 1;
4402  $this->address = '21 jump street';
4403  $this->zip = '99999';
4404  $this->town = 'MyTown';
4405  $this->state_id = 1;
4406  $this->state_code = 'AA';
4407  $this->state = 'MyState';
4408  $this->country_id = 1;
4409  $this->country_code = 'FR';
4410  $this->email = 'specimen@specimen.com';
4411  $this->socialnetworks = array(
4412  'skype' => 'tom.hanson',
4413  'twitter' => 'tomhanson',
4414  'facebook' => 'tomhanson',
4415  'linkedin' => 'tomhanson',
4416  );
4417  $this->url = 'http://www.specimen.com';
4418 
4419  $this->phone = '0909090901';
4420  $this->fax = '0909090909';
4421 
4422  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4423  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4424  $this->capital = 10000;
4425  $this->client = 1;
4426  $this->prospect = 1;
4427  $this->fournisseur = 1;
4428  $this->tva_assuj = 1;
4429  $this->tva_intra = 'EU1234567';
4430  $this->note_public = 'This is a comment (public)';
4431  $this->note_private = 'This is a comment (private)';
4432 
4433  $this->idprof1 = 'idprof1';
4434  $this->idprof2 = 'idprof2';
4435  $this->idprof3 = 'idprof3';
4436  $this->idprof4 = 'idprof4';
4437  $this->idprof5 = 'idprof5';
4438  $this->idprof6 = 'idprof6';
4439  return 1;
4440  }
4441 
4448  public function useLocalTax($localTaxNum = 0)
4449  {
4450  $sql = "SELECT t.localtax1, t.localtax2";
4451  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4452  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4453  $sql .= " AND t.active = 1";
4454  if (empty($localTaxNum)) {
4455  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4456  } elseif ($localTaxNum == 1) {
4457  $sql .= " AND t.localtax1_type <> '0'";
4458  } elseif ($localTaxNum == 2) {
4459  $sql .= " AND t.localtax2_type <> '0'";
4460  }
4461 
4462  $resql = $this->db->query($sql);
4463  if ($resql) {
4464  return ($this->db->num_rows($resql) > 0);
4465  } else {
4466  return false;
4467  }
4468  }
4469 
4475  public function useNPR()
4476  {
4477  $sql = "SELECT t.rowid";
4478  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4479  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4480  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4481 
4482  dol_syslog("useNPR", LOG_DEBUG);
4483  $resql = $this->db->query($sql);
4484  if ($resql) {
4485  return ($this->db->num_rows($resql) > 0);
4486  } else {
4487  return false;
4488  }
4489  }
4490 
4497  public function useRevenueStamp()
4498  {
4499  $sql = "SELECT COUNT(*) as nb";
4500  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4501  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4502  $sql .= " AND r.active = 1";
4503 
4504  dol_syslog("useRevenueStamp", LOG_DEBUG);
4505  $resql = $this->db->query($sql);
4506  if ($resql) {
4507  $obj = $this->db->fetch_object($resql);
4508  return (($obj->nb > 0) ?true:false);
4509  } else {
4510  $this->error = $this->db->lasterror();
4511  return false;
4512  }
4513  }
4514 
4520  public function getLibProspLevel()
4521  {
4522  return $this->LibProspLevel($this->fk_prospectlevel);
4523  }
4524 
4525  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4532  public function LibProspLevel($fk_prospectlevel)
4533  {
4534  // phpcs:enable
4535  global $langs;
4536 
4537  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4538  // If lib not found in language file, we get label from cache/databse
4539  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4540  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4541  }
4542  return $lib;
4543  }
4544 
4552  public function getLibProspCommStatut($mode = 0, $label = '')
4553  {
4554  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4555  }
4556 
4557  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4571  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4572  {
4573  // phpcs:enable
4574  global $langs;
4575  $langs->load('customers');
4576 
4577  if ($mode == 2) {
4578  if ($status == '-1' || $status == 'ST_NO') {
4579  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4580  } elseif ($status == '0' || $status == 'ST_NEVER') {
4581  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4582  } elseif ($status == '1' || $status == 'ST_TODO') {
4583  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4584  } elseif ($status == '2' || $status == 'ST_PEND') {
4585  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4586  } elseif ($status == '3' || $status == 'ST_DONE') {
4587  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4588  } else {
4589  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4590  }
4591  } elseif ($mode == 3) {
4592  if ($status == '-1' || $status == 'ST_NO') {
4593  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4594  } elseif ($status == '0' || $status == 'ST_NEVER') {
4595  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4596  } elseif ($status == '1' || $status == 'ST_TODO') {
4597  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4598  } elseif ($status == '2' || $status == 'ST_PEND') {
4599  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4600  } elseif ($status == '3' || $status == 'ST_DONE') {
4601  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4602  } else {
4603  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4604  }
4605  } elseif ($mode == 4) {
4606  if ($status == '-1' || $status == 'ST_NO') {
4607  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4608  } elseif ($status == '0' || $status == 'ST_NEVER') {
4609  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4610  } elseif ($status == '1' || $status == 'ST_TODO') {
4611  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4612  } elseif ($status == '2' || $status == 'ST_PEND') {
4613  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4614  } elseif ($status == '3' || $status == 'ST_DONE') {
4615  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4616  } else {
4617  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4618  }
4619  }
4620 
4621  return "Error, mode/status not found";
4622  }
4623 
4630  public function getOutstandingProposals($mode = 'customer')
4631  {
4632  $table = 'propal';
4633  if ($mode == 'supplier') {
4634  $table = 'supplier_proposal';
4635  }
4636 
4637  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4638  $sql .= " WHERE fk_soc = ".((int) $this->id);
4639  if ($mode == 'supplier') {
4640  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4641  } else {
4642  $sql .= " AND entity IN (".getEntity('propal').")";
4643  }
4644 
4645  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4646 
4647  $resql = $this->db->query($sql);
4648  if ($resql) {
4649  $outstandingOpened = 0;
4650  $outstandingTotal = 0;
4651  $outstandingTotalIncTax = 0;
4652  $arrayofref = array();
4653  while ($obj = $this->db->fetch_object($resql)) {
4654  $arrayofref[$obj->rowid] = $obj->ref;
4655  $outstandingTotal += $obj->total_ht;
4656  $outstandingTotalIncTax += $obj->total_ttc;
4657  if ($obj->status != 0) {
4658  // Not a draft
4659  $outstandingOpened += $obj->total_ttc;
4660  }
4661  }
4662  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4663  } else {
4664  return array();
4665  }
4666  }
4667 
4674  public function getOutstandingOrders($mode = 'customer')
4675  {
4676  $table = 'commande';
4677  if ($mode == 'supplier') {
4678  $table = 'commande_fournisseur';
4679  }
4680 
4681  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4682  $sql .= " WHERE fk_soc = ".((int) $this->id);
4683  if ($mode == 'supplier') {
4684  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4685  } else {
4686  $sql .= " AND entity IN (".getEntity('commande').")";
4687  }
4688 
4689  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4690  $resql = $this->db->query($sql);
4691  if ($resql) {
4692  $outstandingOpened = 0;
4693  $outstandingTotal = 0;
4694  $outstandingTotalIncTax = 0;
4695  $arrayofref = array();
4696  while ($obj = $this->db->fetch_object($resql)) {
4697  $arrayofref[$obj->rowid] = $obj->ref;
4698  $outstandingTotal += $obj->total_ht;
4699  $outstandingTotalIncTax += $obj->total_ttc;
4700  if ($obj->status != 0) {
4701  // Not a draft
4702  $outstandingOpened += $obj->total_ttc;
4703  }
4704  }
4705  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4706  } else {
4707  return array();
4708  }
4709  }
4710 
4718  public function getOutstandingBills($mode = 'customer', $late = 0)
4719  {
4720  $table = 'facture';
4721  if ($mode == 'supplier') {
4722  $table = 'facture_fourn';
4723  }
4724 
4725  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4726  $paiement = $invoice->getSommePaiement();
4727  $creditnotes=$invoice->getSumCreditNotesUsed();
4728  $deposits=$invoice->getSumDepositsUsed();
4729  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4730  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4731  */
4732  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4733  $sql .= " WHERE fk_soc = ".((int) $this->id);
4734  if (!empty($late)) {
4735  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4736  }
4737  if ($mode == 'supplier') {
4738  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4739  } else {
4740  $sql .= " AND entity IN (".getEntity('invoice').")";
4741  }
4742 
4743  dol_syslog("getOutstandingBills", LOG_DEBUG);
4744  $resql = $this->db->query($sql);
4745  if ($resql) {
4746  $outstandingOpened = 0;
4747  $outstandingTotal = 0;
4748  $outstandingTotalIncTax = 0;
4749  $arrayofref = array();
4750  $arrayofrefopened = array();
4751  if ($mode == 'supplier') {
4752  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4753  $tmpobject = new FactureFournisseur($this->db);
4754  } else {
4755  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4756  $tmpobject = new Facture($this->db);
4757  }
4758  while ($obj = $this->db->fetch_object($resql)) {
4759  $arrayofref[$obj->rowid] = $obj->ref;
4760  $tmpobject->id = $obj->rowid;
4761 
4762  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4763  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4764  ) {
4765  $outstandingTotal += $obj->total_ht;
4766  $outstandingTotalIncTax += $obj->total_ttc;
4767  }
4768 
4769  $remaintopay = 0;
4770 
4771  if ($obj->paye == 0
4772  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4773  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4774  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4775  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4776  $paiement = $tmpobject->getSommePaiement();
4777  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4778  $deposits = $tmpobject->getSumDepositsUsed();
4779 
4780  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4781  $outstandingOpened += $remaintopay;
4782  }
4783 
4784  //if credit note is converted but not used
4785  // TODO Do this also for customer ?
4786  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4787  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4788  $remaintopay -= $remainingcreditnote;
4789  $outstandingOpened -= $remainingcreditnote;
4790  }
4791 
4792  if ($remaintopay) {
4793  $arrayofrefopened[$obj->rowid] = $obj->ref;
4794  }
4795  }
4796  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4797  } else {
4798  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4799  return array();
4800  }
4801  }
4802 
4809  public function getLibCustProspStatut()
4810  {
4811  return $this->LibCustProspStatut($this->client);
4812  }
4813 
4814  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4821  public function LibCustProspStatut($status)
4822  {
4823  // phpcs:enable
4824  global $langs;
4825  $langs->load('companies');
4826 
4827  if ($status == 0) {
4828  return $langs->trans("NorProspectNorCustomer");
4829  } elseif ($status == 1) {
4830  return $langs->trans("Customer");
4831  } elseif ($status == 2) {
4832  return $langs->trans("Prospect");
4833  } elseif ($status == 3) {
4834  return $langs->trans("ProspectCustomer");
4835  }
4836  }
4837 
4838 
4850  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4851  {
4852  global $conf, $user, $langs;
4853 
4854  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4855  $modelpath = "core/modules/bank/doc/";
4856 
4857  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4858  $companybankaccount = new CompanyBankAccount($this->db);
4859  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4860  if (!$result) {
4861  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4862  }
4863  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4864  } else {
4865  // Positionne le modele sur le nom du modele a utiliser
4866  if (!dol_strlen($modele)) {
4867  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4868  $modele = $conf->global->COMPANY_ADDON_PDF;
4869  } else {
4870  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4871  return 0;
4872  }
4873  }
4874 
4875  if (!isset($this->bank_account)) {
4876  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4877  $bac = new CompanyBankAccount($this->db);
4878  $result = $bac->fetch(0, $this->id);
4879  if ($result > 0) {
4880  $this->bank_account = $bac;
4881  } else {
4882  $this->bank_account = '';
4883  }
4884  }
4885 
4886  $modelpath = "core/modules/societe/doc/";
4887 
4888  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4889  }
4890 
4891  return $result;
4892  }
4893 
4894 
4906  public function setCategories($categories, $type_categ)
4907  {
4908  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4909 
4910  // Decode type
4911  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4912  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4913  return -1;
4914  }
4915 
4916  return parent::setCategoriesCommon($categories, $type_categ);
4917  }
4918 
4926  public function setSalesRep($salesrep, $onlyAdd = false)
4927  {
4928  global $user;
4929 
4930  // Handle single user
4931  if (!is_array($salesrep)) {
4932  $salesrep = array($salesrep);
4933  }
4934 
4935  $to_del = array(); // Nothing to delete
4936  $to_add = $salesrep;
4937  if ($onlyAdd === false) {
4938  // Get current users
4939  $existing = $this->getSalesRepresentatives($user, 1);
4940 
4941  // Diff
4942  if (is_array($existing)) {
4943  $to_del = array_diff($existing, $salesrep);
4944  $to_add = array_diff($salesrep, $existing);
4945  }
4946  }
4947 
4948  $error = 0;
4949 
4950  // Process
4951  foreach ($to_del as $del) {
4952  $this->del_commercial($user, $del);
4953  }
4954  foreach ($to_add as $add) {
4955  $result = $this->add_commercial($user, $add);
4956  if ($result < 0) {
4957  $error++;
4958  break;
4959  }
4960  }
4961 
4962  return $error ? -1 : 1;
4963  }
4964 
4971  public function setThirdpartyType($typent_id)
4972  {
4973  global $user;
4974 
4975  dol_syslog(__METHOD__, LOG_DEBUG);
4976 
4977  if ($this->id) {
4978  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
4979 
4980  if ($result > 0) {
4981  $this->typent_id = $typent_id;
4982  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
4983  return 1;
4984  } else {
4985  return -1;
4986  }
4987  } else {
4988  return -1;
4989  }
4990  }
4991 
5001  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5002  {
5003  if ($origin_id == $dest_id) {
5004  dol_syslog('Error: Try to merge a thirdparty into itself');
5005  return false;
5006  }
5007 
5012  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5013  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5014  $sql .= ' SELECT fk_user ';
5015  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5016  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5017 
5018  $resql = $dbs->query($sql);
5019  while ($obj = $dbs->fetch_object($resql)) {
5020  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5021  }
5022 
5027  $tables = array(
5028  'societe_address',
5029  'societe_commerciaux',
5030  'societe_prices',
5031  'societe_remise',
5032  'societe_remise_except',
5033  'societe_rib'
5034  );
5035 
5036  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5037  }
5038 
5047  public function setAccountancyCode($type, $value)
5048  {
5049  global $user, $langs, $conf;
5050 
5051  $this->db->begin();
5052 
5053  $field = 'accountancy_code_sell';
5054  if ($type == 'buy') {
5055  $field = 'accountancy_code_buy';
5056  } elseif ($type == 'sell') {
5057  $field = 'accountancy_code_sell';
5058  } else {
5059  return -1;
5060  }
5061 
5062  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5063  $sql .= $field." = '".$this->db->escape($value)."'";
5064  $sql .= " WHERE rowid = ".((int) $this->id);
5065 
5066  dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
5067  $resql = $this->db->query($sql);
5068 
5069  if ($resql) {
5070  // Call triggers
5071  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5072  $interface = new Interfaces($this->db);
5073  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5074  if ($result < 0) {
5075  $this->errors = $interface->errors;
5076  $this->db->rollback();
5077  return -1;
5078  }
5079  // End call triggers
5080 
5081  $this->$field = $value;
5082 
5083  $this->db->commit();
5084  return 1;
5085  } else {
5086  $this->error = $this->db->lasterror();
5087  $this->db->rollback();
5088  return -1;
5089  }
5090  }
5091 
5098  public function fetchPartnerships($mode)
5099  {
5100  global $langs;
5101 
5102  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5103 
5104 
5105  $this->partnerships[] = array();
5106 
5107  return 1;
5108  }
5109 }
Societe\NO_SUPPLIER
const NO_SUPPLIER
Third party supplier flag is not supplier.
Definition: societe.class.php:834
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:49
Societe\replaceThirdparty
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: societe.class.php:5001
clean_url
clean_url($url, $http=1)
Clean an url string.
Definition: functions2.lib.php:825
db
$conf db
API class for accounts.
Definition: inc.php:41
Societe\PROSPECT
const PROSPECT
Third party type is a prospect.
Definition: societe.class.php:824
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:3503
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1493
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:3949
Societe\LibProspCommStatut
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
Definition: societe.class.php:4571
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1225
FactureFournisseur\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: fournisseur.facture.class.php:336
Societe\get_codefournisseur
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
Definition: societe.class.php:3218
Societe\id_prof_verifiable
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
Definition: societe.class.php:3567
Societe\getParentsForCompany
getParentsForCompany($company_id, $parents=[])
Get parents for company.
Definition: societe.class.php:3536
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:1402
img_action
img_action($titlealt, $numaction, $picto='')
Show logo action.
Definition: functions.lib.php:4445
Societe\codefournisseur_modifiable
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
Definition: societe.class.php:3287
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
dol_substr
dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
Make a substring.
Definition: functions.lib.php:3910
Societe\getNbOfEMailings
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
Definition: societe.class.php:4053
Societe\LoadSupplierCateg
LoadSupplierCateg()
Load the list of provider categories.
Definition: societe.class.php:4006
Societe\set_remise_supplier
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2246
CommonObject\setUpperOrLowerCase
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
Definition: commonobject.class.php:745
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:4993
Societe\CUSTOMER_AND_PROSPECT
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
Definition: societe.class.php:829
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:1032
ref
$object ref
Definition: info.php:78
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:501
Societe\getLibStatut
getLibStatut($mode=0)
Return label of status (activity, closed)
Definition: societe.class.php:2861
CommonIncoterm
trait CommonIncoterm
Superclass for incoterm classes.
Definition: commonincoterm.class.php:29
Societe\NO_CUSTOMER
const NO_CUSTOMER
Third party type is no customer.
Definition: societe.class.php:814
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:3247
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:2051
name
$conf db name
Definition: repair.php:122
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:2505
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:4497
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
CommonObject\getFullName
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
Definition: commonobject.class.php:717
Societe\setCategories
setCategories($categories, $type_categ)
Sets object to supplied categories.
Definition: societe.class.php:4906
CommonObject\isObjectUsed
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
Definition: commonobject.class.php:4572
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:5823
Societe\create_individual
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
Definition: societe.class.php:1064
Societe\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: societe.class.php:4391
Societe\setThirdpartyType
setThirdpartyType($typent_id)
Define third-party type of current company.
Definition: societe.class.php:4971
Societe\__construct
__construct($db)
Constructor.
Definition: societe.class.php:847
Societe\get_codecompta
get_codecompta($type)
Assigns a accounting code from the accounting code module.
Definition: societe.class.php:3412
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:6453
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:4475
Societe\get_codeclient
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
Definition: societe.class.php:3186
getState
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
Definition: company.lib.php:596
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:4024
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:2902
Societe\getSalesRepresentatives
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Definition: societe.class.php:2402
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:5427
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:4926
Societe\AddFournisseurInCategory
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
Definition: societe.class.php:4032
Societe\display_rib
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
Definition: societe.class.php:3118
Societe\setPriceLevel
setPriceLevel($price_level, User $user)
Set the price level.
Definition: societe.class.php:2470
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:2599
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:8880
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:180
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:3668
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1397
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:2379
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6185
Societe\isACompany
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
Definition: societe.class.php:3967
Database\fetch_object
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
Societe\setNoEmail
setNoEmail($no_email)
Set "blacklist" mailing status.
Definition: societe.class.php:4079
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:1267
Societe\SUPPLIER
const SUPPLIER
Third party supplier flag is a supplier.
Definition: societe.class.php:839
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6880
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:2308
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8499
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1628
Societe\getLibProspLevel
getLibProspLevel()
Return prostect level.
Definition: societe.class.php:4520
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:2874
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8437
Contact
Class to manage contact/addresses.
Definition: contact.class.php:40
Societe\has_projects
has_projects()
Indicates if the company has projects.
Definition: societe.class.php:3911
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:2949
Societe\setMysoc
setMysoc(Conf $conf)
Set properties with value into $conf.
Definition: societe.class.php:4263
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:2429
Societe\getOutstandingBills
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
Definition: societe.class.php:4718
Adherent
Class to manage members of a foundation.
Definition: adherent.class.php:46
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:4164
Societe\isInEEC
isInEEC()
Return if a company is inside the EEC (European Economic Community)
Definition: societe.class.php:3994
Societe\getLibProspCommStatut
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
Definition: societe.class.php:4552
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3887
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:3607
Societe\getNoEmail
getNoEmail()
get "blacklist" mailing status set no_email attribut to 1 or 0
Definition: societe.class.php:4136
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:137
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:1715
Societe\contact_get_property
contact_get_property($rowid, $mode)
Return property of contact from its id.
Definition: societe.class.php:3078
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8391
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:4448
User
Class to manage Dolibarr users.
Definition: user.class.php:46
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6145
Societe\set_remise_client
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2187
Societe\getOutstandingProposals
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
Definition: societe.class.php:4630
Societe\setParent
setParent($id)
Define parent company of current company.
Definition: societe.class.php:3464
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10745
Societe\contact_array_objects
contact_array_objects()
Returns the contact list of this company.
Definition: societe.class.php:3044
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:4360
Societe\contact_array
contact_array()
Returns the contact list of this company.
Definition: societe.class.php:3015
Societe\CUSTOMER
const CUSTOMER
Third party type is a customer.
Definition: societe.class.php:819
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:2924
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2951
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:4850
Societe\getOutstandingOrders
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
Definition: societe.class.php:4674
Societe\set_as_client
set_as_client()
Define third party as a customer.
Definition: societe.class.php:2154
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:3291
Societe\get_all_rib
get_all_rib()
Return Array of RIB.
Definition: societe.class.php:3153
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:516
Form\showphoto
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Definition: html.form.class.php:9417
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5818
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8466
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:1137
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:451
Societe\LibCustProspStatut
LibCustProspStatut($status)
Return the label of the customer/prospect status.
Definition: societe.class.php:4821
Societe\del_commercial
del_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2565
Societe\getTypeUrl
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
Definition: societe.class.php:2831
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:3858
Societe\create
create(User $user, $notrigger=0)
Create third party in database.
Definition: societe.class.php:879
Societe\check_codefournisseur
check_codefournisseur()
Check supplier code.
Definition: societe.class.php:3374
Societe\LibProspLevel
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
Definition: societe.class.php:4532
Societe\getLibCustProspStatut
getLibCustProspStatut()
Return label of status customer is prospect/customer.
Definition: societe.class.php:4809
Societe\setAccountancyCode
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
Definition: societe.class.php:5047
Societe\check_codeclient
check_codeclient()
Check customer code.
Definition: societe.class.php:3333
Societe\info
info($id)
Load information for tab info.
Definition: societe.class.php:3934
Societe\fetchPartnerships
fetchPartnerships($mode)
Function to get partnerships array.
Definition: societe.class.php:5098