dolibarr  16.0.1
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-2021 Frédéric France <frederic.france@netlogic.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program. If not, see <https://www.gnu.org/licenses/>.
33  */
34 
40 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
43 
44 
48 class Societe extends CommonObject
49 {
50  use CommonIncoterm;
51 
55  public $element = 'societe';
56 
60  public $table_element = 'societe';
61 
65  public $fk_element = 'fk_soc';
66 
70  public $fieldsforcombobox = 'nom,name_alias';
71 
75  protected $childtables = array(
76  'supplier_proposal' => array('name' => 'SupplierProposal'),
77  'propal' => array('name' => 'Proposal'),
78  'commande' => array('name' => 'Order'),
79  'facture' => array('name' => 'Invoice'),
80  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
81  'contrat' => array('name' => 'Contract'),
82  'fichinter' => array('name' => 'Fichinter'),
83  'facture_fourn' => array('name' => 'SupplierInvoice'),
84  'commande_fournisseur' => array('name' => 'SupplierOrder'),
85  'projet' => array('name' => 'Project'),
86  'expedition' => array('name' => 'Shipment'),
87  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
88  );
89 
94  protected $childtablesoncascade = array(
95  'societe_prices',
96  'societe_address',
97  'product_fournisseur_price',
98  'product_customer_price_log',
99  'product_customer_price',
100  '@Contact:/contact/class/contact.class.php:fk_soc',
101  'adherent',
102  'societe_account',
103  'societe_rib',
104  'societe_remise',
105  'societe_remise_except',
106  'societe_commerciaux',
107  'categorie',
108  'notify',
109  'notify_def',
110  'actioncomm',
111  );
112 
116  public $picto = 'company';
117 
122  public $ismultientitymanaged = 1;
123 
128  public $restrictiononfksoc = 1;
129 
130 
160  public $fields = array(
161  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
162  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
163  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
164  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
165  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
166  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
167  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
168  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
169  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
170  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
171  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CodeCompta', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
172  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'CodeComptaSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
173  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
174  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
175  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
176  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
177  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
178  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
179  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
180  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
181  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
182  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
183  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
184  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
185  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
186  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
187  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
188  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
189  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
190  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
191  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
192  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
193  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
194  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
195  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
196  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
197  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
198  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>'$conf->global->SOCIETE_USEPREFIX', 'visible'=>-1, 'position'=>235),
199  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
200  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
201  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
202  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
203  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
204  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
205  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
206  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
207  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
208  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
209  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
210  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
211  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
212  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
213  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
214  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
215  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
216  'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
217  'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
218  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
219  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
220  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
221  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
222  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
223  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
224  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
225  '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),
226  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
227  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
228  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
229  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
230  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
231  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
232  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
233  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
234  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
235  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
236  'fk_account' =>array('type'=>'integer', 'label'=>'AccountingAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
237  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
238  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
239  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
240  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
241  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
242  );
243 
247  public $entity;
248 
255  public $nom;
256 
260  public $name;
261 
266  public $name_alias;
267 
271  public $particulier;
272 
276  public $address;
277 
281  public $zip;
282 
286  public $town;
287 
292  public $status = 1;
293 
298  public $state_id;
299 
303  public $state_code;
304 
308  public $state;
309 
314  public $region_code;
315 
319  public $region;
320 
326  public $departement_code;
327 
333  public $departement;
334 
340  public $pays;
341 
346  public $phone;
351  public $fax;
356  public $email;
357 
361  public $socialnetworks;
362 
368  public $skype;
369 
375  public $twitter;
376 
382  public $facebook;
383 
389  public $linkedin;
390 
395  public $url;
396 
401  public $barcode;
402 
403  // 6 professional id (usage depends on country)
404 
409  public $idprof1;
410 
416  public $siren;
417 
418 
423  public $idprof2;
424 
430  public $siret;
431 
436  public $idprof3;
437 
443  public $ape;
444 
449  public $idprof4;
450 
455  public $idprof5;
456 
461  public $idprof6;
462 
466  public $prefix_comm;
467 
471  public $tva_assuj = 1;
472 
477  public $tva_intra;
478 
479  // Local taxes
480  public $localtax1_assuj;
481  public $localtax1_value;
482  public $localtax2_assuj;
483  public $localtax2_value;
484 
488  public $managers;
489 
493  public $capital;
494 
498  public $typent_id = 0;
499  public $typent_code;
500  public $effectif;
501  public $effectif_id = 0;
502  public $forme_juridique_code;
503  public $forme_juridique = 0;
504 
505  public $remise_percent;
506  public $remise_supplier_percent;
507 
508  public $mode_reglement_id;
509  public $cond_reglement_id;
510  public $deposit_percent;
511  public $mode_reglement_supplier_id;
512  public $cond_reglement_supplier_id;
513  public $transport_mode_supplier_id;
514 
518  public $fk_prospectlevel;
519 
523  public $name_bis;
524 
525  //Log data
526 
531  public $date_modification;
532 
537  public $user_modification;
538 
543  public $date_creation;
544 
549  public $user_creation;
550 
555  public $client = 0;
556 
561  public $prospect = 0;
562 
567  public $fournisseur;
568 
573  public $code_client;
574 
579  public $code_fournisseur;
580 
585  public $code_compta_client;
586 
591  public $code_compta;
592 
593 
598  public $accountancy_code_customer;
599 
604  public $code_compta_fournisseur;
605 
610  public $accountancy_code_supplier;
611 
612 
617  public $code_compta_product;
618 
619 
625  public $note;
626 
631  public $note_private;
632 
637  public $note_public;
638 
643  public $stcomm_id;
644 
649  public $stcomm_picto;
650 
655  public $status_prospect_label;
656 
661  public $price_level;
662 
666  public $outstanding_limit;
667 
671  public $order_min_amount;
672 
676  public $supplier_order_min_amount;
677 
682  public $commercial_id;
683 
688  public $parent;
689 
694  public $default_lang;
695 
699  public $ref;
700 
705  public $ref_int;
706 
712  public $ref_ext;
713 
720  public $import_key;
721 
726  public $webservices_url;
727 
732  public $webservices_key;
733 
737  public $logo;
738 
742  public $logo_small;
743 
747  public $logo_mini;
748 
752  public $logo_squarred;
753 
757  public $logo_squarred_small;
758 
762  public $logo_squarred_mini;
763 
767  public $accountancy_code_sell;
768 
772  public $accountancy_code_buy;
773 
774  // Multicurrency
778  public $fk_multicurrency;
779 
780  // Warehouse
784  public $fk_warehouse;
785 
789  public $multicurrency_code;
790 
791 
792  // Fields loaded by fetchPartnerships()
793 
794  public $partnerships = array();
795 
796 
797 
801  public $bank_account;
802 
806  const NO_CUSTOMER = 0;
807 
811  const CUSTOMER = 1;
812 
816  const PROSPECT = 2;
817 
822 
826  const NO_SUPPLIER = 0;
827 
831  const SUPPLIER = 1;
832 
838  public function __construct($db)
839  {
840  global $conf;
841 
842  $this->db = $db;
843 
844  $this->client = 0;
845  $this->prospect = 0;
846  $this->fournisseur = 0;
847  $this->typent_id = 0;
848  $this->effectif_id = 0;
849  $this->forme_juridique_code = 0;
850  $this->tva_assuj = 1;
851  $this->status = 1;
852 
853  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
854  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
855  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
856  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
857  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
858  }
859  }
860 
861 
869  public function create(User $user)
870  {
871  global $langs, $conf, $mysoc;
872 
873  $error = 0;
874 
875  // Clean parameters
876  if (empty($this->status)) {
877  $this->status = 0;
878  }
879  $this->name = $this->name ?trim($this->name) : trim($this->nom);
880  $this->setUpperOrLowerCase();
881  $this->nom = $this->name; // For backward compatibility
882  if (empty($this->client)) {
883  $this->client = 0;
884  }
885  if (empty($this->fournisseur)) {
886  $this->fournisseur = 0;
887  }
888  $this->import_key = trim($this->import_key);
889 
890  $this->accountancy_code_customer = trim($this->code_compta);
891  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
892  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
893  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
894 
895  if (!empty($this->multicurrency_code)) {
896  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
897  }
898  if (empty($this->fk_multicurrency)) {
899  $this->multicurrency_code = '';
900  $this->fk_multicurrency = 0;
901  }
902 
903  dol_syslog(get_class($this)."::create ".$this->name);
904 
905  $now = dol_now();
906 
907  $this->db->begin();
908 
909  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
910  if ($this->code_client == -1 || $this->code_client === 'auto') {
911  $this->get_codeclient($this, 0);
912  }
913  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
914  $this->get_codefournisseur($this, 1);
915  }
916 
917  // Check more parameters (including mandatory setup
918  // If error, this->errors[] is filled
919  $result = $this->verify();
920 
921  if ($result >= 0) {
922  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
923 
924  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
925  $sql .= "nom";
926  $sql .= ", name_alias";
927  $sql .= ", entity";
928  $sql .= ", datec";
929  $sql .= ", fk_user_creat";
930  $sql .= ", fk_typent";
931  $sql .= ", canvas";
932  $sql .= ", status";
933  $sql .= ", ref_ext";
934  $sql .= ", fk_stcomm";
935  $sql .= ", fk_incoterms";
936  $sql .= ", location_incoterms";
937  $sql .= ", import_key";
938  $sql .= ", fk_multicurrency";
939  $sql .= ", multicurrency_code";
940  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
941  $sql .= ", accountancy_code_buy";
942  $sql .= ", accountancy_code_sell";
943  }
944  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
945  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
946  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
947  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
948  $sql .= ", ".((int) $this->status);
949  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
950  $sql .= ", 0";
951  $sql .= ", ".(int) $this->fk_incoterms;
952  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
953  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
954  $sql .= ", ".(int) $this->fk_multicurrency;
955  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
956  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
957  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
958  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
959  }
960  $sql .= ")";
961 
962  dol_syslog(get_class($this)."::create", LOG_DEBUG);
963  $result = $this->db->query($sql);
964  if ($result) {
965  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
966 
967  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
968 
969  // update accountancy for this entity
970  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
971  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
972 
973  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
974  $sql .= " fk_soc";
975  $sql .= ", entity";
976  $sql .= ", accountancy_code_customer";
977  $sql .= ", accountancy_code_supplier";
978  $sql .= ", accountancy_code_buy";
979  $sql .= ", accountancy_code_sell";
980  $sql .= ") VALUES (";
981  $sql .= $this->id;
982  $sql .= ", ".((int) $conf->entity);
983  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
984  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
985  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
986  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
987  $sql .= ")";
988  $result = $this->db->query($sql);
989  if (!$result) {
990  $error++;
991  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
992  }
993  }
994 
995  // Ajout du commercial affecte
996  if ($this->commercial_id != '' && $this->commercial_id != -1) {
997  $this->add_commercial($user, $this->commercial_id);
998  } elseif (empty($user->rights->societe->client->voir)) {
999  // si un commercial cree un client il lui est affecte automatiquement
1000  $this->add_commercial($user, $user->id);
1001  }
1002 
1003  if ($ret >= 0) {
1004  // Call trigger
1005  $result = $this->call_trigger('COMPANY_CREATE', $user);
1006  if ($result < 0) {
1007  $error++;
1008  }
1009  // End call triggers
1010  } else {
1011  $error++;
1012  }
1013 
1014  if (!$error) {
1015  dol_syslog(get_class($this)."::Create success id=".$this->id);
1016  $this->db->commit();
1017  return $this->id;
1018  } else {
1019  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1020  $this->db->rollback();
1021  return -4;
1022  }
1023  } else {
1024  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1025  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1026  $result = -1;
1027  } else {
1028  $this->error = $this->db->lasterror();
1029  $result = -2;
1030  }
1031  $this->db->rollback();
1032  return $result;
1033  }
1034  } else {
1035  $this->db->rollback();
1036  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1037  return -3;
1038  }
1039  }
1040 
1041 
1042  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1051  public function create_individual(User $user, $no_email = 0, $tags = array())
1052  {
1053  global $conf;
1054 
1055  $error = 0;
1056 
1057  $this->db->begin();
1058 
1059  // phpcs:enable
1060  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1061  $contact = new Contact($this->db);
1062 
1063  $contact->name = $this->name_bis;
1064  $contact->firstname = $this->firstname;
1065  $contact->civility_id = $this->civility_id;
1066  $contact->socid = $this->id; // fk_soc
1067  $contact->statut = 1; // deprecated
1068  $contact->status = 1;
1069  $contact->priv = 0;
1070  $contact->country_id = $this->country_id;
1071  $contact->state_id = $this->state_id;
1072  $contact->address = $this->address;
1073  $contact->email = $this->email;
1074  $contact->zip = $this->zip;
1075  $contact->town = $this->town;
1076  $this->setUpperOrLowerCase();
1077  $contact->phone_pro = $this->phone;
1078 
1079  $contactId = $contact->create($user);
1080  if ($contactId < 0) {
1081  $error++;
1082  $this->error = $contact->error;
1083  $this->errors = $contact->errors;
1084  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1085  }
1086 
1087  if (empty($error) && is_array($tags) && !empty($tags)) {
1088  $result = $contact->setCategories($tags);
1089  if ($result < 0) {
1090  $error++;
1091  $this->error = $contact->error;
1092  $this->errors = array_merge($this->errors, $contact->errors);
1093  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1094  $contactId = $result;
1095  }
1096  }
1097 
1098  if (empty($error) && !empty($conf->mailing->enabled) && !empty($contact->email) && isset($no_email)) {
1099  $result = $contact->setNoEmail($no_email);
1100  if ($result < 0) {
1101  $this->error = $contact->error;
1102  $this->errors = array_merge($this->errors, $contact->errors);
1103  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1104  $contactId = $result;
1105  }
1106  }
1107 
1108  if (empty($error)) {
1109  dol_syslog(get_class($this)."::create_individual success");
1110  $this->db->commit();
1111  } else {
1112  $this->db->rollback();
1113  }
1114 
1115  return $contactId;
1116  }
1117 
1124  public function verify()
1125  {
1126  global $conf, $langs, $mysoc;
1127 
1128  $error = 0;
1129  $this->errors = array();
1130 
1131  $result = 0;
1132  $this->name = trim($this->name);
1133  $this->nom = $this->name; // For backward compatibility
1134 
1135  if (!$this->name) {
1136  $this->errors[] = 'ErrorBadThirdPartyName';
1137  $result = -2;
1138  }
1139 
1140  if ($this->client) {
1141  $rescode = $this->check_codeclient();
1142  if ($rescode != 0 && $rescode != -5) {
1143  if ($rescode == -1) {
1144  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1145  } elseif ($rescode == -2) {
1146  $this->errors[] = 'ErrorCustomerCodeRequired';
1147  } elseif ($rescode == -3) {
1148  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1149  } elseif ($rescode == -4) {
1150  $this->errors[] = 'ErrorPrefixRequired';
1151  } else {
1152  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1153  }
1154 
1155  $result = -3;
1156  }
1157  }
1158 
1159  if ($this->fournisseur) {
1160  $rescode = $this->check_codefournisseur();
1161  if ($rescode != 0 && $rescode != -5) {
1162  if ($rescode == -1) {
1163  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1164  } elseif ($rescode == -2) {
1165  $this->errors[] = 'ErrorSupplierCodeRequired';
1166  } elseif ($rescode == -3) {
1167  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1168  } elseif ($rescode == -4) {
1169  $this->errors[] = 'ErrorPrefixRequired';
1170  } else {
1171  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1172  }
1173  $result = -3;
1174  }
1175  }
1176 
1177  // Check for duplicate or mandatory fields defined into setup
1178  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
1179  foreach ($array_to_check as $key) {
1180  $keymin = strtolower($key);
1181  $i = (int) preg_replace('/[^0-9]/', '', $key);
1182  $vallabel = $this->$keymin;
1183 
1184  if ($i > 0) {
1185  if ($this->isACompany()) {
1186  // Check for mandatory prof id (but only if country is same than ours)
1187  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1188  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1189  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1190  $langs->load("errors");
1191  $error++;
1192  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1193  }
1194  }
1195  }
1196 
1197  // Check for unicity on profid
1198  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1199  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1200  $langs->load("errors");
1201  $error++;
1202  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1203  }
1204  }
1205  } else {
1206  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1207  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1208  if ($key == 'EMAIL') {
1209  // Check for mandatory
1210  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1211  $langs->load("errors");
1212  $error++;
1213  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1214  }
1215 
1216  // Check for unicity
1217  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1218  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1219  $langs->load("errors");
1220  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1221  }
1222  }
1223  }
1224  }
1225  }
1226 
1227  if ($error) {
1228  $result = -4;
1229  }
1230 
1231  return $result;
1232  }
1233 
1246  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1247  {
1248  global $langs, $conf, $hookmanager;
1249 
1250  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1251 
1252  if (empty($id)) {
1253  $id = $this->id;
1254  }
1255 
1256  $error = 0;
1257 
1258  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1259 
1260  $now = dol_now();
1261 
1262  // Clean parameters
1263  $this->id = $id;
1264  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1265  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1266  $this->nom = $this->name; // For backward compatibility
1267  $this->name_alias = trim($this->name_alias);
1268  $this->ref_ext = trim($this->ref_ext);
1269  $this->address = $this->address ?trim($this->address) : trim($this->address);
1270  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1271  $this->town = $this->town ?trim($this->town) : trim($this->town);
1272  $this->setUpperOrLowerCase();
1273  $this->state_id = trim($this->state_id);
1274  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1275  $this->phone = trim($this->phone);
1276  $this->phone = preg_replace("/\s/", "", $this->phone);
1277  $this->phone = preg_replace("/\./", "", $this->phone);
1278  $this->fax = trim($this->fax);
1279  $this->fax = preg_replace("/\s/", "", $this->fax);
1280  $this->fax = preg_replace("/\./", "", $this->fax);
1281  $this->email = trim($this->email);
1282  $this->url = $this->url ?clean_url($this->url, 0) : '';
1283  $this->note_private = trim($this->note_private);
1284  $this->note_public = trim($this->note_public);
1285  $this->idprof1 = trim($this->idprof1);
1286  $this->idprof2 = trim($this->idprof2);
1287  $this->idprof3 = trim($this->idprof3);
1288  $this->idprof4 = trim($this->idprof4);
1289  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1290  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1291  $this->prefix_comm = trim($this->prefix_comm);
1292  $this->outstanding_limit = price2num($this->outstanding_limit);
1293  $this->order_min_amount = price2num($this->order_min_amount);
1294  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1295 
1296  $this->tva_assuj = trim($this->tva_assuj);
1297  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1298  if (empty($this->status)) {
1299  $this->status = 0;
1300  }
1301 
1302  if (!empty($this->multicurrency_code)) {
1303  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1304  }
1305  if (empty($this->fk_multicurrency)) {
1306  $this->multicurrency_code = '';
1307  $this->fk_multicurrency = 0;
1308  }
1309 
1310  // Local taxes
1311  $this->localtax1_assuj = trim($this->localtax1_assuj);
1312  $this->localtax2_assuj = trim($this->localtax2_assuj);
1313 
1314  $this->localtax1_value = trim($this->localtax1_value);
1315  $this->localtax2_value = trim($this->localtax2_value);
1316 
1317  if ($this->capital != '') {
1318  $this->capital = price2num(trim($this->capital));
1319  }
1320  if (!is_numeric($this->capital)) {
1321  $this->capital = ''; // '' = undef
1322  }
1323 
1324  $this->effectif_id = trim($this->effectif_id);
1325  $this->forme_juridique_code = trim($this->forme_juridique_code);
1326 
1327  //Gencod
1328  $this->barcode = trim($this->barcode);
1329 
1330  // For automatic creation
1331  if ($this->code_client == -1 || $this->code_client === 'auto') {
1332  $this->get_codeclient($this, 0);
1333  }
1334  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1335  $this->get_codefournisseur($this, 1);
1336  }
1337 
1338  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1339  $this->code_compta = $this->code_compta_client; // for backward compatibility
1340  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1341 
1342  // Check parameters. More tests are done later in the ->verify()
1343  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1344  $langs->load("errors");
1345  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1346  return -1;
1347  }
1348 
1349  $customer = false;
1350  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1351  // If $allowmodcodeclient is set and value is not set, we generate it
1352  if (empty($this->code_compta_client)) {
1353  $ret = $this->get_codecompta('customer');
1354  if ($ret < 0) {
1355  return -1;
1356  }
1357  }
1358 
1359  $customer = true;
1360  }
1361 
1362  $supplier = false;
1363  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1364  // If $allowmodcodefournisseur is set and value is not set, we generate it
1365  if (empty($this->code_compta_fournisseur)) {
1366  $ret = $this->get_codecompta('supplier');
1367  if ($ret < 0) {
1368  return -1;
1369  }
1370  }
1371 
1372  $supplier = true;
1373  }
1374 
1375  //Web services
1376  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1377  $this->webservices_key = trim($this->webservices_key);
1378 
1379  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1380  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1381 
1382  //Incoterms
1383  $this->fk_incoterms = (int) $this->fk_incoterms;
1384  $this->location_incoterms = trim($this->location_incoterms);
1385 
1386  $this->db->begin();
1387 
1388  // Check name is required and codes are ok or unique.
1389  // If error, this->errors[] is filled
1390  $result = 0;
1391  if ($action != 'add' && $action != 'merge') {
1392  // We don't check when update called during a create because verify was already done.
1393  // 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
1394  $result = $this->verify();
1395 
1396  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1397  // So we can update record that were using and old numbering rule.
1398  if (is_array($this->errors)) {
1399  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1400  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1401  unset($this->errors[$key]); // Remove error message
1402  }
1403  }
1404  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1405  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1406  unset($this->errors[$key]); // Remove error message
1407  }
1408  }
1409  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1410  $result = 0;
1411  }
1412  }
1413  }
1414 
1415  if ($result >= 0) {
1416  dol_syslog(get_class($this)."::update verify ok or not done");
1417 
1418  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1419  $sql .= "entity = ".$this->db->escape($this->entity);
1420  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1421  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1422  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1423  $sql .= ",address = '".$this->db->escape($this->address)."'";
1424 
1425  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1426  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1427 
1428  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1429  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1430 
1431  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1432  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1433  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1434  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1435  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1436 
1437  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1438 
1439  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1440  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1441 
1442  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1443  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1444  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1445  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1446  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1447  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1448 
1449  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1450  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1451  $sql .= ",status = ".((int) $this->status);
1452 
1453  // Local taxes
1454  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1455  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1456  if ($this->localtax1_assuj == 1) {
1457  if ($this->localtax1_value != '') {
1458  $sql .= ",localtax1_value =".$this->localtax1_value;
1459  } else {
1460  $sql .= ",localtax1_value =0.000";
1461  }
1462  } else {
1463  $sql .= ",localtax1_value =0.000";
1464  }
1465 
1466  if ($this->localtax2_assuj == 1) {
1467  if ($this->localtax2_value != '') {
1468  $sql .= ",localtax2_value =".$this->localtax2_value;
1469  } else {
1470  $sql .= ",localtax2_value =0.000";
1471  }
1472  } else {
1473  $sql .= ",localtax2_value =0.000";
1474  }
1475 
1476  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1477 
1478  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1479 
1480  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1481  if (isset($this->stcomm_id)) {
1482  $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? ((int) $this->stcomm_id) : "0");
1483  }
1484  if (isset($this->typent_id)) {
1485  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1486  }
1487 
1488  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1489 
1490  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1491  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1492  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1493  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1494  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1495  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1496  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1497  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1498 
1499  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1500  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1501  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1502  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1503  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1504  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1505  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1506  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1507  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1508  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1509  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1510  $sql .= ", accountancy_code_buy = '".$this->db->escape($this->accountancy_code_buy)."'";
1511  $sql .= ", accountancy_code_sell= '".$this->db->escape($this->accountancy_code_sell)."'";
1512 
1513  if ($customer) {
1514  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1515  }
1516 
1517  if ($supplier) {
1518  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1519  }
1520  }
1521  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1522  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1523 
1524  //Incoterms
1525  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1526  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1527 
1528  if ($customer) {
1529  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1530  }
1531 
1532  if ($supplier) {
1533  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1534  }
1535  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1536  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1537  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1538  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1539  $sql .= " WHERE rowid = ".(int) $id;
1540 
1541  $resql = $this->db->query($sql);
1542  if ($resql) {
1543  if (is_object($this->oldcopy)) { // If we have information on old values
1544  if ($this->oldcopy->country_id != $this->country_id) {
1545  unset($this->country_code);
1546  unset($this->country);
1547  }
1548  if ($this->oldcopy->state_id != $this->state_id) {
1549  unset($this->state_code);
1550  unset($this->state);
1551  }
1552  } else {
1553  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1554  unset($this->country);
1555  unset($this->state_code);
1556  unset($this->state);
1557  }
1558 
1559  $nbrowsaffected = $this->db->affected_rows($resql);
1560 
1561  if (!$error && $nbrowsaffected) {
1562  // Update information on linked member if it is an update
1563  if (!$nosyncmember && !empty($conf->adherent->enabled)) {
1564  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1565 
1566  dol_syslog(get_class($this)."::update update linked member");
1567 
1568  $lmember = new Adherent($this->db);
1569  $result = $lmember->fetch(0, 0, $this->id);
1570 
1571  if ($result > 0) {
1572  $lmember->company = $this->name;
1573  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1574  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1575  $lmember->address = $this->address;
1576  $lmember->zip = $this->zip;
1577  $lmember->town = $this->town;
1578  $lmember->email = $this->email;
1579  $lmember->socialnetworks = $this->socialnetworks;
1580  $lmember->phone = $this->phone;
1581  $lmember->state_id = $this->state_id;
1582  $lmember->country_id = $this->country_id;
1583 
1584  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1585  if ($result < 0) {
1586  $this->error = $lmember->error;
1587  $this->errors = array_merge($this->errors, $lmember->errors);
1588  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1589  $error++;
1590  }
1591  } elseif ($result < 0) {
1592  $this->error = $lmember->error;
1593  $error++;
1594  }
1595  }
1596  }
1597 
1598  $action = 'update';
1599 
1600  // update accountancy for this entity
1601  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1602  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1603 
1604  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1605  $sql .= " fk_soc";
1606  $sql .= ", entity";
1607  $sql .= ", accountancy_code_customer";
1608  $sql .= ", accountancy_code_supplier";
1609  $sql .= ", accountancy_code_buy";
1610  $sql .= ", accountancy_code_sell";
1611  $sql .= ") VALUES (";
1612  $sql .= $this->id;
1613  $sql .= ", ".$conf->entity;
1614  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1615  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1616  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1617  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1618  $sql .= ")";
1619  $result = $this->db->query($sql);
1620  if (!$result) {
1621  $error++;
1622  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1623  }
1624  }
1625 
1626  // Actions on extra fields
1627  if (!$error) {
1628  $result = $this->insertExtraFields();
1629  if ($result < 0) {
1630  $error++;
1631  }
1632  }
1633  // Actions on extra languages
1634  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1635  $result = $this->insertExtraLanguages();
1636  if ($result < 0) {
1637  $error++;
1638  }
1639  }
1640 
1641  if (!$error && $call_trigger) {
1642  // Call trigger
1643  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1644  if ($result < 0) {
1645  $error++;
1646  }
1647  // End call triggers
1648  }
1649 
1650  if (!$error) {
1651  dol_syslog(get_class($this)."::Update success");
1652  $this->db->commit();
1653  return 1;
1654  } else {
1655  $this->db->rollback();
1656  return -1;
1657  }
1658  } else {
1659  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1660  // Doublon
1661  $this->error = $langs->trans("ErrorDuplicateField");
1662  $result = -1;
1663  } else {
1664  $this->error = $this->db->lasterror();
1665  $result = -2;
1666  }
1667  $this->db->rollback();
1668  return $result;
1669  }
1670  } else {
1671  $this->db->rollback();
1672  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1673  return -3;
1674  }
1675  }
1676 
1694  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1695  {
1696  global $langs;
1697  global $conf;
1698 
1699  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1700  return -1;
1701  }
1702 
1703  $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';
1704  $sql .= ', s.status, s.fk_warehouse';
1705  $sql .= ', s.price_level';
1706  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1707  $sql .= ', s.phone, s.fax, s.email';
1708  $sql .= ', s.socialnetworks';
1709  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1710  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1711  $sql .= ', s.capital, s.tva_intra';
1712  $sql .= ', s.fk_typent as typent_id';
1713  $sql .= ', s.fk_effectif as effectif_id';
1714  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1715  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf';
1716  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1717  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1718  } else {
1719  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1720  }
1721  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1722  $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';
1723  $sql .= ', s.fk_account, s.tva_assuj';
1724  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1725  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1726  $sql .= ', s.fk_shipping_method';
1727  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1728  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1729  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1730  $sql .= ', fj.libelle as forme_juridique';
1731  $sql .= ', e.libelle as effectif';
1732  $sql .= ', c.code as country_code, c.label as country';
1733  $sql .= ', d.code_departement as state_code, d.nom as state';
1734  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1735  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1736  $sql .= ', te.code as typent_code';
1737  $sql .= ', i.libelle as label_incoterms';
1738  if (empty($conf->multicompany->enabled)) {
1739  $sql .= ', s.remise_client, s.remise_supplier';
1740  } else {
1741  $sql .= ', sr.remise_client, sr2.remise_supplier';
1742  }
1743  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1744  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1745  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1746  }
1747  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1748  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1749  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1750  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1751  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1752  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1753  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1754  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1755  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1756  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1757  if (!empty($conf->multicompany->enabled)) {
1758  $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').'))';
1759  $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').'))';
1760  }
1761  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1762  if ($rowid) {
1763  $sql .= ' AND s.rowid = '.((int) $rowid);
1764  }
1765  if ($ref) {
1766  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1767  }
1768  if ($ref_alias) {
1769  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1770  }
1771  if ($ref_ext) {
1772  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1773  }
1774  if ($barcode) {
1775  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1776  }
1777  if ($idprof1) {
1778  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1779  }
1780  if ($idprof2) {
1781  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1782  }
1783  if ($idprof3) {
1784  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1785  }
1786  if ($idprof4) {
1787  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1788  }
1789  if ($idprof5) {
1790  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1791  }
1792  if ($idprof6) {
1793  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1794  }
1795  if ($email) {
1796  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1797  }
1798 
1799  $resql = $this->db->query($sql);
1800  if ($resql) {
1801  $num = $this->db->num_rows($resql);
1802  if ($num > 1) {
1803  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1804  dol_syslog($this->error, LOG_ERR);
1805  $result = -2;
1806  } elseif ($num) { // $num = 1
1807  $obj = $this->db->fetch_object($resql);
1808 
1809  $this->id = $obj->rowid;
1810  $this->entity = $obj->entity;
1811  $this->canvas = $obj->canvas;
1812 
1813  $this->ref = $obj->rowid;
1814  $this->name = $obj->name;
1815  $this->nom = $obj->name; // deprecated
1816  $this->name_alias = $obj->name_alias;
1817  $this->ref_ext = $obj->ref_ext;
1818 
1819  $this->date_creation = $this->db->jdate($obj->date_creation);
1820  $this->date_modification = $this->db->jdate($obj->date_modification);
1821  $this->user_creation = $obj->fk_user_creat;
1822  $this->user_modification = $obj->fk_user_modif;
1823 
1824  $this->address = $obj->address;
1825  $this->zip = $obj->zip;
1826  $this->town = $obj->town;
1827 
1828  $this->country_id = $obj->country_id;
1829  $this->country_code = $obj->country_id ? $obj->country_code : '';
1830  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1831 
1832  $this->state_id = $obj->state_id;
1833  $this->state_code = $obj->state_code;
1834  $this->region_id = $obj->region_id;
1835  $this->region_code = $obj->region_code;
1836  $this->state = ($obj->state != '-' ? $obj->state : '');
1837 
1838  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1839  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1840  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1841  $this->status_prospect_label = $label; // label status prospect
1842  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1843 
1844  $this->email = $obj->email;
1845  $this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
1846 
1847  $this->url = $obj->url;
1848  $this->phone = $obj->phone;
1849  $this->fax = $obj->fax;
1850 
1851  $this->parent = $obj->parent;
1852 
1853  $this->idprof1 = $obj->idprof1;
1854  $this->idprof2 = $obj->idprof2;
1855  $this->idprof3 = $obj->idprof3;
1856  $this->idprof4 = $obj->idprof4;
1857  $this->idprof5 = $obj->idprof5;
1858  $this->idprof6 = $obj->idprof6;
1859 
1860  $this->capital = $obj->capital;
1861 
1862  $this->code_client = $obj->code_client;
1863  $this->code_fournisseur = $obj->code_fournisseur;
1864 
1865  $this->code_compta = $obj->code_compta; // For backward compatibility
1866  $this->code_compta_client = $obj->code_compta;
1867  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1868 
1869  $this->barcode = $obj->barcode;
1870 
1871  $this->tva_assuj = $obj->tva_assuj;
1872  $this->tva_intra = $obj->tva_intra;
1873  $this->status = $obj->status;
1874 
1875  // Local Taxes
1876  $this->localtax1_assuj = $obj->localtax1_assuj;
1877  $this->localtax2_assuj = $obj->localtax2_assuj;
1878 
1879  $this->localtax1_value = $obj->localtax1_value;
1880  $this->localtax2_value = $obj->localtax2_value;
1881 
1882  $this->typent_id = $obj->typent_id;
1883  $this->typent_code = $obj->typent_code;
1884 
1885  $this->effectif_id = $obj->effectif_id;
1886  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1887 
1888  $this->forme_juridique_code = $obj->forme_juridique_code;
1889  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1890 
1891  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1892 
1893  $this->prefix_comm = $obj->prefix_comm;
1894 
1895  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1896  $this->remise_supplier_percent = $obj->remise_supplier;
1897 
1898  $this->mode_reglement_id = $obj->mode_reglement;
1899  $this->cond_reglement_id = $obj->cond_reglement;
1900  $this->deposit_percent = $obj->deposit_percent;
1901  $this->transport_mode_id = $obj->transport_mode;
1902  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1903  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1904  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1905  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1906  $this->fk_account = $obj->fk_account;
1907 
1908  $this->client = $obj->client;
1909  $this->fournisseur = $obj->fournisseur;
1910 
1911  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1912  $this->note_private = $obj->note_private;
1913  $this->note_public = $obj->note_public;
1914  $this->model_pdf = $obj->model_pdf;
1915  $this->modelpdf = $obj->model_pdf; // deprecated
1916  $this->default_lang = $obj->default_lang;
1917  $this->logo = $obj->logo;
1918  $this->logo_squarred = $obj->logo_squarred;
1919 
1920  $this->webservices_url = $obj->webservices_url;
1921  $this->webservices_key = $obj->webservices_key;
1922 
1923  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1924  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1925 
1926  $this->outstanding_limit = $obj->outstanding_limit;
1927  $this->order_min_amount = $obj->order_min_amount;
1928  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1929 
1930  // multiprix
1931  $this->price_level = $obj->price_level;
1932 
1933  // warehouse
1934  $this->fk_warehouse = $obj->fk_warehouse;
1935 
1936  $this->import_key = $obj->import_key;
1937 
1938  //Incoterms
1939  $this->fk_incoterms = $obj->fk_incoterms;
1940  $this->location_incoterms = $obj->location_incoterms;
1941  $this->label_incoterms = $obj->label_incoterms;
1942 
1943  // multicurrency
1944  $this->fk_multicurrency = $obj->fk_multicurrency;
1945  $this->multicurrency_code = $obj->multicurrency_code;
1946  $this->model_pdf = $obj->model_pdf;
1947 
1948  $result = 1;
1949 
1950  // fetch optionals attributes and labels
1951  $this->fetch_optionals();
1952  } else {
1953  $result = 0;
1954  }
1955 
1956  $this->db->free($resql);
1957  } else {
1958  $this->error = $this->db->lasterror();
1959  $this->errors[] = $this->db->lasterror();
1960  $result = -3;
1961  }
1962 
1963  // Use first price level if level not defined for third party
1964  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1965  $this->price_level = 1;
1966  }
1967 
1968  return $result;
1969  }
1970 
1979  public function delete($id, User $fuser = null, $call_trigger = 1)
1980  {
1981  global $langs, $conf, $user;
1982 
1983  if (empty($fuser)) {
1984  $fuser = $user;
1985  }
1986 
1987  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1988 
1989  $entity = isset($this->entity) ? $this->entity : $conf->entity;
1990 
1991  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1992  $error = 0;
1993 
1994  // Test if child exists
1995  $objectisused = $this->isObjectUsed($id);
1996  if (empty($objectisused)) {
1997  $this->db->begin();
1998 
1999  // User is mandatory for trigger call
2000  if (!$error && $call_trigger) {
2001  // Call trigger
2002  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2003  if ($result < 0) {
2004  $error++;
2005  }
2006  // End call triggers
2007  }
2008 
2009  if (!$error) {
2010  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2011  $static_cat = new Categorie($this->db);
2012  $toute_categs = array();
2013 
2014  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2015  if ($this->client || $this->prospect) {
2016  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2017  }
2018  if ($this->fournisseur) {
2019  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2020  }
2021 
2022  // Remove each "Categorie"
2023  foreach ($toute_categs as $type => $categs_type) {
2024  foreach ($categs_type as $cat) {
2025  $cat->del_type($this, $type);
2026  }
2027  }
2028  }
2029 
2030  if (!$error) {
2031  foreach ($this->childtablesoncascade as $tabletodelete) {
2032  $deleteFromObject = explode(':', $tabletodelete);
2033  if (count($deleteFromObject) >= 2) {
2034  $className = str_replace('@', '', $deleteFromObject[0]);
2035  $filepath = $deleteFromObject[1];
2036  $columnName = $deleteFromObject[2];
2037  if (dol_include_once($filepath)) {
2038  $child_object = new $className($this->db);
2039  $result = $child_object->deleteByParentField($id, $columnName);
2040  if ($result < 0) {
2041  $error++;
2042  $this->errors[] = $child_object->error;
2043  break;
2044  }
2045  } else {
2046  $error++;
2047  $this->errors[] = 'Cannot include child class file '.$filepath;
2048  break;
2049  }
2050  } else {
2051  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2052  $sql .= " WHERE fk_soc = ".((int) $id);
2053  if (!$this->db->query($sql)) {
2054  $error++;
2055  $this->errors[] = $this->db->lasterror();
2056  break;
2057  }
2058  }
2059  }
2060  }
2061 
2062  // Removed extrafields
2063  if (!$error) {
2064  $result = $this->deleteExtraFields();
2065  if ($result < 0) {
2066  $error++;
2067  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2068  }
2069  }
2070 
2071  // Remove links to subsidiaries companies
2072  if (!$error) {
2073  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2074  $sql .= " SET parent = NULL";
2075  $sql .= " WHERE parent = ".((int) $id);
2076  if (!$this->db->query($sql)) {
2077  $error++;
2078  $this->errors[] = $this->db->lasterror();
2079  }
2080  }
2081 
2082  // Remove third party
2083  if (!$error) {
2084  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2085  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2086  $sql .= " WHERE fk_soc = ".((int) $id);
2087  if (!$this->db->query($sql)) {
2088  $error++;
2089  $this->errors[] = $this->db->lasterror();
2090  }
2091  }
2092 
2093  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2094  $sql .= " WHERE rowid = ".((int) $id);
2095  if (!$this->db->query($sql)) {
2096  $error++;
2097  $this->errors[] = $this->db->lasterror();
2098  }
2099  }
2100 
2101  if (!$error) {
2102  $this->db->commit();
2103 
2104  // Delete directory
2105  if (!empty($conf->societe->multidir_output[$entity])) {
2106  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2107  if (dol_is_dir($docdir)) {
2108  dol_delete_dir_recursive($docdir);
2109  }
2110  }
2111 
2112  return 1;
2113  } else {
2114  dol_syslog($this->error, LOG_ERR);
2115  $this->db->rollback();
2116  return -1;
2117  }
2118  } else {
2119  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2120  }
2121  return 0;
2122  }
2123 
2124  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2130  public function set_as_client()
2131  {
2132  // phpcs:enable
2133  if ($this->id) {
2134  $newclient = 1;
2135  if ($this->client == 2 || $this->client == 3) {
2136  $newclient = 3; //If prospect, we keep prospect tag
2137  }
2138  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2139  $sql .= " SET client = ".((int) $newclient);
2140  $sql .= " WHERE rowid = ".((int) $this->id);
2141 
2142  $resql = $this->db->query($sql);
2143  if ($resql) {
2144  $this->client = $newclient;
2145  return 1;
2146  } else {
2147  return -1;
2148  }
2149  }
2150  return 0;
2151  }
2152 
2153  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2162  public function set_remise_client($remise, $note, User $user)
2163  {
2164  // phpcs:enable
2165  global $conf, $langs;
2166 
2167  // Parameter cleaning
2168  $note = trim($note);
2169  if (!$note) {
2170  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2171  return -2;
2172  }
2173 
2174  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2175 
2176  if ($this->id) {
2177  $this->db->begin();
2178 
2179  $now = dol_now();
2180 
2181  // Position current discount
2182  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2183  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2184  $sql .= " WHERE rowid = ".((int) $this->id);
2185  $resql = $this->db->query($sql);
2186  if (!$resql) {
2187  $this->db->rollback();
2188  $this->error = $this->db->error();
2189  return -1;
2190  }
2191 
2192  // Writes trace in discount history
2193  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2194  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2195  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2196  $sql .= " '".$this->db->escape($note)."',";
2197  $sql .= " ".((int) $user->id);
2198  $sql .= ")";
2199 
2200  $resql = $this->db->query($sql);
2201  if (!$resql) {
2202  $this->db->rollback();
2203  $this->error = $this->db->lasterror();
2204  return -1;
2205  }
2206 
2207  $this->db->commit();
2208  return 1;
2209  }
2210  }
2211 
2212  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2221  public function set_remise_supplier($remise, $note, User $user)
2222  {
2223  // phpcs:enable
2224  global $conf, $langs;
2225 
2226  // Parameter cleaning
2227  $note = trim($note);
2228  if (!$note) {
2229  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2230  return -2;
2231  }
2232 
2233  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2234 
2235  if ($this->id) {
2236  $this->db->begin();
2237 
2238  $now = dol_now();
2239 
2240  // Position current discount
2241  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2242  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2243  $sql .= " WHERE rowid = ".((int) $this->id);
2244  $resql = $this->db->query($sql);
2245  if (!$resql) {
2246  $this->db->rollback();
2247  $this->error = $this->db->error();
2248  return -1;
2249  }
2250 
2251  // Writes trace in discount history
2252  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2253  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2254  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2255  $sql .= " '".$this->db->escape($note)."',";
2256  $sql .= " ".((int) $user->id);
2257  $sql .= ")";
2258 
2259  $resql = $this->db->query($sql);
2260  if (!$resql) {
2261  $this->db->rollback();
2262  $this->error = $this->db->lasterror();
2263  return -1;
2264  }
2265 
2266  $this->db->commit();
2267  return 1;
2268  }
2269  }
2270 
2271  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2282  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0)
2283  {
2284  // phpcs:enable
2285  global $langs;
2286 
2287  // Clean parameters
2288  $remise = price2num($remise);
2289  $desc = trim($desc);
2290 
2291  // Check parameters
2292  if (!($remise > 0)) {
2293  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2294  return -1;
2295  }
2296  if (!$desc) {
2297  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2298  return -2;
2299  }
2300 
2301  if ($this->id > 0) {
2302  // Clean vat code
2303  $reg = array();
2304  $vat_src_code = '';
2305  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2306  $vat_src_code = $reg[1];
2307  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2308  }
2309 
2310  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2311 
2312  $discount = new DiscountAbsolute($this->db);
2313  $discount->fk_soc = $this->id;
2314 
2315  $discount->discount_type = $discount_type;
2316 
2317  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2318  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2319  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2320 
2321  $discount->tva_tx = price2num($vatrate);
2322  $discount->vat_src_code = $vat_src_code;
2323 
2324  $discount->description = $desc;
2325 
2326  $result = $discount->create($user);
2327  if ($result > 0) {
2328  return $result;
2329  } else {
2330  $this->error = $discount->error;
2331  return -3;
2332  }
2333  } else {
2334  return 0;
2335  }
2336  }
2337 
2347  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2348  {
2349  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2350 
2351  $discountstatic = new DiscountAbsolute($this->db);
2352  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2353  if ($result >= 0) {
2354  return $result;
2355  } else {
2356  $this->error = $discountstatic->error;
2357  return -1;
2358  }
2359  }
2360 
2370  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2371  {
2372  global $conf;
2373 
2374  $reparray = array();
2375 
2376  $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";
2377  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2378  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2379  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2380  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2381  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2382  $sql .= " AND ug.entity = ".$conf->entity.")";
2383  $sql .= " OR u.admin = 1)";
2384  } else {
2385  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2386  }
2387 
2388  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2389  if (empty($sortfield) && empty($sortorder)) {
2390  $sortfield = 'u.lastname,u.firstname';
2391  $sortorder = 'ASC,ASC';
2392  }
2393  $sql .= $this->db->order($sortfield, $sortorder);
2394 
2395  $resql = $this->db->query($sql);
2396  if ($resql) {
2397  $num = $this->db->num_rows($resql);
2398  $i = 0;
2399  while ($i < $num) {
2400  $obj = $this->db->fetch_object($resql);
2401 
2402  if (empty($mode)) {
2403  $reparray[$i]['id'] = $obj->rowid;
2404  $reparray[$i]['lastname'] = $obj->lastname;
2405  $reparray[$i]['firstname'] = $obj->firstname;
2406  $reparray[$i]['email'] = $obj->email;
2407  $reparray[$i]['phone'] = $obj->office_phone;
2408  $reparray[$i]['office_phone'] = $obj->office_phone;
2409  $reparray[$i]['office_fax'] = $obj->office_fax;
2410  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2411  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2412  $reparray[$i]['job'] = $obj->job;
2413  $reparray[$i]['statut'] = $obj->status; // deprecated
2414  $reparray[$i]['status'] = $obj->status;
2415  $reparray[$i]['entity'] = $obj->entity;
2416  $reparray[$i]['login'] = $obj->login;
2417  $reparray[$i]['photo'] = $obj->photo;
2418  $reparray[$i]['gender'] = $obj->gender;
2419  } else {
2420  $reparray[] = $obj->rowid;
2421  }
2422  $i++;
2423  }
2424  return $reparray;
2425  } else {
2426  dol_print_error($this->db);
2427  return -1;
2428  }
2429  }
2430 
2438  public function setPriceLevel($price_level, User $user)
2439  {
2440  if ($this->id) {
2441  $now = dol_now();
2442 
2443  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2444  $sql .= " SET price_level = ".((int) $price_level);
2445  $sql .= " WHERE rowid = ".((int) $this->id);
2446 
2447  if (!$this->db->query($sql)) {
2448  dol_print_error($this->db);
2449  return -1;
2450  }
2451 
2452  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2453  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2454  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2455 
2456  if (!$this->db->query($sql)) {
2457  dol_print_error($this->db);
2458  return -1;
2459  }
2460  return 1;
2461  }
2462  return -1;
2463  }
2464 
2465  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2473  public function add_commercial(User $user, $commid)
2474  {
2475  // phpcs:enable
2476  $error = 0;
2477 
2478  if ($this->id > 0 && $commid > 0) {
2479  $this->db->begin();
2480 
2481  if (!$error) {
2482  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2483  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2484 
2485  $resql = $this->db->query($sql);
2486  if (!$resql) {
2487  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2488  $error++;
2489  }
2490  }
2491 
2492  if (!$error) {
2493  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2494  $sql .= " (fk_soc, fk_user)";
2495  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2496 
2497  $resql = $this->db->query($sql);
2498  if (!$resql) {
2499  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2500  $error++;
2501  }
2502  }
2503 
2504  if (!$error) {
2505  $this->context = array('commercial_modified' => $commid);
2506 
2507  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2508  if ($result < 0) {
2509  $error++;
2510  }
2511  }
2512 
2513  if (!$error) {
2514  $this->db->commit();
2515  return 1;
2516  } else {
2517  $this->db->rollback();
2518  return -1;
2519  }
2520  }
2521 
2522  return 0;
2523  }
2524 
2525  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2533  public function del_commercial(User $user, $commid)
2534  {
2535  // phpcs:enable
2536  $error = 0;
2537  $this->context = array('commercial_modified'=>$commid);
2538 
2539  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2540  if ($result < 0) {
2541  $error++;
2542  }
2543 
2544  if ($this->id > 0 && $commid > 0) {
2545  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2546  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2547 
2548  if (!$this->db->query($sql)) {
2549  dol_syslog(get_class($this)."::del_commercial Erreur");
2550  }
2551  }
2552  }
2553 
2554 
2567  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2568  {
2569  global $conf, $langs, $hookmanager;
2570 
2571  if (!empty($conf->dol_no_mouse_hover)) {
2572  $notooltip = 1; // Force disable tooltips
2573  }
2574 
2575  $name = $this->name ? $this->name : $this->nom;
2576 
2577  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2578  if (empty($option) && $this->client > 0) {
2579  $option = 'customer';
2580  }
2581  if (empty($option) && $this->fournisseur > 0) {
2582  $option = 'supplier';
2583  }
2584  }
2585 
2586  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2587  $code = '';
2588  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2589  $code = $this->code_client.' - ';
2590  }
2591 
2592  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2593  $code .= $this->code_fournisseur.' - ';
2594  }
2595 
2596  if ($code) {
2597  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2598  $name = $code.' '.$name;
2599  } else {
2600  $name = $code;
2601  }
2602  }
2603  }
2604 
2605  if (!empty($this->name_alias) && empty($noaliasinname)) {
2606  $name .= ' ('.$this->name_alias.')';
2607  }
2608 
2609  $result = ''; $label = ''; $label2 = '';
2610  $linkstart = ''; $linkend = '';
2611 
2612  if (!empty($this->logo) && class_exists('Form')) {
2613  $label .= '<div class="photointooltip floatright">';
2614  $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.
2615  $label .= '</div>';
2616  //$label .= '<div style="clear: both;"></div>';
2617  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2618  /*$label.= '<div class="photointooltip">';
2619  $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.
2620  $label.= '</div><div style="clear: both;"></div>';*/
2621  }
2622 
2623  $label .= '<div class="centpercent">';
2624 
2625  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2626  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2627  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2628  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2629  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2630  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2631  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2632  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2633  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2634  } elseif ($option == 'agenda') {
2635  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2636  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2637  } elseif ($option == 'project') {
2638  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2639  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2640  } elseif ($option == 'margin') {
2641  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2642  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2643  } elseif ($option == 'contact') {
2644  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2645  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2646  } elseif ($option == 'ban') {
2647  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2648  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2649  }
2650 
2651  // By default
2652  if (empty($linkstart)) {
2653  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2654  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2655  }
2656  if (isset($this->status)) {
2657  $label .= ' '.$this->getLibStatut(5);
2658  }
2659 
2660  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag($this->name);
2661  if (!empty($this->name_alias)) {
2662  $label .= ' ('.dol_escape_htmltag($this->name_alias).')';
2663  }
2664  if ($this->email) {
2665  $label .= '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2666  }
2667  if (!empty($this->phone) || !empty($this->fax)) {
2668  $phonelist = array();
2669  if ($this->phone) {
2670  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2671  }
2672  if ($this->fax) {
2673  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2674  }
2675  $label .= '<br>'.implode('&nbsp;', $phonelist);
2676  }
2677 
2678  if (!empty($this->address)) {
2679  $label2 .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2680  } elseif (!empty($this->country_code)) {
2681  $label2 .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2682  }
2683  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2684  $label2 .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2685  }
2686  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2687  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) {
2688  $label2 .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2689  }
2690  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) {
2691  $label2 .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2692  }
2693  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) {
2694  $label2 .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2695  }
2696  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) {
2697  $label2 .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2698  }
2699  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) {
2700  $label2 .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2701  }
2702  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) {
2703  $label2 .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2704  }
2705  }
2706  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2707  $label2 .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2708  }
2709  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2710  $label2 .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2711  }
2712  if (!empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3)) {
2713  $label2 .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2714  }
2715  if (!empty($conf->accounting->enabled) && $this->fournisseur) {
2716  $label2 .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2717  }
2718  $label .= ($label2 ? '<br>'.$label2 : '').'</div>';
2719 
2720  // Add type of canvas
2721  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2722  // Add param to save lastsearch_values or not
2723  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2724  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2725  $add_save_lastsearch_values = 1;
2726  }
2727  if ($add_save_lastsearch_values) {
2728  $linkstart .= '&save_lastsearch_values=1';
2729  }
2730  $linkstart .= '"';
2731 
2732  $linkclose = '';
2733  if (empty($notooltip)) {
2734  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2735  $label = $langs->trans("ShowCompany");
2736  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2737  }
2738  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2739  $linkclose .= ' class="classfortooltip refurl"';
2740  $target_value = array('_self', '_blank', '_parent', '_top');
2741  if (in_array($target, $target_value)) {
2742  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2743  }
2744  }
2745  $linkstart .= $linkclose.'>';
2746  $linkend = '</a>';
2747 
2748  global $user;
2749  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2750  $linkstart = '';
2751  $linkend = '';
2752  }
2753 
2754  $result .= $linkstart;
2755  if ($withpicto) {
2756  $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);
2757  }
2758  if ($withpicto != 2) {
2759  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2760  }
2761  $result .= $linkend;
2762 
2763  global $action;
2764  $hookmanager->initHooks(array('thirdpartydao'));
2765  $parameters = array(
2766  'id'=>$this->id,
2767  'getnomurl' => &$result,
2768  'withpicto '=> $withpicto,
2769  'option'=> $option,
2770  'maxlen'=> $maxlen,
2771  'notooltip'=> $notooltip,
2772  'save_lastsearch_value'=> $save_lastsearch_value
2773  );
2774  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2775  if ($reshook > 0) {
2776  $result = $hookmanager->resPrint;
2777  } else {
2778  $result .= $hookmanager->resPrint;
2779  }
2780 
2781  return $result;
2782  }
2783 
2793  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2794  {
2795  global $conf, $langs;
2796 
2797  $s = '';
2798  if (empty($option) || preg_match('/prospect/', $option)) {
2799  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2800  $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.'>';
2801  }
2802  }
2803  if (empty($option) || preg_match('/customer/', $option)) {
2804  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2805  $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.'>';
2806  }
2807  }
2808  if (empty($option) || preg_match('/supplier/', $option)) {
2809  if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $this->fournisseur) {
2810  $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.'>';
2811  }
2812  }
2813  return $s;
2814  }
2815 
2816 
2823  public function getLibStatut($mode = 0)
2824  {
2825  return $this->LibStatut($this->status, $mode);
2826  }
2827 
2828  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2836  public function LibStatut($status, $mode = 0)
2837  {
2838  // phpcs:enable
2839  global $langs;
2840  $langs->load('companies');
2841 
2842  $statusType = 'status4';
2843  if ($status == 0) {
2844  $statusType = 'status6';
2845  }
2846 
2847  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2848  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2849  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2850  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2851  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2852  }
2853 
2854  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2855  }
2856 
2857  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2864  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2865  {
2866  // phpcs:enable
2867  global $langs;
2868 
2869  $contact_emails = $this->contact_property_array('email', 1);
2870  if ($this->email && $addthirdparty) {
2871  if (empty($this->name)) {
2872  $this->name = $this->nom;
2873  }
2874  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2875  }
2876  //var_dump($contact_emails)
2877  return $contact_emails;
2878  }
2879 
2880  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2887  {
2888  // phpcs:enable
2889  global $langs;
2890 
2891  $contact_phone = $this->contact_property_array('mobile');
2892 
2893  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2894  if (empty($this->name)) {
2895  $this->name = $this->nom;
2896  }
2897  // TODO: Tester si tel non deja present dans tableau contact
2898  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2899  }
2900  return $contact_phone;
2901  }
2902 
2903  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2911  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2912  {
2913  // phpcs:enable
2914  global $langs;
2915 
2916  $contact_property = array();
2917 
2918 
2919  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2920  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2921  $sql .= " WHERE fk_soc = ".((int) $this->id);
2922  $sql .= " ORDER BY lastname, firstname";
2923 
2924  $resql = $this->db->query($sql);
2925  if ($resql) {
2926  $nump = $this->db->num_rows($resql);
2927  if ($nump) {
2928  $sepa = "("; $sepb = ")";
2929  if ($mode == 'email') {
2930  //$sepa="&lt;"; $sepb="&gt;";
2931  $sepa = "<"; $sepb = ">";
2932  }
2933  $i = 0;
2934  while ($i < $nump) {
2935  $obj = $this->db->fetch_object($resql);
2936  if ($mode == 'email') {
2937  $property = $obj->email;
2938  } elseif ($mode == 'mobile') {
2939  $property = $obj->phone_mobile;
2940  } else {
2941  $property = $obj->$mode;
2942  }
2943 
2944  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2945  if ($obj->status == 1 || empty($hidedisabled)) {
2946  if (empty($property)) {
2947  if ($mode == 'email') {
2948  $property = $langs->transnoentitiesnoconv("NoEMail");
2949  } elseif ($mode == 'mobile') {
2950  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2951  }
2952  }
2953 
2954  if (!empty($obj->poste)) {
2955  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2956  } else {
2957  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2958  }
2959  }
2960  $i++;
2961  }
2962  }
2963  } else {
2964  dol_print_error($this->db);
2965  }
2966  return $contact_property;
2967  }
2968 
2969 
2970  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2976  public function contact_array()
2977  {
2978  // phpcs:enable
2979  $contacts = array();
2980 
2981  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
2982  $resql = $this->db->query($sql);
2983  if ($resql) {
2984  $nump = $this->db->num_rows($resql);
2985  if ($nump) {
2986  $i = 0;
2987  while ($i < $nump) {
2988  $obj = $this->db->fetch_object($resql);
2989  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2990  $i++;
2991  }
2992  }
2993  } else {
2994  dol_print_error($this->db);
2995  }
2996  return $contacts;
2997  }
2998 
2999  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3005  public function contact_array_objects()
3006  {
3007  // phpcs:enable
3008  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3009  $contacts = array();
3010 
3011  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3012  $resql = $this->db->query($sql);
3013  if ($resql) {
3014  $nump = $this->db->num_rows($resql);
3015  if ($nump) {
3016  $i = 0;
3017  while ($i < $nump) {
3018  $obj = $this->db->fetch_object($resql);
3019  $contact = new Contact($this->db);
3020  $contact->fetch($obj->rowid);
3021  $contacts[] = $contact;
3022  $i++;
3023  }
3024  }
3025  } else {
3026  dol_print_error($this->db);
3027  }
3028  return $contacts;
3029  }
3030 
3031  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3039  public function contact_get_property($rowid, $mode)
3040  {
3041  // phpcs:enable
3042  $contact_property = '';
3043 
3044  if (empty($rowid)) {
3045  return '';
3046  }
3047 
3048  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3049  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3050  $sql .= " WHERE rowid = ".((int) $rowid);
3051 
3052  $resql = $this->db->query($sql);
3053  if ($resql) {
3054  $nump = $this->db->num_rows($resql);
3055 
3056  if ($nump) {
3057  $obj = $this->db->fetch_object($resql);
3058 
3059  if ($mode == 'email') {
3060  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3061  } elseif ($mode == 'mobile') {
3062  $contact_property = $obj->phone_mobile;
3063  }
3064  }
3065  return $contact_property;
3066  } else {
3067  dol_print_error($this->db);
3068  }
3069  }
3070 
3071 
3072  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3079  public function display_rib($mode = 'label')
3080  {
3081  // phpcs:enable
3082  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3083 
3084  $bac = new CompanyBankAccount($this->db);
3085  $bac->fetch(0, $this->id);
3086 
3087  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3088  if ($mode == 'label') {
3089  return $bac->getRibLabel(true);
3090  } elseif ($mode == 'rum') {
3091  if (empty($bac->rum)) {
3092  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3093  $prelevement = new BonPrelevement($this->db);
3094  $bac->fetch_thirdparty();
3095  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3096  }
3097  return $bac->rum;
3098  } elseif ($mode == 'format') {
3099  return $bac->frstrecur;
3100  } else {
3101  return 'BadParameterToFunctionDisplayRib';
3102  }
3103  } else {
3104  return '';
3105  }
3106  }
3107 
3108  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3114  public function get_all_rib()
3115  {
3116  // phpcs:enable
3117  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3118  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3119  $result = $this->db->query($sql);
3120  if (!$result) {
3121  $this->error++;
3122  $this->errors[] = $this->db->lasterror;
3123  return 0;
3124  } else {
3125  $num_rows = $this->db->num_rows($result);
3126  $rib_array = array();
3127  if ($num_rows) {
3128  while ($obj = $this->db->fetch_object($result)) {
3129  $rib = new CompanyBankAccount($this->db);
3130  $rib->fetch($obj->rowid);
3131  $rib_array[] = $rib;
3132  }
3133  }
3134  return $rib_array;
3135  }
3136  }
3137 
3138  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3147  public function get_codeclient($objsoc = 0, $type = 0)
3148  {
3149  // phpcs:enable
3150  global $conf;
3151  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3152  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3153 
3154  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3155  foreach ($dirsociete as $dirroot) {
3156  $res = dol_include_once($dirroot.$module.'.php');
3157  if ($res) {
3158  break;
3159  }
3160  }
3161  $mod = new $module();
3162 
3163  $this->code_client = $mod->getNextValue($objsoc, $type);
3164  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3165 
3166  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3167  }
3168  }
3169 
3170  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3179  public function get_codefournisseur($objsoc = 0, $type = 1)
3180  {
3181  // phpcs:enable
3182  global $conf;
3183  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3184  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3185 
3186  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3187  foreach ($dirsociete as $dirroot) {
3188  $res = dol_include_once($dirroot.$module.'.php');
3189  if ($res) {
3190  break;
3191  }
3192  }
3193  $mod = new $module();
3194 
3195  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3196 
3197  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3198  }
3199  }
3200 
3201  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3208  public function codeclient_modifiable()
3209  {
3210  // phpcs:enable
3211  global $conf;
3212  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3213  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3214 
3215  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3216  foreach ($dirsociete as $dirroot) {
3217  $res = dol_include_once($dirroot.$module.'.php');
3218  if ($res) {
3219  break;
3220  }
3221  }
3222 
3223  $mod = new $module();
3224 
3225  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3226  if ($mod->code_modifiable_null && !$this->code_client) {
3227  return 1;
3228  }
3229  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3230  return 1;
3231  }
3232  if ($mod->code_modifiable) {
3233  return 1; // A mettre en dernier
3234  }
3235  return 0;
3236  } else {
3237  return 0;
3238  }
3239  }
3240 
3241 
3242  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3248  public function codefournisseur_modifiable()
3249  {
3250  // phpcs:enable
3251  global $conf;
3252  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3253  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3254 
3255  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3256  foreach ($dirsociete as $dirroot) {
3257  $res = dol_include_once($dirroot.$module.'.php');
3258  if ($res) {
3259  break;
3260  }
3261  }
3262 
3263  $mod = new $module();
3264 
3265  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3266  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3267  return 1;
3268  }
3269  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3270  return 1;
3271  }
3272  if ($mod->code_modifiable) {
3273  return 1; // A mettre en dernier
3274  }
3275  return 0;
3276  } else {
3277  return 0;
3278  }
3279  }
3280 
3281 
3282  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3294  public function check_codeclient()
3295  {
3296  // phpcs:enable
3297  global $conf;
3298  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3299  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3300 
3301  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3302  foreach ($dirsociete as $dirroot) {
3303  $res = dol_include_once($dirroot.$module.'.php');
3304  if ($res) {
3305  break;
3306  }
3307  }
3308 
3309  $mod = new $module();
3310 
3311  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3312  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3313  if ($result) { // If error
3314  $this->error = $mod->error;
3315  $this->errors = $mod->errors;
3316  }
3317  return $result;
3318  } else {
3319  return 0;
3320  }
3321  }
3322 
3323  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3335  public function check_codefournisseur()
3336  {
3337  // phpcs:enable
3338  global $conf;
3339  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3340  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3341 
3342  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3343  foreach ($dirsociete as $dirroot) {
3344  $res = dol_include_once($dirroot.$module.'.php');
3345  if ($res) {
3346  break;
3347  }
3348  }
3349 
3350  $mod = new $module();
3351 
3352  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3353  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3354  if ($result) { // If error
3355  $this->error = $mod->error;
3356  $this->errors = $mod->errors;
3357  }
3358  return $result;
3359  } else {
3360  return 0;
3361  }
3362  }
3363 
3364  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3373  public function get_codecompta($type)
3374  {
3375  // phpcs:enable
3376  global $conf;
3377 
3378  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3379  $res = false;
3380  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3381  foreach ($dirsociete as $dirroot) {
3382  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3383  if ($res) {
3384  break;
3385  }
3386  }
3387 
3388  if ($res) {
3389  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3390  $mod = new $classname;
3391 
3392  // Set code count in $mod->code
3393  $result = $mod->get_code($this->db, $this, $type);
3394 
3395  if ($type == 'customer') {
3396  $this->code_compta_client = $mod->code;
3397  $this->code_compta = $this->code_compta_client; // For backward compatibility
3398  } elseif ($type == 'supplier') {
3399  $this->code_compta_fournisseur = $mod->code;
3400  }
3401 
3402  return $result;
3403  } else {
3404  $this->error = 'ErrorAccountancyCodeNotDefined';
3405  return -1;
3406  }
3407  } else {
3408  if ($type == 'customer') {
3409  $this->code_compta_client = '';
3410  $this->code_compta = '';
3411  } elseif ($type == 'supplier') {
3412  $this->code_compta_fournisseur = '';
3413  }
3414 
3415  return 0;
3416  }
3417  }
3418 
3425  public function setParent($id)
3426  {
3427  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3428 
3429  if ($this->id) {
3430  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3431  if ($id > 0) {
3432  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3433  if ($sameparent < 0) {
3434  return -1;
3435  }
3436  if ($sameparent == 1) {
3437  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3438  return -1;
3439  }
3440  }
3441 
3442  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3443 
3444  $resql = $this->db->query($sql);
3445  if ($resql) {
3446  $this->parent = $id;
3447  return 1;
3448  } else {
3449  return -1;
3450  }
3451  } else {
3452  return -1;
3453  }
3454  }
3455 
3464  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3465  {
3466  if ($counter > 100) {
3467  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3468  }
3469 
3470  $sql = 'SELECT s.parent';
3471  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3472  $sql .= ' WHERE rowid = '.((int) $idparent);
3473  $resql = $this->db->query($sql);
3474  if ($resql) {
3475  $obj = $this->db->fetch_object($resql);
3476 
3477  if ($obj->parent == '') {
3478  return 0;
3479  } elseif ($obj->parent == $idchild) {
3480  return 1;
3481  } else {
3482  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3483  }
3484  return $sameparent;
3485  } else {
3486  return -1;
3487  }
3488  }
3489 
3497  public function getParentsForCompany($company_id, $parents = [])
3498  {
3499  global $langs;
3500 
3501  if ($company_id > 0) {
3502  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3503  $resql = $this->db->query($sql);
3504  if ($resql) {
3505  if ($obj = $this->db->fetch_object($resql)) {
3506  $parent = $obj->parent;
3507  if ($parent > 0 && !in_array($parent, $parents)) {
3508  $parents[] = $parent;
3509  return $this->getParentsForCompany($parent, $parents);
3510  } else {
3511  return $parents;
3512  }
3513  }
3514  $this->db->free($resql);
3515  } else {
3516  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3517  }
3518  }
3519  }
3520 
3521  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3528  public function id_prof_verifiable($idprof)
3529  {
3530  // phpcs:enable
3531  global $conf;
3532 
3533  switch ($idprof) {
3534  case 1:
3535  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3536  break;
3537  case 2:
3538  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3539  break;
3540  case 3:
3541  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3542  break;
3543  case 4:
3544  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3545  break;
3546  case 5:
3547  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3548  break;
3549  case 6:
3550  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3551  break;
3552  default:
3553  $ret = false;
3554  }
3555 
3556  return $ret;
3557  }
3558 
3559  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3568  public function id_prof_exists($idprof, $value, $socid = 0)
3569  {
3570  // phpcs:enable
3571  $field = $idprof;
3572 
3573  switch ($idprof) { // For backward compatibility
3574  case '1':
3575  case 'idprof1':
3576  $field = "siren";
3577  break;
3578  case '2':
3579  case 'idprof2':
3580  $field = "siret";
3581  break;
3582  case '3':
3583  case 'idprof3':
3584  $field = "ape";
3585  break;
3586  case '4':
3587  case 'idprof4':
3588  $field = "idprof4";
3589  break;
3590  case '5':
3591  $field = "idprof5";
3592  break;
3593  case '6':
3594  $field = "idprof6";
3595  break;
3596  }
3597 
3598  //Verify duplicate entries
3599  $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3600  if ($socid) {
3601  $sql .= " AND rowid <> ".$socid;
3602  }
3603  $resql = $this->db->query($sql);
3604  if ($resql) {
3605  $obj = $this->db->fetch_object($resql);
3606  $count = $obj->idprof;
3607  } else {
3608  $count = 0;
3609  print $this->db->error();
3610  }
3611  $this->db->free($resql);
3612 
3613  if ($count > 0) {
3614  return true;
3615  } else {
3616  return false;
3617  }
3618  }
3619 
3620  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3629  public function id_prof_check($idprof, $soc)
3630  {
3631  // phpcs:enable
3632  global $conf;
3633 
3634  $ok = 1;
3635 
3636  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3637  return 1;
3638  }
3639 
3640  // Check SIREN if country FR
3641  if ($idprof == 1 && $soc->country_code == 'FR') {
3642  $chaine = trim($this->idprof1);
3643  $chaine = preg_replace('/(\s)/', '', $chaine);
3644 
3645  if (!is_numeric($chaine)) {
3646  return -1;
3647  }
3648  if (dol_strlen($chaine) != 9) {
3649  return -1;
3650  }
3651 
3652  // on prend chaque chiffre un par un
3653  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3654  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3655  // on ajoute cette valeur à la somme totale
3656  $sum = 0;
3657  for ($index = 0; $index < 9; $index++) {
3658  $number = (int) $chaine[$index];
3659  if (($index % 2) != 0) {
3660  if (($number *= 2) > 9) {
3661  $number -= 9;
3662  }
3663  }
3664  $sum += $number;
3665  }
3666 
3667  // le numéro est valide si la somme des chiffres est multiple de 10
3668  if (($sum % 10) != 0) {
3669  return -1;
3670  }
3671  }
3672 
3673  // Verifie SIRET si pays FR
3674  if ($idprof == 2 && $soc->country_code == 'FR') {
3675  $chaine = trim($this->idprof2);
3676  $chaine = preg_replace('/(\s)/', '', $chaine);
3677 
3678  if (!is_numeric($chaine)) {
3679  return -1;
3680  }
3681  if (dol_strlen($chaine) != 14) {
3682  return -1;
3683  }
3684 
3685  // on prend chaque chiffre un par un
3686  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3687  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3688  // on ajoute cette valeur à la somme totale
3689  $sum = 0;
3690  for ($index = 0; $index < 14; $index++) {
3691  $number = (int) $chaine[$index];
3692  if (($index % 2) == 0) {
3693  if (($number *= 2) > 9) {
3694  $number -= 9;
3695  }
3696  }
3697  $sum += $number;
3698  }
3699 
3700  // le numéro est valide si la somme des chiffres est multiple de 10
3701  if (($sum % 10) != 0) {
3702  return -1;
3703  }
3704  }
3705 
3706  //Verify CIF/NIF/NIE if pays ES
3707  //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
3708  if ($idprof == 1 && $soc->country_code == 'ES') {
3709  $string = trim($this->idprof1);
3710  $string = preg_replace('/(\s)/', '', $string);
3711  $string = strtoupper($string);
3712 
3713  //Check format
3714  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)) {
3715  return 0;
3716  }
3717 
3718  $num = array();
3719  for ($i = 0; $i < 9; $i++) {
3720  $num[$i] = substr($string, $i, 1);
3721  }
3722 
3723  //Check NIF
3724  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3725  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3726  return 1;
3727  } else {
3728  return -1;
3729  }
3730  }
3731 
3732  //algorithm checking type code CIF
3733  $sum = $num[2] + $num[4] + $num[6];
3734  for ($i = 1; $i < 8; $i += 2) {
3735  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3736  }
3737  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3738 
3739  //Chek special NIF
3740  if (preg_match('/^[KLM]{1}/', $string)) {
3741  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3742  return 1;
3743  } else {
3744  return -1;
3745  }
3746  }
3747 
3748  //Check CIF
3749  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3750  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3751  return 2;
3752  } else {
3753  return -2;
3754  }
3755  }
3756 
3757  //Check NIE T
3758  if (preg_match('/^[T]{1}/', $string)) {
3759  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3760  return 3;
3761  } else {
3762  return -3;
3763  }
3764  }
3765 
3766  //Check NIE XYZ
3767  if (preg_match('/^[XYZ]{1}/', $string)) {
3768  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3769  return 3;
3770  } else {
3771  return -3;
3772  }
3773  }
3774 
3775  //Can not be verified
3776  return -4;
3777  }
3778 
3779  //Verify NIF if country is PT
3780  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3781  if ($idprof == 1 && $soc->country_code == 'PT') {
3782  $string = trim($this->idprof1);
3783  $string = preg_replace('/(\s)/', '', $string);
3784 
3785  //Check NIF
3786  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3787  return 1;
3788  } else {
3789  return -1;
3790  }
3791  }
3792 
3793  return $ok;
3794  }
3795 
3796  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3805  public function id_prof_url($idprof, $thirdparty)
3806  {
3807  // phpcs:enable
3808  global $conf, $langs, $hookmanager;
3809 
3810  $url = '';
3811  $action = '';
3812 
3813  $hookmanager->initHooks(array('idprofurl'));
3814  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3815  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3816  if (empty($reshook)) {
3817  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3818  return '';
3819  }
3820 
3821  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3822  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3823  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3824  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3825  }
3826  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3827  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3828  }
3829  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3830  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3831  }
3832  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3833  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3834  }
3835  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3836  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3837  }
3838 
3839  if ($url) {
3840  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3841  }
3842  } else {
3843  return $hookmanager->resPrint;
3844  }
3845 
3846  return '';
3847  }
3848 
3849  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3855  public function has_projects()
3856  {
3857  // phpcs:enable
3858  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3859  $resql = $this->db->query($sql);
3860  if ($resql) {
3861  $obj = $this->db->fetch_object($resql);
3862  $count = $obj->numproj;
3863  } else {
3864  $count = 0;
3865  print $this->db->error();
3866  }
3867  $this->db->free($resql);
3868  return ($count > 0);
3869  }
3870 
3871 
3878  public function info($id)
3879  {
3880  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
3881  $sql .= " fk_user_creat, fk_user_modif";
3882  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3883  $sql .= " WHERE s.rowid = ".((int) $id);
3884 
3885  $result = $this->db->query($sql);
3886  if ($result) {
3887  if ($this->db->num_rows($result)) {
3888  $obj = $this->db->fetch_object($result);
3889 
3890  $this->id = $obj->rowid;
3891 
3892  $this->user_creation_id = $obj->fk_user_creat;
3893  $this->user_modification_id = $obj->fk_user_modif;
3894  $this->date_creation = $this->db->jdate($obj->datec);
3895  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
3896 
3897  $this->ref = $obj->name;
3898  }
3899 
3900  $this->db->free($result);
3901  } else {
3902  dol_print_error($this->db);
3903  }
3904  }
3905 
3911  public function isACompany()
3912  {
3913  global $conf;
3914 
3915  // Define if third party is treated as company (or not) when nature is unknown
3916  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3917  if (!empty($this->tva_intra)) {
3918  $isacompany = 1;
3919  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3920  $isacompany = 1;
3921  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3922  // TODO Add a field is_a_company into dictionary
3923  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3924  $isacompany = 0;
3925  } else {
3926  $isacompany = 1;
3927  }
3928  }
3929 
3930  return $isacompany;
3931  }
3932 
3938  public function isInEEC()
3939  {
3940  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3941  return isInEEC($this);
3942  }
3943 
3944  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3950  public function LoadSupplierCateg()
3951  {
3952  // phpcs:enable
3953  $this->SupplierCategories = array();
3954  $sql = "SELECT rowid, label";
3955  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
3956  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3957 
3958  $resql = $this->db->query($sql);
3959  if ($resql) {
3960  while ($obj = $this->db->fetch_object($resql)) {
3961  $this->SupplierCategories[$obj->rowid] = $obj->label;
3962  }
3963  return 0;
3964  } else {
3965  return -1;
3966  }
3967  }
3968 
3969  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3976  public function AddFournisseurInCategory($categorie_id)
3977  {
3978  // phpcs:enable
3979  if ($categorie_id > 0 && $this->id > 0) {
3980  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3981  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
3982 
3983  if ($resql = $this->db->query($sql)) {
3984  return 0;
3985  }
3986  } else {
3987  return 0;
3988  }
3989  return -1;
3990  }
3991 
3992 
3993  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4003  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4004  {
4005  // phpcs:enable
4006  global $conf, $user, $langs;
4007 
4008  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4009 
4010  $name = $socname ? $socname : $member->societe;
4011  if (empty($name)) {
4012  $name = $member->getFullName($langs);
4013  }
4014 
4015  $alias = $socalias ? $socalias : '';
4016 
4017  // Positionne parametres
4018  $this->nom = $name; // TODO deprecated
4019  $this->name = $name;
4020  $this->name_alias = $alias;
4021  $this->address = $member->address;
4022  $this->zip = $member->zip;
4023  $this->town = $member->town;
4024  $this->country_code = $member->country_code;
4025  $this->country_id = $member->country_id;
4026  $this->phone = $member->phone; // Prof phone
4027  $this->email = $member->email;
4028  $this->socialnetworks = $member->socialnetworks;
4029  $this->entity = $member->entity;
4030 
4031  $this->client = 1; // A member is a customer by default
4032  $this->code_client = ($customercode ? $customercode : -1);
4033  $this->code_fournisseur = -1;
4034  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4035  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4036 
4037  $this->db->begin();
4038 
4039  // Cree et positionne $this->id
4040  $result = $this->create($user);
4041 
4042  if ($result >= 0) {
4043  // Auto-create contact on thirdparty creation
4044  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4045  // Fill fields needed by contact
4046  $this->name_bis = $member->lastname;
4047  $this->firstname = $member->firstname;
4048  $this->civility_id = $member->civility_id;
4049 
4050  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4051  $result = $this->create_individual($user);
4052 
4053  if ($result < 0) {
4054  setEventMessages($this->error, $this->errors, 'errors');
4055  $this->db->rollback();
4056  return -1;
4057  }
4058  }
4059 
4060  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4061  $sql .= " SET fk_soc = ".((int) $this->id);
4062  $sql .= " WHERE rowid = ".((int) $member->id);
4063 
4064  $resql = $this->db->query($sql);
4065  if ($resql) {
4066  $this->db->commit();
4067  return $this->id;
4068  } else {
4069  $this->error = $this->db->error();
4070 
4071  $this->db->rollback();
4072  return -1;
4073  }
4074  } else {
4075  // $this->error deja positionne
4076  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4077 
4078  $this->db->rollback();
4079  return $result;
4080  }
4081  }
4082 
4089  public function setMysoc(Conf $conf)
4090  {
4091  global $langs;
4092 
4093  $this->id = 0;
4094  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
4095  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
4096  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
4097  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
4098  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
4099  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
4100 
4101  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
4102 
4103  $this->nom = $this->name; // deprecated
4104 
4105  // We define country_id, country_code and country
4106  $country_id = $country_code = $country_label = '';
4107  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4108  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4109  $country_id = $tmp[0];
4110  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4111  $country_code = $tmp[1];
4112  $country_label = $tmp[2];
4113  } else // For backward compatibility
4114  {
4115  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4116  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4117  $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
4118  $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
4119  }
4120  }
4121  $this->country_id = $country_id;
4122  $this->country_code = $country_code;
4123  $this->country = $country_label;
4124  if (is_object($langs)) {
4125  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4126  }
4127 
4128  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4129  // We define state_id, state_code and state
4130  $state_id = 0; $state_code = $state_label = '';
4131  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4132  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4133  $state_id = $tmp[0];
4134  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4135  $state_code = $tmp[1];
4136  $state_label = $tmp[2];
4137  } else { // For backward compatibility
4138  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);
4139  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4140  $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
4141  $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
4142  }
4143  }
4144  $this->state_id = $state_id;
4145  $this->state_code = $state_code;
4146  $this->state = $state_label;
4147  if (is_object($langs)) {
4148  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4149  }
4150 
4151  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
4152  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
4153  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
4154 
4155  // Social networks
4156  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
4157  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
4158  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
4159  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
4160  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
4161  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
4162  $this->socialnetworks = array();
4163  if (!empty($this->facebook_url)) {
4164  $this->socialnetworks['facebook'] = $this->facebook_url;
4165  }
4166  if (!empty($this->twitter_url)) {
4167  $this->socialnetworks['twitter'] = $this->twitter_url;
4168  }
4169  if (!empty($this->linkedin_url)) {
4170  $this->socialnetworks['linkedin'] = $this->linkedin_url;
4171  }
4172  if (!empty($this->instagram_url)) {
4173  $this->socialnetworks['instagram'] = $this->instagram_url;
4174  }
4175  if (!empty($this->youtube_url)) {
4176  $this->socialnetworks['youtube'] = $this->youtube_url;
4177  }
4178  if (!empty($this->github_url)) {
4179  $this->socialnetworks['github'] = $this->github_url;
4180  }
4181 
4182  // Id prof generiques
4183  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
4184  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
4185  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
4186  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
4187  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
4188  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
4189  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
4190  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
4191  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
4192  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
4193  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
4194  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
4195  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
4196  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
4197  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
4198  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
4199  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
4200  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
4201 
4202  // Define if company use vat or not
4203  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4204 
4205  // Define if company use local taxes
4206  $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);
4207  $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);
4208  }
4209 
4217  public function initAsSpecimen()
4218  {
4219  $now = dol_now();
4220 
4221  // Initialize parameters
4222  $this->id = 0;
4223  $this->entity = 1;
4224  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4225  $this->nom = $this->name; // For backward compatibility
4226  $this->ref_ext = 'Ref ext';
4227  $this->specimen = 1;
4228  $this->address = '21 jump street';
4229  $this->zip = '99999';
4230  $this->town = 'MyTown';
4231  $this->state_id = 1;
4232  $this->state_code = 'AA';
4233  $this->state = 'MyState';
4234  $this->country_id = 1;
4235  $this->country_code = 'FR';
4236  $this->email = 'specimen@specimen.com';
4237  $this->socialnetworks = array(
4238  'skype' => 'tom.hanson',
4239  'twitter' => 'tomhanson',
4240  'facebook' => 'tomhanson',
4241  'linkedin' => 'tomhanson',
4242  );
4243  $this->url = 'http://www.specimen.com';
4244 
4245  $this->phone = '0909090901';
4246  $this->fax = '0909090909';
4247 
4248  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4249  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4250  $this->capital = 10000;
4251  $this->client = 1;
4252  $this->prospect = 1;
4253  $this->fournisseur = 1;
4254  $this->tva_assuj = 1;
4255  $this->tva_intra = 'EU1234567';
4256  $this->note_public = 'This is a comment (public)';
4257  $this->note_private = 'This is a comment (private)';
4258 
4259  $this->idprof1 = 'idprof1';
4260  $this->idprof2 = 'idprof2';
4261  $this->idprof3 = 'idprof3';
4262  $this->idprof4 = 'idprof4';
4263  $this->idprof5 = 'idprof5';
4264  $this->idprof6 = 'idprof6';
4265  return 1;
4266  }
4267 
4274  public function useLocalTax($localTaxNum = 0)
4275  {
4276  $sql = "SELECT t.localtax1, t.localtax2";
4277  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4278  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4279  $sql .= " AND t.active = 1";
4280  if (empty($localTaxNum)) {
4281  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4282  } elseif ($localTaxNum == 1) {
4283  $sql .= " AND t.localtax1_type <> '0'";
4284  } elseif ($localTaxNum == 2) {
4285  $sql .= " AND t.localtax2_type <> '0'";
4286  }
4287 
4288  $resql = $this->db->query($sql);
4289  if ($resql) {
4290  return ($this->db->num_rows($resql) > 0);
4291  } else {
4292  return false;
4293  }
4294  }
4295 
4301  public function useNPR()
4302  {
4303  $sql = "SELECT t.rowid";
4304  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4305  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4306  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4307 
4308  dol_syslog("useNPR", LOG_DEBUG);
4309  $resql = $this->db->query($sql);
4310  if ($resql) {
4311  return ($this->db->num_rows($resql) > 0);
4312  } else {
4313  return false;
4314  }
4315  }
4316 
4323  public function useRevenueStamp()
4324  {
4325  $sql = "SELECT COUNT(*) as nb";
4326  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4327  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4328  $sql .= " AND r.active = 1";
4329 
4330  dol_syslog("useRevenueStamp", LOG_DEBUG);
4331  $resql = $this->db->query($sql);
4332  if ($resql) {
4333  $obj = $this->db->fetch_object($resql);
4334  return (($obj->nb > 0) ?true:false);
4335  } else {
4336  $this->error = $this->db->lasterror();
4337  return false;
4338  }
4339  }
4340 
4346  public function getLibProspLevel()
4347  {
4348  return $this->LibProspLevel($this->fk_prospectlevel);
4349  }
4350 
4351  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4358  public function LibProspLevel($fk_prospectlevel)
4359  {
4360  // phpcs:enable
4361  global $langs;
4362 
4363  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4364  // If lib not found in language file, we get label from cache/databse
4365  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4366  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4367  }
4368  return $lib;
4369  }
4370 
4378  public function getLibProspCommStatut($mode = 0, $label = '')
4379  {
4380  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4381  }
4382 
4383  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4397  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4398  {
4399  // phpcs:enable
4400  global $langs;
4401  $langs->load('customers');
4402 
4403  if ($mode == 2) {
4404  if ($status == '-1' || $status == 'ST_NO') {
4405  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4406  } elseif ($status == '0' || $status == 'ST_NEVER') {
4407  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4408  } elseif ($status == '1' || $status == 'ST_TODO') {
4409  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4410  } elseif ($status == '2' || $status == 'ST_PEND') {
4411  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4412  } elseif ($status == '3' || $status == 'ST_DONE') {
4413  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4414  } else {
4415  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);
4416  }
4417  } elseif ($mode == 3) {
4418  if ($status == '-1' || $status == 'ST_NO') {
4419  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4420  } elseif ($status == '0' || $status == 'ST_NEVER') {
4421  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4422  } elseif ($status == '1' || $status == 'ST_TODO') {
4423  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4424  } elseif ($status == '2' || $status == 'ST_PEND') {
4425  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4426  } elseif ($status == '3' || $status == 'ST_DONE') {
4427  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4428  } else {
4429  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4430  }
4431  } elseif ($mode == 4) {
4432  if ($status == '-1' || $status == 'ST_NO') {
4433  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4434  } elseif ($status == '0' || $status == 'ST_NEVER') {
4435  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4436  } elseif ($status == '1' || $status == 'ST_TODO') {
4437  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4438  } elseif ($status == '2' || $status == 'ST_PEND') {
4439  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4440  } elseif ($status == '3' || $status == 'ST_DONE') {
4441  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4442  } else {
4443  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);
4444  }
4445  }
4446 
4447  return "Error, mode/status not found";
4448  }
4449 
4456  public function getOutstandingProposals($mode = 'customer')
4457  {
4458  $table = 'propal';
4459  if ($mode == 'supplier') {
4460  $table = 'supplier_proposal';
4461  }
4462 
4463  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4464  $sql .= " WHERE fk_soc = ".((int) $this->id);
4465  if ($mode == 'supplier') {
4466  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4467  } else {
4468  $sql .= " AND entity IN (".getEntity('propal').")";
4469  }
4470 
4471  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4472 
4473  $resql = $this->db->query($sql);
4474  if ($resql) {
4475  $outstandingOpened = 0;
4476  $outstandingTotal = 0;
4477  $outstandingTotalIncTax = 0;
4478  $arrayofref = array();
4479  while ($obj = $this->db->fetch_object($resql)) {
4480  $arrayofref[$obj->rowid] = $obj->ref;
4481  $outstandingTotal += $obj->total_ht;
4482  $outstandingTotalIncTax += $obj->total_ttc;
4483  if ($obj->status != 0) {
4484  // Not a draft
4485  $outstandingOpened += $obj->total_ttc;
4486  }
4487  }
4488  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4489  } else {
4490  return array();
4491  }
4492  }
4493 
4500  public function getOutstandingOrders($mode = 'customer')
4501  {
4502  $table = 'commande';
4503  if ($mode == 'supplier') {
4504  $table = 'commande_fournisseur';
4505  }
4506 
4507  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4508  $sql .= " WHERE fk_soc = ".((int) $this->id);
4509  if ($mode == 'supplier') {
4510  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4511  } else {
4512  $sql .= " AND entity IN (".getEntity('commande').")";
4513  }
4514 
4515  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4516  $resql = $this->db->query($sql);
4517  if ($resql) {
4518  $outstandingOpened = 0;
4519  $outstandingTotal = 0;
4520  $outstandingTotalIncTax = 0;
4521  $arrayofref = array();
4522  while ($obj = $this->db->fetch_object($resql)) {
4523  $arrayofref[$obj->rowid] = $obj->ref;
4524  $outstandingTotal += $obj->total_ht;
4525  $outstandingTotalIncTax += $obj->total_ttc;
4526  if ($obj->status != 0) {
4527  // Not a draft
4528  $outstandingOpened += $obj->total_ttc;
4529  }
4530  }
4531  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4532  } else {
4533  return array();
4534  }
4535  }
4536 
4544  public function getOutstandingBills($mode = 'customer', $late = 0)
4545  {
4546  $table = 'facture';
4547  if ($mode == 'supplier') {
4548  $table = 'facture_fourn';
4549  }
4550 
4551  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4552  $paiement = $invoice->getSommePaiement();
4553  $creditnotes=$invoice->getSumCreditNotesUsed();
4554  $deposits=$invoice->getSumDepositsUsed();
4555  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4556  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4557  */
4558  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4559  $sql .= " WHERE fk_soc = ".((int) $this->id);
4560  if (!empty($late)) {
4561  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4562  }
4563  if ($mode == 'supplier') {
4564  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4565  } else {
4566  $sql .= " AND entity IN (".getEntity('invoice').")";
4567  }
4568 
4569  dol_syslog("getOutstandingBills", LOG_DEBUG);
4570  $resql = $this->db->query($sql);
4571  if ($resql) {
4572  $outstandingOpened = 0;
4573  $outstandingTotal = 0;
4574  $outstandingTotalIncTax = 0;
4575  $arrayofref = array();
4576  $arrayofrefopened = array();
4577  if ($mode == 'supplier') {
4578  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4579  $tmpobject = new FactureFournisseur($this->db);
4580  } else {
4581  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4582  $tmpobject = new Facture($this->db);
4583  }
4584  while ($obj = $this->db->fetch_object($resql)) {
4585  $arrayofref[$obj->rowid] = $obj->ref;
4586  $tmpobject->id = $obj->rowid;
4587 
4588  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4589  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4590  ) {
4591  $outstandingTotal += $obj->total_ht;
4592  $outstandingTotalIncTax += $obj->total_ttc;
4593  }
4594 
4595  $remaintopay = 0;
4596 
4597  if ($obj->paye == 0
4598  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4599  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4600  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4601  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4602  $paiement = $tmpobject->getSommePaiement();
4603  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4604  $deposits = $tmpobject->getSumDepositsUsed();
4605 
4606  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4607  $outstandingOpened += $remaintopay;
4608  }
4609 
4610  //if credit note is converted but not used
4611  // TODO Do this also for customer ?
4612  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4613  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4614  $remaintopay -= $remainingcreditnote;
4615  $outstandingOpened -= $remainingcreditnote;
4616  }
4617 
4618  if ($remaintopay) {
4619  $arrayofrefopened[$obj->rowid] = $obj->ref;
4620  }
4621  }
4622  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4623  } else {
4624  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4625  return array();
4626  }
4627  }
4628 
4635  public function getLibCustProspStatut()
4636  {
4637  return $this->LibCustProspStatut($this->client);
4638  }
4639 
4640  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4647  public function LibCustProspStatut($status)
4648  {
4649  // phpcs:enable
4650  global $langs;
4651  $langs->load('companies');
4652 
4653  if ($status == 0) {
4654  return $langs->trans("NorProspectNorCustomer");
4655  } elseif ($status == 1) {
4656  return $langs->trans("Customer");
4657  } elseif ($status == 2) {
4658  return $langs->trans("Prospect");
4659  } elseif ($status == 3) {
4660  return $langs->trans("ProspectCustomer");
4661  }
4662  }
4663 
4664 
4676  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4677  {
4678  global $conf, $user, $langs;
4679 
4680  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4681  $modelpath = "core/modules/bank/doc/";
4682 
4683  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4684  $companybankaccount = new CompanyBankAccount($this->db);
4685  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4686  if (!$result) {
4687  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4688  }
4689  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4690  } else {
4691  // Positionne le modele sur le nom du modele a utiliser
4692  if (!dol_strlen($modele)) {
4693  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4694  $modele = $conf->global->COMPANY_ADDON_PDF;
4695  } else {
4696  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4697  return 0;
4698  }
4699  }
4700 
4701  if (!isset($this->bank_account)) {
4702  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4703  $bac = new CompanyBankAccount($this->db);
4704  $result = $bac->fetch(0, $this->id);
4705  if ($result > 0) {
4706  $this->bank_account = $bac;
4707  } else {
4708  $this->bank_account = '';
4709  }
4710  }
4711 
4712  $modelpath = "core/modules/societe/doc/";
4713 
4714  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4715  }
4716 
4717  return $result;
4718  }
4719 
4720 
4732  public function setCategories($categories, $type_categ)
4733  {
4734  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4735 
4736  // Decode type
4737  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4738  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4739  return -1;
4740  }
4741 
4742  return parent::setCategoriesCommon($categories, $type_categ);
4743  }
4744 
4752  public function setSalesRep($salesrep, $onlyAdd = false)
4753  {
4754  global $user;
4755 
4756  // Handle single user
4757  if (!is_array($salesrep)) {
4758  $salesrep = array($salesrep);
4759  }
4760 
4761  $to_del = array(); // Nothing to delete
4762  $to_add = $salesrep;
4763  if ($onlyAdd === false) {
4764  // Get current users
4765  $existing = $this->getSalesRepresentatives($user, 1);
4766 
4767  // Diff
4768  if (is_array($existing)) {
4769  $to_del = array_diff($existing, $salesrep);
4770  $to_add = array_diff($salesrep, $existing);
4771  }
4772  }
4773 
4774  $error = 0;
4775 
4776  // Process
4777  foreach ($to_del as $del) {
4778  $this->del_commercial($user, $del);
4779  }
4780  foreach ($to_add as $add) {
4781  $result = $this->add_commercial($user, $add);
4782  if ($result < 0) {
4783  $error++;
4784  break;
4785  }
4786  }
4787 
4788  return $error ? -1 : 1;
4789  }
4790 
4797  public function setThirdpartyType($typent_id)
4798  {
4799  if ($this->id) {
4800  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
4801  $sql .= " SET fk_typent = ".($typent_id > 0 ? $typent_id : "null");
4802  $sql .= " WHERE rowid = ".((int) $this->id);
4803  dol_syslog(get_class($this).'::setThirdpartyType', LOG_DEBUG);
4804  $resql = $this->db->query($sql);
4805  if ($resql) {
4806  $this->typent_id = $typent_id;
4807  $this->typent_code = dol_getIdFromCode($this->db, $this->$typent_id, 'c_typent', 'id', 'code');
4808  return 1;
4809  } else {
4810  return -1;
4811  }
4812  } else {
4813  return -1;
4814  }
4815  }
4816 
4826  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4827  {
4828  if ($origin_id == $dest_id) {
4829  dol_syslog('Error: Try to merge a thirdparty into itself');
4830  return false;
4831  }
4832 
4837  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4838  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4839  $sql .= ' SELECT fk_user ';
4840  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4841  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
4842 
4843  $resql = $dbs->query($sql);
4844  while ($obj = $dbs->fetch_object($resql)) {
4845  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
4846  }
4847 
4852  $tables = array(
4853  'societe_address',
4854  'societe_commerciaux',
4855  'societe_prices',
4856  'societe_remise',
4857  'societe_remise_except',
4858  'societe_rib'
4859  );
4860 
4861  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4862  }
4863 
4872  public function setAccountancyCode($type, $value)
4873  {
4874  global $user, $langs, $conf;
4875 
4876  $this->db->begin();
4877 
4878  $field = 'accountancy_code_sell';
4879  if ($type == 'buy') {
4880  $field = 'accountancy_code_buy';
4881  } elseif ($type == 'sell') {
4882  $field = 'accountancy_code_sell';
4883  } else {
4884  return -1;
4885  }
4886 
4887  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
4888  $sql .= $field." = '".$this->db->escape($value)."'";
4889  $sql .= " WHERE rowid = ".((int) $this->id);
4890 
4891  dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
4892  $resql = $this->db->query($sql);
4893 
4894  if ($resql) {
4895  // Call triggers
4896  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
4897  $interface = new Interfaces($this->db);
4898  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
4899  if ($result < 0) {
4900  $this->errors = $interface->errors;
4901  $this->db->rollback();
4902  return -1;
4903  }
4904  // End call triggers
4905 
4906  $this->$field = $value;
4907 
4908  $this->db->commit();
4909  return 1;
4910  } else {
4911  $this->error = $this->db->lasterror();
4912  $this->db->rollback();
4913  return -1;
4914  }
4915  }
4916 
4923  public function fetchPartnerships($mode)
4924  {
4925  global $langs;
4926 
4927  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
4928 
4929 
4930  $this->partnerships[] = array();
4931 
4932  return 1;
4933  }
4934 }
fetchPartnerships($mode)
Function to get partnerships array.
__construct($db)
Constructor.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases)...
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
check_codeclient()
Check customer code.
const PROSPECT
Third party is a prospect.
create(User $user)
Create third party in database.
setParent($id)
Define parent company of current company.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
getLibStatut($mode=0)
Return label of status (activity, closed)
Class to stock current configuration.
Definition: conf.class.php:33
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
dol_substr($string, $start, $length, $stringencoding= '', $trunconbytes=0)
Make a substring.
del_commercial(User $user, $commid)
Add link to sales representative.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
initAsSpecimen()
Initialise an instance with random values.
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
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.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
const CUSTOMER_AND_PROSPECT
Third party is a customer and a prospect.
add_commercial(User $user, $commid)
Add link to sales representative.
$conf db
API class for accounts.
Definition: inc.php:41
setCategories($categories, $type_categ)
Sets object to supplied categories.
Class to manage contact/addresses.
getOutstandingBills($mode= 'customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
dol_now($mode= 'auto')
Return date for now.
const NO_CUSTOMER
Third party is no customer.
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
dol_print_phone($phone, $countrycode= '', $cid=0, $socid=0, $addlink= '', $separ="&nbsp;", $withpicto= '', $titlealt= '', $adddivfloat=0)
Format phone numbers according to country.
setEventMessage($mesgs, $style= 'mesgs')
Set event message in dol_events session object.
getOutstandingProposals($mode= 'customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Class to manage bank accounts description of third parties.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
clean_url($url, $http=1)
Clean an url string.
dol_string_nospecial($str, $newstr= '_', $badcharstoreplace= '', $badcharstoremove= '')
Clean a string from all punctuation characters to use it as a ref or login.
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:446
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
Class to manage suppliers invoices.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+&#39; &#39;+name+&#39; &#39;+lastname)
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:122
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...
dol_getIdFromCode($db, $key, $tablename, $fieldkey= 'code', $fieldid= 'id', $entityfilter=0, $filters= '')
Return an id or code from a code or id.
has_projects()
Indicates if the company has projects.
img_action($titlealt, $numaction, $picto= '')
Show logo action.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
create_from_member(Adherent $member, $socname= '', $socalias= '', $customercode= '')
Create a third party into database from a member object.
LoadSupplierCateg()
Load the list of provider categories.
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
const NO_SUPPLIER
Third party is no supplier.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
getOutstandingOrders($mode= 'customer')
Return amount of order not yet paid and total and list of all orders.
getLibProspLevel()
Return prostect level.
Class to manage third parties objects (customers, suppliers, prospects...)
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
Class to manage categories.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
set_as_client()
Define third party as a customer.
const CUSTOMER
Third party is a customer.
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:1382
Class to manage withdrawal receipts.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
getNomUrl($withpicto=0, $option= '', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target= '')
Return a link on thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
contact_get_property($rowid, $mode)
Return property of contact from its id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
Class to manage members of a foundation.
fetch($rowid, $ref= '', $ref_ext= '', $barcode= '', $idprof1= '', $idprof2= '', $idprof3= '', $idprof4= '', $idprof5= '', $idprof6= '', $email= '', $ref_alias= '')
Load a third party from database into memory.
LibProspCommStatut($status, $mode=0, $label= '', $picto= '')
Return label of a given status.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
info($id)
Load information for tab info.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
deleteExtraFields()
Delete all extra fields values for the current object.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
getState($id, $withcode= '', $dbtouse=0, $withregion=0, $outputlangs= '', $entconv=1)
Return state translated from an id.
static getIdFromCode($dbs, $code)
Get id of currency from code.
display_rib($mode= 'label')
Return bank number property of thirdparty (label or rum)
getAvailableDiscounts($user= '', $filter= '', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
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.
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->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->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
get_codecompta($type)
Assigns a accounting code from the accounting code module.
getTypeUrl($withpicto=0, $option= '', $notooltip=0, $tag= 'a')
Return link(s) on type of thirdparty (with picto)
contact_array_objects()
Returns the contact list of this company.
const TYPE_CREDIT_NOTE
Credit note invoice.
trait CommonIncoterm
Superclass for incoterm classes.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
call_trigger($triggerName, $user)
Call trigger based on this instance.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
create_individual(User $user, $no_email=0, $tags=array())
Create a contact/address from thirdparty.
$object ref
Definition: info.php:77
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Class to manage absolute discounts.
getLibProspCommStatut($mode=0, $label= '')
Return status of prospect.
const SUPPLIER
Third party is a supplier.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;…&#39; if string larger than length. ...
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
query($query, $usesavepoint=0, $type= 'auto', $result_mode=0)
Execute a SQL request and return the resultset.
contact_array()
Returns the contact list of this company.
Class to manage invoices.
setMysoc(Conf $conf)
Set properties with value into $conf.
set_remise_except($remise, User $user, $desc, $vatrate= '', $discount_type=0)
Add a discount for third party.
LibStatut($status, $mode=0)
Return the label of a given status.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
getParentsForCompany($company_id, $parents=[])
Get parents for company.
update($id, $user= '', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action= 'update', $nosyncmember=1)
Update parameters of third party.
check_codefournisseur()
Check supplier code.
setThirdpartyType($typent_id)
Define third-party type of current company.
get_all_rib()
Return Array of RIB.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren...
LibCustProspStatut($status)
Return the label of the customer/prospect status.
getCountry($searchkey, $withcode= '', $dbtouse=0, $outputlangs= '', $entconv=1, $searchlabel= '')
Return country label, code or id from an id, code or label.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
Class to manage triggers.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
contact_property_array($mode= 'email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
insertExtraLanguages($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.