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 && !$notrigger) {
1014  // Call trigger
1015  $result = $this->call_trigger('COMPANY_CREATE', $user);
1016  if ($result < 0) {
1017  $error++;
1018  }
1019  // End call triggers
1020  } else {
1021  $error++;
1022  }
1023 
1024  if (!$error) {
1025  dol_syslog(get_class($this)."::Create success id=".$this->id);
1026  $this->db->commit();
1027  return $this->id;
1028  } else {
1029  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1030  $this->db->rollback();
1031  return -4;
1032  }
1033  } else {
1034  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1035  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1036  $result = -1;
1037  } else {
1038  $this->error = $this->db->lasterror();
1039  $result = -2;
1040  }
1041  $this->db->rollback();
1042  return $result;
1043  }
1044  } else {
1045  $this->db->rollback();
1046  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1047  return -3;
1048  }
1049  }
1050 
1051 
1052  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1062  public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1063  {
1064  global $conf;
1065 
1066  $error = 0;
1067 
1068  $this->db->begin();
1069 
1070  // phpcs:enable
1071  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1072  $contact = new Contact($this->db);
1073 
1074  $contact->name = $this->name_bis;
1075  $contact->firstname = $this->firstname;
1076  $contact->civility_id = $this->civility_id;
1077  $contact->socid = $this->id; // fk_soc
1078  $contact->statut = 1; // deprecated
1079  $contact->status = 1;
1080  $contact->priv = 0;
1081  $contact->country_id = $this->country_id;
1082  $contact->state_id = $this->state_id;
1083  $contact->address = $this->address;
1084  $contact->email = $this->email;
1085  $contact->zip = $this->zip;
1086  $contact->town = $this->town;
1087  $this->setUpperOrLowerCase();
1088  $contact->phone_pro = $this->phone;
1089 
1090  $contactId = $contact->create($user, $notrigger);
1091  if ($contactId < 0) {
1092  $error++;
1093  $this->error = $contact->error;
1094  $this->errors = $contact->errors;
1095  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1096  }
1097 
1098  if (empty($error) && is_array($tags) && !empty($tags)) {
1099  $result = $contact->setCategories($tags);
1100  if ($result < 0) {
1101  $error++;
1102  $this->error = $contact->error;
1103  $this->errors = array_merge($this->errors, $contact->errors);
1104  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1105  $contactId = $result;
1106  }
1107  }
1108 
1109  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1110  $result = $contact->setNoEmail($no_email);
1111  if ($result < 0) {
1112  $this->error = $contact->error;
1113  $this->errors = array_merge($this->errors, $contact->errors);
1114  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1115  $contactId = $result;
1116  }
1117  }
1118 
1119  if (empty($error)) {
1120  dol_syslog(get_class($this)."::create_individual success");
1121  $this->db->commit();
1122  } else {
1123  $this->db->rollback();
1124  }
1125 
1126  return $contactId;
1127  }
1128 
1135  public function verify()
1136  {
1137  global $conf, $langs, $mysoc;
1138 
1139  $error = 0;
1140  $this->errors = array();
1141 
1142  $result = 0;
1143  $this->name = trim($this->name);
1144  $this->nom = $this->name; // For backward compatibility
1145 
1146  if (!$this->name) {
1147  $this->errors[] = 'ErrorBadThirdPartyName';
1148  $result = -2;
1149  }
1150 
1151  if ($this->client) {
1152  $rescode = $this->check_codeclient();
1153  if ($rescode != 0 && $rescode != -5) {
1154  if ($rescode == -1) {
1155  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1156  } elseif ($rescode == -2) {
1157  $this->errors[] = 'ErrorCustomerCodeRequired';
1158  } elseif ($rescode == -3) {
1159  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1160  } elseif ($rescode == -4) {
1161  $this->errors[] = 'ErrorPrefixRequired';
1162  } else {
1163  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1164  }
1165 
1166  $result = -3;
1167  }
1168  }
1169 
1170  if ($this->fournisseur) {
1171  $rescode = $this->check_codefournisseur();
1172  if ($rescode != 0 && $rescode != -5) {
1173  if ($rescode == -1) {
1174  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1175  } elseif ($rescode == -2) {
1176  $this->errors[] = 'ErrorSupplierCodeRequired';
1177  } elseif ($rescode == -3) {
1178  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1179  } elseif ($rescode == -4) {
1180  $this->errors[] = 'ErrorPrefixRequired';
1181  } else {
1182  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1183  }
1184  $result = -3;
1185  }
1186  }
1187 
1188  // Check for duplicate or mandatory fields defined into setup
1189  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA');
1190  foreach ($array_to_check as $key) {
1191  $keymin = strtolower($key);
1192  $i = (int) preg_replace('/[^0-9]/', '', $key);
1193  $vallabel = $this->$keymin;
1194 
1195  if ($i > 0) {
1196  if ($this->isACompany()) {
1197  // Check for mandatory prof id (but only if country is same than ours)
1198  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1199  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1200  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1201  $langs->load("errors");
1202  $error++;
1203  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1204  }
1205  }
1206  }
1207 
1208  // Check for unicity on profid
1209  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1210  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1211  $langs->load("errors");
1212  $error++;
1213  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1214  }
1215  }
1216  } else {
1217  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1218  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1219  if ($key == 'EMAIL') {
1220  // Check for mandatory
1221  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1222  $langs->load("errors");
1223  $error++;
1224  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1225  }
1226 
1227  // Check for unicity
1228  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1229  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1230  $langs->load("errors");
1231  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1232  }
1233  }
1234  } elseif ($key == 'TVA_INTRA') {
1235  // Check for unicity
1236  if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
1237  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1238  $langs->load("errors");
1239  $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1240  }
1241  }
1242  }
1243  }
1244  }
1245 
1246  if ($error) {
1247  $result = -4;
1248  }
1249 
1250  return $result;
1251  }
1252 
1265  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1266  {
1267  global $langs, $conf, $hookmanager;
1268 
1269  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1270 
1271  if (empty($id)) {
1272  $id = $this->id;
1273  }
1274 
1275  $error = 0;
1276 
1277  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1278 
1279  $now = dol_now();
1280 
1281  // Clean parameters
1282  $this->id = $id;
1283  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1284  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1285  $this->nom = $this->name; // For backward compatibility
1286  $this->name_alias = trim($this->name_alias);
1287  $this->ref_ext = trim($this->ref_ext);
1288  $this->address = $this->address ?trim($this->address) : trim($this->address);
1289  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1290  $this->town = $this->town ?trim($this->town) : trim($this->town);
1291  $this->state_id = trim($this->state_id);
1292  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1293  $this->phone = trim($this->phone);
1294  $this->phone = preg_replace("/\s/", "", $this->phone);
1295  $this->phone = preg_replace("/\./", "", $this->phone);
1296  $this->fax = trim($this->fax);
1297  $this->fax = preg_replace("/\s/", "", $this->fax);
1298  $this->fax = preg_replace("/\./", "", $this->fax);
1299  $this->email = trim($this->email);
1300  $this->url = $this->url ?clean_url($this->url, 0) : '';
1301  $this->note_private = trim($this->note_private);
1302  $this->note_public = trim($this->note_public);
1303  $this->idprof1 = trim($this->idprof1);
1304  $this->idprof2 = trim($this->idprof2);
1305  $this->idprof3 = trim($this->idprof3);
1306  $this->idprof4 = trim($this->idprof4);
1307  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1308  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1309  $this->prefix_comm = trim($this->prefix_comm);
1310  $this->outstanding_limit = price2num($this->outstanding_limit);
1311  $this->order_min_amount = price2num($this->order_min_amount);
1312  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1313 
1314  $this->tva_assuj = trim($this->tva_assuj);
1315  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1316  if (empty($this->status)) {
1317  $this->status = 0;
1318  }
1319 
1320  if (!empty($this->multicurrency_code)) {
1321  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1322  }
1323  if (empty($this->fk_multicurrency)) {
1324  $this->multicurrency_code = '';
1325  $this->fk_multicurrency = 0;
1326  }
1327 
1328  // Local taxes
1329  $this->localtax1_assuj = trim($this->localtax1_assuj);
1330  $this->localtax2_assuj = trim($this->localtax2_assuj);
1331 
1332  $this->localtax1_value = trim($this->localtax1_value);
1333  $this->localtax2_value = trim($this->localtax2_value);
1334 
1335  if ($this->capital != '') {
1336  $this->capital = price2num(trim($this->capital));
1337  }
1338  if (!is_numeric($this->capital)) {
1339  $this->capital = ''; // '' = undef
1340  }
1341 
1342  $this->effectif_id = trim($this->effectif_id);
1343  $this->forme_juridique_code = trim($this->forme_juridique_code);
1344 
1345  //Gencod
1346  $this->barcode = trim($this->barcode);
1347 
1348  // For automatic creation
1349  if ($this->code_client == -1 || $this->code_client === 'auto') {
1350  $this->get_codeclient($this, 0);
1351  }
1352  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1353  $this->get_codefournisseur($this, 1);
1354  }
1355 
1356  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1357  $this->code_compta = $this->code_compta_client; // for backward compatibility
1358  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1359 
1360  // Check parameters. More tests are done later in the ->verify()
1361  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1362  $langs->load("errors");
1363  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1364  return -1;
1365  }
1366 
1367  $customer = false;
1368  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1369  // If $allowmodcodeclient is set and value is not set, we generate it
1370  if (empty($this->code_compta_client)) {
1371  $ret = $this->get_codecompta('customer');
1372  if ($ret < 0) {
1373  return -1;
1374  }
1375  }
1376 
1377  $customer = true;
1378  }
1379 
1380  $supplier = false;
1381  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1382  // If $allowmodcodefournisseur is set and value is not set, we generate it
1383  if (empty($this->code_compta_fournisseur)) {
1384  $ret = $this->get_codecompta('supplier');
1385  if ($ret < 0) {
1386  return -1;
1387  }
1388  }
1389 
1390  $supplier = true;
1391  }
1392 
1393  //Web services
1394  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1395  $this->webservices_key = trim($this->webservices_key);
1396 
1397  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1398  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1399 
1400  //Incoterms
1401  $this->fk_incoterms = (int) $this->fk_incoterms;
1402  $this->location_incoterms = trim($this->location_incoterms);
1403 
1404  $this->db->begin();
1405 
1406  // Check name is required and codes are ok or unique.
1407  // If error, this->errors[] is filled
1408  $result = 0;
1409  if ($action != 'add' && $action != 'merge') {
1410  // We don't check when update called during a create because verify was already done.
1411  // 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
1412  $result = $this->verify();
1413 
1414  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1415  // So we can update record that were using and old numbering rule.
1416  if (is_array($this->errors)) {
1417  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1418  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1419  unset($this->errors[$key]); // Remove error message
1420  }
1421  }
1422  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1423  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1424  unset($this->errors[$key]); // Remove error message
1425  }
1426  }
1427  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1428  $result = 0;
1429  }
1430  }
1431  }
1432  $this->setUpperOrLowerCase();
1433  if ($result >= 0) {
1434  dol_syslog(get_class($this)."::update verify ok or not done");
1435 
1436  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1437  $sql .= "entity = ".$this->db->escape($this->entity);
1438  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1439  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1440  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1441  $sql .= ",address = '".$this->db->escape($this->address)."'";
1442 
1443  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1444  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1445 
1446  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1447  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1448 
1449  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1450  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1451  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1452  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1453  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1454 
1455  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1456 
1457  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1458  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1459 
1460  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1461  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1462  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1463  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1464  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1465  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1466 
1467  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1468  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1469  $sql .= ",status = ".((int) $this->status);
1470 
1471  // Local taxes
1472  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1473  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1474  if ($this->localtax1_assuj == 1) {
1475  if ($this->localtax1_value != '') {
1476  $sql .= ",localtax1_value =".$this->localtax1_value;
1477  } else {
1478  $sql .= ",localtax1_value =0.000";
1479  }
1480  } else {
1481  $sql .= ",localtax1_value =0.000";
1482  }
1483 
1484  if ($this->localtax2_assuj == 1) {
1485  if ($this->localtax2_value != '') {
1486  $sql .= ",localtax2_value =".$this->localtax2_value;
1487  } else {
1488  $sql .= ",localtax2_value =0.000";
1489  }
1490  } else {
1491  $sql .= ",localtax2_value =0.000";
1492  }
1493 
1494  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1495 
1496  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1497 
1498  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1499  if (isset($this->stcomm_id)) {
1500  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1501  }
1502  if (isset($this->typent_id)) {
1503  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1504  }
1505 
1506  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1507 
1508  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1509  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1510  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1511  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1512  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1513  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1514  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1515  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1516 
1517  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1518  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1519  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1520  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1521  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1522  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1523  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1524  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1525  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1526  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1527  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1528  $sql .= ", accountancy_code_buy = '".$this->db->escape($this->accountancy_code_buy)."'";
1529  $sql .= ", accountancy_code_sell= '".$this->db->escape($this->accountancy_code_sell)."'";
1530 
1531  if ($customer) {
1532  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1533  }
1534 
1535  if ($supplier) {
1536  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1537  }
1538  }
1539  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1540  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1541 
1542  //Incoterms
1543  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1544  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1545 
1546  if ($customer) {
1547  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1548  }
1549 
1550  if ($supplier) {
1551  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1552  }
1553  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1554  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1555  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1556  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1557  $sql .= " WHERE rowid = ".(int) $id;
1558 
1559  $resql = $this->db->query($sql);
1560  if ($resql) {
1561  if (is_object($this->oldcopy)) { // If we have information on old values
1562  if ($this->oldcopy->country_id != $this->country_id) {
1563  unset($this->country_code);
1564  unset($this->country);
1565  }
1566  if ($this->oldcopy->state_id != $this->state_id) {
1567  unset($this->state_code);
1568  unset($this->state);
1569  }
1570  } else {
1571  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1572  unset($this->country);
1573  unset($this->state_code);
1574  unset($this->state);
1575  }
1576 
1577  $nbrowsaffected = $this->db->affected_rows($resql);
1578 
1579  if (!$error && $nbrowsaffected) {
1580  // Update information on linked member if it is an update
1581  if (!$nosyncmember && isModEnabled('adherent')) {
1582  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1583 
1584  dol_syslog(get_class($this)."::update update linked member");
1585 
1586  $lmember = new Adherent($this->db);
1587  $result = $lmember->fetch(0, 0, $this->id);
1588 
1589  if ($result > 0) {
1590  $lmember->company = $this->name;
1591  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1592  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1593  $lmember->address = $this->address;
1594  $lmember->zip = $this->zip;
1595  $lmember->town = $this->town;
1596  $lmember->email = $this->email;
1597  $lmember->socialnetworks = $this->socialnetworks;
1598  $lmember->phone = $this->phone;
1599  $lmember->state_id = $this->state_id;
1600  $lmember->country_id = $this->country_id;
1601  $lmember->default_lang = $this->default_lang;
1602 
1603  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1604  if ($result < 0) {
1605  $this->error = $lmember->error;
1606  $this->errors = array_merge($this->errors, $lmember->errors);
1607  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1608  $error++;
1609  }
1610  } elseif ($result < 0) {
1611  $this->error = $lmember->error;
1612  $error++;
1613  }
1614  }
1615  }
1616 
1617  $action = 'update';
1618 
1619  // update accountancy for this entity
1620  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1621  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1622 
1623  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1624  $sql .= " fk_soc";
1625  $sql .= ", entity";
1626  $sql .= ", accountancy_code_customer";
1627  $sql .= ", accountancy_code_supplier";
1628  $sql .= ", accountancy_code_buy";
1629  $sql .= ", accountancy_code_sell";
1630  $sql .= ") VALUES (";
1631  $sql .= $this->id;
1632  $sql .= ", ".$conf->entity;
1633  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1634  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1635  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1636  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1637  $sql .= ")";
1638  $result = $this->db->query($sql);
1639  if (!$result) {
1640  $error++;
1641  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1642  }
1643  }
1644 
1645  // Actions on extra fields
1646  if (!$error) {
1647  $result = $this->insertExtraFields();
1648  if ($result < 0) {
1649  $error++;
1650  }
1651  }
1652  // Actions on extra languages
1653  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1654  $result = $this->insertExtraLanguages();
1655  if ($result < 0) {
1656  $error++;
1657  }
1658  }
1659 
1660  if (!$error && $call_trigger) {
1661  // Call trigger
1662  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1663  if ($result < 0) {
1664  $error++;
1665  }
1666  // End call triggers
1667  }
1668 
1669  if (!$error) {
1670  dol_syslog(get_class($this)."::Update success");
1671  $this->db->commit();
1672  return 1;
1673  } else {
1674  $this->db->rollback();
1675  return -1;
1676  }
1677  } else {
1678  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1679  // Doublon
1680  $this->error = $langs->trans("ErrorDuplicateField");
1681  $result = -1;
1682  } else {
1683  $this->error = $this->db->lasterror();
1684  $result = -2;
1685  }
1686  $this->db->rollback();
1687  return $result;
1688  }
1689  } else {
1690  $this->db->rollback();
1691  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1692  return -3;
1693  }
1694  }
1695 
1713  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1714  {
1715  global $langs;
1716  global $conf;
1717 
1718  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1719  return -1;
1720  }
1721 
1722  $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';
1723  $sql .= ', s.status, s.fk_warehouse';
1724  $sql .= ', s.price_level';
1725  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1726  $sql .= ', s.phone, s.fax, s.email';
1727  $sql .= ', s.socialnetworks';
1728  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1729  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1730  $sql .= ', s.capital, s.tva_intra';
1731  $sql .= ', s.fk_typent as typent_id';
1732  $sql .= ', s.fk_effectif as effectif_id';
1733  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1734  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1735  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1736  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1737  } else {
1738  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1739  }
1740  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1741  $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';
1742  $sql .= ', s.fk_account, s.tva_assuj';
1743  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1744  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1745  $sql .= ', s.fk_shipping_method';
1746  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1747  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1748  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1749  $sql .= ', fj.libelle as forme_juridique';
1750  $sql .= ', e.libelle as effectif';
1751  $sql .= ', c.code as country_code, c.label as country';
1752  $sql .= ', d.code_departement as state_code, d.nom as state';
1753  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1754  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1755  $sql .= ', te.code as typent_code';
1756  $sql .= ', i.libelle as label_incoterms';
1757  if (!isModEnabled('multicompany')) {
1758  $sql .= ', s.remise_client, s.remise_supplier';
1759  } else {
1760  $sql .= ', sr.remise_client, sr2.remise_supplier';
1761  }
1762  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1763  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1764  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1765  }
1766  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1767  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1768  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1769  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1770  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1771  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1772  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1773  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1774  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1775  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1776  if (isModEnabled('multicompany')) {
1777  $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').'))';
1778  $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').'))';
1779  }
1780  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1781  if ($rowid) {
1782  $sql .= ' AND s.rowid = '.((int) $rowid);
1783  }
1784  if ($ref) {
1785  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1786  }
1787  if ($ref_alias) {
1788  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1789  }
1790  if ($ref_ext) {
1791  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1792  }
1793  if ($barcode) {
1794  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1795  }
1796  if ($idprof1) {
1797  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1798  }
1799  if ($idprof2) {
1800  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1801  }
1802  if ($idprof3) {
1803  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1804  }
1805  if ($idprof4) {
1806  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1807  }
1808  if ($idprof5) {
1809  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1810  }
1811  if ($idprof6) {
1812  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1813  }
1814  if ($email) {
1815  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1816  }
1817 
1818  $resql = $this->db->query($sql);
1819  if ($resql) {
1820  $num = $this->db->num_rows($resql);
1821  if ($num > 1) {
1822  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1823  dol_syslog($this->error, LOG_ERR);
1824  $result = -2;
1825  } elseif ($num) { // $num = 1
1826  $obj = $this->db->fetch_object($resql);
1827 
1828  $this->id = $obj->rowid;
1829  $this->entity = $obj->entity;
1830  $this->canvas = $obj->canvas;
1831 
1832  $this->ref = $obj->rowid;
1833  $this->name = $obj->name;
1834  $this->nom = $obj->name; // deprecated
1835  $this->name_alias = $obj->name_alias;
1836  $this->ref_ext = $obj->ref_ext;
1837 
1838  $this->date_creation = $this->db->jdate($obj->date_creation);
1839  $this->date_modification = $this->db->jdate($obj->date_modification);
1840  $this->user_creation = $obj->fk_user_creat;
1841  $this->user_modification = $obj->fk_user_modif;
1842 
1843  $this->address = $obj->address;
1844  $this->zip = $obj->zip;
1845  $this->town = $obj->town;
1846 
1847  $this->country_id = $obj->country_id;
1848  $this->country_code = $obj->country_id ? $obj->country_code : '';
1849  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1850 
1851  $this->state_id = $obj->state_id;
1852  $this->state_code = $obj->state_code;
1853  $this->region_id = $obj->region_id;
1854  $this->region_code = $obj->region_code;
1855  $this->state = ($obj->state != '-' ? $obj->state : '');
1856 
1857  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1858  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1859  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1860  $this->status_prospect_label = $label; // label status prospect
1861  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1862 
1863  $this->email = $obj->email;
1864  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1865 
1866  $this->url = $obj->url;
1867  $this->phone = $obj->phone;
1868  $this->fax = $obj->fax;
1869 
1870  $this->parent = $obj->parent;
1871 
1872  $this->idprof1 = $obj->idprof1;
1873  $this->idprof2 = $obj->idprof2;
1874  $this->idprof3 = $obj->idprof3;
1875  $this->idprof4 = $obj->idprof4;
1876  $this->idprof5 = $obj->idprof5;
1877  $this->idprof6 = $obj->idprof6;
1878 
1879  $this->capital = $obj->capital;
1880 
1881  $this->code_client = $obj->code_client;
1882  $this->code_fournisseur = $obj->code_fournisseur;
1883 
1884  $this->code_compta = $obj->code_compta; // For backward compatibility
1885  $this->code_compta_client = $obj->code_compta;
1886  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1887 
1888  $this->barcode = $obj->barcode;
1889 
1890  $this->tva_assuj = $obj->tva_assuj;
1891  $this->tva_intra = $obj->tva_intra;
1892  $this->status = $obj->status;
1893 
1894  // Local Taxes
1895  $this->localtax1_assuj = $obj->localtax1_assuj;
1896  $this->localtax2_assuj = $obj->localtax2_assuj;
1897 
1898  $this->localtax1_value = $obj->localtax1_value;
1899  $this->localtax2_value = $obj->localtax2_value;
1900 
1901  $this->typent_id = $obj->typent_id;
1902  $this->typent_code = $obj->typent_code;
1903 
1904  $this->effectif_id = $obj->effectif_id;
1905  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1906 
1907  $this->forme_juridique_code = $obj->forme_juridique_code;
1908  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1909 
1910  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1911 
1912  $this->prefix_comm = $obj->prefix_comm;
1913 
1914  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1915  $this->remise_supplier_percent = $obj->remise_supplier;
1916 
1917  $this->mode_reglement_id = $obj->mode_reglement;
1918  $this->cond_reglement_id = $obj->cond_reglement;
1919  $this->deposit_percent = $obj->deposit_percent;
1920  $this->transport_mode_id = $obj->transport_mode;
1921  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1922  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1923  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1924  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1925  $this->fk_account = $obj->fk_account;
1926 
1927  $this->client = $obj->client;
1928  $this->fournisseur = $obj->fournisseur;
1929 
1930  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1931  $this->note_private = $obj->note_private;
1932  $this->note_public = $obj->note_public;
1933  $this->model_pdf = $obj->model_pdf;
1934  $this->modelpdf = $obj->model_pdf; // deprecated
1935  $this->default_lang = $obj->default_lang;
1936  $this->logo = $obj->logo;
1937  $this->logo_squarred = $obj->logo_squarred;
1938 
1939  $this->webservices_url = $obj->webservices_url;
1940  $this->webservices_key = $obj->webservices_key;
1941 
1942  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1943  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1944 
1945  $this->outstanding_limit = $obj->outstanding_limit;
1946  $this->order_min_amount = $obj->order_min_amount;
1947  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1948 
1949  // multiprix
1950  $this->price_level = $obj->price_level;
1951 
1952  // warehouse
1953  $this->fk_warehouse = $obj->fk_warehouse;
1954 
1955  $this->import_key = $obj->import_key;
1956 
1957  //Incoterms
1958  $this->fk_incoterms = $obj->fk_incoterms;
1959  $this->location_incoterms = $obj->location_incoterms;
1960  $this->label_incoterms = $obj->label_incoterms;
1961 
1962  // multicurrency
1963  $this->fk_multicurrency = $obj->fk_multicurrency;
1964  $this->multicurrency_code = $obj->multicurrency_code;
1965 
1966  // pdf
1967  $this->model_pdf = $obj->model_pdf;
1968  $this->last_main_doc = $obj->last_main_doc;
1969 
1970  $result = 1;
1971 
1972  // fetch optionals attributes and labels
1973  $this->fetch_optionals();
1974  } else {
1975  $result = 0;
1976  }
1977 
1978  $this->db->free($resql);
1979  } else {
1980  $this->error = $this->db->lasterror();
1981  $this->errors[] = $this->db->lasterror();
1982  $result = -3;
1983  }
1984 
1985  // Use first price level if level not defined for third party
1986  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1987  $this->price_level = 1;
1988  }
1989 
1990  return $result;
1991  }
1992 
2001  public function delete($id, User $fuser = null, $call_trigger = 1)
2002  {
2003  global $langs, $conf, $user;
2004 
2005  if (empty($fuser)) {
2006  $fuser = $user;
2007  }
2008 
2009  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2010 
2011  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2012 
2013  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2014  $error = 0;
2015 
2016  // Test if child exists
2017  $objectisused = $this->isObjectUsed($id);
2018  if (empty($objectisused)) {
2019  $this->db->begin();
2020 
2021  // User is mandatory for trigger call
2022  if (!$error && $call_trigger) {
2023  // Call trigger
2024  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2025  if ($result < 0) {
2026  $error++;
2027  }
2028  // End call triggers
2029  }
2030 
2031  if (!$error) {
2032  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2033  $static_cat = new Categorie($this->db);
2034  $toute_categs = array();
2035 
2036  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2037  if ($this->client || $this->prospect) {
2038  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2039  }
2040  if ($this->fournisseur) {
2041  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2042  }
2043 
2044  // Remove each "Categorie"
2045  foreach ($toute_categs as $type => $categs_type) {
2046  foreach ($categs_type as $cat) {
2047  $cat->del_type($this, $type);
2048  }
2049  }
2050  }
2051 
2052  if (!$error) {
2053  foreach ($this->childtablesoncascade as $tabletodelete) {
2054  $deleteFromObject = explode(':', $tabletodelete);
2055  if (count($deleteFromObject) >= 2) {
2056  $className = str_replace('@', '', $deleteFromObject[0]);
2057  $filepath = $deleteFromObject[1];
2058  $columnName = $deleteFromObject[2];
2059  if (dol_include_once($filepath)) {
2060  $child_object = new $className($this->db);
2061  $result = $child_object->deleteByParentField($id, $columnName);
2062  if ($result < 0) {
2063  $error++;
2064  $this->errors[] = $child_object->error;
2065  break;
2066  }
2067  } else {
2068  $error++;
2069  $this->errors[] = 'Cannot include child class file '.$filepath;
2070  break;
2071  }
2072  } else {
2073  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2074  $sql .= " WHERE fk_soc = ".((int) $id);
2075  if (!$this->db->query($sql)) {
2076  $error++;
2077  $this->errors[] = $this->db->lasterror();
2078  break;
2079  }
2080  }
2081  }
2082  }
2083 
2084  // Removed extrafields
2085  if (!$error) {
2086  $result = $this->deleteExtraFields();
2087  if ($result < 0) {
2088  $error++;
2089  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2090  }
2091  }
2092 
2093  // Remove links to subsidiaries companies
2094  if (!$error) {
2095  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2096  $sql .= " SET parent = NULL";
2097  $sql .= " WHERE parent = ".((int) $id);
2098  if (!$this->db->query($sql)) {
2099  $error++;
2100  $this->errors[] = $this->db->lasterror();
2101  }
2102  }
2103 
2104  // Remove third party
2105  if (!$error) {
2106  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2107  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2108  $sql .= " WHERE fk_soc = ".((int) $id);
2109  if (!$this->db->query($sql)) {
2110  $error++;
2111  $this->errors[] = $this->db->lasterror();
2112  }
2113  }
2114 
2115  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2116  $sql .= " WHERE rowid = ".((int) $id);
2117  if (!$this->db->query($sql)) {
2118  $error++;
2119  $this->errors[] = $this->db->lasterror();
2120  }
2121  }
2122 
2123  if (!$error) {
2124  $this->db->commit();
2125 
2126  // Delete directory
2127  if (!empty($conf->societe->multidir_output[$entity])) {
2128  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2129  if (dol_is_dir($docdir)) {
2130  dol_delete_dir_recursive($docdir);
2131  }
2132  }
2133 
2134  return 1;
2135  } else {
2136  dol_syslog($this->error, LOG_ERR);
2137  $this->db->rollback();
2138  return -1;
2139  }
2140  } else {
2141  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2142  }
2143  return 0;
2144  }
2145 
2146  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2152  public function set_as_client()
2153  {
2154  global $conf;
2155  // phpcs:enable
2156  if ($this->id) {
2157  $newclient = 1;
2158  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
2159  $newclient = 3; //If prospect, we keep prospect tag
2160  }
2161  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2162  $sql .= " SET client = ".((int) $newclient);
2163  $sql .= " WHERE rowid = ".((int) $this->id);
2164 
2165  $resql = $this->db->query($sql);
2166  if ($resql) {
2167  $this->client = $newclient;
2168  return 1;
2169  } else {
2170  return -1;
2171  }
2172  }
2173  return 0;
2174  }
2175 
2176  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2185  public function set_remise_client($remise, $note, User $user)
2186  {
2187  // phpcs:enable
2188  global $conf, $langs;
2189 
2190  // Parameter cleaning
2191  $note = trim($note);
2192  if (!$note) {
2193  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2194  return -2;
2195  }
2196 
2197  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2198 
2199  if ($this->id) {
2200  $this->db->begin();
2201 
2202  $now = dol_now();
2203 
2204  // Position current discount
2205  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2206  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2207  $sql .= " WHERE rowid = ".((int) $this->id);
2208  $resql = $this->db->query($sql);
2209  if (!$resql) {
2210  $this->db->rollback();
2211  $this->error = $this->db->error();
2212  return -1;
2213  }
2214 
2215  // Writes trace in discount history
2216  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2217  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2218  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2219  $sql .= " '".$this->db->escape($note)."',";
2220  $sql .= " ".((int) $user->id);
2221  $sql .= ")";
2222 
2223  $resql = $this->db->query($sql);
2224  if (!$resql) {
2225  $this->db->rollback();
2226  $this->error = $this->db->lasterror();
2227  return -1;
2228  }
2229 
2230  $this->db->commit();
2231  return 1;
2232  }
2233  }
2234 
2235  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2244  public function set_remise_supplier($remise, $note, User $user)
2245  {
2246  // phpcs:enable
2247  global $conf, $langs;
2248 
2249  // Parameter cleaning
2250  $note = trim($note);
2251  if (!$note) {
2252  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2253  return -2;
2254  }
2255 
2256  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2257 
2258  if ($this->id) {
2259  $this->db->begin();
2260 
2261  $now = dol_now();
2262 
2263  // Position current discount
2264  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2265  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2266  $sql .= " WHERE rowid = ".((int) $this->id);
2267  $resql = $this->db->query($sql);
2268  if (!$resql) {
2269  $this->db->rollback();
2270  $this->error = $this->db->error();
2271  return -1;
2272  }
2273 
2274  // Writes trace in discount history
2275  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2276  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2277  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2278  $sql .= " '".$this->db->escape($note)."',";
2279  $sql .= " ".((int) $user->id);
2280  $sql .= ")";
2281 
2282  $resql = $this->db->query($sql);
2283  if (!$resql) {
2284  $this->db->rollback();
2285  $this->error = $this->db->lasterror();
2286  return -1;
2287  }
2288 
2289  $this->db->commit();
2290  return 1;
2291  }
2292  }
2293 
2294  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2306  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2307  {
2308  // phpcs:enable
2309  global $langs;
2310 
2311  // Clean parameters
2312  $remise = price2num($remise);
2313  $desc = trim($desc);
2314 
2315  // Check parameters
2316  if (!($remise > 0)) {
2317  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2318  return -1;
2319  }
2320  if (!$desc) {
2321  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2322  return -2;
2323  }
2324 
2325  if ($this->id > 0) {
2326  // Clean vat code
2327  $reg = array();
2328  $vat_src_code = '';
2329  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2330  $vat_src_code = $reg[1];
2331  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2332  }
2333 
2334  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2335 
2336  $discount = new DiscountAbsolute($this->db);
2337  $discount->fk_soc = $this->id;
2338 
2339  $discount->discount_type = $discount_type;
2340 
2341  if ($price_base_type == 'TTC') {
2342  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2343  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2344  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2345  } else {
2346  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2347  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2348  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2349  }
2350 
2351  $discount->tva_tx = price2num($vatrate);
2352  $discount->vat_src_code = $vat_src_code;
2353 
2354  $discount->description = $desc;
2355 
2356  $result = $discount->create($user);
2357  if ($result > 0) {
2358  return $result;
2359  } else {
2360  $this->error = $discount->error;
2361  return -3;
2362  }
2363  } else {
2364  return 0;
2365  }
2366  }
2367 
2377  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2378  {
2379  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2380 
2381  $discountstatic = new DiscountAbsolute($this->db);
2382  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2383  if ($result >= 0) {
2384  return $result;
2385  } else {
2386  $this->error = $discountstatic->error;
2387  return -1;
2388  }
2389  }
2390 
2400  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2401  {
2402  global $conf;
2403 
2404  $reparray = array();
2405 
2406  $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";
2407  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2408  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2409  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2410  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2411  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2412  $sql .= " AND ug.entity = ".$conf->entity.")";
2413  $sql .= " OR u.admin = 1)";
2414  } else {
2415  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2416  }
2417 
2418  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2419  if (empty($sortfield) && empty($sortorder)) {
2420  $sortfield = 'u.lastname,u.firstname';
2421  $sortorder = 'ASC,ASC';
2422  }
2423  $sql .= $this->db->order($sortfield, $sortorder);
2424 
2425  $resql = $this->db->query($sql);
2426  if ($resql) {
2427  $num = $this->db->num_rows($resql);
2428  $i = 0;
2429  while ($i < $num) {
2430  $obj = $this->db->fetch_object($resql);
2431 
2432  if (empty($mode)) {
2433  $reparray[$i]['id'] = $obj->rowid;
2434  $reparray[$i]['lastname'] = $obj->lastname;
2435  $reparray[$i]['firstname'] = $obj->firstname;
2436  $reparray[$i]['email'] = $obj->email;
2437  $reparray[$i]['phone'] = $obj->office_phone;
2438  $reparray[$i]['office_phone'] = $obj->office_phone;
2439  $reparray[$i]['office_fax'] = $obj->office_fax;
2440  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2441  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2442  $reparray[$i]['job'] = $obj->job;
2443  $reparray[$i]['statut'] = $obj->status; // deprecated
2444  $reparray[$i]['status'] = $obj->status;
2445  $reparray[$i]['entity'] = $obj->entity;
2446  $reparray[$i]['login'] = $obj->login;
2447  $reparray[$i]['photo'] = $obj->photo;
2448  $reparray[$i]['gender'] = $obj->gender;
2449  } else {
2450  $reparray[] = $obj->rowid;
2451  }
2452  $i++;
2453  }
2454  return $reparray;
2455  } else {
2456  dol_print_error($this->db);
2457  return -1;
2458  }
2459  }
2460 
2468  public function setPriceLevel($price_level, User $user)
2469  {
2470  if ($this->id) {
2471  $now = dol_now();
2472 
2473  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2474  $sql .= " SET price_level = ".((int) $price_level);
2475  $sql .= " WHERE rowid = ".((int) $this->id);
2476 
2477  if (!$this->db->query($sql)) {
2478  dol_print_error($this->db);
2479  return -1;
2480  }
2481 
2482  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2483  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2484  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2485 
2486  if (!$this->db->query($sql)) {
2487  dol_print_error($this->db);
2488  return -1;
2489  }
2490  return 1;
2491  }
2492  return -1;
2493  }
2494 
2495  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2503  public function add_commercial(User $user, $commid)
2504  {
2505  // phpcs:enable
2506  $error = 0;
2507 
2508  if ($this->id > 0 && $commid > 0) {
2509  $this->db->begin();
2510 
2511  if (!$error) {
2512  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2513  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2514 
2515  $resql = $this->db->query($sql);
2516  if (!$resql) {
2517  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2518  $error++;
2519  }
2520  }
2521 
2522  if (!$error) {
2523  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2524  $sql .= " (fk_soc, fk_user)";
2525  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2526 
2527  $resql = $this->db->query($sql);
2528  if (!$resql) {
2529  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2530  $error++;
2531  }
2532  }
2533 
2534  if (!$error) {
2535  $this->context = array('commercial_modified' => $commid);
2536 
2537  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2538  if ($result < 0) {
2539  $error++;
2540  }
2541  }
2542 
2543  if (!$error) {
2544  $this->db->commit();
2545  return 1;
2546  } else {
2547  $this->db->rollback();
2548  return -1;
2549  }
2550  }
2551 
2552  return 0;
2553  }
2554 
2555  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2563  public function del_commercial(User $user, $commid)
2564  {
2565  // phpcs:enable
2566  $error = 0;
2567  $this->context = array('commercial_modified'=>$commid);
2568 
2569  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2570  if ($result < 0) {
2571  $error++;
2572  }
2573 
2574  if ($this->id > 0 && $commid > 0) {
2575  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2576  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2577 
2578  if (!$this->db->query($sql)) {
2579  dol_syslog(get_class($this)."::del_commercial Erreur");
2580  }
2581  }
2582  }
2583 
2584 
2597  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2598  {
2599  global $conf, $langs, $hookmanager;
2600 
2601  if (!empty($conf->dol_no_mouse_hover)) {
2602  $notooltip = 1; // Force disable tooltips
2603  }
2604 
2605  $name = $this->name ? $this->name : $this->nom;
2606 
2607  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2608  if (empty($option) && $this->client > 0) {
2609  $option = 'customer';
2610  }
2611  if (empty($option) && $this->fournisseur > 0) {
2612  $option = 'supplier';
2613  }
2614  }
2615 
2616  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2617  $code = '';
2618  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2619  $code = $this->code_client.' - ';
2620  }
2621 
2622  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2623  $code .= $this->code_fournisseur.' - ';
2624  }
2625 
2626  if ($code) {
2627  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2628  $name = $code.' '.$name;
2629  } else {
2630  $name = $code;
2631  }
2632  }
2633  }
2634 
2635  if (!empty($this->name_alias) && empty($noaliasinname)) {
2636  $name .= ' ('.$this->name_alias.')';
2637  }
2638 
2639  $result = ''; $label = ''; $label2 = '';
2640  $linkstart = ''; $linkend = '';
2641 
2642  if (!empty($this->logo) && class_exists('Form')) {
2643  $label .= '<div class="photointooltip floatright">';
2644  $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.
2645  $label .= '</div>';
2646  //$label .= '<div style="clear: both;"></div>';
2647  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2648  /*$label.= '<div class="photointooltip">';
2649  $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.
2650  $label.= '</div><div style="clear: both;"></div>';*/
2651  }
2652 
2653  $label .= '<div class="centpercent">';
2654 
2655  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2656  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2657  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2658  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2659  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2660  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2661  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2662  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2663  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2664  } elseif ($option == 'agenda') {
2665  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2666  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2667  } elseif ($option == 'project') {
2668  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2669  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2670  } elseif ($option == 'margin') {
2671  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2672  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2673  } elseif ($option == 'contact') {
2674  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2675  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2676  } elseif ($option == 'ban') {
2677  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2678  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2679  }
2680 
2681  // By default
2682  if (empty($linkstart)) {
2683  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2684  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2685  }
2686  if (isset($this->status)) {
2687  $label .= ' '.$this->getLibStatut(5);
2688  }
2689  if (isset($this->client) && isset($this->fournisseur)) {
2690  $label .= ' &nbsp; ';
2691  $label .= $this->getTypeUrl(1);
2692  }
2693 
2694  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2695  if (!empty($this->name_alias)) {
2696  $label .= ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2697  }
2698 
2699  if ($this->email) {
2700  $label .= '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2701  }
2702  if (!empty($this->phone) || !empty($this->fax)) {
2703  $phonelist = array();
2704  if ($this->phone) {
2705  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2706  }
2707  if ($this->fax) {
2708  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2709  }
2710  $label .= '<br>'.implode('&nbsp;', $phonelist);
2711  }
2712 
2713  if (!empty($this->address)) {
2714  $label2 .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2715  } elseif (!empty($this->country_code)) {
2716  $label2 .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2717  }
2718  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2719  $label2 .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2720  }
2721 
2722  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2723  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2724  $label2 .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2725  }
2726  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2727  $label2 .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2728  }
2729  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2730  $label2 .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2731  }
2732  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2733  $label2 .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2734  }
2735  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2736  $label2 .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2737  }
2738  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2739  $label2 .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2740  }
2741  }
2742  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2743  $label2 .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2744  }
2745  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2746  $label2 .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2747  }
2748  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2749  $label2 .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2750  }
2751  if (isModEnabled('accounting') && $this->fournisseur) {
2752  $label2 .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2753  }
2754  $label .= ($label2 ? '<br>'.$label2 : '').'</div>';
2755 
2756  // Add type of canvas
2757  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2758  // Add param to save lastsearch_values or not
2759  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2760  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2761  $add_save_lastsearch_values = 1;
2762  }
2763  if ($add_save_lastsearch_values) {
2764  $linkstart .= '&save_lastsearch_values=1';
2765  }
2766  $linkstart .= '"';
2767 
2768  $linkclose = '';
2769  if (empty($notooltip)) {
2770  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2771  $label = $langs->trans("ShowCompany");
2772  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2773  }
2774  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2775  $linkclose .= ' class="classfortooltip refurl"';
2776  $target_value = array('_self', '_blank', '_parent', '_top');
2777  if (in_array($target, $target_value)) {
2778  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2779  }
2780  }
2781  $linkstart .= $linkclose.'>';
2782  $linkend = '</a>';
2783 
2784  global $user;
2785  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2786  $linkstart = '';
2787  $linkend = '';
2788  }
2789 
2790  $result .= $linkstart;
2791  if ($withpicto) {
2792  $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);
2793  }
2794  if ($withpicto != 2) {
2795  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2796  }
2797  $result .= $linkend;
2798 
2799  global $action;
2800  $hookmanager->initHooks(array('thirdpartydao'));
2801  $parameters = array(
2802  'id'=>$this->id,
2803  'getnomurl' => &$result,
2804  'withpicto '=> $withpicto,
2805  'option'=> $option,
2806  'maxlen'=> $maxlen,
2807  'notooltip'=> $notooltip,
2808  'save_lastsearch_value'=> $save_lastsearch_value
2809  );
2810  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2811  if ($reshook > 0) {
2812  $result = $hookmanager->resPrint;
2813  } else {
2814  $result .= $hookmanager->resPrint;
2815  }
2816 
2817  return $result;
2818  }
2819 
2829  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2830  {
2831  global $conf, $langs;
2832 
2833  $s = '';
2834  if (empty($option) || preg_match('/prospect/', $option)) {
2835  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2836  $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.'>';
2837  }
2838  }
2839  if (empty($option) || preg_match('/customer/', $option)) {
2840  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2841  $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.'>';
2842  }
2843  }
2844  if (empty($option) || preg_match('/supplier/', $option)) {
2845  if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
2846  $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.'>';
2847  }
2848  }
2849  return $s;
2850  }
2851 
2852 
2859  public function getLibStatut($mode = 0)
2860  {
2861  return $this->LibStatut($this->status, $mode);
2862  }
2863 
2864  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2872  public function LibStatut($status, $mode = 0)
2873  {
2874  // phpcs:enable
2875  global $langs;
2876  $langs->load('companies');
2877 
2878  $statusType = 'status4';
2879  if ($status == 0) {
2880  $statusType = 'status6';
2881  }
2882 
2883  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2884  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2885  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2886  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2887  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2888  }
2889 
2890  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2891  }
2892 
2893  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2900  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2901  {
2902  // phpcs:enable
2903  global $langs;
2904 
2905  $contact_emails = $this->contact_property_array('email', 1);
2906  if ($this->email && $addthirdparty) {
2907  if (empty($this->name)) {
2908  $this->name = $this->nom;
2909  }
2910  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2911  }
2912  //var_dump($contact_emails)
2913  return $contact_emails;
2914  }
2915 
2916  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2923  {
2924  // phpcs:enable
2925  global $langs;
2926 
2927  $contact_phone = $this->contact_property_array('mobile');
2928 
2929  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2930  if (empty($this->name)) {
2931  $this->name = $this->nom;
2932  }
2933  // TODO: Tester si tel non deja present dans tableau contact
2934  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2935  }
2936  return $contact_phone;
2937  }
2938 
2939  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2947  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2948  {
2949  // phpcs:enable
2950  global $langs;
2951 
2952  $contact_property = array();
2953 
2954 
2955  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2956  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2957  $sql .= " WHERE fk_soc = ".((int) $this->id);
2958  $sql .= " ORDER BY lastname, firstname";
2959 
2960  $resql = $this->db->query($sql);
2961  if ($resql) {
2962  $nump = $this->db->num_rows($resql);
2963  if ($nump) {
2964  $sepa = "("; $sepb = ")";
2965  if ($mode == 'email') {
2966  //$sepa="&lt;"; $sepb="&gt;";
2967  $sepa = "<"; $sepb = ">";
2968  }
2969  $i = 0;
2970  while ($i < $nump) {
2971  $obj = $this->db->fetch_object($resql);
2972  if ($mode == 'email') {
2973  $property = $obj->email;
2974  } elseif ($mode == 'mobile') {
2975  $property = $obj->phone_mobile;
2976  } else {
2977  $property = $obj->$mode;
2978  }
2979 
2980  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2981  if ($obj->status == 1 || empty($hidedisabled)) {
2982  if (empty($property)) {
2983  if ($mode == 'email') {
2984  $property = $langs->transnoentitiesnoconv("NoEMail");
2985  } elseif ($mode == 'mobile') {
2986  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2987  }
2988  }
2989 
2990  if (!empty($obj->poste)) {
2991  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2992  } else {
2993  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2994  }
2995  }
2996  $i++;
2997  }
2998  }
2999  } else {
3000  dol_print_error($this->db);
3001  }
3002  return $contact_property;
3003  }
3004 
3005 
3006  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3012  public function contact_array()
3013  {
3014  // phpcs:enable
3015  $contacts = array();
3016 
3017  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3018  $resql = $this->db->query($sql);
3019  if ($resql) {
3020  $nump = $this->db->num_rows($resql);
3021  if ($nump) {
3022  $i = 0;
3023  while ($i < $nump) {
3024  $obj = $this->db->fetch_object($resql);
3025  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3026  $i++;
3027  }
3028  }
3029  } else {
3030  dol_print_error($this->db);
3031  }
3032  return $contacts;
3033  }
3034 
3035  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3041  public function contact_array_objects()
3042  {
3043  // phpcs:enable
3044  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3045  $contacts = array();
3046 
3047  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3048  $resql = $this->db->query($sql);
3049  if ($resql) {
3050  $nump = $this->db->num_rows($resql);
3051  if ($nump) {
3052  $i = 0;
3053  while ($i < $nump) {
3054  $obj = $this->db->fetch_object($resql);
3055  $contact = new Contact($this->db);
3056  $contact->fetch($obj->rowid);
3057  $contacts[] = $contact;
3058  $i++;
3059  }
3060  }
3061  } else {
3062  dol_print_error($this->db);
3063  }
3064  return $contacts;
3065  }
3066 
3067  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3075  public function contact_get_property($rowid, $mode)
3076  {
3077  // phpcs:enable
3078  $contact_property = '';
3079 
3080  if (empty($rowid)) {
3081  return '';
3082  }
3083 
3084  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3085  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3086  $sql .= " WHERE rowid = ".((int) $rowid);
3087 
3088  $resql = $this->db->query($sql);
3089  if ($resql) {
3090  $nump = $this->db->num_rows($resql);
3091 
3092  if ($nump) {
3093  $obj = $this->db->fetch_object($resql);
3094 
3095  if ($mode == 'email') {
3096  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3097  } elseif ($mode == 'mobile') {
3098  $contact_property = $obj->phone_mobile;
3099  }
3100  }
3101  return $contact_property;
3102  } else {
3103  dol_print_error($this->db);
3104  }
3105  }
3106 
3107 
3108  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3115  public function display_rib($mode = 'label')
3116  {
3117  // phpcs:enable
3118  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3119 
3120  $bac = new CompanyBankAccount($this->db);
3121  $bac->fetch(0, $this->id);
3122 
3123  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3124  if ($mode == 'label') {
3125  return $bac->getRibLabel(true);
3126  } elseif ($mode == 'rum') {
3127  if (empty($bac->rum)) {
3128  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3129  $prelevement = new BonPrelevement($this->db);
3130  $bac->fetch_thirdparty();
3131  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3132  }
3133  return $bac->rum;
3134  } elseif ($mode == 'format') {
3135  return $bac->frstrecur;
3136  } else {
3137  return 'BadParameterToFunctionDisplayRib';
3138  }
3139  } else {
3140  return '';
3141  }
3142  }
3143 
3144  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3150  public function get_all_rib()
3151  {
3152  // phpcs:enable
3153  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3154  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3155  $result = $this->db->query($sql);
3156  if (!$result) {
3157  $this->error++;
3158  $this->errors[] = $this->db->lasterror;
3159  return 0;
3160  } else {
3161  $num_rows = $this->db->num_rows($result);
3162  $rib_array = array();
3163  if ($num_rows) {
3164  while ($obj = $this->db->fetch_object($result)) {
3165  $rib = new CompanyBankAccount($this->db);
3166  $rib->fetch($obj->rowid);
3167  $rib_array[] = $rib;
3168  }
3169  }
3170  return $rib_array;
3171  }
3172  }
3173 
3174  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3183  public function get_codeclient($objsoc = 0, $type = 0)
3184  {
3185  // phpcs:enable
3186  global $conf;
3187  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3188  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3189 
3190  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3191  foreach ($dirsociete as $dirroot) {
3192  $res = dol_include_once($dirroot.$module.'.php');
3193  if ($res) {
3194  break;
3195  }
3196  }
3197  $mod = new $module();
3198 
3199  $this->code_client = $mod->getNextValue($objsoc, $type);
3200  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3201 
3202  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3203  }
3204  }
3205 
3206  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3215  public function get_codefournisseur($objsoc = 0, $type = 1)
3216  {
3217  // phpcs:enable
3218  global $conf;
3219  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3220  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3221 
3222  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3223  foreach ($dirsociete as $dirroot) {
3224  $res = dol_include_once($dirroot.$module.'.php');
3225  if ($res) {
3226  break;
3227  }
3228  }
3229  $mod = new $module();
3230 
3231  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3232 
3233  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3234  }
3235  }
3236 
3237  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3244  public function codeclient_modifiable()
3245  {
3246  // phpcs:enable
3247  global $conf;
3248  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3249  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3250 
3251  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3252  foreach ($dirsociete as $dirroot) {
3253  $res = dol_include_once($dirroot.$module.'.php');
3254  if ($res) {
3255  break;
3256  }
3257  }
3258 
3259  $mod = new $module();
3260 
3261  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3262  if ($mod->code_modifiable_null && !$this->code_client) {
3263  return 1;
3264  }
3265  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3266  return 1;
3267  }
3268  if ($mod->code_modifiable) {
3269  return 1; // A mettre en dernier
3270  }
3271  return 0;
3272  } else {
3273  return 0;
3274  }
3275  }
3276 
3277 
3278  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3284  public function codefournisseur_modifiable()
3285  {
3286  // phpcs:enable
3287  global $conf;
3288  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3289  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3290 
3291  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3292  foreach ($dirsociete as $dirroot) {
3293  $res = dol_include_once($dirroot.$module.'.php');
3294  if ($res) {
3295  break;
3296  }
3297  }
3298 
3299  $mod = new $module();
3300 
3301  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3302  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3303  return 1;
3304  }
3305  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3306  return 1;
3307  }
3308  if ($mod->code_modifiable) {
3309  return 1; // A mettre en dernier
3310  }
3311  return 0;
3312  } else {
3313  return 0;
3314  }
3315  }
3316 
3317 
3318  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3330  public function check_codeclient()
3331  {
3332  // phpcs:enable
3333  global $conf;
3334  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3335  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3336 
3337  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3338  foreach ($dirsociete as $dirroot) {
3339  $res = dol_include_once($dirroot.$module.'.php');
3340  if ($res) {
3341  break;
3342  }
3343  }
3344 
3345  $mod = new $module();
3346 
3347  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3348  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3349  if ($result) { // If error
3350  $this->error = $mod->error;
3351  $this->errors = $mod->errors;
3352  }
3353  return $result;
3354  } else {
3355  return 0;
3356  }
3357  }
3358 
3359  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3371  public function check_codefournisseur()
3372  {
3373  // phpcs:enable
3374  global $conf;
3375  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3376  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3377 
3378  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3379  foreach ($dirsociete as $dirroot) {
3380  $res = dol_include_once($dirroot.$module.'.php');
3381  if ($res) {
3382  break;
3383  }
3384  }
3385 
3386  $mod = new $module();
3387 
3388  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3389  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3390  if ($result) { // If error
3391  $this->error = $mod->error;
3392  $this->errors = $mod->errors;
3393  }
3394  return $result;
3395  } else {
3396  return 0;
3397  }
3398  }
3399 
3400  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3409  public function get_codecompta($type)
3410  {
3411  // phpcs:enable
3412  global $conf;
3413 
3414  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3415  $res = false;
3416  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3417  foreach ($dirsociete as $dirroot) {
3418  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3419  if ($res) {
3420  break;
3421  }
3422  }
3423 
3424  if ($res) {
3425  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3426  $mod = new $classname;
3427 
3428  // Set code count in $mod->code
3429  $result = $mod->get_code($this->db, $this, $type);
3430 
3431  if ($type == 'customer') {
3432  $this->code_compta_client = $mod->code;
3433  $this->code_compta = $this->code_compta_client; // For backward compatibility
3434  } elseif ($type == 'supplier') {
3435  $this->code_compta_fournisseur = $mod->code;
3436  }
3437 
3438  return $result;
3439  } else {
3440  $this->error = 'ErrorAccountancyCodeNotDefined';
3441  return -1;
3442  }
3443  } else {
3444  if ($type == 'customer') {
3445  $this->code_compta_client = '';
3446  $this->code_compta = '';
3447  } elseif ($type == 'supplier') {
3448  $this->code_compta_fournisseur = '';
3449  }
3450 
3451  return 0;
3452  }
3453  }
3454 
3461  public function setParent($id)
3462  {
3463  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3464 
3465  if ($this->id) {
3466  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3467  if ($id > 0) {
3468  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3469  if ($sameparent < 0) {
3470  return -1;
3471  }
3472  if ($sameparent == 1) {
3473  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3474  return -1;
3475  }
3476  }
3477 
3478  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3479 
3480  $resql = $this->db->query($sql);
3481  if ($resql) {
3482  $this->parent = $id;
3483  return 1;
3484  } else {
3485  return -1;
3486  }
3487  } else {
3488  return -1;
3489  }
3490  }
3491 
3500  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3501  {
3502  if ($counter > 100) {
3503  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3504  }
3505 
3506  $sql = 'SELECT s.parent';
3507  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3508  $sql .= ' WHERE rowid = '.((int) $idparent);
3509  $resql = $this->db->query($sql);
3510  if ($resql) {
3511  $obj = $this->db->fetch_object($resql);
3512 
3513  if ($obj->parent == '') {
3514  return 0;
3515  } elseif ($obj->parent == $idchild) {
3516  return 1;
3517  } else {
3518  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3519  }
3520  return $sameparent;
3521  } else {
3522  return -1;
3523  }
3524  }
3525 
3533  public function getParentsForCompany($company_id, $parents = [])
3534  {
3535  global $langs;
3536 
3537  if ($company_id > 0) {
3538  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3539  $resql = $this->db->query($sql);
3540  if ($resql) {
3541  if ($obj = $this->db->fetch_object($resql)) {
3542  $parent = $obj->parent;
3543  if ($parent > 0 && !in_array($parent, $parents)) {
3544  $parents[] = $parent;
3545  return $this->getParentsForCompany($parent, $parents);
3546  } else {
3547  return $parents;
3548  }
3549  }
3550  $this->db->free($resql);
3551  } else {
3552  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3553  }
3554  }
3555  }
3556 
3557  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3564  public function id_prof_verifiable($idprof)
3565  {
3566  // phpcs:enable
3567  global $conf;
3568 
3569  switch ($idprof) {
3570  case 1:
3571  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3572  break;
3573  case 2:
3574  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3575  break;
3576  case 3:
3577  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3578  break;
3579  case 4:
3580  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3581  break;
3582  case 5:
3583  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3584  break;
3585  case 6:
3586  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3587  break;
3588  default:
3589  $ret = false;
3590  }
3591 
3592  return $ret;
3593  }
3594 
3595  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3604  public function id_prof_exists($idprof, $value, $socid = 0)
3605  {
3606  // phpcs:enable
3607  $field = $idprof;
3608 
3609  switch ($idprof) { // For backward compatibility
3610  case '1':
3611  case 'idprof1':
3612  $field = "siren";
3613  break;
3614  case '2':
3615  case 'idprof2':
3616  $field = "siret";
3617  break;
3618  case '3':
3619  case 'idprof3':
3620  $field = "ape";
3621  break;
3622  case '4':
3623  case 'idprof4':
3624  $field = "idprof4";
3625  break;
3626  case '5':
3627  $field = "idprof5";
3628  break;
3629  case '6':
3630  $field = "idprof6";
3631  break;
3632  }
3633 
3634  //Verify duplicate entries
3635  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3636  if ($socid) {
3637  $sql .= " AND rowid <> ".$socid;
3638  }
3639  $resql = $this->db->query($sql);
3640  if ($resql) {
3641  $obj = $this->db->fetch_object($resql);
3642  $count = $obj->nb;
3643  } else {
3644  $count = 0;
3645  print $this->db->error();
3646  }
3647  $this->db->free($resql);
3648 
3649  if ($count > 0) {
3650  return true;
3651  } else {
3652  return false;
3653  }
3654  }
3655 
3656  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3665  public function id_prof_check($idprof, $soc)
3666  {
3667  // phpcs:enable
3668  global $conf;
3669 
3670  $ok = 1;
3671 
3672  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3673  return 1;
3674  }
3675 
3676  // Check SIREN if country FR
3677  if ($idprof == 1 && $soc->country_code == 'FR') {
3678  $chaine = trim($this->idprof1);
3679  $chaine = preg_replace('/(\s)/', '', $chaine);
3680 
3681  if (!is_numeric($chaine)) {
3682  return -1;
3683  }
3684  if (dol_strlen($chaine) != 9) {
3685  return -1;
3686  }
3687 
3688  // on prend chaque chiffre un par un
3689  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3690  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3691  // on ajoute cette valeur à la somme totale
3692  $sum = 0;
3693  for ($index = 0; $index < 9; $index++) {
3694  $number = (int) $chaine[$index];
3695  if (($index % 2) != 0) {
3696  if (($number *= 2) > 9) {
3697  $number -= 9;
3698  }
3699  }
3700  $sum += $number;
3701  }
3702 
3703  // le numéro est valide si la somme des chiffres est multiple de 10
3704  if (($sum % 10) != 0) {
3705  return -1;
3706  }
3707  }
3708 
3709  // Verifie SIRET si pays FR
3710  if ($idprof == 2 && $soc->country_code == 'FR') {
3711  $chaine = trim($this->idprof2);
3712  $chaine = preg_replace('/(\s)/', '', $chaine);
3713 
3714  if (!is_numeric($chaine)) {
3715  return -1;
3716  }
3717  if (dol_strlen($chaine) != 14) {
3718  return -1;
3719  }
3720 
3721  // on prend chaque chiffre un par un
3722  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3723  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3724  // on ajoute cette valeur à la somme totale
3725  $sum = 0;
3726  for ($index = 0; $index < 14; $index++) {
3727  $number = (int) $chaine[$index];
3728  if (($index % 2) == 0) {
3729  if (($number *= 2) > 9) {
3730  $number -= 9;
3731  }
3732  }
3733  $sum += $number;
3734  }
3735 
3736  // le numéro est valide si la somme des chiffres est multiple de 10
3737  if (($sum % 10) != 0) {
3738  return -1;
3739  }
3740  }
3741 
3742  //Verify CIF/NIF/NIE if pays ES
3743  //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
3744  if ($idprof == 1 && $soc->country_code == 'ES') {
3745  $string = trim($this->idprof1);
3746  $string = preg_replace('/(\s)/', '', $string);
3747  $string = strtoupper($string);
3748 
3749  //Check format
3750  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)) {
3751  return 0;
3752  }
3753 
3754  $num = array();
3755  for ($i = 0; $i < 9; $i++) {
3756  $num[$i] = substr($string, $i, 1);
3757  }
3758 
3759  //Check NIF
3760  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3761  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3762  return 1;
3763  } else {
3764  return -1;
3765  }
3766  }
3767 
3768  //algorithm checking type code CIF
3769  $sum = $num[2] + $num[4] + $num[6];
3770  for ($i = 1; $i < 8; $i += 2) {
3771  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3772  }
3773  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3774 
3775  //Chek special NIF
3776  if (preg_match('/^[KLM]{1}/', $string)) {
3777  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3778  return 1;
3779  } else {
3780  return -1;
3781  }
3782  }
3783 
3784  //Check CIF
3785  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3786  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3787  return 2;
3788  } else {
3789  return -2;
3790  }
3791  }
3792 
3793  //Check NIE T
3794  if (preg_match('/^[T]{1}/', $string)) {
3795  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3796  return 3;
3797  } else {
3798  return -3;
3799  }
3800  }
3801 
3802  //Check NIE XYZ
3803  if (preg_match('/^[XYZ]{1}/', $string)) {
3804  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3805  return 3;
3806  } else {
3807  return -3;
3808  }
3809  }
3810 
3811  //Can not be verified
3812  return -4;
3813  }
3814 
3815  //Verify NIF if country is PT
3816  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3817  if ($idprof == 1 && $soc->country_code == 'PT') {
3818  $string = trim($this->idprof1);
3819  $string = preg_replace('/(\s)/', '', $string);
3820 
3821  //Check NIF
3822  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3823  return 1;
3824  } else {
3825  return -1;
3826  }
3827  }
3828 
3829  //Verify NIF if country is DZ
3830  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3831  if ($idprof == 1 && $soc->country_code == 'DZ') {
3832  $string = trim($this->idprof1);
3833  $string = preg_replace('/(\s)/', '', $string);
3834 
3835  //Check NIF
3836  if (preg_match('/(^[0-9]{15}$)/', $string)) {
3837  return 1;
3838  } else {
3839  return -1;
3840  }
3841  }
3842 
3843  return $ok;
3844  }
3845 
3846  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3855  public function id_prof_url($idprof, $thirdparty)
3856  {
3857  // phpcs:enable
3858  global $conf, $langs, $hookmanager;
3859 
3860  $url = '';
3861  $action = '';
3862 
3863  $hookmanager->initHooks(array('idprofurl'));
3864  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3865  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3866  if (empty($reshook)) {
3867  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3868  return '';
3869  }
3870 
3871  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3872  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3873  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3874  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3875  }
3876  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3877  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3878  }
3879  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3880  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3881  }
3882  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3883  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3884  }
3885  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3886  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3887  }
3888  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3889  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3890  }
3891 
3892  if ($url) {
3893  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3894  }
3895  } else {
3896  return $hookmanager->resPrint;
3897  }
3898 
3899  return '';
3900  }
3901 
3902  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3908  public function has_projects()
3909  {
3910  // phpcs:enable
3911  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3912  $resql = $this->db->query($sql);
3913  if ($resql) {
3914  $obj = $this->db->fetch_object($resql);
3915  $count = $obj->numproj;
3916  } else {
3917  $count = 0;
3918  print $this->db->error();
3919  }
3920  $this->db->free($resql);
3921  return ($count > 0);
3922  }
3923 
3924 
3931  public function info($id)
3932  {
3933  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
3934  $sql .= " fk_user_creat, fk_user_modif";
3935  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3936  $sql .= " WHERE s.rowid = ".((int) $id);
3937 
3938  $result = $this->db->query($sql);
3939  if ($result) {
3940  if ($this->db->num_rows($result)) {
3941  $obj = $this->db->fetch_object($result);
3942 
3943  $this->id = $obj->rowid;
3944 
3945  $this->user_creation_id = $obj->fk_user_creat;
3946  $this->user_modification_id = $obj->fk_user_modif;
3947  $this->date_creation = $this->db->jdate($obj->datec);
3948  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
3949 
3950  $this->ref = $obj->name;
3951  }
3952 
3953  $this->db->free($result);
3954  } else {
3955  dol_print_error($this->db);
3956  }
3957  }
3958 
3964  public function isACompany()
3965  {
3966  global $conf;
3967 
3968  // Define if third party is treated as company (or not) when nature is unknown
3969  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3970  if (!empty($this->tva_intra)) {
3971  $isacompany = 1;
3972  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3973  $isacompany = 1;
3974  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3975  // TODO Add a field is_a_company into dictionary
3976  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3977  $isacompany = 0;
3978  } else {
3979  $isacompany = 1;
3980  }
3981  }
3982 
3983  return $isacompany;
3984  }
3985 
3991  public function isInEEC()
3992  {
3993  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3994  return isInEEC($this);
3995  }
3996 
3997  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4003  public function LoadSupplierCateg()
4004  {
4005  // phpcs:enable
4006  $this->SupplierCategories = array();
4007  $sql = "SELECT rowid, label";
4008  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4009  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4010 
4011  $resql = $this->db->query($sql);
4012  if ($resql) {
4013  while ($obj = $this->db->fetch_object($resql)) {
4014  $this->SupplierCategories[$obj->rowid] = $obj->label;
4015  }
4016  return 0;
4017  } else {
4018  return -1;
4019  }
4020  }
4021 
4022  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4029  public function AddFournisseurInCategory($categorie_id)
4030  {
4031  // phpcs:enable
4032  if ($categorie_id > 0 && $this->id > 0) {
4033  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4034  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4035 
4036  if ($resql = $this->db->query($sql)) {
4037  return 0;
4038  }
4039  } else {
4040  return 0;
4041  }
4042  return -1;
4043  }
4044 
4050  public function getNbOfEMailings()
4051  {
4052  $sql = "SELECT count(mc.email) as nb";
4053  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4054  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4055  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4056 
4057  $resql = $this->db->query($sql);
4058  if ($resql) {
4059  $obj = $this->db->fetch_object($resql);
4060  $nb = $obj->nb;
4061 
4062  $this->db->free($resql);
4063  return $nb;
4064  } else {
4065  $this->error = $this->db->error();
4066  return -1;
4067  }
4068  }
4069 
4076  public function setNoEmail($no_email)
4077  {
4078  $error = 0;
4079 
4080  // Update mass emailing flag into table mailing_unsubscribe
4081  if ($this->email) {
4082  $this->db->begin();
4083 
4084  if ($no_email) {
4085  $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)."'";
4086  $resql = $this->db->query($sql);
4087  if ($resql) {
4088  $obj = $this->db->fetch_object($resql);
4089  $noemail = $obj->nb;
4090  if (empty($noemail)) {
4091  $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())."')";
4092  $resql = $this->db->query($sql);
4093  if (!$resql) {
4094  $error++;
4095  $this->error = $this->db->lasterror();
4096  $this->errors[] = $this->error;
4097  }
4098  }
4099  } else {
4100  $error++;
4101  $this->error = $this->db->lasterror();
4102  $this->errors[] = $this->error;
4103  }
4104  } else {
4105  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4106  $resql = $this->db->query($sql);
4107  if (!$resql) {
4108  $error++;
4109  $this->error = $this->db->lasterror();
4110  $this->errors[] = $this->error;
4111  }
4112  }
4113 
4114  if (empty($error)) {
4115  $this->no_email = $no_email;
4116  $this->db->commit();
4117  return 1;
4118  } else {
4119  $this->db->rollback();
4120  return $error * -1;
4121  }
4122  }
4123 
4124  return 0;
4125  }
4126 
4133  public function getNoEmail()
4134  {
4135  if ($this->email) {
4136  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4137  $resql = $this->db->query($sql);
4138  if ($resql) {
4139  $obj = $this->db->fetch_object($resql);
4140  $this->no_email = $obj->nb;
4141  return 1;
4142  } else {
4143  $this->error = $this->db->lasterror();
4144  $this->errors[] = $this->error;
4145  return -1;
4146  }
4147  }
4148  return 0;
4149  }
4150 
4151  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4161  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4162  {
4163  // phpcs:enable
4164  global $conf, $user, $langs;
4165 
4166  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4167  $fullname = $member->getFullName($langs);
4168 
4169  if ($member->morphy == 'mor') {
4170  if (empty($socname)) {
4171  $socname = $member->company? $member->company : $member->societe;
4172  }
4173  if (!empty($fullname) && empty($socalias)) {
4174  $socalias = $fullname;
4175  }
4176  } elseif (empty($socname) && $member->morphy == 'phy') {
4177  if (empty($socname)) {
4178  $socname = $fullname;
4179  }
4180  if (!empty($member->company) && empty($socalias)) {
4181  $socalias = $member->company;
4182  }
4183  }
4184 
4185  $name = $socname;
4186  $alias = $socalias ? $socalias : '';
4187 
4188  // Positionne parametres
4189  $this->nom = $name; // TODO deprecated
4190  $this->name = $name;
4191  $this->name_alias = $alias;
4192  $this->address = $member->address;
4193  $this->zip = $member->zip;
4194  $this->town = $member->town;
4195  $this->country_code = $member->country_code;
4196  $this->country_id = $member->country_id;
4197  $this->phone = $member->phone; // Prof phone
4198  $this->email = $member->email;
4199  $this->socialnetworks = $member->socialnetworks;
4200  $this->entity = $member->entity;
4201 
4202  $this->client = 1; // A member is a customer by default
4203  $this->code_client = ($customercode ? $customercode : -1);
4204  $this->code_fournisseur = -1;
4205  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4206  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4207 
4208  $this->db->begin();
4209 
4210  // Cree et positionne $this->id
4211  $result = $this->create($user);
4212 
4213  if ($result >= 0) {
4214  // Auto-create contact on thirdparty creation
4215  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4216  // Fill fields needed by contact
4217  $this->name_bis = $member->lastname;
4218  $this->firstname = $member->firstname;
4219  $this->civility_id = $member->civility_id;
4220 
4221  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4222  $result = $this->create_individual($user);
4223 
4224  if ($result < 0) {
4225  setEventMessages($this->error, $this->errors, 'errors');
4226  $this->db->rollback();
4227  return -1;
4228  }
4229  }
4230 
4231  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4232  $sql .= " SET fk_soc = ".((int) $this->id);
4233  $sql .= " WHERE rowid = ".((int) $member->id);
4234 
4235  $resql = $this->db->query($sql);
4236  if ($resql) {
4237  $this->db->commit();
4238  return $this->id;
4239  } else {
4240  $this->error = $this->db->error();
4241 
4242  $this->db->rollback();
4243  return -1;
4244  }
4245  } else {
4246  // $this->error deja positionne
4247  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4248 
4249  $this->db->rollback();
4250  return $result;
4251  }
4252  }
4253 
4260  public function setMysoc(Conf $conf)
4261  {
4262  global $langs;
4263 
4264  $this->id = 0;
4265  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
4266  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
4267  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
4268  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
4269  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
4270  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
4271 
4272  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
4273 
4274  $this->nom = $this->name; // deprecated
4275 
4276  // We define country_id, country_code and country
4277  $country_id = $country_code = $country_label = '';
4278  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4279  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4280  $country_id = $tmp[0];
4281  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4282  $country_code = $tmp[1];
4283  $country_label = $tmp[2];
4284  } else // For backward compatibility
4285  {
4286  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4287  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4288  $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
4289  $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
4290  }
4291  }
4292  $this->country_id = $country_id;
4293  $this->country_code = $country_code;
4294  $this->country = $country_label;
4295  if (is_object($langs)) {
4296  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4297  }
4298 
4299  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4300  // We define state_id, state_code and state
4301  $state_id = 0; $state_code = $state_label = '';
4302  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4303  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4304  $state_id = $tmp[0];
4305  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4306  $state_code = $tmp[1];
4307  $state_label = $tmp[2];
4308  } else { // For backward compatibility
4309  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);
4310  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4311  $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
4312  $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
4313  }
4314  }
4315  $this->state_id = $state_id;
4316  $this->state_code = $state_code;
4317  $this->state = $state_label;
4318  if (is_object($langs)) {
4319  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4320  }
4321 
4322  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
4323  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
4324  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
4325 
4326  // Social networks
4327  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
4328  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
4329  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
4330  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
4331  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
4332  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
4333  $this->socialnetworks = array();
4334  if (!empty($this->facebook_url)) {
4335  $this->socialnetworks['facebook'] = $this->facebook_url;
4336  }
4337  if (!empty($this->twitter_url)) {
4338  $this->socialnetworks['twitter'] = $this->twitter_url;
4339  }
4340  if (!empty($this->linkedin_url)) {
4341  $this->socialnetworks['linkedin'] = $this->linkedin_url;
4342  }
4343  if (!empty($this->instagram_url)) {
4344  $this->socialnetworks['instagram'] = $this->instagram_url;
4345  }
4346  if (!empty($this->youtube_url)) {
4347  $this->socialnetworks['youtube'] = $this->youtube_url;
4348  }
4349  if (!empty($this->github_url)) {
4350  $this->socialnetworks['github'] = $this->github_url;
4351  }
4352 
4353  // Id prof generiques
4354  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
4355  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
4356  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
4357  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
4358  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
4359  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
4360  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
4361  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
4362  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
4363  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
4364  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
4365  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
4366  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
4367  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
4368  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
4369  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
4370  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
4371  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
4372 
4373  // Define if company use vat or not
4374  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4375 
4376  // Define if company use local taxes
4377  $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);
4378  $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);
4379  }
4380 
4388  public function initAsSpecimen()
4389  {
4390  $now = dol_now();
4391 
4392  // Initialize parameters
4393  $this->id = 0;
4394  $this->entity = 1;
4395  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4396  $this->nom = $this->name; // For backward compatibility
4397  $this->ref_ext = 'Ref ext';
4398  $this->specimen = 1;
4399  $this->address = '21 jump street';
4400  $this->zip = '99999';
4401  $this->town = 'MyTown';
4402  $this->state_id = 1;
4403  $this->state_code = 'AA';
4404  $this->state = 'MyState';
4405  $this->country_id = 1;
4406  $this->country_code = 'FR';
4407  $this->email = 'specimen@specimen.com';
4408  $this->socialnetworks = array(
4409  'skype' => 'tom.hanson',
4410  'twitter' => 'tomhanson',
4411  'facebook' => 'tomhanson',
4412  'linkedin' => 'tomhanson',
4413  );
4414  $this->url = 'http://www.specimen.com';
4415 
4416  $this->phone = '0909090901';
4417  $this->fax = '0909090909';
4418 
4419  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4420  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4421  $this->capital = 10000;
4422  $this->client = 1;
4423  $this->prospect = 1;
4424  $this->fournisseur = 1;
4425  $this->tva_assuj = 1;
4426  $this->tva_intra = 'EU1234567';
4427  $this->note_public = 'This is a comment (public)';
4428  $this->note_private = 'This is a comment (private)';
4429 
4430  $this->idprof1 = 'idprof1';
4431  $this->idprof2 = 'idprof2';
4432  $this->idprof3 = 'idprof3';
4433  $this->idprof4 = 'idprof4';
4434  $this->idprof5 = 'idprof5';
4435  $this->idprof6 = 'idprof6';
4436  return 1;
4437  }
4438 
4445  public function useLocalTax($localTaxNum = 0)
4446  {
4447  $sql = "SELECT t.localtax1, t.localtax2";
4448  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4449  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4450  $sql .= " AND t.active = 1";
4451  if (empty($localTaxNum)) {
4452  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4453  } elseif ($localTaxNum == 1) {
4454  $sql .= " AND t.localtax1_type <> '0'";
4455  } elseif ($localTaxNum == 2) {
4456  $sql .= " AND t.localtax2_type <> '0'";
4457  }
4458 
4459  $resql = $this->db->query($sql);
4460  if ($resql) {
4461  return ($this->db->num_rows($resql) > 0);
4462  } else {
4463  return false;
4464  }
4465  }
4466 
4472  public function useNPR()
4473  {
4474  $sql = "SELECT t.rowid";
4475  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4476  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4477  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4478 
4479  dol_syslog("useNPR", LOG_DEBUG);
4480  $resql = $this->db->query($sql);
4481  if ($resql) {
4482  return ($this->db->num_rows($resql) > 0);
4483  } else {
4484  return false;
4485  }
4486  }
4487 
4494  public function useRevenueStamp()
4495  {
4496  $sql = "SELECT COUNT(*) as nb";
4497  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4498  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4499  $sql .= " AND r.active = 1";
4500 
4501  dol_syslog("useRevenueStamp", LOG_DEBUG);
4502  $resql = $this->db->query($sql);
4503  if ($resql) {
4504  $obj = $this->db->fetch_object($resql);
4505  return (($obj->nb > 0) ?true:false);
4506  } else {
4507  $this->error = $this->db->lasterror();
4508  return false;
4509  }
4510  }
4511 
4517  public function getLibProspLevel()
4518  {
4519  return $this->LibProspLevel($this->fk_prospectlevel);
4520  }
4521 
4522  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4529  public function LibProspLevel($fk_prospectlevel)
4530  {
4531  // phpcs:enable
4532  global $langs;
4533 
4534  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4535  // If lib not found in language file, we get label from cache/databse
4536  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4537  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4538  }
4539  return $lib;
4540  }
4541 
4549  public function getLibProspCommStatut($mode = 0, $label = '')
4550  {
4551  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4552  }
4553 
4554  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4568  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4569  {
4570  // phpcs:enable
4571  global $langs;
4572  $langs->load('customers');
4573 
4574  if ($mode == 2) {
4575  if ($status == '-1' || $status == 'ST_NO') {
4576  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4577  } elseif ($status == '0' || $status == 'ST_NEVER') {
4578  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4579  } elseif ($status == '1' || $status == 'ST_TODO') {
4580  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4581  } elseif ($status == '2' || $status == 'ST_PEND') {
4582  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4583  } elseif ($status == '3' || $status == 'ST_DONE') {
4584  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4585  } else {
4586  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);
4587  }
4588  } elseif ($mode == 3) {
4589  if ($status == '-1' || $status == 'ST_NO') {
4590  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4591  } elseif ($status == '0' || $status == 'ST_NEVER') {
4592  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4593  } elseif ($status == '1' || $status == 'ST_TODO') {
4594  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4595  } elseif ($status == '2' || $status == 'ST_PEND') {
4596  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4597  } elseif ($status == '3' || $status == 'ST_DONE') {
4598  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4599  } else {
4600  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4601  }
4602  } elseif ($mode == 4) {
4603  if ($status == '-1' || $status == 'ST_NO') {
4604  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4605  } elseif ($status == '0' || $status == 'ST_NEVER') {
4606  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4607  } elseif ($status == '1' || $status == 'ST_TODO') {
4608  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4609  } elseif ($status == '2' || $status == 'ST_PEND') {
4610  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4611  } elseif ($status == '3' || $status == 'ST_DONE') {
4612  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4613  } else {
4614  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);
4615  }
4616  }
4617 
4618  return "Error, mode/status not found";
4619  }
4620 
4627  public function getOutstandingProposals($mode = 'customer')
4628  {
4629  $table = 'propal';
4630  if ($mode == 'supplier') {
4631  $table = 'supplier_proposal';
4632  }
4633 
4634  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4635  $sql .= " WHERE fk_soc = ".((int) $this->id);
4636  if ($mode == 'supplier') {
4637  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4638  } else {
4639  $sql .= " AND entity IN (".getEntity('propal').")";
4640  }
4641 
4642  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4643 
4644  $resql = $this->db->query($sql);
4645  if ($resql) {
4646  $outstandingOpened = 0;
4647  $outstandingTotal = 0;
4648  $outstandingTotalIncTax = 0;
4649  $arrayofref = array();
4650  while ($obj = $this->db->fetch_object($resql)) {
4651  $arrayofref[$obj->rowid] = $obj->ref;
4652  $outstandingTotal += $obj->total_ht;
4653  $outstandingTotalIncTax += $obj->total_ttc;
4654  if ($obj->status != 0) {
4655  // Not a draft
4656  $outstandingOpened += $obj->total_ttc;
4657  }
4658  }
4659  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4660  } else {
4661  return array();
4662  }
4663  }
4664 
4671  public function getOutstandingOrders($mode = 'customer')
4672  {
4673  $table = 'commande';
4674  if ($mode == 'supplier') {
4675  $table = 'commande_fournisseur';
4676  }
4677 
4678  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4679  $sql .= " WHERE fk_soc = ".((int) $this->id);
4680  if ($mode == 'supplier') {
4681  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4682  } else {
4683  $sql .= " AND entity IN (".getEntity('commande').")";
4684  }
4685 
4686  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4687  $resql = $this->db->query($sql);
4688  if ($resql) {
4689  $outstandingOpened = 0;
4690  $outstandingTotal = 0;
4691  $outstandingTotalIncTax = 0;
4692  $arrayofref = array();
4693  while ($obj = $this->db->fetch_object($resql)) {
4694  $arrayofref[$obj->rowid] = $obj->ref;
4695  $outstandingTotal += $obj->total_ht;
4696  $outstandingTotalIncTax += $obj->total_ttc;
4697  if ($obj->status != 0) {
4698  // Not a draft
4699  $outstandingOpened += $obj->total_ttc;
4700  }
4701  }
4702  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4703  } else {
4704  return array();
4705  }
4706  }
4707 
4715  public function getOutstandingBills($mode = 'customer', $late = 0)
4716  {
4717  $table = 'facture';
4718  if ($mode == 'supplier') {
4719  $table = 'facture_fourn';
4720  }
4721 
4722  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4723  $paiement = $invoice->getSommePaiement();
4724  $creditnotes=$invoice->getSumCreditNotesUsed();
4725  $deposits=$invoice->getSumDepositsUsed();
4726  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4727  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4728  */
4729  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4730  $sql .= " WHERE fk_soc = ".((int) $this->id);
4731  if (!empty($late)) {
4732  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4733  }
4734  if ($mode == 'supplier') {
4735  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4736  } else {
4737  $sql .= " AND entity IN (".getEntity('invoice').")";
4738  }
4739 
4740  dol_syslog("getOutstandingBills", LOG_DEBUG);
4741  $resql = $this->db->query($sql);
4742  if ($resql) {
4743  $outstandingOpened = 0;
4744  $outstandingTotal = 0;
4745  $outstandingTotalIncTax = 0;
4746  $arrayofref = array();
4747  $arrayofrefopened = array();
4748  if ($mode == 'supplier') {
4749  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4750  $tmpobject = new FactureFournisseur($this->db);
4751  } else {
4752  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4753  $tmpobject = new Facture($this->db);
4754  }
4755  while ($obj = $this->db->fetch_object($resql)) {
4756  $arrayofref[$obj->rowid] = $obj->ref;
4757  $tmpobject->id = $obj->rowid;
4758 
4759  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4760  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4761  ) {
4762  $outstandingTotal += $obj->total_ht;
4763  $outstandingTotalIncTax += $obj->total_ttc;
4764  }
4765 
4766  $remaintopay = 0;
4767 
4768  if ($obj->paye == 0
4769  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4770  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4771  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4772  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4773  $paiement = $tmpobject->getSommePaiement();
4774  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4775  $deposits = $tmpobject->getSumDepositsUsed();
4776 
4777  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4778  $outstandingOpened += $remaintopay;
4779  }
4780 
4781  //if credit note is converted but not used
4782  // TODO Do this also for customer ?
4783  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4784  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4785  $remaintopay -= $remainingcreditnote;
4786  $outstandingOpened -= $remainingcreditnote;
4787  }
4788 
4789  if ($remaintopay) {
4790  $arrayofrefopened[$obj->rowid] = $obj->ref;
4791  }
4792  }
4793  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4794  } else {
4795  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4796  return array();
4797  }
4798  }
4799 
4806  public function getLibCustProspStatut()
4807  {
4808  return $this->LibCustProspStatut($this->client);
4809  }
4810 
4811  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4818  public function LibCustProspStatut($status)
4819  {
4820  // phpcs:enable
4821  global $langs;
4822  $langs->load('companies');
4823 
4824  if ($status == 0) {
4825  return $langs->trans("NorProspectNorCustomer");
4826  } elseif ($status == 1) {
4827  return $langs->trans("Customer");
4828  } elseif ($status == 2) {
4829  return $langs->trans("Prospect");
4830  } elseif ($status == 3) {
4831  return $langs->trans("ProspectCustomer");
4832  }
4833  }
4834 
4835 
4847  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4848  {
4849  global $conf, $user, $langs;
4850 
4851  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4852  $modelpath = "core/modules/bank/doc/";
4853 
4854  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4855  $companybankaccount = new CompanyBankAccount($this->db);
4856  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4857  if (!$result) {
4858  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4859  }
4860  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4861  } else {
4862  // Positionne le modele sur le nom du modele a utiliser
4863  if (!dol_strlen($modele)) {
4864  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4865  $modele = $conf->global->COMPANY_ADDON_PDF;
4866  } else {
4867  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4868  return 0;
4869  }
4870  }
4871 
4872  if (!isset($this->bank_account)) {
4873  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4874  $bac = new CompanyBankAccount($this->db);
4875  $result = $bac->fetch(0, $this->id);
4876  if ($result > 0) {
4877  $this->bank_account = $bac;
4878  } else {
4879  $this->bank_account = '';
4880  }
4881  }
4882 
4883  $modelpath = "core/modules/societe/doc/";
4884 
4885  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4886  }
4887 
4888  return $result;
4889  }
4890 
4891 
4903  public function setCategories($categories, $type_categ)
4904  {
4905  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4906 
4907  // Decode type
4908  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4909  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4910  return -1;
4911  }
4912 
4913  return parent::setCategoriesCommon($categories, $type_categ);
4914  }
4915 
4923  public function setSalesRep($salesrep, $onlyAdd = false)
4924  {
4925  global $user;
4926 
4927  // Handle single user
4928  if (!is_array($salesrep)) {
4929  $salesrep = array($salesrep);
4930  }
4931 
4932  $to_del = array(); // Nothing to delete
4933  $to_add = $salesrep;
4934  if ($onlyAdd === false) {
4935  // Get current users
4936  $existing = $this->getSalesRepresentatives($user, 1);
4937 
4938  // Diff
4939  if (is_array($existing)) {
4940  $to_del = array_diff($existing, $salesrep);
4941  $to_add = array_diff($salesrep, $existing);
4942  }
4943  }
4944 
4945  $error = 0;
4946 
4947  // Process
4948  foreach ($to_del as $del) {
4949  $this->del_commercial($user, $del);
4950  }
4951  foreach ($to_add as $add) {
4952  $result = $this->add_commercial($user, $add);
4953  if ($result < 0) {
4954  $error++;
4955  break;
4956  }
4957  }
4958 
4959  return $error ? -1 : 1;
4960  }
4961 
4968  public function setThirdpartyType($typent_id)
4969  {
4970  global $user;
4971 
4972  dol_syslog(__METHOD__, LOG_DEBUG);
4973 
4974  if ($this->id) {
4975  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
4976 
4977  if ($result > 0) {
4978  $this->typent_id = $typent_id;
4979  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
4980  return 1;
4981  } else {
4982  return -1;
4983  }
4984  } else {
4985  return -1;
4986  }
4987  }
4988 
4998  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4999  {
5000  if ($origin_id == $dest_id) {
5001  dol_syslog('Error: Try to merge a thirdparty into itself');
5002  return false;
5003  }
5004 
5009  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5010  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5011  $sql .= ' SELECT fk_user ';
5012  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5013  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5014 
5015  $resql = $dbs->query($sql);
5016  while ($obj = $dbs->fetch_object($resql)) {
5017  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5018  }
5019 
5024  $tables = array(
5025  'societe_address',
5026  'societe_commerciaux',
5027  'societe_prices',
5028  'societe_remise',
5029  'societe_remise_except',
5030  'societe_rib'
5031  );
5032 
5033  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5034  }
5035 
5044  public function setAccountancyCode($type, $value)
5045  {
5046  global $user, $langs, $conf;
5047 
5048  $this->db->begin();
5049 
5050  $field = 'accountancy_code_sell';
5051  if ($type == 'buy') {
5052  $field = 'accountancy_code_buy';
5053  } elseif ($type == 'sell') {
5054  $field = 'accountancy_code_sell';
5055  } else {
5056  return -1;
5057  }
5058 
5059  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5060  $sql .= $field." = '".$this->db->escape($value)."'";
5061  $sql .= " WHERE rowid = ".((int) $this->id);
5062 
5063  dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
5064  $resql = $this->db->query($sql);
5065 
5066  if ($resql) {
5067  // Call triggers
5068  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5069  $interface = new Interfaces($this->db);
5070  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5071  if ($result < 0) {
5072  $this->errors = $interface->errors;
5073  $this->db->rollback();
5074  return -1;
5075  }
5076  // End call triggers
5077 
5078  $this->$field = $value;
5079 
5080  $this->db->commit();
5081  return 1;
5082  } else {
5083  $this->error = $this->db->lasterror();
5084  $this->db->rollback();
5085  return -1;
5086  }
5087  }
5088 
5095  public function fetchPartnerships($mode)
5096  {
5097  global $langs;
5098 
5099  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5100 
5101 
5102  $this->partnerships[] = array();
5103 
5104  return 1;
5105  }
5106 }
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:4998
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:3500
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:4568
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:3215
Societe\id_prof_verifiable
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
Definition: societe.class.php:3564
Societe\getParentsForCompany
getParentsForCompany($company_id, $parents=[])
Get parents for company.
Definition: societe.class.php:3533
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:3284
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:4050
Societe\LoadSupplierCateg
LoadSupplierCateg()
Load the list of provider categories.
Definition: societe.class.php:4003
Societe\set_remise_supplier
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2244
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:2859
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:3244
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:2503
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:4494
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:4903
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:1062
Societe\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: societe.class.php:4388
Societe\setThirdpartyType
setThirdpartyType($typent_id)
Define third-party type of current company.
Definition: societe.class.php:4968
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:3409
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:4472
Societe\get_codeclient
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
Definition: societe.class.php:3183
getState
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
Definition: company.lib.php:595
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php: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:2900
Societe\getSalesRepresentatives
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Definition: societe.class.php:2400
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:4923
Societe\AddFournisseurInCategory
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
Definition: societe.class.php:4029
Societe\display_rib
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
Definition: societe.class.php:3115
Societe\setPriceLevel
setPriceLevel($price_level, User $user)
Set the price level.
Definition: societe.class.php:2468
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:2597
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:8879
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:3665
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:2377
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:3964
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:4076
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:1265
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:2306
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:4517
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:2872
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8436
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:3908
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:2947
Societe\setMysoc
setMysoc(Conf $conf)
Set properties with value into $conf.
Definition: societe.class.php:4260
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:4715
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:4161
Societe\isInEEC
isInEEC()
Return if a company is inside the EEC (European Economic Community)
Definition: societe.class.php:3991
Societe\getLibProspCommStatut
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
Definition: societe.class.php:4549
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:3604
Societe\getNoEmail
getNoEmail()
get "blacklist" mailing status set no_email attribut to 1 or 0
Definition: societe.class.php:4133
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:1713
Societe\contact_get_property
contact_get_property($rowid, $mode)
Return property of contact from its id.
Definition: societe.class.php:3075
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8390
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:4445
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:2185
Societe\getOutstandingProposals
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
Definition: societe.class.php:4627
Societe\setParent
setParent($id)
Define parent company of current company.
Definition: societe.class.php:3461
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10744
Societe\contact_array_objects
contact_array_objects()
Returns the contact list of this company.
Definition: societe.class.php:3041
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:3012
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:2922
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:4847
Societe\getOutstandingOrders
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
Definition: societe.class.php:4671
Societe\set_as_client
set_as_client()
Define third party as a customer.
Definition: societe.class.php:2152
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:3150
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:515
Form\showphoto
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Definition: html.form.class.php:9419
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:8465
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:1135
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:4818
Societe\del_commercial
del_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2563
Societe\getTypeUrl
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
Definition: societe.class.php:2829
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:3855
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:3371
Societe\LibProspLevel
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
Definition: societe.class.php:4529
Societe\getLibCustProspStatut
getLibCustProspStatut()
Return label of status customer is prospect/customer.
Definition: societe.class.php:4806
Societe\setAccountancyCode
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
Definition: societe.class.php:5044
Societe\check_codeclient
check_codeclient()
Check customer code.
Definition: societe.class.php:3330
Societe\info
info($id)
Load information for tab info.
Definition: societe.class.php:3931
Societe\fetchPartnerships
fetchPartnerships($mode)
Function to get partnerships array.
Definition: societe.class.php:5095