dolibarr  20.0.0-alpha
societe.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9  * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2013-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
12  * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16  * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17  * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18  * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21  * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22  * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23  * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
24  *
25  * This program is free software; you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation; either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program. If not, see <https://www.gnu.org/licenses/>.
37  */
38 
44 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46 require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47 require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
49 
50 
54 class Societe extends CommonObject
55 {
56  use CommonIncoterm;
58  use CommonPeople;
59 
63  public $module = 'societe';
64 
68  public $element = 'societe';
69 
73  public $table_element = 'societe';
74 
78  public $fk_element = 'fk_soc';
79 
83  public $fieldsforcombobox = 'nom,name_alias';
84 
88  protected $childtables = array(
89  'supplier_proposal' => array('name' => 'SupplierProposal'),
90  'propal' => array('name' => 'Proposal'),
91  'commande' => array('name' => 'Order'),
92  'facture' => array('name' => 'Invoice'),
93  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
94  'contrat' => array('name' => 'Contract'),
95  'fichinter' => array('name' => 'Fichinter'),
96  'facture_fourn' => array('name' => 'SupplierInvoice'),
97  'commande_fournisseur' => array('name' => 'SupplierOrder'),
98  'projet' => array('name' => 'Project'),
99  'expedition' => array('name' => 'Shipment'),
100  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
101  );
102 
107  protected $childtablesoncascade = array(
108  'societe_prices',
109  'product_fournisseur_price',
110  'product_customer_price_log',
111  'product_customer_price',
112  '@Contact:/contact/class/contact.class.php:fk_soc',
113  'adherent',
114  'societe_account',
115  'societe_rib',
116  'societe_remise',
117  'societe_remise_except',
118  'societe_commerciaux',
119  'categorie',
120  'notify',
121  'notify_def',
122  'actioncomm',
123  );
124 
128  public $picto = 'company';
129 
134  public $ismultientitymanaged = 1;
135 
139  public $isextrafieldmanaged = 1;
140 
145  public $restrictiononfksoc = 1;
146 
150  public $oldcopy;
151 
156  public $SupplierCategories = array();
157 
162  public $prefixCustomerIsRequired;
163 
193  public $fields = array(
194  'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
195  'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
196  'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
197  'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
198  'nom' => array('type' => 'varchar(128)', 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1),
199  'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
200  'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
201  'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
202  'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
203  'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
204  'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
205  'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
206  'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
207  'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
208  'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
209  'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
210  'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
211  'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
212  'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
213  'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
214  'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
215  'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
216  'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
217  'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
218  'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
219  'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
220  'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
221  'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
222  'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
223  'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
224  'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
225  'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
226  'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
227  'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
228  'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
229  'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
230  'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
231  'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
232  'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
233  'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
234  'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
235  'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
236  'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
237  'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
238  'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
239  'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
240  'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
241  'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
242  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
243  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
244  'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
245  'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
246  'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
247  'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
248  'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
249  'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
250  'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
251  'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
252  'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
253  'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
254  'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
255  'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
256  'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
257  'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
258  'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
259  'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
260  'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES")', 'visible' => -1, 'position' => 365),
261  'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
262  'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
263  'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
264  'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
265  'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
266  'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
267  'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
268  'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
269  'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
270  'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
271  'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
272  'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
273  'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
274  'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
275  'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
276  'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
277  'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
278  );
279 
283  public $entity;
284 
291  public $nom;
292 
296  public $name;
297 
302  public $name_alias;
303 
307  public $particulier;
308 
313  public $status = 1;
314 
318  public $region_code;
319 
323  public $region;
324 
328  public $country_id;
329 
335  public $departement_code;
336 
342  public $departement;
343 
349  public $pays;
350 
355  public $phone;
360  public $phone_mobile;
365  public $fax;
366 
371  public $email;
372 
377  public $no_email;
378 
384  public $skype;
385 
391  public $twitter;
392 
398  public $facebook;
399 
405  public $linkedin;
406 
411  public $url;
412 
417  public $barcode;
418 
419  // 6 professional id (usage depends on country)
420 
425  public $idprof1;
426 
432  public $siren;
433 
434 
439  public $idprof2;
440 
446  public $siret;
447 
452  public $idprof3;
453 
459  public $ape;
460 
465  public $idprof4;
466 
471  public $idprof5;
472 
477  public $idprof6;
478 
483  public $idprof7;
484 
489  public $idprof8;
490 
495  public $idprof9;
496 
501  public $idprof10;
502 
507  public $socialobject;
508 
512  public $prefix_comm;
513 
517  public $tva_assuj = 1;
518 
522  public $tva_intra;
523 
527  public $vat_reverse_charge = 0;
528 
529  // Local taxes
530  public $localtax1_assuj;
531  public $localtax1_value;
532  public $localtax2_assuj;
533  public $localtax2_value;
534 
538  public $managers;
539 
543  public $capital;
544 
548  public $typent_id = 0;
549  public $typent_code;
550  public $effectif;
551  public $effectif_id = 0;
552  public $forme_juridique_code;
553  public $forme_juridique = 0;
554 
555  public $remise_percent;
556  public $remise_supplier_percent;
557 
558  public $mode_reglement_id;
559  public $cond_reglement_id;
560  public $deposit_percent;
561  public $mode_reglement_supplier_id;
562  public $cond_reglement_supplier_id;
563  public $transport_mode_supplier_id;
564 
568  public $fk_prospectlevel;
569 
573  public $name_bis;
574 
575  //Log data
576 
581  public $date_modification;
582 
588  public $user_modification;
589 
594  public $date_creation;
595 
601  public $user_creation;
602 
607  public $client = 0;
608 
613  public $prospect = 0;
614 
619  public $fournisseur;
620 
625  public $code_client;
626 
631  public $code_fournisseur;
632 
637  public $code_compta_client;
638 
645  public $code_compta;
646 
651  public $accountancy_code_customer;
652 
657  public $code_compta_fournisseur;
658 
663  public $accountancy_code_supplier;
664 
669  public $code_compta_product;
670 
676  public $note;
677 
682  public $note_private;
683 
688  public $note_public;
689 
694  public $stcomm_id;
695 
700  public $stcomm_picto;
701 
706  public $status_prospect_label;
707 
712  public $price_level;
713 
717  public $outstanding_limit;
718 
722  public $order_min_amount;
723 
727  public $supplier_order_min_amount;
728 
733  public $commercial_id;
734 
739  public $parent;
740 
745  public $default_lang;
746 
750  public $ref;
751 
757  public $ref_ext;
758 
765  public $import_key;
766 
771  public $webservices_url;
772 
777  public $webservices_key;
778 
782  public $logo;
783 
787  public $logo_small;
788 
792  public $logo_mini;
793 
797  public $logo_squarred;
798 
802  public $logo_squarred_small;
803 
807  public $logo_squarred_mini;
808 
812  public $accountancy_code_sell;
813 
817  public $accountancy_code_buy;
818 
819  // Multicurrency
823  public $fk_multicurrency;
824 
825  // Warehouse
829  public $fk_warehouse;
830 
834  public $multicurrency_code;
835 
836  // Fields loaded by fetchPartnerships()
837 
838  public $partnerships = array();
839 
840 
844  public $bank_account;
845 
846 
847  const STATUS_CEASED = 0;
848  const STATUS_INACTIVITY = 1;
849 
853  const NO_CUSTOMER = 0;
854 
858  const CUSTOMER = 1;
859 
863  const PROSPECT = 2;
864 
869 
873  const NO_SUPPLIER = 0;
874 
878  const SUPPLIER = 1;
879 
880 
886  public function __construct($db)
887  {
888  global $conf;
889 
890  $this->db = $db;
891 
892  $this->client = 0;
893  $this->prospect = 0;
894  $this->fournisseur = 0;
895  $this->typent_id = 0;
896  $this->effectif_id = 0;
897  $this->forme_juridique_code = 0;
898  $this->tva_assuj = 1;
899  $this->vat_reverse_charge = 0;
900  $this->status = 1;
901 
902  if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
903  $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
904  $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
905  $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
906  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
907  }
908  }
909 
910 
919  public function create(User $user, $notrigger = 0)
920  {
921  global $langs, $conf;
922 
923  $error = 0;
924 
925  // Clean parameters
926  if (empty($this->status)) {
927  $this->status = 0;
928  }
929  $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
930  $this->setUpperOrLowerCase();
931  $this->nom = $this->name; // For backward compatibility
932  if (empty($this->client)) {
933  $this->client = 0;
934  }
935  if (empty($this->fournisseur)) {
936  $this->fournisseur = 0;
937  }
938  $this->import_key = trim((string) $this->import_key);
939 
940  $this->accountancy_code_customer = trim((string) $this->code_compta);
941  $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
942  $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
943  $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
944 
945  if (!empty($this->multicurrency_code)) {
946  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
947  }
948  if (empty($this->fk_multicurrency)) {
949  $this->multicurrency_code = '';
950  $this->fk_multicurrency = 0;
951  }
952 
953  dol_syslog(get_class($this)."::create ".$this->name);
954 
955  $now = dol_now();
956 
957  if (empty($this->date_creation)) {
958  $this->date_creation = $now;
959  }
960 
961  $this->db->begin();
962 
963  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
964  if ($this->code_client == -1 || $this->code_client === 'auto') {
965  $this->get_codeclient($this, 0);
966  }
967  if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
968  $this->get_codefournisseur($this, 1);
969  }
970 
971  // Check more parameters (including mandatory setup
972  // If error, this->errors[] is filled
973  $result = $this->verify();
974 
975  if ($result >= 0) {
976  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
977 
978  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
979  $sql .= "nom";
980  $sql .= ", name_alias";
981  $sql .= ", entity";
982  $sql .= ", datec";
983  $sql .= ", fk_user_creat";
984  $sql .= ", fk_typent";
985  $sql .= ", canvas";
986  $sql .= ", status";
987  $sql .= ", ref_ext";
988  $sql .= ", fk_stcomm";
989  $sql .= ", fk_incoterms";
990  $sql .= ", location_incoterms";
991  $sql .= ", import_key";
992  $sql .= ", fk_multicurrency";
993  $sql .= ", multicurrency_code";
994  if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
995  $sql .= ", vat_reverse_charge";
996  $sql .= ", accountancy_code_buy";
997  $sql .= ", accountancy_code_sell";
998  }
999  $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1000  $sql .= " '".$this->db->escape($this->name_alias)."',";
1001  $sql .= " ".((int) $this->entity).",";
1002  $sql .= " '".$this->db->idate($this->date_creation)."'";
1003  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1004  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1005  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1006  $sql .= ", ".((int) $this->status);
1007  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1008  $sql .= ", 0";
1009  $sql .= ", ".(int) $this->fk_incoterms;
1010  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1011  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1012  $sql .= ", ".(int) $this->fk_multicurrency;
1013  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1014  if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1015  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1016  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1017  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1018  }
1019  $sql .= ")";
1020 
1021  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1022 
1023  $result = $this->db->query($sql);
1024  if ($result) {
1025  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1026 
1027  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1028 
1029  // update accountancy for this entity
1030  if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1031  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1032 
1033  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1034  $sql .= " fk_soc";
1035  $sql .= ", entity";
1036  $sql .= ", vat_reverse_charge";
1037  $sql .= ", accountancy_code_customer";
1038  $sql .= ", accountancy_code_supplier";
1039  $sql .= ", accountancy_code_buy";
1040  $sql .= ", accountancy_code_sell";
1041  $sql .= ") VALUES (";
1042  $sql .= $this->id;
1043  $sql .= ", ".((int) $conf->entity);
1044  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1045  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1046  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1047  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1048  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1049  $sql .= ")";
1050  $result = $this->db->query($sql);
1051  if (!$result) {
1052  $error++;
1053  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1054  }
1055  }
1056 
1057  // Ajout du commercial affecte
1058  if ($this->commercial_id != '' && $this->commercial_id != -1) {
1059  $this->add_commercial($user, $this->commercial_id);
1060  } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1061  // si un commercial cree un client il lui est affecte automatiquement
1062  $this->add_commercial($user, $user->id);
1063  }
1064 
1065  if ($ret >= 0) {
1066  if (! $notrigger) {
1067  // Call trigger
1068  $result = $this->call_trigger('COMPANY_CREATE', $user);
1069  if ($result < 0) {
1070  $error++;
1071  }
1072  // End call triggers
1073  }
1074  } else {
1075  $error++;
1076  }
1077 
1078  if (!$error) {
1079  dol_syslog(get_class($this)."::Create success id=".$this->id);
1080  $this->db->commit();
1081  return $this->id;
1082  } else {
1083  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1084  $this->db->rollback();
1085  return -4;
1086  }
1087  } else {
1088  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1089  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1090  $result = -1;
1091  } else {
1092  $this->error = $this->db->lasterror();
1093  $result = -2;
1094  }
1095  $this->db->rollback();
1096  return $result;
1097  }
1098  } else {
1099  $this->db->rollback();
1100  dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1101  return -3;
1102  }
1103  }
1104 
1105 
1106  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1116  public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1117  {
1118  global $conf;
1119 
1120  $error = 0;
1121 
1122  $this->db->begin();
1123 
1124  // phpcs:enable
1125  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1126  $contact = new Contact($this->db);
1127 
1128  $contact->name = $this->name_bis;
1129  $contact->firstname = $this->firstname;
1130  $contact->civility_id = $this->civility_id;
1131  $contact->socid = $this->id; // fk_soc
1132  $contact->statut = 1; // deprecated
1133  $contact->status = 1;
1134  $contact->priv = 0;
1135  $contact->country_id = $this->country_id;
1136  $contact->state_id = $this->state_id;
1137  $contact->address = $this->address;
1138  $contact->email = $this->email;
1139  $contact->zip = $this->zip;
1140  $contact->town = $this->town;
1141  $this->setUpperOrLowerCase();
1142  $contact->phone_pro = $this->phone;
1143 
1144  $contactId = $contact->create($user, $notrigger);
1145  if ($contactId < 0) {
1146  $error++;
1147  $this->error = $contact->error;
1148  $this->errors = $contact->errors;
1149  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1150  }
1151 
1152  if (empty($error) && is_array($tags) && !empty($tags)) {
1153  $result = $contact->setCategories($tags);
1154  if ($result < 0) {
1155  $error++;
1156  $this->error = $contact->error;
1157  $this->errors = array_merge($this->errors, $contact->errors);
1158  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1159  $contactId = $result;
1160  }
1161  }
1162 
1163  if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1164  $result = $contact->setNoEmail($no_email);
1165  if ($result < 0) {
1166  $this->error = $contact->error;
1167  $this->errors = array_merge($this->errors, $contact->errors);
1168  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1169  $contactId = $result;
1170  }
1171  }
1172 
1173  if (empty($error)) {
1174  dol_syslog(get_class($this)."::create_individual success");
1175  $this->db->commit();
1176  } else {
1177  $this->db->rollback();
1178  }
1179 
1180  return $contactId;
1181  }
1182 
1189  public function verify()
1190  {
1191  global $conf, $langs, $mysoc;
1192 
1193  $error = 0;
1194  $this->errors = array();
1195 
1196  $result = 0;
1197  $this->name = trim($this->name);
1198  $this->nom = $this->name; // For backward compatibility
1199 
1200  if (!$this->name) {
1201  $this->errors[] = 'ErrorBadThirdPartyName';
1202  $result = -2;
1203  }
1204 
1205  if ($this->client) {
1206  $rescode = $this->check_codeclient();
1207  if ($rescode != 0 && $rescode != -5) {
1208  if ($rescode == -1) {
1209  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1210  } elseif ($rescode == -2) {
1211  $this->errors[] = 'ErrorCustomerCodeRequired';
1212  } elseif ($rescode == -3) {
1213  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1214  } elseif ($rescode == -4) {
1215  $this->errors[] = 'ErrorPrefixRequired';
1216  } else {
1217  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1218  }
1219 
1220  $result = -3;
1221  }
1222  }
1223 
1224  if ($this->fournisseur) {
1225  $rescode = $this->check_codefournisseur();
1226  if ($rescode != 0 && $rescode != -5) {
1227  if ($rescode == -1) {
1228  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1229  } elseif ($rescode == -2) {
1230  $this->errors[] = 'ErrorSupplierCodeRequired';
1231  } elseif ($rescode == -3) {
1232  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1233  } elseif ($rescode == -4) {
1234  $this->errors[] = 'ErrorPrefixRequired';
1235  } else {
1236  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1237  }
1238  $result = -3;
1239  }
1240  }
1241 
1242  // Check for duplicate or mandatory fields defined into setup
1243  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1244  foreach ($array_to_check as $key) {
1245  $keymin = strtolower($key);
1246  if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1247  $keymin = 'code_compta';
1248  } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1249  $keymin = 'code_compta_fournisseur';
1250  }
1251  $i = (int) preg_replace('/[^0-9]/', '', $key);
1252  $vallabel = $this->$keymin;
1253 
1254  if ($i > 0) {
1255  if ($this->isACompany()) {
1256  // Check for mandatory prof id (but only if country is same than ours)
1257  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1258  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1259  if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1260  $langs->load("errors");
1261  $error++;
1262  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1263  }
1264  }
1265  }
1266 
1267  // Check for unicity on profid
1268  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1269  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1270  $langs->load("errors");
1271  $error++;
1272  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1273  }
1274  }
1275  } else {
1276  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1277  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1278  if ($key == 'EMAIL') {
1279  // Check for mandatory
1280  if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1281  $langs->load("errors");
1282  $error++;
1283  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1284  }
1285 
1286  // Check for unicity
1287  if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1288  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1289  $langs->load("errors");
1290  $error++;
1291  $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1292  }
1293  }
1294  } elseif ($key == 'TVA_INTRA') {
1295  // Check for unicity
1296  if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1297  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1298  $langs->load("errors");
1299  $error++;
1300  $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1301  }
1302  }
1303  } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1304  // Check for unicity
1305  if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1306  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1307  $langs->loadLangs(array("errors", 'compta'));
1308  $error++;
1309  $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1310  }
1311  }
1312 
1313  // Check for mandatory
1314  if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1315  $langs->loadLangs(array("errors", 'compta'));
1316  $error++;
1317  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1318  }
1319  } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1320  // Check for unicity
1321  if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1322  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1323  $langs->loadLangs(array("errors", 'compta'));
1324  $error++;
1325  $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1326  }
1327  }
1328 
1329  // Check for mandatory
1330  if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1331  $langs->loadLangs(array("errors", 'compta'));
1332  $error++;
1333  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1334  }
1335  }
1336  }
1337  }
1338 
1339  if ($error) {
1340  $result = -4;
1341  }
1342 
1343  return $result;
1344  }
1345 
1358  public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1359  {
1360  global $langs, $conf, $hookmanager;
1361 
1362  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1363 
1364  if (empty($id)) {
1365  $id = $this->id;
1366  }
1367 
1368  $error = 0;
1369 
1370  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1371 
1372  $now = dol_now();
1373 
1374  // Clean parameters
1375  $this->id = $id;
1376  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1377  $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1378  $this->nom = $this->name; // For backward compatibility
1379  $this->name_alias = trim((string) $this->name_alias);
1380  $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1381  $this->address = trim((string) $this->address);
1382  $this->zip = trim((string) $this->zip);
1383  $this->town = trim((string) $this->town);
1384  $this->state_id = (is_numeric($this->state_id)) ? (int) trim((string) $this->state_id) : 0;
1385  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1386  $this->phone = trim((string) $this->phone);
1387  $this->phone = preg_replace("/\s/", "", $this->phone);
1388  $this->phone = preg_replace("/\./", "", $this->phone);
1389  $this->phone_mobile = trim((string) $this->phone_mobile);
1390  $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1391  $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1392  $this->fax = trim((string) $this->fax);
1393  $this->fax = preg_replace("/\s/", "", $this->fax);
1394  $this->fax = preg_replace("/\./", "", $this->fax);
1395  $this->email = trim((string) $this->email);
1396  $this->url = $this->url ? clean_url($this->url, 0) : '';
1397  $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1398  $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1399  $this->idprof1 = trim((string) $this->idprof1);
1400  $this->idprof2 = trim((string) $this->idprof2);
1401  $this->idprof3 = trim((string) $this->idprof3);
1402  $this->idprof4 = trim((string) $this->idprof4);
1403  $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1404  $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1405  $this->prefix_comm = trim((string) $this->prefix_comm);
1406  $this->outstanding_limit = price2num($this->outstanding_limit);
1407  $this->order_min_amount = price2num($this->order_min_amount);
1408  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1409 
1410  $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1411  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1412  $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1413  if (empty($this->status)) {
1414  $this->status = 0;
1415  }
1416 
1417  if (!empty($this->multicurrency_code)) {
1418  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1419  }
1420  if (empty($this->fk_multicurrency)) {
1421  $this->multicurrency_code = '';
1422  $this->fk_multicurrency = 0;
1423  }
1424 
1425  // Local taxes
1426  $this->localtax1_assuj = trim($this->localtax1_assuj);
1427  $this->localtax2_assuj = trim($this->localtax2_assuj);
1428 
1429  $this->localtax1_value = trim($this->localtax1_value);
1430  $this->localtax2_value = trim($this->localtax2_value);
1431 
1432  $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1433 
1434  $this->effectif_id = trim((string) $this->effectif_id);
1435  $this->forme_juridique_code = trim((string) $this->forme_juridique_code);
1436 
1437  //Gencod
1438  $this->barcode = trim($this->barcode);
1439 
1440  // For automatic creation
1441  if ($this->code_client == -1 || $this->code_client === 'auto') {
1442  $this->get_codeclient($this, 0);
1443  }
1444  if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1445  $this->get_codefournisseur($this, 1);
1446  }
1447 
1448  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1449  $this->code_compta = $this->code_compta_client; // for backward compatibility
1450  $this->code_compta_fournisseur = (empty($this->code_compta_fournisseur) ? '' : trim($this->code_compta_fournisseur));
1451 
1452  // Check parameters. More tests are done later in the ->verify()
1453  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1454  $langs->load("errors");
1455  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1456  return -1;
1457  }
1458 
1459  $customer = false;
1460  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1461  // If $allowmodcodeclient is set and value is not set, we generate it
1462  if (empty($this->code_compta_client)) {
1463  $ret = $this->get_codecompta('customer');
1464  if ($ret < 0) {
1465  return -1;
1466  }
1467  }
1468 
1469  $customer = true;
1470  }
1471 
1472  $supplier = false;
1473  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1474  // If $allowmodcodefournisseur is set and value is not set, we generate it
1475  if (empty($this->code_compta_fournisseur)) {
1476  $ret = $this->get_codecompta('supplier');
1477  if ($ret < 0) {
1478  return -1;
1479  }
1480  }
1481 
1482  $supplier = true;
1483  }
1484 
1485  //Web services
1486  $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1487  $this->webservices_key = trim($this->webservices_key);
1488 
1489  $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1490  $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1491 
1492  //Incoterms
1493  $this->fk_incoterms = (int) $this->fk_incoterms;
1494  $this->location_incoterms = trim($this->location_incoterms);
1495 
1496  $this->db->begin();
1497 
1498  // Check name is required and codes are ok or unique.
1499  // If error, this->errors[] is filled
1500  $result = 0;
1501  if ($action != 'add' && $action != 'merge') {
1502  // We don't check when update called during a create because verify was already done.
1503  // 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
1504  $result = $this->verify();
1505 
1506  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1507  // So we can update record that were using and old numbering rule.
1508  if (is_array($this->errors)) {
1509  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1510  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1511  unset($this->errors[$key]); // Remove error message
1512  }
1513  }
1514  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1515  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1516  unset($this->errors[$key]); // Remove error message
1517  }
1518  }
1519  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1520  $result = 0;
1521  }
1522  }
1523  }
1524  $this->setUpperOrLowerCase();
1525  if ($result >= 0) {
1526  dol_syslog(get_class($this)."::update verify ok or not done");
1527 
1528  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1529  $sql .= "entity = ".$this->db->escape($this->entity);
1530  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1531  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1532  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1533  $sql .= ",address = '".$this->db->escape($this->address)."'";
1534 
1535  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1536  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1537 
1538  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1539  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1540 
1541  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1542  $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1543  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1544  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1545  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1546  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1547 
1548  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1549 
1550  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1551  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1552 
1553  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1554  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1555  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1556  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1557  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1558  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1559 
1560  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1561  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1562  if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1563  $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1564  }
1565  $sql .= ",status = ".((int) $this->status);
1566 
1567  // Local taxes
1568  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1569  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1570  if ($this->localtax1_assuj == 1) {
1571  if ($this->localtax1_value != '') {
1572  $sql .= ",localtax1_value =".$this->localtax1_value;
1573  } else {
1574  $sql .= ",localtax1_value =0.000";
1575  }
1576  } else {
1577  $sql .= ",localtax1_value =0.000";
1578  }
1579 
1580  if ($this->localtax2_assuj == 1) {
1581  if ($this->localtax2_value != '') {
1582  $sql .= ",localtax2_value =".$this->localtax2_value;
1583  } else {
1584  $sql .= ",localtax2_value =0.000";
1585  }
1586  } else {
1587  $sql .= ",localtax2_value =0.000";
1588  }
1589 
1590  $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1591 
1592  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1593 
1594  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1595  if (isset($this->stcomm_id)) {
1596  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1597  }
1598  if (isset($this->typent_id)) {
1599  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1600  }
1601 
1602  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1603 
1604  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1605  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1606  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1607  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1608  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1609  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1610  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1611  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1612 
1613  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1614  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1615  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1616  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1617  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1618  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1619  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1620  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1621  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1622  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1623  if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1624  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1625  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1626  if ($customer) {
1627  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1628  }
1629 
1630  if ($supplier) {
1631  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1632  }
1633  }
1634  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1635  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1636 
1637  //Incoterms
1638  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1639  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1640 
1641  if ($customer) {
1642  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1643  }
1644 
1645  if ($supplier) {
1646  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1647  }
1648  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1649  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1650  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1651  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1652  $sql .= " WHERE rowid = ".(int) $id;
1653 
1654  $resql = $this->db->query($sql);
1655  if ($resql) {
1656  if (is_object($this->oldcopy)) { // If we have information on old values
1657  if ($this->oldcopy->country_id != $this->country_id) {
1658  unset($this->country_code);
1659  unset($this->country);
1660  }
1661  if ($this->oldcopy->state_id != $this->state_id) {
1662  unset($this->state_code);
1663  unset($this->state);
1664  }
1665  } else {
1666  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1667  unset($this->country);
1668  unset($this->state_code);
1669  unset($this->state);
1670  }
1671 
1672  $nbrowsaffected = $this->db->affected_rows($resql);
1673 
1674  if (!$error && $nbrowsaffected) {
1675  // Update information on linked member if it is an update
1676  if (!$nosyncmember && isModEnabled('member')) {
1677  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1678 
1679  dol_syslog(get_class($this)."::update update linked member");
1680 
1681  $lmember = new Adherent($this->db);
1682  $result = $lmember->fetch(0, 0, $this->id);
1683 
1684  if ($result > 0) {
1685  $lmember->company = $this->name;
1686  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1687  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1688  $lmember->address = $this->address;
1689  $lmember->zip = $this->zip;
1690  $lmember->town = $this->town;
1691  $lmember->email = $this->email;
1692  $lmember->socialnetworks = $this->socialnetworks;
1693  $lmember->phone = $this->phone;
1694  $lmember->state_id = $this->state_id;
1695  $lmember->country_id = $this->country_id;
1696  $lmember->default_lang = $this->default_lang;
1697 
1698  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1699  if ($result < 0) {
1700  $this->error = $lmember->error;
1701  $this->errors = array_merge($this->errors, $lmember->errors);
1702  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1703  $error++;
1704  }
1705  } elseif ($result < 0) {
1706  $this->error = $lmember->error;
1707  $error++;
1708  }
1709  }
1710  }
1711 
1712  $action = 'update';
1713 
1714  // update accountancy for this entity
1715  if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1716  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1717 
1718  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1719  $sql .= " fk_soc";
1720  $sql .= ", entity";
1721  $sql .= ", vat_reverse_charge";
1722  $sql .= ", accountancy_code_customer";
1723  $sql .= ", accountancy_code_supplier";
1724  $sql .= ", accountancy_code_buy";
1725  $sql .= ", accountancy_code_sell";
1726  $sql .= ") VALUES (";
1727  $sql .= $this->id;
1728  $sql .= ", ".$conf->entity;
1729  $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1730  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1731  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1732  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1733  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1734  $sql .= ")";
1735  $result = $this->db->query($sql);
1736  if (!$result) {
1737  $error++;
1738  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1739  }
1740  }
1741 
1742  // Actions on extra fields
1743  if (!$error) {
1744  $result = $this->insertExtraFields();
1745  if ($result < 0) {
1746  $error++;
1747  }
1748  }
1749  // Actions on extra languages
1750  if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1751  $result = $this->insertExtraLanguages();
1752  if ($result < 0) {
1753  $error++;
1754  }
1755  }
1756 
1757  if (!$error && $call_trigger) {
1758  // Call trigger
1759  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1760  if ($result < 0) {
1761  $error++;
1762  }
1763  // End call triggers
1764  }
1765 
1766  if (!$error) {
1767  dol_syslog(get_class($this)."::Update success");
1768  $this->db->commit();
1769  return 1;
1770  } else {
1771  $this->db->rollback();
1772  return -1;
1773  }
1774  } else {
1775  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1776  // Doublon
1777  $this->error = $langs->trans("ErrorDuplicateField");
1778  $result = -1;
1779  } else {
1780  $this->error = $this->db->lasterror();
1781  $result = -2;
1782  }
1783  $this->db->rollback();
1784  return $result;
1785  }
1786  } else {
1787  $this->db->rollback();
1788  dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1789  return -3;
1790  }
1791  }
1792 
1812  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1813  {
1814  global $langs;
1815  global $conf;
1816 
1817  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email) && empty($ref_alias)) {
1818  return -1;
1819  }
1820 
1821  $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';
1822  $sql .= ', s.status, s.fk_warehouse';
1823  $sql .= ', s.price_level';
1824  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1825  $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1826  $sql .= ', s.socialnetworks';
1827  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1828  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1829  $sql .= ', s.capital, s.tva_intra';
1830  $sql .= ', s.fk_typent as typent_id';
1831  $sql .= ', s.fk_effectif as effectif_id';
1832  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1833  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1834  if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1835  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1836  $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1837  } else {
1838  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1839  $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1840  }
1841  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1842  $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';
1843  $sql .= ', s.fk_account, s.tva_assuj';
1844  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1845  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1846  $sql .= ', s.fk_shipping_method';
1847  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1848  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1849  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1850  $sql .= ', fj.libelle as forme_juridique';
1851  $sql .= ', e.libelle as effectif';
1852  $sql .= ', c.code as country_code, c.label as country';
1853  $sql .= ', d.code_departement as state_code, d.nom as state';
1854  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1855  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1856  $sql .= ', te.code as typent_code';
1857  $sql .= ', i.libelle as label_incoterms';
1858  if (!isModEnabled('multicompany')) {
1859  $sql .= ', s.remise_client, s.remise_supplier';
1860  } else {
1861  $sql .= ', sr.remise_client, sr2.remise_supplier';
1862  }
1863  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1864  if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1865  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1866  }
1867  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1868  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1869  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1870  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1871  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1872  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1873  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1874  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1875  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1876  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1877  if (isModEnabled('multicompany')) {
1878  $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').'))';
1879  $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').'))';
1880  }
1881  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1882 
1883  // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1884  if ($is_client) {
1885  $sql .= ' AND s.client > 0';
1886  }
1887  if ($is_supplier) {
1888  $sql .= ' AND s.fournisseur > 0';
1889  } // if both false, no test (the thirdparty can be client and/or supplier)
1890 
1891  if ($rowid) {
1892  $sql .= ' AND s.rowid = '.((int) $rowid);
1893  }
1894  if ($ref) {
1895  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1896  }
1897  if ($ref_alias) {
1898  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1899  }
1900  if ($ref_ext) {
1901  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1902  }
1903  if ($barcode) {
1904  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1905  }
1906  if ($idprof1) {
1907  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1908  }
1909  if ($idprof2) {
1910  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1911  }
1912  if ($idprof3) {
1913  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1914  }
1915  if ($idprof4) {
1916  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1917  }
1918  if ($idprof5) {
1919  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1920  }
1921  if ($idprof6) {
1922  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1923  }
1924  if ($email) {
1925  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1926  }
1927 
1928  $resql = $this->db->query($sql);
1929  if ($resql) {
1930  $num = $this->db->num_rows($resql);
1931  if ($num > 1) {
1932  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1933  dol_syslog($this->error, LOG_ERR);
1934  $result = -2;
1935  } elseif ($num) { // $num = 1
1936  $obj = $this->db->fetch_object($resql);
1937 
1938  $this->id = $obj->rowid;
1939  $this->entity = $obj->entity;
1940  $this->canvas = $obj->canvas;
1941 
1942  $this->ref = $obj->rowid;
1943  $this->name = $obj->name;
1944  $this->nom = $obj->name; // deprecated
1945  $this->name_alias = $obj->name_alias;
1946  $this->ref_ext = $obj->ref_ext;
1947 
1948  $this->date_creation = $this->db->jdate($obj->date_creation);
1949  $this->date_modification = $this->db->jdate($obj->date_modification);
1950  $this->user_creation_id = $obj->fk_user_creat;
1951  $this->user_modification_id = $obj->fk_user_modif;
1952 
1953  $this->address = $obj->address;
1954  $this->zip = $obj->zip;
1955  $this->town = $obj->town;
1956 
1957  $this->country_id = $obj->country_id;
1958  $this->country_code = $obj->country_id ? $obj->country_code : '';
1959  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1960 
1961  $this->state_id = $obj->state_id;
1962  $this->state_code = $obj->state_code;
1963  $this->region_id = $obj->region_id;
1964  $this->region_code = $obj->region_code;
1965  $this->state = ($obj->state != '-' ? $obj->state : '');
1966 
1967  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1968  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1969  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1970  $this->status_prospect_label = $label; // label status prospect
1971  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1972 
1973  $this->email = $obj->email;
1974  $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1975 
1976  $this->url = $obj->url;
1977  $this->phone = $obj->phone;
1978  $this->phone_mobile = $obj->phone_mobile;
1979  $this->fax = $obj->fax;
1980 
1981  $this->parent = $obj->parent;
1982 
1983  $this->idprof1 = $obj->idprof1;
1984  $this->idprof2 = $obj->idprof2;
1985  $this->idprof3 = $obj->idprof3;
1986  $this->idprof4 = $obj->idprof4;
1987  $this->idprof5 = $obj->idprof5;
1988  $this->idprof6 = $obj->idprof6;
1989 
1990  $this->capital = $obj->capital;
1991 
1992  $this->code_client = $obj->code_client;
1993  $this->code_fournisseur = $obj->code_fournisseur;
1994 
1995  $this->code_compta = $obj->code_compta; // For backward compatibility
1996  $this->code_compta_client = $obj->code_compta;
1997  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1998 
1999  $this->barcode = $obj->barcode;
2000 
2001  $this->tva_assuj = $obj->tva_assuj;
2002  $this->tva_intra = $obj->tva_intra;
2003 
2004  if (!empty($obj->spe_vat_reverse_charge)) {
2005  $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2006  } elseif (!empty($obj->soc_vat_reverse_charge)) {
2007  $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2008  } else {
2009  $this->vat_reverse_charge = 0;
2010  }
2011 
2012  $this->status = $obj->status;
2013 
2014  // Local Taxes
2015  $this->localtax1_assuj = $obj->localtax1_assuj;
2016  $this->localtax2_assuj = $obj->localtax2_assuj;
2017 
2018  $this->localtax1_value = $obj->localtax1_value;
2019  $this->localtax2_value = $obj->localtax2_value;
2020 
2021  $this->typent_id = $obj->typent_id;
2022  $this->typent_code = $obj->typent_code;
2023 
2024  $this->effectif_id = $obj->effectif_id;
2025  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2026 
2027  $this->forme_juridique_code = $obj->forme_juridique_code;
2028  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2029 
2030  $this->fk_prospectlevel = $obj->fk_prospectlevel;
2031 
2032  $this->prefix_comm = $obj->prefix_comm;
2033 
2034  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2035  $this->remise_supplier_percent = $obj->remise_supplier;
2036 
2037  $this->mode_reglement_id = $obj->mode_reglement;
2038  $this->cond_reglement_id = $obj->cond_reglement;
2039  $this->deposit_percent = $obj->deposit_percent;
2040  $this->transport_mode_id = $obj->transport_mode;
2041  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2042  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2043  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2044  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2045  $this->fk_account = $obj->fk_account;
2046 
2047  $this->client = $obj->client;
2048  $this->fournisseur = $obj->fournisseur;
2049 
2050  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2051  $this->note_private = $obj->note_private;
2052  $this->note_public = $obj->note_public;
2053  $this->model_pdf = $obj->model_pdf;
2054  $this->default_lang = $obj->default_lang;
2055  $this->logo = $obj->logo;
2056  $this->logo_squarred = $obj->logo_squarred;
2057 
2058  $this->webservices_url = $obj->webservices_url;
2059  $this->webservices_key = $obj->webservices_key;
2060 
2061  $this->accountancy_code_buy = $obj->accountancy_code_buy;
2062  $this->accountancy_code_sell = $obj->accountancy_code_sell;
2063 
2064  $this->outstanding_limit = $obj->outstanding_limit;
2065  $this->order_min_amount = $obj->order_min_amount;
2066  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2067 
2068  // multiprix
2069  $this->price_level = $obj->price_level;
2070 
2071  // warehouse
2072  $this->fk_warehouse = $obj->fk_warehouse;
2073 
2074  $this->import_key = $obj->import_key;
2075 
2076  //Incoterms
2077  $this->fk_incoterms = $obj->fk_incoterms;
2078  $this->location_incoterms = $obj->location_incoterms;
2079  $this->label_incoterms = $obj->label_incoterms;
2080 
2081  // multicurrency
2082  $this->fk_multicurrency = $obj->fk_multicurrency;
2083  $this->multicurrency_code = $obj->multicurrency_code;
2084 
2085  // pdf
2086  $this->model_pdf = $obj->model_pdf;
2087  $this->last_main_doc = $obj->last_main_doc;
2088 
2089  $result = 1;
2090 
2091  // fetch optionals attributes and labels
2092  $this->fetch_optionals();
2093  } else {
2094  $result = 0;
2095  }
2096 
2097  $this->db->free($resql);
2098  } else {
2099  $this->error = $this->db->lasterror();
2100  $this->errors[] = $this->db->lasterror();
2101  $result = -3;
2102  }
2103 
2104  // Use first price level if level not defined for third party
2105  if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && empty($this->price_level)) {
2106  $this->price_level = 1;
2107  }
2108 
2109  return $result;
2110  }
2111 
2120  public function delete($id, User $fuser = null, $call_trigger = 1)
2121  {
2122  global $conf, $user;
2123 
2124  if (empty($fuser)) {
2125  $fuser = $user;
2126  }
2127 
2128  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2129 
2130  $entity = isset($this->entity) ? $this->entity : $conf->entity;
2131 
2132  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2133  $error = 0;
2134 
2135  // Test if child exists
2136  $objectisused = $this->isObjectUsed($id);
2137  if (empty($objectisused)) {
2138  $this->db->begin();
2139 
2140  // User is mandatory for trigger call
2141  if (!$error && $call_trigger) {
2142  // Call trigger
2143  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2144  if ($result < 0) {
2145  $error++;
2146  }
2147  // End call triggers
2148  }
2149 
2150  if (!$error) {
2151  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2152  $static_cat = new Categorie($this->db);
2153  $toute_categs = array();
2154 
2155  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2156  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2157  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2158 
2159  // Remove each "Categorie"
2160  foreach ($toute_categs as $type => $categs_type) {
2161  foreach ($categs_type as $cat) {
2162  $cat->del_type($this, $type);
2163  }
2164  }
2165  }
2166 
2167  if (!$error) {
2168  foreach ($this->childtablesoncascade as $tabletodelete) {
2169  $deleteFromObject = explode(':', $tabletodelete, 4);
2170  if (count($deleteFromObject) >= 2) {
2171  $className = str_replace('@', '', $deleteFromObject[0]);
2172  $filepath = $deleteFromObject[1];
2173  $columnName = $deleteFromObject[2];
2174  if (dol_include_once($filepath)) {
2175  $child_object = new $className($this->db);
2176  $result = $child_object->deleteByParentField($id, $columnName);
2177  if ($result < 0) {
2178  $error++;
2179  $this->errors[] = $child_object->error;
2180  break;
2181  }
2182  } else {
2183  $error++;
2184  $this->errors[] = 'Cannot include child class file '.$filepath;
2185  break;
2186  }
2187  } else {
2188  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2189  $sql .= " WHERE fk_soc = ".((int) $id);
2190  if (!$this->db->query($sql)) {
2191  $error++;
2192  $this->errors[] = $this->db->lasterror();
2193  break;
2194  }
2195  }
2196  }
2197  }
2198 
2199  // Removed extrafields
2200  if (!$error) {
2201  $result = $this->deleteExtraFields();
2202  if ($result < 0) {
2203  $error++;
2204  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2205  }
2206  }
2207 
2208  // Remove links to subsidiaries companies
2209  if (!$error) {
2210  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2211  $sql .= " SET parent = NULL";
2212  $sql .= " WHERE parent = ".((int) $id);
2213  if (!$this->db->query($sql)) {
2214  $error++;
2215  $this->errors[] = $this->db->lasterror();
2216  }
2217  }
2218 
2219  // Remove third party
2220  if (!$error) {
2221  if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2222  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2223  $sql .= " WHERE fk_soc = ".((int) $id);
2224  if (!$this->db->query($sql)) {
2225  $error++;
2226  $this->errors[] = $this->db->lasterror();
2227  }
2228  }
2229 
2230  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2231  $sql .= " WHERE rowid = ".((int) $id);
2232  if (!$this->db->query($sql)) {
2233  $error++;
2234  $this->errors[] = $this->db->lasterror();
2235  }
2236  }
2237 
2238  if (!$error) {
2239  $this->db->commit();
2240 
2241  // Delete directory
2242  if (!empty($conf->societe->multidir_output[$entity])) {
2243  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2244  if (dol_is_dir($docdir)) {
2245  dol_delete_dir_recursive($docdir);
2246  }
2247  }
2248 
2249  return 1;
2250  } else {
2251  dol_syslog($this->error, LOG_ERR);
2252  $this->db->rollback();
2253  return -1;
2254  }
2255  } else {
2256  dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2257  }
2258  return 0;
2259  }
2260 
2261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2269  public function set_as_client()
2270  {
2271  global $conf;
2272  // phpcs:enable
2273  dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2274  return $this->setAsCustomer();
2275  }
2276 
2283  public function setAsCustomer()
2284  {
2285  if ($this->id) {
2286  $newclient = 1;
2287  if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2288  $newclient = 3; //If prospect, we keep prospect tag
2289  }
2290  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2291  $sql .= " SET client = ".((int) $newclient);
2292  $sql .= " WHERE rowid = ".((int) $this->id);
2293 
2294  $resql = $this->db->query($sql);
2295  if ($resql) {
2296  $this->client = $newclient;
2297  return 1;
2298  } else {
2299  return -1;
2300  }
2301  }
2302  return 0;
2303  }
2304 
2305  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2314  public function set_remise_client($remise, $note, User $user)
2315  {
2316  // phpcs:enable
2317  global $conf, $langs;
2318 
2319  // Parameter cleaning
2320  $note = trim($note);
2321  if (!$note) {
2322  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2323  return -2;
2324  }
2325 
2326  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2327 
2328  if ($this->id) {
2329  $this->db->begin();
2330 
2331  $now = dol_now();
2332 
2333  // Position current discount
2334  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2335  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2336  $sql .= " WHERE rowid = ".((int) $this->id);
2337  $resql = $this->db->query($sql);
2338  if (!$resql) {
2339  $this->db->rollback();
2340  $this->error = $this->db->error();
2341  return -1;
2342  }
2343 
2344  // Writes trace in discount history
2345  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2346  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2347  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2348  $sql .= " '".$this->db->escape($note)."',";
2349  $sql .= " ".((int) $user->id);
2350  $sql .= ")";
2351 
2352  $resql = $this->db->query($sql);
2353  if (!$resql) {
2354  $this->db->rollback();
2355  $this->error = $this->db->lasterror();
2356  return -1;
2357  }
2358 
2359  $this->db->commit();
2360 
2361  return 1;
2362  }
2363  return -1;
2364  }
2365 
2366  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2375  public function set_remise_supplier($remise, $note, User $user)
2376  {
2377  // phpcs:enable
2378  global $conf, $langs;
2379 
2380  // Parameter cleaning
2381  $note = trim($note);
2382  if (!$note) {
2383  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2384  return -2;
2385  }
2386 
2387  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2388 
2389  if ($this->id) {
2390  $this->db->begin();
2391 
2392  $now = dol_now();
2393 
2394  // Position current discount
2395  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2396  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2397  $sql .= " WHERE rowid = ".((int) $this->id);
2398  $resql = $this->db->query($sql);
2399  if (!$resql) {
2400  $this->db->rollback();
2401  $this->error = $this->db->error();
2402  return -1;
2403  }
2404 
2405  // Writes trace in discount history
2406  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2407  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2408  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2409  $sql .= " '".$this->db->escape($note)."',";
2410  $sql .= " ".((int) $user->id);
2411  $sql .= ")";
2412 
2413  $resql = $this->db->query($sql);
2414  if (!$resql) {
2415  $this->db->rollback();
2416  $this->error = $this->db->lasterror();
2417  return -1;
2418  }
2419 
2420  $this->db->commit();
2421  return 1;
2422  }
2423 
2424  return -1;
2425  }
2426 
2427  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2439  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2440  {
2441  // phpcs:enable
2442  global $langs;
2443 
2444  // Clean parameters
2445  $remise = price2num($remise);
2446  $desc = trim($desc);
2447 
2448  // Check parameters
2449  if (!($remise > 0)) {
2450  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2451  return -1;
2452  }
2453  if (!$desc) {
2454  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2455  return -2;
2456  }
2457 
2458  if ($this->id > 0) {
2459  // Clean vat code
2460  $reg = array();
2461  $vat_src_code = '';
2462  if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2463  $vat_src_code = $reg[1];
2464  $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2465  }
2466 
2467  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2468 
2469  $discount = new DiscountAbsolute($this->db);
2470  $discount->fk_soc = $this->id;
2471  $discount->socid = $this->id;
2472 
2473  $discount->discount_type = $discount_type;
2474 
2475  if ($price_base_type == 'TTC') {
2476  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2477  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2478  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2479  } else {
2480  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2481  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2482  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2483  }
2484 
2485  $discount->tva_tx = (float) price2num($vatrate);
2486  $discount->vat_src_code = $vat_src_code;
2487 
2488  $discount->description = $desc;
2489 
2490  $result = $discount->create($user);
2491  if ($result > 0) {
2492  return $result;
2493  } else {
2494  $this->error = $discount->error;
2495  return -3;
2496  }
2497  } else {
2498  return 0;
2499  }
2500  }
2501 
2511  public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2512  {
2513  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2514 
2515  $discountstatic = new DiscountAbsolute($this->db);
2516  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2517  if ($result >= 0) {
2518  return $result;
2519  } else {
2520  $this->error = $discountstatic->error;
2521  return -1;
2522  }
2523  }
2524 
2534  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2535  {
2536  global $conf;
2537 
2538  $reparray = array();
2539 
2540  $sql = "SELECT 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";
2541  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2542  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2543  // Condition here should be the same than into select_dolusers()
2544  if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2545  $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2546  } else {
2547  $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2548  }
2549 
2550  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2551  if (empty($sortfield) && empty($sortorder)) {
2552  $sortfield = 'u.lastname,u.firstname';
2553  $sortorder = 'ASC,ASC';
2554  }
2555  $sql .= $this->db->order($sortfield, $sortorder);
2556 
2557  $resql = $this->db->query($sql);
2558  if ($resql) {
2559  $num = $this->db->num_rows($resql);
2560  $i = 0;
2561  while ($i < $num) {
2562  $obj = $this->db->fetch_object($resql);
2563 
2564  if (empty($mode)) {
2565  $reparray[$i]['id'] = $obj->rowid;
2566  $reparray[$i]['lastname'] = $obj->lastname;
2567  $reparray[$i]['firstname'] = $obj->firstname;
2568  $reparray[$i]['email'] = $obj->email;
2569  $reparray[$i]['phone'] = $obj->office_phone;
2570  $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2571  $reparray[$i]['office_fax'] = $obj->office_fax;
2572  $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2573  $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2574  $reparray[$i]['job'] = $obj->job;
2575  $reparray[$i]['statut'] = $obj->status; // deprecated
2576  $reparray[$i]['status'] = $obj->status;
2577  $reparray[$i]['entity'] = $obj->entity;
2578  $reparray[$i]['login'] = $obj->login;
2579  $reparray[$i]['photo'] = $obj->photo;
2580  $reparray[$i]['gender'] = $obj->gender;
2581  } else {
2582  $reparray[] = $obj->rowid;
2583  }
2584  $i++;
2585  }
2586  return $reparray;
2587  } else {
2588  dol_print_error($this->db);
2589  return -1;
2590  }
2591  }
2592 
2600  public function setPriceLevel($price_level, User $user)
2601  {
2602  if ($this->id) {
2603  $now = dol_now();
2604 
2605  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2606  $sql .= " SET price_level = ".((int) $price_level);
2607  $sql .= " WHERE rowid = ".((int) $this->id);
2608 
2609  if (!$this->db->query($sql)) {
2610  dol_print_error($this->db);
2611  return -1;
2612  }
2613 
2614  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2615  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2616  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2617 
2618  if (!$this->db->query($sql)) {
2619  dol_print_error($this->db);
2620  return -1;
2621  }
2622  return 1;
2623  }
2624  return -1;
2625  }
2626 
2627  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2635  public function add_commercial(User $user, $commid)
2636  {
2637  // phpcs:enable
2638  $error = 0;
2639 
2640  if ($this->id > 0 && $commid > 0) {
2641  $this->db->begin();
2642 
2643  if (!$error) {
2644  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2645  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2646 
2647  $resql = $this->db->query($sql);
2648  if (!$resql) {
2649  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2650  $error++;
2651  }
2652  }
2653 
2654  if (!$error) {
2655  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2656  $sql .= " (fk_soc, fk_user)";
2657  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2658 
2659  $resql = $this->db->query($sql);
2660  if (!$resql) {
2661  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2662  $error++;
2663  }
2664  }
2665 
2666  if (!$error) {
2667  $this->context = array('commercial_modified' => $commid);
2668 
2669  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2670  if ($result < 0) {
2671  $error++;
2672  }
2673  }
2674 
2675  if (!$error) {
2676  $this->db->commit();
2677  return 1;
2678  } else {
2679  $this->db->rollback();
2680  return -1;
2681  }
2682  }
2683 
2684  return 0;
2685  }
2686 
2687  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2695  public function del_commercial(User $user, $commid)
2696  {
2697  // phpcs:enable
2698  $error = 0;
2699  $this->context = array('commercial_modified' => $commid);
2700 
2701  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2702  if ($result < 0) {
2703  $error++;
2704  }
2705 
2706  if ($this->id > 0 && $commid > 0) {
2707  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2708  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2709 
2710  if (!$this->db->query($sql)) {
2711  $error++;
2712  dol_syslog(get_class($this)."::del_commercial Erreur");
2713  }
2714  }
2715 
2716  if ($error) {
2717  return -1;
2718  } else {
2719  return 1;
2720  }
2721  }
2722 
2730  public function getTooltipContentArray($params)
2731  {
2732  global $conf, $langs, $user;
2733 
2734  $langs->loadLangs(['companies', 'commercial']);
2735 
2736  $datas = array();
2737 
2738  $option = $params['option'] ?? '';
2739  $nofetch = !empty($params['nofetch']);
2740 
2741  $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2742 
2743  if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2744  return ['optimize' => $langs->trans("ShowCompany")];
2745  }
2746 
2747  if (!empty($this->logo) && class_exists('Form')) {
2748  $photo = '<div class="photointooltip floatright">';
2749  $photo .= Form::showphoto('societe', $this, 0, 40, 0, 'photoref', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
2750  $photo .= '</div>';
2751  $datas['photo'] = $photo;
2752  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2753  /*$label.= '<div class="photointooltip">';
2754  $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.
2755  $label.= '</div><div style="clear: both;"></div>';*/
2756  }
2757 
2758  $datas['divopen'] = '<div class="centpercent">';
2759 
2760  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2761  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2762  } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2763  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2764  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2765  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2766  } elseif ($option == 'agenda') {
2767  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2768  } elseif ($option == 'project') {
2769  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2770  } elseif ($option == 'margin') {
2771  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2772  } elseif ($option == 'contact') {
2773  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2774  } elseif ($option == 'ban') {
2775  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2776  }
2777 
2778  // By default
2779  if (empty($datas['picto'])) {
2780  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2781  }
2782  if (isset($this->status)) {
2783  $datas['status'] = ' '.$this->getLibStatut(5);
2784  }
2785  if (isset($this->client) && isset($this->fournisseur)) {
2786  $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2787  }
2788  $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2789  if (!empty($this->name_alias) && empty($noaliasinname)) {
2790  $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2791  }
2792  if (!empty($this->email)) {
2793  $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2794  }
2795  if (!empty($this->url)) {
2796  $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2797  }
2798  if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2799  $phonelist = array();
2800  if ($this->phone) {
2801  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2802  }
2803  // deliberately not making new list because fax uses same list as phone
2804  if ($this->phone_mobile) {
2805  $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2806  }
2807  if ($this->fax) {
2808  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2809  }
2810  $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2811  }
2812 
2813  if (!empty($this->address)) {
2814  $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2815  } elseif (!empty($this->country_code)) {
2816  $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2817  }
2818  if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2819  $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2820  }
2821 
2822  if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2823  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2824  $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2825  }
2826  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2827  $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2828  }
2829  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2830  $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2831  }
2832  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2833  $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2834  }
2835  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2836  $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2837  }
2838  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2839  $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2840  }
2841  }
2842 
2843  $datas['separator'] = '<br>';
2844 
2845  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2846  $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2847  }
2848  if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2849  $langs->load('compta');
2850  $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2851  }
2852  // show categories for this record only in ajax to not overload lists
2853  if (!$nofetch && isModEnabled('category') && $this->client) {
2854  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2855  $form = new Form($this->db);
2856  $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2857  }
2858  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2859  $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2860  }
2861  if (isModEnabled('accounting') && $this->fournisseur) {
2862  $langs->load('compta');
2863  $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2864  }
2865  // show categories for this record only in ajax to not overload lists
2866  if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2867  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2868  $form = new Form($this->db);
2869  $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2870  }
2871 
2872  $datas['divclose'] = '</div>';
2873 
2874  return $datas;
2875  }
2876 
2890  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
2891  {
2892  global $conf, $langs, $hookmanager, $user;
2893 
2894  if (!empty($conf->dol_no_mouse_hover)) {
2895  $notooltip = 1; // Force disable tooltips
2896  }
2897 
2898  $name = $this->name ? $this->name : $this->nom;
2899 
2900  if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
2901  if (empty($option) && $this->client > 0) {
2902  $option = 'customer';
2903  }
2904  if (empty($option) && $this->fournisseur > 0) {
2905  $option = 'supplier';
2906  }
2907  }
2908 
2909  if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
2910  $code = '';
2911  if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
2912  $code = $this->code_client.' - ';
2913  }
2914 
2915  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
2916  $code .= $this->code_fournisseur.' - ';
2917  }
2918 
2919  if ($code) {
2920  if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
2921  $name = $code.' '.$name;
2922  } else {
2923  $name = $code;
2924  }
2925  }
2926  }
2927 
2928  if (!empty($this->name_alias) && empty($noaliasinname)) {
2929  $name .= ' ('.$this->name_alias.')';
2930  }
2931 
2932  $result = '';
2933  $params = [
2934  'id' => $this->id,
2935  'objecttype' => $this->element,
2936  'option' => $option,
2937  'nofetch' => 1,
2938  ];
2939  $classfortooltip = 'classfortooltip';
2940  $dataparams = '';
2941  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2942  $classfortooltip = 'classforajaxtooltip';
2943  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2944  $label = '';
2945  } else {
2946  $label = implode($this->getTooltipContentArray($params));
2947  }
2948 
2949  $linkstart = '';
2950  $linkend = '';
2951 
2952  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2953  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2954  } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2955  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2956  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2957  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2958  } elseif ($option == 'agenda') {
2959  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2960  } elseif ($option == 'project') {
2961  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2962  } elseif ($option == 'margin') {
2963  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2964  } elseif ($option == 'contact') {
2965  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2966  } elseif ($option == 'ban') {
2967  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2968  }
2969 
2970  // By default
2971  if (empty($linkstart)) {
2972  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2973  }
2974 
2975  // Add type of canvas
2976  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2977  // Add param to save lastsearch_values or not
2978  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2979  if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2980  $add_save_lastsearch_values = 1;
2981  }
2982  if ($add_save_lastsearch_values) {
2983  $linkstart .= '&save_lastsearch_values=1';
2984  }
2985  $linkstart .= '"';
2986 
2987  $linkclose = '';
2988  if (empty($notooltip)) {
2989  if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2990  $label = $langs->trans("ShowCompany");
2991  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2992  }
2993  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2994  $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
2995  $target_value = array('_self', '_blank', '_parent', '_top');
2996  if (in_array($target, $target_value)) {
2997  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2998  }
2999  } else {
3000  $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3001  }
3002  $linkstart .= $linkclose.'>';
3003  $linkend = '</a>';
3004 
3005  if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3006  $linkstart = '';
3007  $linkend = '';
3008  }
3009 
3010  $result .= $linkstart;
3011  if ($withpicto) {
3012  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3013  }
3014  if ($withpicto != 2) {
3015  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3016  }
3017  $result .= $linkend;
3018 
3019  global $action;
3020  $hookmanager->initHooks(array('thirdpartydao'));
3021  $parameters = array(
3022  'id' => $this->id,
3023  'getnomurl' => &$result,
3024  'withpicto ' => $withpicto,
3025  'option' => $option,
3026  'maxlen' => $maxlen,
3027  'notooltip' => $notooltip,
3028  'save_lastsearch_value' => $save_lastsearch_value
3029  );
3030  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3031  if ($reshook > 0) {
3032  $result = $hookmanager->resPrint;
3033  } else {
3034  $result .= $hookmanager->resPrint;
3035  }
3036 
3037  return $result;
3038  }
3039 
3049  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3050  {
3051  global $conf, $langs;
3052 
3053  $s = '';
3054  if (empty($option) || preg_match('/prospect/', $option)) {
3055  if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3056  $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.'>';
3057  }
3058  }
3059  if (empty($option) || preg_match('/customer/', $option)) {
3060  if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3061  $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.'>';
3062  }
3063  }
3064  if (empty($option) || preg_match('/supplier/', $option)) {
3065  if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3066  $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.'>';
3067  }
3068  }
3069  return $s;
3070  }
3071 
3072 
3079  public function getLibStatut($mode = 0)
3080  {
3081  return $this->LibStatut($this->status, $mode);
3082  }
3083 
3084  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3092  public function LibStatut($status, $mode = 0)
3093  {
3094  // phpcs:enable
3095  global $langs;
3096  $langs->load('companies');
3097 
3098  $statusType = 'status4';
3099  if ($status == 0) {
3100  $statusType = 'status6';
3101  }
3102 
3103  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3104  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3105  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3106  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3107  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3108  }
3109 
3110  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3111  }
3112 
3113  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3120  public function thirdparty_and_contact_email_array($addthirdparty = 0)
3121  {
3122  // phpcs:enable
3123  global $langs;
3124 
3125  $contact_emails = $this->contact_property_array('email', 1);
3126 
3127  if ($this->email && $addthirdparty) {
3128  if (empty($this->name)) {
3129  $this->name = $this->nom;
3130  }
3131  $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3132  }
3133 
3134  //var_dump($contact_emails)
3135  return $contact_emails;
3136  }
3137 
3138  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3145  {
3146  // phpcs:enable
3147  global $langs;
3148 
3149  $contact_phone = $this->contact_property_array('mobile');
3150 
3151  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3152  if (empty($this->name)) {
3153  $this->name = $this->nom;
3154  }
3155  // TODO: Tester si tel non deja present dans tableau contact
3156  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3157  }
3158  return $contact_phone;
3159  }
3160 
3161  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3169  public function contact_property_array($mode = 'email', $hidedisabled = 0)
3170  {
3171  // phpcs:enable
3172  global $langs;
3173 
3174  $contact_property = array();
3175 
3176 
3177  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3178  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3179  $sql .= " WHERE fk_soc = ".((int) $this->id);
3180  $sql .= " AND entity IN (".getEntity($this->element).")";
3181  $sql .= " ORDER BY lastname, firstname";
3182 
3183  $resql = $this->db->query($sql);
3184  if ($resql) {
3185  $nump = $this->db->num_rows($resql);
3186  if ($nump) {
3187  $sepa = "(";
3188  $sepb = ")";
3189  if ($mode == 'email') {
3190  //$sepa="&lt;"; $sepb="&gt;";
3191  $sepa = "<";
3192  $sepb = ">";
3193  }
3194  $i = 0;
3195  while ($i < $nump) {
3196  $obj = $this->db->fetch_object($resql);
3197  if ($mode == 'email') {
3198  $property = $obj->email;
3199  } elseif ($mode == 'mobile') {
3200  $property = $obj->phone_mobile;
3201  } else {
3202  $property = $obj->$mode;
3203  }
3204 
3205  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3206  if ($obj->status == 1 || empty($hidedisabled)) {
3207  if (empty($property)) {
3208  if ($mode == 'email') {
3209  $property = $langs->transnoentitiesnoconv("NoEMail");
3210  } elseif ($mode == 'mobile') {
3211  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3212  }
3213  }
3214 
3215  if (!empty($obj->poste)) {
3216  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3217  } else {
3218  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3219  }
3220  }
3221  $i++;
3222  }
3223  }
3224  } else {
3225  dol_print_error($this->db);
3226  }
3227  return $contact_property;
3228  }
3229 
3230 
3231  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3237  public function contact_array()
3238  {
3239  // phpcs:enable
3240  $contacts = array();
3241 
3242  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3243  $resql = $this->db->query($sql);
3244  if ($resql) {
3245  $nump = $this->db->num_rows($resql);
3246  if ($nump) {
3247  $i = 0;
3248  while ($i < $nump) {
3249  $obj = $this->db->fetch_object($resql);
3250  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3251  $i++;
3252  }
3253  }
3254  } else {
3255  dol_print_error($this->db);
3256  }
3257  return $contacts;
3258  }
3259 
3260  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3266  public function contact_array_objects()
3267  {
3268  // phpcs:enable
3269  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3270  $contacts = array();
3271 
3272  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3273  $resql = $this->db->query($sql);
3274  if ($resql) {
3275  $nump = $this->db->num_rows($resql);
3276  if ($nump) {
3277  $i = 0;
3278  while ($i < $nump) {
3279  $obj = $this->db->fetch_object($resql);
3280  $contact = new Contact($this->db);
3281  $contact->fetch($obj->rowid);
3282  $contacts[] = $contact;
3283  $i++;
3284  }
3285  }
3286  } else {
3287  dol_print_error($this->db);
3288  }
3289  return $contacts;
3290  }
3291 
3292  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3300  public function contact_get_property($rowid, $mode)
3301  {
3302  // phpcs:enable
3303  $contact_property = '';
3304 
3305  if (empty($rowid)) {
3306  return '';
3307  }
3308 
3309  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3310  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3311  $sql .= " WHERE rowid = ".((int) $rowid);
3312 
3313  $resql = $this->db->query($sql);
3314  if ($resql) {
3315  $nump = $this->db->num_rows($resql);
3316 
3317  if ($nump) {
3318  $obj = $this->db->fetch_object($resql);
3319 
3320  if ($mode == 'email') {
3321  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3322  } elseif ($mode == 'mobile') {
3323  $contact_property = $obj->phone_mobile;
3324  }
3325  }
3326  return $contact_property;
3327  } else {
3328  dol_print_error($this->db);
3329  }
3330 
3331  return '';
3332  }
3333 
3334 
3335  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3342  public function display_rib($mode = 'label')
3343  {
3344  // phpcs:enable
3345  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3346 
3347  $bac = new CompanyBankAccount($this->db);
3348  // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3349  $bac->fetch(0, '', $this->id);
3350 
3351  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3352  if ($mode == 'label') {
3353  return $bac->getRibLabel(true);
3354  } elseif ($mode == 'rum') {
3355  if (empty($bac->rum)) {
3356  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3357  $prelevement = new BonPrelevement($this->db);
3358  $bac->fetch_thirdparty();
3359  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3360  }
3361  return $bac->rum;
3362  } elseif ($mode == 'format') {
3363  return $bac->frstrecur;
3364  } else {
3365  return 'BadParameterToFunctionDisplayRib';
3366  }
3367  } else {
3368  return '';
3369  }
3370  }
3371 
3372  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3378  public function get_all_rib()
3379  {
3380  // phpcs:enable
3381  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3382  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3383  $result = $this->db->query($sql);
3384  if (!$result) {
3385  $this->error++;
3386  $this->errors[] = $this->db->lasterror;
3387  return 0;
3388  } else {
3389  $num_rows = $this->db->num_rows($result);
3390  $rib_array = array();
3391  if ($num_rows) {
3392  while ($obj = $this->db->fetch_object($result)) {
3393  $rib = new CompanyBankAccount($this->db);
3394  $rib->fetch($obj->rowid);
3395  $rib_array[] = $rib;
3396  }
3397  }
3398  return $rib_array;
3399  }
3400  }
3401 
3402  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3411  public function get_codeclient($objsoc = null, $type = 0)
3412  {
3413  // phpcs:enable
3414  global $conf;
3415  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3416  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3417 
3418  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3419  foreach ($dirsociete as $dirroot) {
3420  $res = dol_include_once($dirroot.$module.'.php');
3421  if ($res) {
3422  break;
3423  }
3424  }
3426  $mod = new $module($this->db);
3427 
3428  $this->code_client = $mod->getNextValue($objsoc, $type);
3429  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3430 
3431  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3432  }
3433  }
3434 
3435  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3444  public function get_codefournisseur($objsoc = null, $type = 1)
3445  {
3446  // phpcs:enable
3447  global $conf;
3448  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3449  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3450 
3451  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3452  foreach ($dirsociete as $dirroot) {
3453  $res = dol_include_once($dirroot.$module.'.php');
3454  if ($res) {
3455  break;
3456  }
3457  }
3459  $mod = new $module($this->db);
3460 
3461  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3462 
3463  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3464  }
3465  }
3466 
3467  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3474  public function codeclient_modifiable()
3475  {
3476  // phpcs:enable
3477  global $conf;
3478  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3479  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3480 
3481  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3482  foreach ($dirsociete as $dirroot) {
3483  $res = dol_include_once($dirroot.$module.'.php');
3484  if ($res) {
3485  break;
3486  }
3487  }
3488 
3489  $mod = new $module($this->db);
3490 
3491  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3492  if ($mod->code_modifiable_null && !$this->code_client) {
3493  return 1;
3494  }
3495  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3496  return 1;
3497  }
3498  if ($mod->code_modifiable) {
3499  return 1; // A mettre en dernier
3500  }
3501  return 0;
3502  } else {
3503  return 0;
3504  }
3505  }
3506 
3507 
3508  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3514  public function codefournisseur_modifiable()
3515  {
3516  // phpcs:enable
3517  global $conf;
3518  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3519  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3520 
3521  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3522  foreach ($dirsociete as $dirroot) {
3523  $res = dol_include_once($dirroot.$module.'.php');
3524  if ($res) {
3525  break;
3526  }
3527  }
3528 
3529  $mod = new $module($this->db);
3530 
3531  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3532  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3533  return 1;
3534  }
3535  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3536  return 1;
3537  }
3538  if ($mod->code_modifiable) {
3539  return 1; // A mettre en dernier
3540  }
3541  return 0;
3542  } else {
3543  return 0;
3544  }
3545  }
3546 
3547 
3548  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3560  public function check_codeclient()
3561  {
3562  // phpcs:enable
3563  global $conf;
3564  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3565  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3566 
3567  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3568  foreach ($dirsociete as $dirroot) {
3569  $res = dol_include_once($dirroot.$module.'.php');
3570  if ($res) {
3571  break;
3572  }
3573  }
3574 
3575  $mod = new $module($this->db);
3576 
3577  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3578  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3579  if ($result) { // If error
3580  $this->error = $mod->error;
3581  $this->errors = $mod->errors;
3582  }
3583  return $result;
3584  } else {
3585  return 0;
3586  }
3587  }
3588 
3589  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3601  public function check_codefournisseur()
3602  {
3603  // phpcs:enable
3604  global $conf;
3605  if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3606  $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3607 
3608  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3609  foreach ($dirsociete as $dirroot) {
3610  $res = dol_include_once($dirroot.$module.'.php');
3611  if ($res) {
3612  break;
3613  }
3614  }
3615 
3616  $mod = new $module($this->db);
3617 
3618  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3619  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3620  if ($result) { // If error
3621  $this->error = $mod->error;
3622  $this->errors = $mod->errors;
3623  }
3624  return $result;
3625  } else {
3626  return 0;
3627  }
3628  }
3629 
3630  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3639  public function get_codecompta($type)
3640  {
3641  // phpcs:enable
3642  global $conf;
3643 
3644  if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3645  $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3646  $res = false;
3647  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3648  foreach ($dirsociete as $dirroot) {
3649  $res = dol_include_once($dirroot.$module.'.php');
3650  if ($res) {
3651  break;
3652  }
3653  }
3654 
3655  if ($res) {
3656  $mod = new $module();
3657 
3658  // Set code count in $mod->code
3659  $result = $mod->get_code($this->db, $this, $type);
3660 
3661  if ($type == 'customer') {
3662  $this->code_compta_client = $mod->code;
3663  $this->code_compta = $this->code_compta_client; // For backward compatibility
3664  } elseif ($type == 'supplier') {
3665  $this->code_compta_fournisseur = $mod->code;
3666  }
3667 
3668  return $result;
3669  } else {
3670  $this->error = 'ErrorAccountancyCodeNotDefined';
3671  return -1;
3672  }
3673  } else {
3674  if ($type == 'customer') {
3675  $this->code_compta_client = '';
3676  $this->code_compta = '';
3677  } elseif ($type == 'supplier') {
3678  $this->code_compta_fournisseur = '';
3679  }
3680 
3681  return 0;
3682  }
3683  }
3684 
3691  public function setParent($id)
3692  {
3693  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3694 
3695  if ($this->id) {
3696  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3697  if ($id > 0) {
3698  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3699  if ($sameparent < 0) {
3700  return -1;
3701  }
3702  if ($sameparent == 1) {
3703  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3704  return -1;
3705  }
3706  }
3707 
3708  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3709 
3710  $resql = $this->db->query($sql);
3711  if ($resql) {
3712  $this->parent = $id;
3713  return 1;
3714  } else {
3715  return -1;
3716  }
3717  }
3718 
3719  return -1;
3720  }
3721 
3730  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3731  {
3732  if ($counter > 100) {
3733  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3734  }
3735 
3736  $sql = 'SELECT s.parent';
3737  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3738  $sql .= ' WHERE rowid = '.((int) $idparent);
3739  $resql = $this->db->query($sql);
3740  if ($resql) {
3741  $obj = $this->db->fetch_object($resql);
3742 
3743  if ($obj->parent == '') {
3744  return 0;
3745  } elseif ($obj->parent == $idchild) {
3746  return 1;
3747  } else {
3748  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3749  }
3750  return $sameparent;
3751  } else {
3752  return -1;
3753  }
3754  }
3755 
3763  public function getParentsForCompany($company_id, $parents = array())
3764  {
3765  global $langs;
3766 
3767  if ($company_id > 0) {
3768  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3769  $resql = $this->db->query($sql);
3770  if ($resql) {
3771  if ($obj = $this->db->fetch_object($resql)) {
3772  $parent = $obj->parent;
3773  if ($parent > 0 && !in_array($parent, $parents)) {
3774  $parents[] = $parent;
3775  return $this->getParentsForCompany($parent, $parents);
3776  } else {
3777  return $parents;
3778  }
3779  }
3780  $this->db->free($resql);
3781  } else {
3782  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3783  }
3784  }
3785  // Return a default value when $company_id is not greater than 0
3786  return array();
3787  }
3788 
3789  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3796  public function id_prof_verifiable($idprof)
3797  {
3798  // phpcs:enable
3799  global $conf;
3800 
3801  switch ($idprof) {
3802  case 1:
3803  $ret = (!getDolGlobalString('SOCIETE_IDPROF1_UNIQUE') ? false : true);
3804  break;
3805  case 2:
3806  $ret = (!getDolGlobalString('SOCIETE_IDPROF2_UNIQUE') ? false : true);
3807  break;
3808  case 3:
3809  $ret = (!getDolGlobalString('SOCIETE_IDPROF3_UNIQUE') ? false : true);
3810  break;
3811  case 4:
3812  $ret = (!getDolGlobalString('SOCIETE_IDPROF4_UNIQUE') ? false : true);
3813  break;
3814  case 5:
3815  $ret = (!getDolGlobalString('SOCIETE_IDPROF5_UNIQUE') ? false : true);
3816  break;
3817  case 6:
3818  $ret = (!getDolGlobalString('SOCIETE_IDPROF6_UNIQUE') ? false : true);
3819  break;
3820  default:
3821  $ret = false;
3822  }
3823 
3824  return $ret;
3825  }
3826 
3827  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3836  public function id_prof_exists($idprof, $value, $socid = 0)
3837  {
3838  // phpcs:enable
3839  $field = $idprof;
3840 
3841  switch ($idprof) { // For backward compatibility
3842  case '1':
3843  case 'idprof1':
3844  $field = "siren";
3845  break;
3846  case '2':
3847  case 'idprof2':
3848  $field = "siret";
3849  break;
3850  case '3':
3851  case 'idprof3':
3852  $field = "ape";
3853  break;
3854  case '4':
3855  case 'idprof4':
3856  $field = "idprof4";
3857  break;
3858  case '5':
3859  $field = "idprof5";
3860  break;
3861  case '6':
3862  $field = "idprof6";
3863  break;
3864  }
3865 
3866  //Verify duplicate entries
3867  $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3868  if ($socid) {
3869  $sql .= " AND rowid <> ".$socid;
3870  }
3871  $resql = $this->db->query($sql);
3872  if ($resql) {
3873  $obj = $this->db->fetch_object($resql);
3874  $count = $obj->nb;
3875  } else {
3876  $count = 0;
3877  print $this->db->error();
3878  }
3879  $this->db->free($resql);
3880 
3881  if ($count > 0) {
3882  return true;
3883  } else {
3884  return false;
3885  }
3886  }
3887 
3888  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3897  public function id_prof_check($idprof, $soc)
3898  {
3899  // phpcs:enable
3900  global $conf;
3901 
3902  // load the library necessary to check the professional identifiers
3903  require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
3904 
3905  $ok = 1;
3906 
3907  if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3908  return 1;
3909  }
3910 
3911  // Check SIREN
3912  if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
3913  return -1;
3914  }
3915 
3916  // Check SIRET
3917  if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
3918  return -1;
3919  }
3920 
3921  //Verify CIF/NIF/NIE if pays ES
3922  if ($idprof == 1 && $soc->country_code == 'ES') {
3923  return isValidTinForES($this->idprof1);
3924  }
3925 
3926  //Verify NIF if country is PT
3927  if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
3928  return -1;
3929  }
3930 
3931  //Verify NIF if country is DZ
3932  if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
3933  return -1;
3934  }
3935 
3936  //Verify ID Prof 1 if country is BE
3937  if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
3938  return -1;
3939  }
3940 
3941  return $ok;
3942  }
3943 
3944  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3953  public function id_prof_url($idprof, $thirdparty)
3954  {
3955  // phpcs:enable
3956  global $conf, $langs, $hookmanager;
3957 
3958  $url = '';
3959  $action = '';
3960 
3961  $hookmanager->initHooks(array('idprofurl'));
3962  $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
3963  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3964  if (empty($reshook)) {
3965  if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3966  return '';
3967  }
3968 
3969  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3970  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3971  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3972  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3973  }
3974  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3975  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3976  }
3977  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3978  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3979  }
3980  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3981  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3982  }
3983  if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3984  $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3985  }
3986  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3987  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3988  }
3989 
3990  if ($url) {
3991  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3992  }
3993  } else {
3994  return $hookmanager->resPrint;
3995  }
3996 
3997  return '';
3998  }
3999 
4000  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4006  public function has_projects()
4007  {
4008  // phpcs:enable
4009  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4010  $resql = $this->db->query($sql);
4011  if ($resql) {
4012  $obj = $this->db->fetch_object($resql);
4013  $count = $obj->numproj;
4014  } else {
4015  $count = 0;
4016  print $this->db->error();
4017  }
4018  $this->db->free($resql);
4019  return ($count > 0);
4020  }
4021 
4022 
4029  public function info($id)
4030  {
4031  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4032  $sql .= " fk_user_creat, fk_user_modif";
4033  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4034  $sql .= " WHERE s.rowid = ".((int) $id);
4035 
4036  $result = $this->db->query($sql);
4037  if ($result) {
4038  if ($this->db->num_rows($result)) {
4039  $obj = $this->db->fetch_object($result);
4040 
4041  $this->id = $obj->rowid;
4042 
4043  $this->user_creation_id = $obj->fk_user_creat;
4044  $this->user_modification_id = $obj->fk_user_modif;
4045  $this->date_creation = $this->db->jdate($obj->datec);
4046  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4047 
4048  $this->ref = $obj->name;
4049  }
4050 
4051  $this->db->free($result);
4052  } else {
4053  dol_print_error($this->db);
4054  }
4055  }
4056 
4062  public function isACompany()
4063  {
4064  // Define if third party is treated as company (or not) when nature is unknown
4065  $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4066 
4067  // Now try to guess using different tips
4068  if (!empty($this->tva_intra)) {
4069  $isACompany = 1;
4070  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4071  $isACompany = 1;
4072  } else {
4073  if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4074  // TODO Add a field is_a_company into dictionary
4075  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4076  $isACompany = 0;
4077  } else {
4078  $isACompany = 1;
4079  }
4080  } else {
4081  $isACompany = 1;
4082  }
4083  }
4084 
4085  return (bool) $isACompany;
4086  }
4087 
4093  public function isInEEC()
4094  {
4095  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4096  return isInEEC($this);
4097  }
4098 
4099  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4105  public function LoadSupplierCateg()
4106  {
4107  // phpcs:enable
4108  $this->SupplierCategories = array();
4109  $sql = "SELECT rowid, label";
4110  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4111  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4112 
4113  $resql = $this->db->query($sql);
4114  if ($resql) {
4115  while ($obj = $this->db->fetch_object($resql)) {
4116  $this->SupplierCategories[$obj->rowid] = $obj->label;
4117  }
4118  return 0;
4119  } else {
4120  return -1;
4121  }
4122  }
4123 
4124  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4131  public function AddFournisseurInCategory($categorie_id)
4132  {
4133  // phpcs:enable
4134  if ($categorie_id > 0 && $this->id > 0) {
4135  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4136  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4137 
4138  if ($resql = $this->db->query($sql)) {
4139  return 0;
4140  }
4141  } else {
4142  return 0;
4143  }
4144  return -1;
4145  }
4146 
4152  public function getNbOfEMailings()
4153  {
4154  $sql = "SELECT count(mc.email) as nb";
4155  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4156  $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4157  $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4158 
4159  $resql = $this->db->query($sql);
4160  if ($resql) {
4161  $obj = $this->db->fetch_object($resql);
4162  $nb = $obj->nb;
4163 
4164  $this->db->free($resql);
4165  return $nb;
4166  } else {
4167  $this->error = $this->db->error();
4168  return -1;
4169  }
4170  }
4171 
4178  public function setNoEmail($no_email)
4179  {
4180  $error = 0;
4181 
4182  // Update mass emailing flag into table mailing_unsubscribe
4183  if ($this->email) {
4184  $this->db->begin();
4185 
4186  if ($no_email) {
4187  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'";
4188  $resql = $this->db->query($sql);
4189  if ($resql) {
4190  $obj = $this->db->fetch_object($resql);
4191  $noemail = $obj->nb;
4192  if (empty($noemail)) {
4193  $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".getEntity('mailing', 0).", '".$this->db->idate(dol_now())."')";
4194  $resql = $this->db->query($sql);
4195  if (!$resql) {
4196  $error++;
4197  $this->error = $this->db->lasterror();
4198  $this->errors[] = $this->error;
4199  }
4200  }
4201  } else {
4202  $error++;
4203  $this->error = $this->db->lasterror();
4204  $this->errors[] = $this->error;
4205  }
4206  } else {
4207  $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4208  $resql = $this->db->query($sql);
4209  if (!$resql) {
4210  $error++;
4211  $this->error = $this->db->lasterror();
4212  $this->errors[] = $this->error;
4213  }
4214  }
4215 
4216  if (empty($error)) {
4217  $this->no_email = $no_email;
4218  $this->db->commit();
4219  return 1;
4220  } else {
4221  $this->db->rollback();
4222  return $error * -1;
4223  }
4224  }
4225 
4226  return 0;
4227  }
4228 
4235  public function getNoEmail()
4236  {
4237  if ($this->email) {
4238  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4239  $resql = $this->db->query($sql);
4240  if ($resql) {
4241  $obj = $this->db->fetch_object($resql);
4242  $this->no_email = $obj->nb;
4243  return 1;
4244  } else {
4245  $this->error = $this->db->lasterror();
4246  $this->errors[] = $this->error;
4247  return -1;
4248  }
4249  }
4250  return 0;
4251  }
4252 
4253  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4263  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4264  {
4265  // phpcs:enable
4266  global $conf, $user, $langs;
4267 
4268  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4269  $fullname = $member->getFullName($langs);
4270 
4271  if ($member->morphy == 'mor') {
4272  if (empty($socname)) {
4273  $socname = $member->company ? $member->company : $member->societe;
4274  }
4275  if (!empty($fullname) && empty($socalias)) {
4276  $socalias = $fullname;
4277  }
4278  } elseif (empty($socname) && $member->morphy == 'phy') {
4279  if (empty($socname)) {
4280  $socname = $fullname;
4281  }
4282  if (!empty($member->company) && empty($socalias)) {
4283  $socalias = $member->company;
4284  }
4285  }
4286 
4287  $name = $socname;
4288  $alias = $socalias ? $socalias : '';
4289 
4290  // Positionne parameters
4291  $this->nom = $name; // TODO deprecated
4292  $this->name = $name;
4293  $this->name_alias = $alias;
4294  $this->address = $member->address;
4295  $this->zip = $member->zip;
4296  $this->town = $member->town;
4297  $this->country_code = $member->country_code;
4298  $this->country_id = $member->country_id;
4299  $this->phone = $member->phone; // Prof phone
4300  $this->email = $member->email;
4301  $this->socialnetworks = $member->socialnetworks;
4302  $this->entity = $member->entity;
4303 
4304  $this->client = 1; // A member is a customer by default
4305  $this->code_client = ($customercode ? $customercode : -1);
4306  $this->code_fournisseur = '-1';
4307  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4308  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4309 
4310  $this->db->begin();
4311 
4312  // Cree et positionne $this->id
4313  $result = $this->create($user);
4314 
4315  if ($result >= 0) {
4316  // Auto-create contact on thirdparty creation
4317  if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4318  // Fill fields needed by contact
4319  $this->name_bis = $member->lastname;
4320  $this->firstname = $member->firstname;
4321  $this->civility_id = $member->civility_id;
4322 
4323  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4324  $result = $this->create_individual($user);
4325 
4326  if ($result < 0) {
4327  setEventMessages($this->error, $this->errors, 'errors');
4328  $this->db->rollback();
4329  return -1;
4330  }
4331  }
4332 
4333  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4334  $sql .= " SET fk_soc = ".((int) $this->id);
4335  $sql .= " WHERE rowid = ".((int) $member->id);
4336 
4337  $resql = $this->db->query($sql);
4338  if ($resql) {
4339  $this->db->commit();
4340  return $this->id;
4341  } else {
4342  $this->error = $this->db->error();
4343 
4344  $this->db->rollback();
4345  return -1;
4346  }
4347  } else {
4348  // $this->error deja positionne
4349  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4350 
4351  $this->db->rollback();
4352  return $result;
4353  }
4354  }
4355 
4362  public function setMysoc(Conf $conf)
4363  {
4364  global $langs;
4365 
4366  $this->id = 0;
4367  $this->entity = $conf->entity;
4368  $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4369  $this->nom = $this->name; // deprecated
4370  $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4371  $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4372  $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4373  $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4374 
4375  $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4376 
4377  $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4378 
4379  // We define country_id, country_code and country
4380  $country_id = 0;
4381  $country_code = $country_label = '';
4382  if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4383  $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4384  $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4385  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4386  $country_code = $tmp[1];
4387  $country_label = $tmp[2];
4388  } else {
4389  // For backward compatibility
4390  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4391  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4392  $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
4393  $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
4394  }
4395  }
4396  $this->country_id = $country_id;
4397  $this->country_code = $country_code;
4398  $this->country = $country_label;
4399  if (is_object($langs)) {
4400  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4401  }
4402 
4403  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4404  // We define state_id, state_code and state
4405  $state_id = 0;
4406  $state_code = $state_label = '';
4407  if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4408  $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4409  $state_id = $tmp[0];
4410  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4411  $state_code = $tmp[1];
4412  $state_label = $tmp[2];
4413  } else { // For backward compatibility
4414  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);
4415  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4416  $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
4417  $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
4418  }
4419  }
4420  $this->state_id = $state_id;
4421  $this->state_code = $state_code;
4422  $this->state = $state_label;
4423  if (is_object($langs)) {
4424  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4425  }
4426 
4427  $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4428  $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4429  $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4430  $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4431 
4432  // Social networks
4433  $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4434  $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4435  $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4436  $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4437  $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4438  $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4439  $this->socialnetworks = array();
4440  if (!empty($facebook_url)) {
4441  $this->socialnetworks['facebook'] = $facebook_url;
4442  }
4443  if (!empty($twitter_url)) {
4444  $this->socialnetworks['twitter'] = $twitter_url;
4445  }
4446  if (!empty($linkedin_url)) {
4447  $this->socialnetworks['linkedin'] = $linkedin_url;
4448  }
4449  if (!empty($instagram_url)) {
4450  $this->socialnetworks['instagram'] = $instagram_url;
4451  }
4452  if (!empty($youtube_url)) {
4453  $this->socialnetworks['youtube'] = $youtube_url;
4454  }
4455  if (!empty($github_url)) {
4456  $this->socialnetworks['github'] = $github_url;
4457  }
4458 
4459  // Id prof generiques
4460  $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4461  $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4462  $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4463  $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4464  $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4465  $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4466  $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4467  $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4468  $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4469  $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4470  $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4471  $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4472  $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4473  $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4474  $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4475  $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4476  $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4477  $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4478 
4479  // Define if company use vat or not
4480  $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4481 
4482  // Define if company use local taxes
4483  $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4484  $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4485  }
4486 
4494  public function initAsSpecimen()
4495  {
4496  $now = dol_now();
4497 
4498  // Initialize parameters
4499  $this->id = 0;
4500  $this->entity = 1;
4501  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4502  $this->nom = $this->name; // For backward compatibility
4503  $this->ref_ext = 'Ref ext';
4504  $this->specimen = 1;
4505  $this->address = '21 jump street';
4506  $this->zip = '99999';
4507  $this->town = 'MyTown';
4508  $this->state_id = 1;
4509  $this->state_code = 'AA';
4510  $this->state = 'MyState';
4511  $this->country_id = 1;
4512  $this->country_code = 'FR';
4513  $this->email = 'specimen@specimen.com';
4514  $this->socialnetworks = array(
4515  'skype' => 'skypepseudo',
4516  'twitter' => 'twitterpseudo',
4517  'facebook' => 'facebookpseudo',
4518  'linkedin' => 'linkedinpseudo',
4519  );
4520  $this->url = 'http://www.specimen.com';
4521 
4522  $this->phone = '0909090901';
4523  $this->phone_mobile = '0909090901';
4524  $this->fax = '0909090909';
4525 
4526  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4527  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4528  $this->capital = 10000;
4529  $this->client = 1;
4530  $this->prospect = 1;
4531  $this->fournisseur = 1;
4532  $this->tva_assuj = 1;
4533  $this->tva_intra = 'EU1234567';
4534  $this->note_public = 'This is a comment (public)';
4535  $this->note_private = 'This is a comment (private)';
4536 
4537  $this->idprof1 = 'idprof1';
4538  $this->idprof2 = 'idprof2';
4539  $this->idprof3 = 'idprof3';
4540  $this->idprof4 = 'idprof4';
4541  $this->idprof5 = 'idprof5';
4542  $this->idprof6 = 'idprof6';
4543 
4544  return 1;
4545  }
4546 
4553  public function useLocalTax($localTaxNum = 0)
4554  {
4555  $sql = "SELECT t.localtax1, t.localtax2";
4556  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4557  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4558  $sql .= " AND t.active = 1";
4559  $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4560  if (empty($localTaxNum)) {
4561  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4562  } elseif ($localTaxNum == 1) {
4563  $sql .= " AND t.localtax1_type <> '0'";
4564  } elseif ($localTaxNum == 2) {
4565  $sql .= " AND t.localtax2_type <> '0'";
4566  }
4567 
4568  $resql = $this->db->query($sql);
4569  if ($resql) {
4570  return ($this->db->num_rows($resql) > 0);
4571  } else {
4572  return false;
4573  }
4574  }
4575 
4581  public function useNPR()
4582  {
4583  $sql = "SELECT t.rowid";
4584  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4585  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4586  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4587  $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4588 
4589  dol_syslog("useNPR", LOG_DEBUG);
4590  $resql = $this->db->query($sql);
4591  if ($resql) {
4592  return ($this->db->num_rows($resql) > 0);
4593  } else {
4594  return false;
4595  }
4596  }
4597 
4604  public function useRevenueStamp()
4605  {
4606  $sql = "SELECT COUNT(*) as nb";
4607  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4608  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4609  $sql .= " AND r.active = 1";
4610 
4611  dol_syslog("useRevenueStamp", LOG_DEBUG);
4612  $resql = $this->db->query($sql);
4613  if ($resql) {
4614  $obj = $this->db->fetch_object($resql);
4615  return (($obj->nb > 0) ? true : false);
4616  } else {
4617  $this->error = $this->db->lasterror();
4618  return false;
4619  }
4620  }
4621 
4627  public function getLibProspLevel()
4628  {
4629  return $this->LibProspLevel($this->fk_prospectlevel);
4630  }
4631 
4632  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4639  public function LibProspLevel($fk_prospectlevel)
4640  {
4641  // phpcs:enable
4642  global $langs;
4643 
4644  $label = '';
4645  if ($fk_prospectlevel != '') {
4646  $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4647  // If label is not found in language file, we get label from cache/database
4648  if ($label == "ProspectLevel".$fk_prospectlevel) {
4649  $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4650  }
4651  }
4652 
4653  return $label;
4654  }
4655 
4663  public function getLibProspCommStatut($mode = 0, $label = '')
4664  {
4665  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4666  }
4667 
4668  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4682  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4683  {
4684  // phpcs:enable
4685  global $langs;
4686 
4687  $langs->load('customers');
4688 
4689  if ($mode == 2) {
4690  if ($status == '-1' || $status == 'ST_NO') {
4691  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4692  } elseif ($status == '0' || $status == 'ST_NEVER') {
4693  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4694  } elseif ($status == '1' || $status == 'ST_TODO') {
4695  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4696  } elseif ($status == '2' || $status == 'ST_PEND') {
4697  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4698  } elseif ($status == '3' || $status == 'ST_DONE') {
4699  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4700  } else {
4701  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4702  }
4703  } elseif ($mode == 3) {
4704  if ($status == '-1' || $status == 'ST_NO') {
4705  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4706  } elseif ($status == '0' || $status == 'ST_NEVER') {
4707  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4708  } elseif ($status == '1' || $status == 'ST_TODO') {
4709  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4710  } elseif ($status == '2' || $status == 'ST_PEND') {
4711  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4712  } elseif ($status == '3' || $status == 'ST_DONE') {
4713  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4714  } else {
4715  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4716  }
4717  } elseif ($mode == 4) {
4718  if ($status == '-1' || $status == 'ST_NO') {
4719  return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4720  } elseif ($status == '0' || $status == 'ST_NEVER') {
4721  return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4722  } elseif ($status == '1' || $status == 'ST_TODO') {
4723  return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4724  } elseif ($status == '2' || $status == 'ST_PEND') {
4725  return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4726  } elseif ($status == '3' || $status == 'ST_DONE') {
4727  return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4728  } else {
4729  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4730  }
4731  }
4732 
4733  return "Error, mode/status not found";
4734  }
4735 
4742  public function getOutstandingProposals($mode = 'customer')
4743  {
4744  $table = 'propal';
4745  if ($mode == 'supplier') {
4746  $table = 'supplier_proposal';
4747  }
4748 
4749  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4750  $sql .= " WHERE fk_soc = ".((int) $this->id);
4751  if ($mode == 'supplier') {
4752  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4753  } else {
4754  $sql .= " AND entity IN (".getEntity('propal').")";
4755  }
4756 
4757  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4758 
4759  $resql = $this->db->query($sql);
4760  if ($resql) {
4761  $outstandingOpened = 0;
4762  $outstandingTotal = 0;
4763  $outstandingTotalIncTax = 0;
4764  $arrayofref = array();
4765  while ($obj = $this->db->fetch_object($resql)) {
4766  $arrayofref[$obj->rowid] = $obj->ref;
4767  $outstandingTotal += $obj->total_ht;
4768  $outstandingTotalIncTax += $obj->total_ttc;
4769  if ($obj->status != 0) {
4770  // Not a draft
4771  $outstandingOpened += $obj->total_ttc;
4772  }
4773  }
4774  return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4775  } else {
4776  return array();
4777  }
4778  }
4779 
4786  public function getOutstandingOrders($mode = 'customer')
4787  {
4788  $table = 'commande';
4789  if ($mode == 'supplier') {
4790  $table = 'commande_fournisseur';
4791  }
4792 
4793  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4794  $sql .= " WHERE fk_soc = ".((int) $this->id);
4795  if ($mode == 'supplier') {
4796  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4797  } else {
4798  $sql .= " AND entity IN (".getEntity('commande').")";
4799  }
4800 
4801  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4802  $resql = $this->db->query($sql);
4803  if ($resql) {
4804  $outstandingOpened = 0;
4805  $outstandingTotal = 0;
4806  $outstandingTotalIncTax = 0;
4807  $arrayofref = array();
4808  while ($obj = $this->db->fetch_object($resql)) {
4809  $arrayofref[$obj->rowid] = $obj->ref;
4810  $outstandingTotal += $obj->total_ht;
4811  $outstandingTotalIncTax += $obj->total_ttc;
4812  if ($obj->status != 0) {
4813  // Not a draft
4814  $outstandingOpened += $obj->total_ttc;
4815  }
4816  }
4817  return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4818  } else {
4819  return array();
4820  }
4821  }
4822 
4830  public function getOutstandingBills($mode = 'customer', $late = 0)
4831  {
4832  $table = 'facture';
4833  if ($mode == 'supplier') {
4834  $table = 'facture_fourn';
4835  }
4836 
4837  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4838  $paiement = $invoice->getSommePaiement();
4839  $creditnotes=$invoice->getSumCreditNotesUsed();
4840  $deposits=$invoice->getSumDepositsUsed();
4841  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4842  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4843  */
4844  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4845  $sql .= " WHERE fk_soc = ".((int) $this->id);
4846  if (!empty($late)) {
4847  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4848  }
4849  if ($mode == 'supplier') {
4850  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4851  } else {
4852  $sql .= " AND entity IN (".getEntity('invoice').")";
4853  }
4854 
4855  dol_syslog("getOutstandingBills", LOG_DEBUG);
4856  $resql = $this->db->query($sql);
4857  if ($resql) {
4858  $outstandingOpened = 0;
4859  $outstandingTotal = 0;
4860  $outstandingTotalIncTax = 0;
4861  $arrayofref = array();
4862  $arrayofrefopened = array();
4863  if ($mode == 'supplier') {
4864  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4865  $tmpobject = new FactureFournisseur($this->db);
4866  } else {
4867  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4868  $tmpobject = new Facture($this->db);
4869  }
4870  while ($obj = $this->db->fetch_object($resql)) {
4871  $arrayofref[$obj->rowid] = $obj->ref;
4872  $tmpobject->id = $obj->rowid;
4873 
4874  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4875  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4876  ) {
4877  $outstandingTotal += $obj->total_ht;
4878  $outstandingTotalIncTax += $obj->total_ttc;
4879  }
4880 
4881  $remaintopay = 0;
4882 
4883  if ($obj->paye == 0
4884  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4885  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
4886  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4887  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
4888  $paiement = $tmpobject->getSommePaiement();
4889  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4890  $deposits = $tmpobject->getSumDepositsUsed();
4891 
4892  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4893  $outstandingOpened += $remaintopay;
4894  }
4895 
4896  //if credit note is converted but not used
4897  // TODO Do this also for customer ?
4898  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4899  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4900  $remaintopay -= $remainingcreditnote;
4901  $outstandingOpened -= $remainingcreditnote;
4902  }
4903 
4904  if ($remaintopay) {
4905  $arrayofrefopened[$obj->rowid] = $obj->ref;
4906  }
4907  }
4908  return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
4909  } else {
4910  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4911  return array();
4912  }
4913  }
4914 
4921  public function getLibCustProspStatut()
4922  {
4923  return $this->LibCustProspStatut($this->client);
4924  }
4925 
4926  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4933  public function LibCustProspStatut($status)
4934  {
4935  // phpcs:enable
4936  global $langs;
4937  $langs->load('companies');
4938 
4939  if ($status == 0) {
4940  return $langs->trans("NorProspectNorCustomer");
4941  } elseif ($status == 1) {
4942  return $langs->trans("Customer");
4943  } elseif ($status == 2) {
4944  return $langs->trans("Prospect");
4945  } elseif ($status == 3) {
4946  return $langs->trans("ProspectCustomer");
4947  }
4948 
4949  return '';
4950  }
4951 
4952 
4964  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4965  {
4966  global $langs;
4967 
4968  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4969  $modelpath = "core/modules/bank/doc/";
4970 
4971  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4972  $companybankaccount = new CompanyBankAccount($this->db);
4973  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4974  if (!$result) {
4975  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4976  }
4977  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4978  $this->last_main_doc = $companybankaccount->last_main_doc;
4979  } else {
4980  // Positionne le modele sur le nom du modele a utiliser
4981  if (!dol_strlen($modele)) {
4982  if (getDolGlobalString('COMPANY_ADDON_PDF')) {
4983  $modele = getDolGlobalString('COMPANY_ADDON_PDF');
4984  } else {
4985  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4986  return 0;
4987  }
4988  }
4989 
4990  if (!isset($this->bank_account)) {
4991  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4992  $bac = new CompanyBankAccount($this->db);
4993  // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
4994  $result = $bac->fetch(0, '', $this->id);
4995  if ($result > 0) {
4996  $this->bank_account = $bac;
4997  } else {
4998  $this->bank_account = '';
4999  }
5000  }
5001 
5002  $modelpath = "core/modules/societe/doc/";
5003 
5004  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5005  }
5006 
5007  return $result;
5008  }
5009 
5010 
5022  public function setCategories($categories, $type_categ)
5023  {
5024  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5025 
5026  // Decode type
5027  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5028  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5029  return -1;
5030  }
5031 
5032  return parent::setCategoriesCommon($categories, $type_categ);
5033  }
5034 
5042  public function setSalesRep($salesrep, $onlyAdd = false)
5043  {
5044  global $user;
5045 
5046  // Handle single user
5047  if (!is_array($salesrep)) {
5048  $salesrep = array($salesrep);
5049  }
5050 
5051  $to_del = array(); // Nothing to delete
5052  $to_add = $salesrep;
5053  if ($onlyAdd === false) {
5054  // Get current users
5055  $existing = $this->getSalesRepresentatives($user, 1);
5056 
5057  // Diff
5058  if (is_array($existing)) {
5059  $to_del = array_diff($existing, $salesrep);
5060  $to_add = array_diff($salesrep, $existing);
5061  }
5062  }
5063 
5064  $error = 0;
5065 
5066  // Process
5067  foreach ($to_del as $del) {
5068  $this->del_commercial($user, $del);
5069  }
5070  foreach ($to_add as $add) {
5071  $result = $this->add_commercial($user, $add);
5072  if ($result < 0) {
5073  $error++;
5074  break;
5075  }
5076  }
5077 
5078  return $error ? -1 : 1;
5079  }
5080 
5087  public function setThirdpartyType($typent_id)
5088  {
5089  global $user;
5090 
5091  dol_syslog(__METHOD__, LOG_DEBUG);
5092 
5093  if ($this->id) {
5094  $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5095 
5096  if ($result > 0) {
5097  $this->typent_id = $typent_id;
5098  $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5099  return 1;
5100  } else {
5101  return -1;
5102  }
5103  } else {
5104  return -1;
5105  }
5106  }
5107 
5117  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5118  {
5119  if ($origin_id == $dest_id) {
5120  dol_syslog('Error: Try to merge a thirdparty into itself');
5121  return false;
5122  }
5123 
5124  // Sales representationves cannot be twice in the same thirdparties so we look for them and remove the one that are common some to avoid duplicate.
5125  // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5126  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5127  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5128  $sql .= ' SELECT fk_user ';
5129  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5130  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5131 
5132  $resql = $dbs->query($sql);
5133  while ($obj = $dbs->fetch_object($resql)) {
5134  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5135  }
5136 
5137  // llx_societe_extrafields table must not be here because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5138  // Do not include llx_societe because it will be replaced later.
5139  $tables = array(
5140  'societe_account',
5141  'societe_commerciaux',
5142  'societe_prices',
5143  'societe_remise',
5144  'societe_remise_except',
5145  'societe_rib'
5146  );
5147 
5148  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5149  }
5150 
5159  public function setAccountancyCode($type, $value)
5160  {
5161  global $user, $langs, $conf;
5162 
5163  $this->db->begin();
5164 
5165  if ($type == 'buy') {
5166  $field = 'accountancy_code_buy';
5167  } elseif ($type == 'sell') {
5168  $field = 'accountancy_code_sell';
5169  } else {
5170  return -1;
5171  }
5172 
5173  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5174  $sql .= $field." = '".$this->db->escape($value)."'";
5175  $sql .= " WHERE rowid = ".((int) $this->id);
5176 
5177  dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5178  $resql = $this->db->query($sql);
5179 
5180  if ($resql) {
5181  // Call triggers
5182  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5183  $interface = new Interfaces($this->db);
5184  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5185  if ($result < 0) {
5186  $this->errors = $interface->errors;
5187  $this->db->rollback();
5188  return -1;
5189  }
5190  // End call triggers
5191 
5192  $this->$field = $value;
5193 
5194  $this->db->commit();
5195  return 1;
5196  } else {
5197  $this->error = $this->db->lasterror();
5198  $this->db->rollback();
5199  return -1;
5200  }
5201  }
5202 
5209  public function fetchPartnerships($mode)
5210  {
5211  global $langs;
5212 
5213  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5214 
5215 
5216  $this->partnerships[] = array();
5217 
5218  return 1;
5219  }
5220 
5228  public function getKanbanView($option = '', $arraydata = array())
5229  {
5230  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5231 
5232  $return = '<div class="box-flex-item box-flex-grow-zero">';
5233  $return .= '<div class="info-box info-box-sm">';
5234  $return .= '<span class="info-box-icon bg-infobox-action">';
5235  $return .= img_picto('', $this->picto);
5236  $return .= '</span>';
5237  $return .= '<div class="info-box-content">';
5238  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5239  if ($selected >= 0) {
5240  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5241  }
5242  if (property_exists($this, 'code_client')) {
5243  $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5244  }
5245  if (method_exists($this, 'getLibStatut')) {
5246  $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5247  }
5248  $return .= '</div>';
5249  $return .= '</div>';
5250  $return .= '</div>';
5251 
5252  return $return;
5253  }
5254 
5264  public function getContacts($list = 0, $code = '', $element = '')
5265  {
5266  // phpcs:enable
5267  global $langs;
5268 
5269  $tab = array();
5270 
5271  $sql = "SELECT sc.rowid, sc.fk_socpeople as id, sc.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
5272  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5273  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5274  $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5275  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5276  $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5277  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5278  $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5279  $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5280  if (!empty($element)) {
5281  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5282  }
5283  if ($code) {
5284  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5285  }
5286  $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5287  $sql .= " AND tc.source = 'external'";
5288  $sql .= " AND tc.active = 1";
5289 
5290  $sql .= " ORDER BY t.lastname ASC";
5291 
5292  dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5293  $resql = $this->db->query($sql);
5294  if ($resql) {
5295  $num = $this->db->num_rows($resql);
5296  $i = 0;
5297  while ($i < $num) {
5298  $obj = $this->db->fetch_object($resql);
5299 
5300  if (!$list) {
5301  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5302  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5303  $tab[$i] = array(
5304  'source' => $obj->source,
5305  'socid' => $obj->socid,
5306  'id' => $obj->id,
5307  'nom' => $obj->lastname, // For backward compatibility
5308  'civility' => $obj->civility,
5309  'lastname' => $obj->lastname,
5310  'firstname' => $obj->firstname,
5311  'email' => $obj->email,
5312  'login' => (empty($obj->login) ? '' : $obj->login),
5313  'photo' => (empty($obj->photo) ? '' : $obj->photo),
5314  'statuscontact' => $obj->statuscontact,
5315  'rowid' => $obj->rowid,
5316  'code' => $obj->code,
5317  'element' => $obj->element,
5318  'libelle' => $libelle_type,
5319  'status' => $obj->statuslink,
5320  'fk_c_type_contact' => $obj->fk_c_type_contact
5321  );
5322  } else {
5323  $tab[$i] = $obj->id;
5324  }
5325 
5326  $i++;
5327  }
5328 
5329  return $tab;
5330  } else {
5331  $this->error = $this->db->lasterror();
5332  dol_print_error($this->db);
5333  return -1;
5334  }
5335  }
5336 
5347  public function mergeCompany($soc_origin_id)
5348  {
5349  global $conf, $langs, $hookmanager, $user, $action;
5350 
5351  $error = 0;
5352  $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5353 
5354  dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5355 
5356  if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5357  $this->error = $langs->trans('ErrorRecordNotFound');
5358  $error++;
5359  }
5360 
5361  if (!$error) {
5362  $this->db->begin();
5363 
5364  // Recopy some data
5365  $this->client |= $soc_origin->client;
5366  $this->fournisseur |= $soc_origin->fournisseur;
5367  $listofproperties = array(
5368  'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5369  'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5370  'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5371  'stcomm_id', 'outstanding_limit', 'order_min_amount', 'supplier_order_min_amount', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
5372  'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5373  'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5374  );
5375  foreach ($listofproperties as $property) {
5376  if (empty($this->$property)) {
5377  $this->$property = $soc_origin->$property;
5378  }
5379  }
5380 
5381  if ($this->typent_id == -1) {
5382  $this->typent_id = $soc_origin->typent_id;
5383  }
5384 
5385  // Concat some data
5386  $listofproperties = array(
5387  'note_public', 'note_private'
5388  );
5389  foreach ($listofproperties as $property) {
5390  $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5391  }
5392 
5393  // Merge extrafields
5394  if (is_array($soc_origin->array_options)) {
5395  foreach ($soc_origin->array_options as $key => $val) {
5396  if (empty($this->array_options[$key])) {
5397  $this->array_options[$key] = $val;
5398  }
5399  }
5400  }
5401 
5402  // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5403  if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5404  $this->name_bis = $this->name;
5405  }
5406 
5407  // Merge categories
5408  include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5409  $static_cat = new Categorie($this->db);
5410 
5411  $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5412  $custcats = $static_cat->containing($this->id, 'customer', 'id');
5413  $custcats = array_merge($custcats, $custcats_ori);
5414  $this->setCategories($custcats, 'customer');
5415 
5416  $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5417  $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5418  $suppcats = array_merge($suppcats, $suppcats_ori);
5419  $this->setCategories($suppcats, 'supplier');
5420 
5421  // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5422  if ($soc_origin->code_client == $this->code_client
5423  || $soc_origin->code_fournisseur == $this->code_fournisseur
5424  || $soc_origin->barcode == $this->barcode) {
5425  dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5426  $soc_origin->code_client = '';
5427  $soc_origin->code_fournisseur = '';
5428  $soc_origin->barcode = '';
5429  $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5430  }
5431 
5432  // Update
5433  $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5434 
5435  if ($result < 0) {
5436  $error++;
5437  }
5438 
5439  // Move links
5440  if (!$error) {
5441  $objects = array(
5442  'Adherent' => '/adherents/class/adherent.class.php',
5443  //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5444  'ActionComm' => '/comm/action/class/actioncomm.class.php',
5445  'Propal' => '/comm/propal/class/propal.class.php',
5446  'Commande' => '/commande/class/commande.class.php',
5447  'Facture' => '/compta/facture/class/facture.class.php',
5448  'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5449  'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5450  'Contact' => '/contact/class/contact.class.php',
5451  'Contrat' => '/contrat/class/contrat.class.php',
5452  'Expedition' => '/expedition/class/expedition.class.php',
5453  'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5454  'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5455  'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5456  'Reception' => '/reception/class/reception.class.php',
5457  'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5458  'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5459  'Product' => '/product/class/product.class.php',
5460  //'ProductThirparty' => '...', // for llx_product_thirdparty
5461  'Project' => '/projet/class/project.class.php',
5462  'User' => '/user/class/user.class.php',
5463  'Account' => '/compta/bank/class/account.class.php',
5464  'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5465  'Societe' => '/societe/class/societe.class.php',
5466  //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirparty of Societe.
5467  );
5468  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5469  $objects['Delivery'] = '/delivery/class/delivery.class.php';
5470  }
5471  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5472  $objects['Mo'] = '/mrp/class/mo.class.php';
5473  }
5474  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5475  $objects['Don'] = '/don/class/don.class.php';
5476  }
5477  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5478  $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5479  }
5480  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5481  $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5482  }
5483  if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5484  $objects['Ticket'] = '/ticket/class/ticket.class.php';
5485  }
5486 
5487  //First, all core objects must update their tables
5488  foreach ($objects as $object_name => $object_file) {
5489  if (is_array($object_file)) {
5490  if (empty($object_file['enabled'])) {
5491  continue;
5492  }
5493  $object_file = $object_file['file'];
5494  }
5495 
5496  require_once DOL_DOCUMENT_ROOT.$object_file;
5497 
5498  if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5499  $error++;
5500  $this->error = $this->db->lasterror();
5501  break;
5502  }
5503  }
5504  }
5505 
5506  // External modules should update their ones too
5507  if (!$error) {
5508  $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5509  $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5510 
5511  if ($reshook < 0) {
5512  $this->error = $hookmanager->error;
5513  $this->errors = $hookmanager->errors;
5514  $error++;
5515  }
5516  }
5517 
5518 
5519  if (!$error) {
5520  $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5521 
5522  // Call trigger
5523  $result = $this->call_trigger('COMPANY_MODIFY', $user);
5524  if ($result < 0) {
5525  $error++;
5526  }
5527  // End call triggers
5528  }
5529 
5530  if (!$error) {
5531  // Move files from the dir of the third party to delete into the dir of the third party to keep
5532  if (!empty($conf->societe->multidir_output[$this->entity])) {
5533  $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5534  $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5535 
5536  if (dol_is_dir($srcdir)) {
5537  $dirlist = dol_dir_list($srcdir, 'files', 1);
5538  foreach ($dirlist as $filetomove) {
5539  $destfile = $destdir.'/'.$filetomove['relativename'];
5540  //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5541  dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5542  }
5543  //exit;
5544  }
5545  }
5546  }
5547 
5548 
5549  if (!$error) {
5550  // We finally remove the old thirdparty
5551  if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5552  $this->error = $soc_origin->error;
5553  $this->errors = $soc_origin->errors;
5554  $error++;
5555  }
5556  }
5557 
5558  if (!$error) {
5559  $this->db->commit();
5560  return 0;
5561  } else {
5562  $langs->load("errors");
5563  $this->error = $langs->trans('ErrorsThirdpartyMerge');
5564  $this->db->rollback();
5565  return -1;
5566  }
5567  }
5568 
5569  return -1;
5570  }
5571 }
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition: security.php:604
$object ref
Definition: info.php:79
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage bank accounts description of third parties.
Class to stock current configuration.
Definition: conf.class.php:34
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
update($id, User $user, $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
const PROSPECT
Third party type is a prospect.
create(User $user, $notrigger=0)
Create third party in database.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
setCategories($categories, $type_categ)
Sets object to supplied categories.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
setNoEmail($no_email)
Set "blacklist" mailing status.
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Returns the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='')
Return a link on thirdparty (with picto)
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
getTooltipContentArray($params)
getTooltipContentArray
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
getKanbanView($option='', $arraydata=array())
Return clicable link of object (with eventually picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Returns the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
Definition: user.class.php:50
trait CommonIncoterm
Superclass for incoterm classes.
trait CommonPeople
Support class for thirdparties, contacts, members, users or resources.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getState($id, $withcode='', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:744
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1589
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
Definition: files.lib.php:991
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:489
clean_url($url, $http=1)
Clean an url string.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
div float
Buy price without taxes.
Definition: style.css.php:959
isValidSiren($siren)
Check the syntax validity of a SIREN.
Definition: profid.lib.php:59
isValidTinForPT($str)
Check the syntax validity of a Portuguese (PT) Tax Identification Number (TIN).
Definition: profid.lib.php:111
isValidSiret($siret)
Check the syntax validity of a SIRET.
Definition: profid.lib.php:79
isValidTinForES($str)
Check the syntax validity of a Spanish (ES) Tax Identification Number (TIN), where:
Definition: profid.lib.php:177
isValidTinForBE($str)
Check the syntax validity of a Belgium (BE) Tax Identification Number (TIN).
Definition: profid.lib.php:153
isValidTinForDZ($str)
Check the syntax validity of an Algerian (DZ) Tax Identification Number (TIN).
Definition: profid.lib.php:132
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:125