dolibarr 21.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-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
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-2024 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
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
49
50
54class 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 $restrictiononfksoc = 1;
135
139 public $oldcopy;
140
145 public $SupplierCategories = array();
146
151 public $prefixCustomerIsRequired;
152
182 public $fields = array(
183 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
184 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
185 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
186 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
187 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
188 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
189 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
190 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
191 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
192 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
193 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
194 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
195 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
196 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
197 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
198 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
199 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
200 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
201 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
202 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
203 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
204 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
205 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
206 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
207 'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
208 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
209 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
210 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
211 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
212 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
213 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
214 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
215 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
216 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
217 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
218 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
219 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
220 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
221 'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
222 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
223 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
224 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
225 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
226 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
227 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
228 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
229 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
230 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
231 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
232 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
233 'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
234 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
235 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
236 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
237 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
238 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
239 '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),
240 '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),
241 'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
242 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
243 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
244 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
245 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
246 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
247 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
248 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
249 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
250 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
251 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
252 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
253 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
254 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
255 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
256 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
257 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
258 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
259 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
260 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
261 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
262 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
263 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
264 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
265 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
266 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
267 );
268
272 public $entity;
273
280 public $nom;
281
285 public $name;
286
291 public $name_alias;
292
296 public $particulier;
297
302 public $status = 1;
303
307 public $region_code;
308
312 public $region;
313
317 public $country_id;
318
324 public $departement_code;
325
331 public $departement;
332
338 public $pays;
339
344 public $phone;
349 public $phone_mobile;
354 public $fax;
355
360 public $email;
361
366 public $no_email;
367
373 public $skype;
374
380 public $twitter;
381
387 public $facebook;
388
394 public $linkedin;
395
400 public $url;
401
406 public $barcode;
407
408 // 6 professional id (usage depends on country)
409
414 public $idprof1;
415
421 public $siren;
422
423
428 public $idprof2;
429
435 public $siret;
436
441 public $idprof3;
442
448 public $ape;
449
454 public $idprof4;
455
460 public $idprof5;
461
466 public $idprof6;
467
472 public $idprof7;
473
478 public $idprof8;
479
484 public $idprof9;
485
490 public $idprof10;
491
496 public $socialobject;
497
501 public $prefix_comm;
502
506 public $tva_assuj = 1;
507
511 public $tva_intra;
512
516 public $vat_reverse_charge = 0;
517
518 // Local taxes
522 public $localtax1_assuj;
526 public $localtax1_value;
530 public $localtax2_assuj;
534 public $localtax2_value;
535
539 public $managers;
540
544 public $capital;
545
549 public $typent_id = 0;
553 public $typent_code;
557 public $effectif;
561 public $effectif_id = 0;
565 public $forme_juridique_code = 0;
570 public $forme_juridique;
571
575 public $remise_percent;
579 public $remise_supplier_percent;
580
584 public $mode_reglement_id;
588 public $cond_reglement_id;
592 public $deposit_percent;
596 public $mode_reglement_supplier_id;
600 public $cond_reglement_supplier_id;
604 public $transport_mode_supplier_id;
605
609 public $fk_prospectlevel;
610
614 public $name_bis;
615
621 public $user_modification;
622
628 public $user_creation;
629
634 public $client = 0;
635
640 public $prospect = 0;
641
646 public $fournisseur;
647
652 public $code_client;
653
658 public $code_fournisseur;
659
664 public $code_compta_client;
665
670 public $accountancy_code_customer_general;
671
676 public $accountancy_code_customer;
677
682 public $code_compta_fournisseur;
683
688 public $accountancy_code_supplier_general;
689
694 public $accountancy_code_supplier;
695
700 public $code_compta_product;
701
707 public $note;
708
713 public $note_private;
714
719 public $note_public;
720
725 public $stcomm_id;
726
731 public $stcomm_picto;
732
737 public $status_prospect_label;
738
743 public $price_level;
744
748 public $outstanding_limit;
749
753 public $order_min_amount;
754
758 public $supplier_order_min_amount;
759
764 public $commercial_id;
765
770 public $parent;
771
776 public $default_lang;
777
781 public $ref;
782
788 public $ref_ext;
789
793 public $ip;
794
801 public $import_key;
802
807 public $webservices_url;
808
813 public $webservices_key;
814
818 public $logo;
819
823 public $logo_small;
824
828 public $logo_mini;
829
833 public $logo_squarred;
834
838 public $logo_squarred_small;
839
843 public $logo_squarred_mini;
844
848 public $accountancy_code_sell;
849
853 public $accountancy_code_buy;
854
855 // Multicurrency
859 public $fk_multicurrency;
860
861 // Warehouse
865 public $fk_warehouse;
866
870 public $multicurrency_code;
871
872 // Fields loaded by fetchPartnerships()
873
877 public $partnerships = array();
878
879
883 public $bank_account;
884
885
886 const STATUS_CEASED = 0;
887 const STATUS_INACTIVITY = 1;
888
892 const NO_CUSTOMER = 0;
893
897 const CUSTOMER = 1;
898
902 const PROSPECT = 2;
903
908
912 const NO_SUPPLIER = 0;
913
917 const SUPPLIER = 1;
918
924 protected function deprecatedProperties()
925 {
926 return
927 array(
928 'code_compta' => 'code_compta_client',
929 )
930 + parent::deprecatedProperties();
931 }
932
933
934
940 public function __construct($db)
941 {
942 $this->db = $db;
943
944 $this->ismultientitymanaged = 1;
945 $this->isextrafieldmanaged = 1;
946 $this->client = 0;
947 $this->prospect = 0;
948 $this->fournisseur = 0;
949 $this->typent_id = 0;
950 $this->effectif_id = 0;
951 $this->forme_juridique_code = 0;
952 $this->tva_assuj = 1;
953 $this->vat_reverse_charge = 0;
954 $this->status = 1;
955
956 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
957 $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
958 $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
959 $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
960 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
961 }
962 }
963
964
973 public function create(User $user, $notrigger = 0)
974 {
975 global $langs, $conf;
976
977 $error = 0;
978
979 // Clean parameters
980 if (empty($this->status)) {
981 $this->status = 0;
982 }
983 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
984 $this->setUpperOrLowerCase();
985 $this->nom = $this->name; // For backward compatibility
986 if (empty($this->client)) {
987 $this->client = 0;
988 }
989 if (empty($this->fournisseur)) {
990 $this->fournisseur = 0;
991 }
992 $this->import_key = trim((string) $this->import_key);
993
994 $this->code_compta_client = trim($this->code_compta_client);
995
996 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general);
997 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
998 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general);
999 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1000 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1001 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1002
1003 if (!empty($this->multicurrency_code)) {
1004 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1005 }
1006 if (empty($this->fk_multicurrency)) {
1007 $this->multicurrency_code = '';
1008 $this->fk_multicurrency = 0;
1009 }
1010
1011 dol_syslog(get_class($this)."::create ".$this->name);
1012
1013 $now = dol_now();
1014
1015 if (empty($this->date_creation)) {
1016 $this->date_creation = $now;
1017 }
1018
1019 $this->db->begin();
1020
1021 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1022 if ($this->code_client == -1 || $this->code_client === 'auto') {
1023 $this->get_codeclient($this, 0);
1024 }
1025 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1026 $this->get_codefournisseur($this, 1);
1027 }
1028
1029 // Check more parameters (including mandatory setup
1030 // If error, this->errors[] is filled
1031 $result = $this->verify();
1032
1033 if ($result >= 0) {
1034 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1035
1036 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1037 $sql .= "nom";
1038 $sql .= ", name_alias";
1039 $sql .= ", entity";
1040 $sql .= ", datec";
1041 $sql .= ", fk_user_creat";
1042 $sql .= ", fk_typent";
1043 $sql .= ", canvas";
1044 $sql .= ", status";
1045 $sql .= ", ref_ext";
1046 $sql .= ", fk_stcomm";
1047 $sql .= ", fk_incoterms";
1048 $sql .= ", location_incoterms";
1049 $sql .= ", import_key";
1050 $sql .= ", fk_multicurrency";
1051 $sql .= ", multicurrency_code";
1052 $sql .= ", ip";
1053 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1054 $sql .= ", vat_reverse_charge";
1055 $sql .= ", accountancy_code_buy";
1056 $sql .= ", accountancy_code_sell";
1057 }
1058 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1059 $sql .= " '".$this->db->escape($this->name_alias)."',";
1060 $sql .= " ".((int) $this->entity).",";
1061 $sql .= " '".$this->db->idate($this->date_creation)."'";
1062 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1063 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1064 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1065 $sql .= ", ".((int) $this->status);
1066 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1067 $sql .= ", 0";
1068 $sql .= ", ".(int) $this->fk_incoterms;
1069 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1070 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1071 $sql .= ", ".(int) $this->fk_multicurrency;
1072 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1073 $sql .= ", '".$this->db->escape($this->ip)."'";
1074 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1075 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1076 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1077 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1078 }
1079 $sql .= ")";
1080
1081 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1082
1083 $result = $this->db->query($sql);
1084 if ($result) {
1085 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1086
1087 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1088
1089 // update accountancy for this entity
1090 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1091 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1092
1093 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1094 $sql .= " fk_soc";
1095 $sql .= ", entity";
1096 $sql .= ", vat_reverse_charge";
1097 $sql .= ", accountancy_code_customer_general";
1098 $sql .= ", accountancy_code_customer";
1099 $sql .= ", accountancy_code_supplier_general";
1100 $sql .= ", accountancy_code_supplier";
1101 $sql .= ", accountancy_code_buy";
1102 $sql .= ", accountancy_code_sell";
1103 $sql .= ") VALUES (";
1104 $sql .= $this->id;
1105 $sql .= ", ".((int) $conf->entity);
1106 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1107 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1108 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1109 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1110 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1111 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1112 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1113 $sql .= ")";
1114 $result = $this->db->query($sql);
1115 if (!$result) {
1116 $error++;
1117 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1118 }
1119 }
1120
1121 // Ajout du commercial affecte
1122 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1123 $this->add_commercial($user, $this->commercial_id);
1124 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1125 // si un commercial cree un client il lui est affecte automatiquement
1126 $this->add_commercial($user, $user->id);
1127 }
1128
1129 if ($ret >= 0) {
1130 if (! $notrigger) {
1131 // Call trigger
1132 $result = $this->call_trigger('COMPANY_CREATE', $user);
1133 if ($result < 0) {
1134 $error++;
1135 }
1136 // End call triggers
1137 }
1138 } else {
1139 $error++;
1140 }
1141
1142 if (!$error) {
1143 dol_syslog(get_class($this)."::Create success id=".$this->id);
1144 $this->db->commit();
1145 return $this->id;
1146 } else {
1147 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1148 $this->db->rollback();
1149 return -4;
1150 }
1151 } else {
1152 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1153 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1154 $result = -1;
1155 } else {
1156 $this->error = $this->db->lasterror();
1157 $result = -2;
1158 }
1159 $this->db->rollback();
1160 return $result;
1161 }
1162 } else {
1163 $this->db->rollback();
1164 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1165 return -3;
1166 }
1167 }
1168
1169
1170 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1180 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1181 {
1182 global $conf;
1183
1184 $error = 0;
1185
1186 $this->db->begin();
1187
1188 // phpcs:enable
1189 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1190 $contact = new Contact($this->db);
1191
1192 $contact->name = $this->name_bis;
1193 $contact->firstname = $this->firstname;
1194 $contact->civility_id = $this->civility_id;
1195 $contact->socid = $this->id; // fk_soc
1196 $contact->statut = 1; // deprecated
1197 $contact->status = 1;
1198 $contact->priv = 0;
1199 $contact->country_id = $this->country_id;
1200 $contact->state_id = $this->state_id;
1201 $contact->address = $this->address;
1202 $contact->email = $this->email;
1203 $contact->zip = $this->zip;
1204 $contact->town = $this->town;
1205 $this->setUpperOrLowerCase();
1206 $contact->phone_pro = $this->phone;
1207 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1208 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1209 }
1210
1211 $contactId = $contact->create($user, $notrigger);
1212 if ($contactId < 0) {
1213 $error++;
1214 $this->error = $contact->error;
1215 $this->errors = $contact->errors;
1216 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1217 }
1218
1219 if (empty($error) && is_array($tags) && !empty($tags)) {
1220 $result = $contact->setCategories($tags);
1221 if ($result < 0) {
1222 $error++;
1223 $this->error = $contact->error;
1224 $this->errors = array_merge($this->errors, $contact->errors);
1225 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1226 $contactId = $result;
1227 }
1228 }
1229
1230 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1231 $result = $contact->setNoEmail($no_email);
1232 if ($result < 0) {
1233 $this->error = $contact->error;
1234 $this->errors = array_merge($this->errors, $contact->errors);
1235 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1236 $contactId = $result;
1237 }
1238 }
1239
1240 if (empty($error)) {
1241 dol_syslog(get_class($this)."::create_individual success");
1242 $this->db->commit();
1243 } else {
1244 $this->db->rollback();
1245 }
1246
1247 return $contactId;
1248 }
1249
1256 public function verify()
1257 {
1258 global $conf, $langs, $mysoc;
1259
1260 $error = 0;
1261 $this->errors = array();
1262
1263 $result = 0;
1264 $this->name = trim($this->name);
1265 $this->nom = $this->name; // For backward compatibility
1266
1267 if (!$this->name) {
1268 $this->errors[] = 'ErrorBadThirdPartyName';
1269 $result = -2;
1270 }
1271
1272 if ($this->client) {
1273 $rescode = $this->check_codeclient();
1274 if ($rescode != 0 && $rescode != -5) {
1275 if ($rescode == -1) {
1276 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1277 } elseif ($rescode == -2) {
1278 $this->errors[] = 'ErrorCustomerCodeRequired';
1279 } elseif ($rescode == -3) {
1280 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1281 } elseif ($rescode == -4) {
1282 $this->errors[] = 'ErrorPrefixRequired';
1283 } else {
1284 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1285 }
1286
1287 $result = -3;
1288 }
1289 }
1290
1291 if ($this->fournisseur) {
1292 $rescode = $this->check_codefournisseur();
1293 if ($rescode != 0 && $rescode != -5) {
1294 if ($rescode == -1) {
1295 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1296 } elseif ($rescode == -2) {
1297 $this->errors[] = 'ErrorSupplierCodeRequired';
1298 } elseif ($rescode == -3) {
1299 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1300 } elseif ($rescode == -4) {
1301 $this->errors[] = 'ErrorPrefixRequired';
1302 } else {
1303 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1304 }
1305 $result = -3;
1306 }
1307 }
1308
1309 // Check for duplicate or mandatory fields defined into setup
1310 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1311 foreach ($array_to_check as $key) {
1312 $keymin = strtolower($key);
1313 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1314 $keymin = 'code_compta_client';
1315 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1316 $keymin = 'code_compta_fournisseur';
1317 }
1318 $i = (int) preg_replace('/[^0-9]/', '', $key);
1319 $vallabel = $this->$keymin;
1320
1321 if ($i > 0) {
1322 if ($mysoc != null && $this->isACompany()) {
1323 // Check for mandatory prof id (but only if country is same than ours)
1324 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1325 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1326 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1327 $langs->load("errors");
1328 $error++;
1329 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1330 }
1331 }
1332 }
1333
1334 // Check for unicity on profid
1335 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1336 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1337 $langs->load("errors");
1338 $error++;
1339 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1340 }
1341 }
1342 } else {
1343 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1344 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1345 if ($key == 'EMAIL') {
1346 // Check for mandatory
1347 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1348 $langs->load("errors");
1349 $error++;
1350 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1351 }
1352
1353 // Check for unicity
1354 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1355 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1356 $langs->load("errors");
1357 $error++;
1358 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1359 }
1360 }
1361 } elseif ($key == 'TVA_INTRA') {
1362 // Check for unicity
1363 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1364 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1365 $langs->load("errors");
1366 $error++;
1367 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1368 }
1369 }
1370 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1371 // Check for unicity
1372 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1373 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1374 $langs->loadLangs(array("errors", 'compta'));
1375 $error++;
1376 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1377 }
1378 }
1379
1380 // Check for mandatory
1381 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1382 $langs->loadLangs(array("errors", 'compta'));
1383 $error++;
1384 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1385 }
1386 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1387 // Check for unicity
1388 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1389 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1390 $langs->loadLangs(array("errors", 'compta'));
1391 $error++;
1392 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1393 }
1394 }
1395
1396 // Check for mandatory
1397 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1398 $langs->loadLangs(array("errors", 'compta'));
1399 $error++;
1400 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1401 }
1402 }
1403 }
1404 }
1405
1406 if ($error) {
1407 $result = -4;
1408 }
1409
1410 return $result;
1411 }
1412
1425 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1426 {
1427 global $langs, $conf, $hookmanager;
1428
1429 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1430
1431 if (empty($id)) {
1432 $id = $this->id;
1433 }
1434
1435 $error = 0;
1436
1437 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1438
1439 $now = dol_now();
1440
1441 // Clean parameters
1442 $this->id = $id;
1443 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1444 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1445 $this->nom = $this->name; // For backward compatibility
1446 $this->name_alias = trim((string) $this->name_alias);
1447 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1448 $this->address = trim((string) $this->address);
1449 $this->zip = trim((string) $this->zip);
1450 $this->town = trim((string) $this->town);
1451 $this->state_id = (is_numeric($this->state_id)) ? (int) trim((string) $this->state_id) : 0;
1452 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1453 $this->phone = trim((string) $this->phone);
1454 $this->phone = preg_replace("/\s/", "", $this->phone);
1455 $this->phone = preg_replace("/\./", "", $this->phone);
1456 $this->phone_mobile = trim((string) $this->phone_mobile);
1457 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1458 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1459 $this->fax = trim((string) $this->fax);
1460 $this->fax = preg_replace("/\s/", "", $this->fax);
1461 $this->fax = preg_replace("/\./", "", $this->fax);
1462 $this->email = trim((string) $this->email);
1463 $this->url = $this->url ? clean_url($this->url, 0) : '';
1464 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1465 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1466 $this->idprof1 = trim((string) $this->idprof1);
1467 $this->idprof2 = trim((string) $this->idprof2);
1468 $this->idprof3 = trim((string) $this->idprof3);
1469 $this->idprof4 = trim((string) $this->idprof4);
1470 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1471 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1472 $this->prefix_comm = trim((string) $this->prefix_comm);
1473 $this->outstanding_limit = price2num($this->outstanding_limit);
1474 $this->order_min_amount = price2num($this->order_min_amount);
1475 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1476
1477 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1478 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1479 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1480 if (empty($this->status)) {
1481 $this->status = 0;
1482 }
1483
1484 if (!empty($this->multicurrency_code)) {
1485 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1486 }
1487 if (empty($this->fk_multicurrency)) {
1488 $this->multicurrency_code = '';
1489 $this->fk_multicurrency = 0;
1490 }
1491
1492 // Local taxes
1493 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1494 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1495
1496 $this->localtax1_value = trim($this->localtax1_value);
1497 $this->localtax2_value = trim($this->localtax2_value);
1498
1499 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1500
1501 $this->effectif_id = (int) trim((string) $this->effectif_id);
1502 $this->forme_juridique_code = (int) trim((string) $this->forme_juridique_code);
1503
1504 //Gencod
1505 $this->barcode = trim($this->barcode);
1506
1507 // For automatic creation
1508 if ($this->code_client == -1 || $this->code_client === 'auto') {
1509 $this->get_codeclient($this, 0);
1510 }
1511 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1512 $this->get_codefournisseur($this, 1);
1513 }
1514
1515 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general);
1516 $this->code_compta_client = trim($this->code_compta_client);
1517 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general);
1518 $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1519
1520 // Check parameters. More tests are done later in the ->verify()
1521 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1522 $langs->load("errors");
1523 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1524 return -1;
1525 }
1526
1527 $customer = false;
1528 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1529 // If $allowmodcodeclient is set and value is not set, we generate it
1530 if (empty($this->code_compta_client)) {
1531 $ret = $this->get_codecompta('customer');
1532 if ($ret < 0) {
1533 return -1;
1534 }
1535 }
1536
1537 $customer = true;
1538 }
1539
1540 $supplier = false;
1541 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1542 // If $allowmodcodefournisseur is set and value is not set, we generate it
1543 if (empty($this->code_compta_fournisseur)) {
1544 $ret = $this->get_codecompta('supplier');
1545 if ($ret < 0) {
1546 return -1;
1547 }
1548 }
1549
1550 $supplier = true;
1551 }
1552
1553 //Web services
1554 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1555 $this->webservices_key = trim($this->webservices_key);
1556
1557 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1558 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1559
1560 //Incoterms
1561 $this->fk_incoterms = (int) $this->fk_incoterms;
1562 $this->location_incoterms = trim($this->location_incoterms);
1563
1564 $this->db->begin();
1565
1566 // Check name is required and codes are ok or unique.
1567 // If error, this->errors[] is filled
1568 $result = 0;
1569 if ($action != 'add' && $action != 'merge') {
1570 // We don't check when update called during a create because verify was already done.
1571 // 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
1572 $result = $this->verify();
1573
1574 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1575 // So we can update record that were using and old numbering rule.
1576 if (is_array($this->errors)) {
1577 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1578 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1579 unset($this->errors[$key]); // Remove error message
1580 }
1581 }
1582 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1583 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1584 unset($this->errors[$key]); // Remove error message
1585 }
1586 }
1587 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1588 $result = 0;
1589 }
1590 }
1591 }
1592 $this->setUpperOrLowerCase();
1593 if ($result >= 0) {
1594 dol_syslog(get_class($this)."::update verify ok or not done");
1595
1596 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1597 $sql .= "entity = ".((int) $this->entity);
1598 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1599 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1600 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1601 $sql .= ",address = '".$this->db->escape($this->address)."'";
1602
1603 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1604 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1605
1606 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1607 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1608
1609 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1610 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1611 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1612 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1613 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1614 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1615
1616 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1617
1618 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1619 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1620
1621 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1622 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1623 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1624 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1625 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1626 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1627
1628 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1629 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1630 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1631 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1632 }
1633 $sql .= ",status = ".((int) $this->status);
1634
1635 // Local taxes
1636 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1637 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1638 if ($this->localtax1_assuj == 1) {
1639 if ($this->localtax1_value != '') {
1640 $sql .= ",localtax1_value =".$this->localtax1_value;
1641 } else {
1642 $sql .= ",localtax1_value =0.000";
1643 }
1644 } else {
1645 $sql .= ",localtax1_value =0.000";
1646 }
1647
1648 if ($this->localtax2_assuj == 1) {
1649 if ($this->localtax2_value != '') {
1650 $sql .= ",localtax2_value =".$this->localtax2_value;
1651 } else {
1652 $sql .= ",localtax2_value =0.000";
1653 }
1654 } else {
1655 $sql .= ",localtax2_value =0.000";
1656 }
1657
1658 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1659
1660 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1661
1662 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1663 if (isset($this->stcomm_id)) {
1664 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1665 }
1666 if (isset($this->typent_id)) {
1667 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1668 }
1669
1670 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1671
1672 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1673 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1674 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1675 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1676 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1677 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1678 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1679 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1680
1681 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1682 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1683 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1684 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1685 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1686 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1687 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1688 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1689 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1690 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1691 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1692 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1693 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1694 if ($customer) {
1695 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1696 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1697 }
1698
1699 if ($supplier) {
1700 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1701 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1702 }
1703 }
1704 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1705 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1706
1707 //Incoterms
1708 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1709 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1710
1711 if ($customer) {
1712 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1713 }
1714
1715 if ($supplier) {
1716 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1717 }
1718 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1719 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1720 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1721 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1722 $sql .= " WHERE rowid = ".(int) $id;
1723
1724 $resql = $this->db->query($sql);
1725 if ($resql) {
1726 if (is_object($this->oldcopy)) { // If we have information on old values
1727 if ($this->oldcopy->country_id != $this->country_id) {
1728 unset($this->country_code);
1729 unset($this->country);
1730 }
1731 if ($this->oldcopy->state_id != $this->state_id) {
1732 unset($this->state_code);
1733 unset($this->state);
1734 }
1735 } else {
1736 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1737 unset($this->country);
1738 unset($this->state_code);
1739 unset($this->state);
1740 }
1741
1742 $nbrowsaffected = $this->db->affected_rows($resql);
1743
1744 if (!$error && $nbrowsaffected) {
1745 // Update information on linked member if it is an update
1746 if (!$nosyncmember && isModEnabled('member')) {
1747 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1748
1749 dol_syslog(get_class($this)."::update update linked member");
1750
1751 $lmember = new Adherent($this->db);
1752 $result = $lmember->fetch(0, 0, $this->id);
1753
1754 if ($result > 0) {
1755 $lmember->company = $this->name;
1756 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1757 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1758 $lmember->address = $this->address;
1759 $lmember->zip = $this->zip;
1760 $lmember->town = $this->town;
1761 $lmember->email = $this->email;
1762 $lmember->socialnetworks = $this->socialnetworks;
1763 $lmember->phone = $this->phone;
1764 $lmember->state_id = $this->state_id;
1765 $lmember->country_id = $this->country_id;
1766 $lmember->default_lang = $this->default_lang;
1767
1768 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1769 if ($result < 0) {
1770 $this->error = $lmember->error;
1771 $this->errors = array_merge($this->errors, $lmember->errors);
1772 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1773 $error++;
1774 }
1775 } elseif ($result < 0) {
1776 $this->error = $lmember->error;
1777 $error++;
1778 }
1779 }
1780 }
1781
1782 $action = 'update';
1783
1784 // update accountancy for this entity
1785 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1786 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1787
1788 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1789 $sql .= " fk_soc";
1790 $sql .= ", entity";
1791 $sql .= ", vat_reverse_charge";
1792 $sql .= ", accountancy_code_customer_general";
1793 $sql .= ", accountancy_code_customer";
1794 $sql .= ", accountancy_code_supplier_general";
1795 $sql .= ", accountancy_code_supplier";
1796 $sql .= ", accountancy_code_buy";
1797 $sql .= ", accountancy_code_sell";
1798 $sql .= ") VALUES (";
1799 $sql .= $this->id;
1800 $sql .= ", ".$conf->entity;
1801 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1802 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1803 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1804 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1805 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1806 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1807 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1808 $sql .= ")";
1809 $result = $this->db->query($sql);
1810 if (!$result) {
1811 $error++;
1812 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1813 }
1814 }
1815
1816 // Actions on extra fields
1817 if (!$error) {
1818 $result = $this->insertExtraFields();
1819 if ($result < 0) {
1820 $error++;
1821 }
1822 }
1823 // Actions on extra languages
1824 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1825 $result = $this->insertExtraLanguages();
1826 if ($result < 0) {
1827 $error++;
1828 }
1829 }
1830
1831 if (!$error && $call_trigger) {
1832 // Call trigger
1833 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1834 if ($result < 0) {
1835 $error++;
1836 }
1837 // End call triggers
1838 }
1839
1840 if (!$error) {
1841 dol_syslog(get_class($this)."::Update success");
1842 $this->db->commit();
1843 return 1;
1844 } else {
1845 $this->db->rollback();
1846 return -1;
1847 }
1848 } else {
1849 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1850 // Doublon
1851 $this->error = $langs->trans("ErrorDuplicateField");
1852 $result = -1;
1853 } else {
1854 $this->error = $this->db->lasterror();
1855 $result = -2;
1856 }
1857 $this->db->rollback();
1858 return $result;
1859 }
1860 } else {
1861 $this->db->rollback();
1862 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1863 return -3;
1864 }
1865 }
1866
1886 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1887 {
1888 global $langs;
1889 global $conf;
1890
1891 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)) {
1892 return -1;
1893 }
1894
1895 $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';
1896 $sql .= ', s.status, s.fk_warehouse';
1897 $sql .= ', s.price_level';
1898 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1899 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1900 $sql .= ', s.socialnetworks';
1901 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1902 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1903 $sql .= ', s.capital, s.tva_intra';
1904 $sql .= ', s.fk_typent as typent_id';
1905 $sql .= ', s.fk_effectif as effectif_id';
1906 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1907 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1908 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1909 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1910 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1911 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1912 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1913 } else {
1914 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1915 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1916 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1917 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1918 }
1919 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1920 $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';
1921 $sql .= ', s.fk_account, s.tva_assuj';
1922 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1923 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1924 $sql .= ', s.fk_shipping_method';
1925 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1926 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1927 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1928 $sql .= ', fj.libelle as forme_juridique';
1929 $sql .= ', e.libelle as effectif';
1930 $sql .= ', c.code as country_code, c.label as country';
1931 $sql .= ', d.code_departement as state_code, d.nom as state';
1932 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1933 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1934 $sql .= ', te.code as typent_code';
1935 $sql .= ', i.libelle as label_incoterms';
1936 if (!isModEnabled('multicompany')) {
1937 $sql .= ', s.remise_client, s.remise_supplier';
1938 } else {
1939 $sql .= ', sr.remise_client, sr2.remise_supplier';
1940 }
1941 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1942 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1943 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1944 }
1945 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1946 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1947 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1948 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1949 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1950 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1951 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1952 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1953 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1954 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1955 if (isModEnabled('multicompany')) {
1956 $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').'))';
1957 $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').'))';
1958 }
1959 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1960
1961 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1962 if ($is_client) {
1963 $sql .= ' AND s.client > 0';
1964 }
1965 if ($is_supplier) {
1966 $sql .= ' AND s.fournisseur > 0';
1967 } // if both false, no test (the thirdparty can be client and/or supplier)
1968
1969 if ($rowid) {
1970 $sql .= ' AND s.rowid = '.((int) $rowid);
1971 }
1972 if ($ref) {
1973 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1974 }
1975 if ($ref_alias) {
1976 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1977 }
1978 if ($ref_ext) {
1979 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1980 }
1981 if ($barcode) {
1982 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1983 }
1984 if ($idprof1) {
1985 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1986 }
1987 if ($idprof2) {
1988 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1989 }
1990 if ($idprof3) {
1991 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1992 }
1993 if ($idprof4) {
1994 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1995 }
1996 if ($idprof5) {
1997 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1998 }
1999 if ($idprof6) {
2000 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2001 }
2002 if ($email) {
2003 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2004 }
2005
2006 $resql = $this->db->query($sql);
2007 if ($resql) {
2008 $num = $this->db->num_rows($resql);
2009 if ($num > 1) {
2010 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2011 dol_syslog($this->error, LOG_ERR);
2012 $result = -2;
2013 } elseif ($num) { // $num = 1
2014 $obj = $this->db->fetch_object($resql);
2015
2016 $this->id = $obj->rowid;
2017 $this->entity = $obj->entity;
2018 $this->canvas = $obj->canvas;
2019
2020 $this->ref = $obj->rowid;
2021 $this->name = $obj->name;
2022 $this->nom = $obj->name; // deprecated
2023 $this->name_alias = $obj->name_alias;
2024 $this->ref_ext = $obj->ref_ext;
2025
2026 $this->date_creation = $this->db->jdate($obj->date_creation);
2027 $this->date_modification = $this->db->jdate($obj->date_modification);
2028 $this->user_creation_id = $obj->fk_user_creat;
2029 $this->user_modification_id = $obj->fk_user_modif;
2030
2031 $this->address = $obj->address;
2032 $this->zip = $obj->zip;
2033 $this->town = $obj->town;
2034
2035 $this->country_id = $obj->country_id;
2036 $this->country_code = $obj->country_id ? $obj->country_code : '';
2037 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2038
2039 $this->state_id = $obj->state_id;
2040 $this->state_code = $obj->state_code;
2041 $this->region_id = $obj->region_id;
2042 $this->region_code = $obj->region_code;
2043 $this->state = ($obj->state != '-' ? $obj->state : '');
2044
2045 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2046 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2047 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2048 $this->status_prospect_label = $label; // label status prospect
2049 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2050
2051 $this->email = $obj->email;
2052 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2053
2054 $this->url = $obj->url;
2055 $this->phone = $obj->phone;
2056 $this->phone_mobile = $obj->phone_mobile;
2057 $this->fax = $obj->fax;
2058
2059 $this->parent = $obj->parent;
2060
2061 $this->idprof1 = $obj->idprof1;
2062 $this->idprof2 = $obj->idprof2;
2063 $this->idprof3 = $obj->idprof3;
2064 $this->idprof4 = $obj->idprof4;
2065 $this->idprof5 = $obj->idprof5;
2066 $this->idprof6 = $obj->idprof6;
2067
2068 $this->capital = $obj->capital;
2069
2070 $this->code_client = $obj->code_client;
2071 $this->code_fournisseur = $obj->code_fournisseur;
2072
2073 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2074 $this->code_compta_client = $obj->code_compta;
2075 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2076 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2077
2078 $this->barcode = $obj->barcode;
2079
2080 $this->tva_assuj = $obj->tva_assuj;
2081 $this->tva_intra = $obj->tva_intra;
2082
2083 if (!empty($obj->spe_vat_reverse_charge)) {
2084 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2085 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2086 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2087 } else {
2088 $this->vat_reverse_charge = 0;
2089 }
2090
2091 $this->status = $obj->status;
2092
2093 // Local Taxes
2094 $this->localtax1_assuj = $obj->localtax1_assuj;
2095 $this->localtax2_assuj = $obj->localtax2_assuj;
2096
2097 $this->localtax1_value = $obj->localtax1_value;
2098 $this->localtax2_value = $obj->localtax2_value;
2099
2100 $this->typent_id = $obj->typent_id;
2101 $this->typent_code = $obj->typent_code;
2102
2103 $this->effectif_id = $obj->effectif_id;
2104 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2105
2106 $this->forme_juridique_code = $obj->forme_juridique_code;
2107 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2108
2109 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2110
2111 $this->prefix_comm = $obj->prefix_comm;
2112
2113 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2114 $this->remise_supplier_percent = $obj->remise_supplier;
2115
2116 $this->mode_reglement_id = $obj->mode_reglement;
2117 $this->cond_reglement_id = $obj->cond_reglement;
2118 $this->deposit_percent = $obj->deposit_percent;
2119 $this->transport_mode_id = $obj->transport_mode;
2120 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2121 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2122 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2123 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2124 $this->fk_account = $obj->fk_account;
2125
2126 $this->client = $obj->client;
2127 $this->fournisseur = $obj->fournisseur;
2128
2129 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2130 $this->note_private = $obj->note_private;
2131 $this->note_public = $obj->note_public;
2132 $this->model_pdf = $obj->model_pdf;
2133 $this->default_lang = $obj->default_lang;
2134 $this->logo = $obj->logo;
2135 $this->logo_squarred = $obj->logo_squarred;
2136
2137 $this->webservices_url = $obj->webservices_url;
2138 $this->webservices_key = $obj->webservices_key;
2139
2140 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2141 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2142
2143 $this->outstanding_limit = $obj->outstanding_limit;
2144 $this->order_min_amount = $obj->order_min_amount;
2145 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2146
2147 // multiprix
2148 $this->price_level = $obj->price_level;
2149
2150 // warehouse
2151 $this->fk_warehouse = $obj->fk_warehouse;
2152
2153 $this->import_key = $obj->import_key;
2154
2155 //Incoterms
2156 $this->fk_incoterms = $obj->fk_incoterms;
2157 $this->location_incoterms = $obj->location_incoterms;
2158 $this->label_incoterms = $obj->label_incoterms;
2159
2160 // multicurrency
2161 $this->fk_multicurrency = $obj->fk_multicurrency;
2162 $this->multicurrency_code = $obj->multicurrency_code;
2163
2164 // pdf
2165 $this->model_pdf = $obj->model_pdf;
2166 $this->last_main_doc = $obj->last_main_doc;
2167
2168 $result = $this->id;
2169
2170 // fetch optionals attributes and labels
2171 $this->fetch_optionals();
2172 } else {
2173 $result = 0;
2174 }
2175
2176 $this->db->free($resql);
2177 } else {
2178 $this->error = $this->db->lasterror();
2179 $this->errors[] = $this->db->lasterror();
2180 $result = -3;
2181 }
2182
2183 // Use first price level if level not defined for third party
2184 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2185 $this->price_level = 1;
2186 }
2187
2188 return $result;
2189 }
2190
2211 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2212 {
2213 // A rowid is known, it is a unique key so we found it
2214 if ($rowid) {
2215 return $rowid;
2216 }
2217
2218 // We try to find the thirdparty with exact matching on all fields
2219 // TODO Replace this with step by step search
2220 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2221 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2222 // Then search on email (+ restriction on is_client and is_supplier)
2223 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2224 $tmpthirdparty = new Societe($this->db);
2225 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2226
2227 return $result;
2228 }
2229
2238 public function delete($id, $fuser = null, $call_trigger = 1)
2239 {
2240 global $conf, $user;
2241
2242 if (empty($fuser)) {
2243 $fuser = $user;
2244 }
2245
2246 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2247
2248 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2249
2250 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2251 $error = 0;
2252
2253 // Test if child exists
2254 $objectisused = $this->isObjectUsed($id);
2255 if (empty($objectisused)) {
2256 $this->db->begin();
2257
2258 // User is mandatory for trigger call
2259 if (!$error && $call_trigger) {
2260 // Call trigger
2261 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2262 if ($result < 0) {
2263 $error++;
2264 }
2265 // End call triggers
2266 }
2267
2268 if (!$error) {
2269 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2270 $static_cat = new Categorie($this->db);
2271 $toute_categs = array();
2272
2273 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2274 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2275 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2276
2277 // Remove each "Categorie"
2278 foreach ($toute_categs as $type => $categs_type) {
2279 foreach ($categs_type as $cat) {
2280 $cat->del_type($this, $type);
2281 }
2282 }
2283 }
2284
2285 if (!$error) {
2286 foreach ($this->childtablesoncascade as $tabletodelete) {
2287 $deleteFromObject = explode(':', $tabletodelete, 4);
2288 if (count($deleteFromObject) >= 2) {
2289 $className = str_replace('@', '', $deleteFromObject[0]);
2290 $filepath = $deleteFromObject[1];
2291 $columnName = $deleteFromObject[2];
2292 if (dol_include_once($filepath)) {
2293 $child_object = new $className($this->db);
2294 '@phan-var-force CommonObject $child_object';
2295 $result = $child_object->deleteByParentField($id, $columnName);
2296 if ($result < 0) {
2297 $error++;
2298 $this->errors[] = $child_object->error;
2299 break;
2300 }
2301 } else {
2302 $error++;
2303 $this->errors[] = 'Cannot include child class file '.$filepath;
2304 break;
2305 }
2306 } else {
2307 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2308 $sql .= " WHERE fk_soc = ".((int) $id);
2309 if (!$this->db->query($sql)) {
2310 $error++;
2311 $this->errors[] = $this->db->lasterror();
2312 break;
2313 }
2314 }
2315 }
2316 }
2317
2318 // Removed extrafields
2319 if (!$error) {
2320 $result = $this->deleteExtraFields();
2321 if ($result < 0) {
2322 $error++;
2323 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2324 }
2325 }
2326
2327 // Remove links to subsidiaries companies
2328 if (!$error) {
2329 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2330 $sql .= " SET parent = NULL";
2331 $sql .= " WHERE parent = ".((int) $id);
2332 if (!$this->db->query($sql)) {
2333 $error++;
2334 $this->errors[] = $this->db->lasterror();
2335 }
2336 }
2337
2338 // Remove third party
2339 if (!$error) {
2340 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2341 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2342 $sql .= " WHERE fk_soc = ".((int) $id);
2343 if (!$this->db->query($sql)) {
2344 $error++;
2345 $this->errors[] = $this->db->lasterror();
2346 }
2347 }
2348
2349 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2350 $sql .= " WHERE rowid = ".((int) $id);
2351 if (!$this->db->query($sql)) {
2352 $error++;
2353 $this->errors[] = $this->db->lasterror();
2354 }
2355 }
2356
2357 if (!$error) {
2358 $this->db->commit();
2359
2360 // Delete directory
2361 if (!empty($conf->societe->multidir_output[$entity])) {
2362 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2363 if (dol_is_dir($docdir)) {
2364 dol_delete_dir_recursive($docdir);
2365 }
2366 }
2367
2368 return 1;
2369 } else {
2370 dol_syslog($this->error, LOG_ERR);
2371 $this->db->rollback();
2372 return -1;
2373 }
2374 } else {
2375 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2376 }
2377 return 0;
2378 }
2379
2380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2388 public function set_as_client()
2389 {
2390 global $conf;
2391 // phpcs:enable
2392 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2393 return $this->setAsCustomer();
2394 }
2395
2402 public function setAsCustomer()
2403 {
2404 if ($this->id) {
2405 $newclient = 1;
2406 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2407 $newclient = 3; //If prospect, we keep prospect tag
2408 }
2409 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2410 $sql .= " SET client = ".((int) $newclient);
2411 $sql .= " WHERE rowid = ".((int) $this->id);
2412
2413 $resql = $this->db->query($sql);
2414 if ($resql) {
2415 $this->client = $newclient;
2416 return 1;
2417 } else {
2418 return -1;
2419 }
2420 }
2421 return 0;
2422 }
2423
2424 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2433 public function set_remise_client($remise, $note, User $user)
2434 {
2435 // phpcs:enable
2436 global $conf, $langs;
2437
2438 // Parameter cleaning
2439 $note = trim($note);
2440 if (!$note) {
2441 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2442 return -2;
2443 }
2444
2445 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2446
2447 if ($this->id) {
2448 $this->db->begin();
2449
2450 $now = dol_now();
2451
2452 // Position current discount
2453 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2454 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2455 $sql .= " WHERE rowid = ".((int) $this->id);
2456 $resql = $this->db->query($sql);
2457 if (!$resql) {
2458 $this->db->rollback();
2459 $this->error = $this->db->error();
2460 return -1;
2461 }
2462
2463 // Writes trace in discount history
2464 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2465 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2466 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2467 $sql .= " '".$this->db->escape($note)."',";
2468 $sql .= " ".((int) $user->id);
2469 $sql .= ")";
2470
2471 $resql = $this->db->query($sql);
2472 if (!$resql) {
2473 $this->db->rollback();
2474 $this->error = $this->db->lasterror();
2475 return -1;
2476 }
2477
2478 $this->db->commit();
2479
2480 return 1;
2481 }
2482 return -1;
2483 }
2484
2485 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2494 public function set_remise_supplier($remise, $note, User $user)
2495 {
2496 // phpcs:enable
2497 global $conf, $langs;
2498
2499 // Parameter cleaning
2500 $note = trim($note);
2501 if (!$note) {
2502 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2503 return -2;
2504 }
2505
2506 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2507
2508 if ($this->id) {
2509 $this->db->begin();
2510
2511 $now = dol_now();
2512
2513 // Position current discount
2514 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2515 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2516 $sql .= " WHERE rowid = ".((int) $this->id);
2517 $resql = $this->db->query($sql);
2518 if (!$resql) {
2519 $this->db->rollback();
2520 $this->error = $this->db->error();
2521 return -1;
2522 }
2523
2524 // Writes trace in discount history
2525 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2526 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2527 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2528 $sql .= " '".$this->db->escape($note)."',";
2529 $sql .= " ".((int) $user->id);
2530 $sql .= ")";
2531
2532 $resql = $this->db->query($sql);
2533 if (!$resql) {
2534 $this->db->rollback();
2535 $this->error = $this->db->lasterror();
2536 return -1;
2537 }
2538
2539 $this->db->commit();
2540 return 1;
2541 }
2542
2543 return -1;
2544 }
2545
2546 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2558 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2559 {
2560 // phpcs:enable
2561 global $langs;
2562
2563 // Clean parameters
2564 $remise = price2num($remise);
2565 $desc = trim($desc);
2566
2567 // Check parameters
2568 if (!($remise > 0)) {
2569 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2570 return -1;
2571 }
2572 if (!$desc) {
2573 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2574 return -2;
2575 }
2576
2577 if ($this->id > 0) {
2578 // Clean vat code
2579 $reg = array();
2580 $vat_src_code = '';
2581 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2582 $vat_src_code = $reg[1];
2583 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2584 }
2585
2586 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2587
2588 $discount = new DiscountAbsolute($this->db);
2589 $discount->fk_soc = $this->id;
2590 $discount->socid = $this->id;
2591
2592 $discount->discount_type = $discount_type;
2593
2594 if ($price_base_type == 'TTC') {
2595 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2596 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2597 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2598 } else {
2599 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2600 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2601 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2602 }
2603
2604 $discount->tva_tx = (float) price2num($vatrate);
2605 $discount->vat_src_code = $vat_src_code;
2606
2607 $discount->description = $desc;
2608
2609 $result = $discount->create($user);
2610 if ($result > 0) {
2611 return $result;
2612 } else {
2613 $this->error = $discount->error;
2614 return -3;
2615 }
2616 } else {
2617 return 0;
2618 }
2619 }
2620
2630 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2631 {
2632 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2633
2634 $discountstatic = new DiscountAbsolute($this->db);
2635 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2636 if ($result >= 0) {
2637 return $result;
2638 } else {
2639 $this->error = $discountstatic->error;
2640 return -1;
2641 }
2642 }
2643
2653 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2654 {
2655 global $conf;
2656
2657 $reparray = array();
2658
2659 $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";
2660 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2661 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2662 // Condition here should be the same than into select_dolusers()
2663 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2664 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2665 } else {
2666 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2667 }
2668
2669 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2670 if (empty($sortfield) && empty($sortorder)) {
2671 $sortfield = 'u.lastname,u.firstname';
2672 $sortorder = 'ASC,ASC';
2673 }
2674 $sql .= $this->db->order($sortfield, $sortorder);
2675
2676 $resql = $this->db->query($sql);
2677 if ($resql) {
2678 $num = $this->db->num_rows($resql);
2679 $i = 0;
2680 while ($i < $num) {
2681 $obj = $this->db->fetch_object($resql);
2682
2683 if (empty($mode)) {
2684 $reparray[$i]['id'] = $obj->rowid;
2685 $reparray[$i]['lastname'] = $obj->lastname;
2686 $reparray[$i]['firstname'] = $obj->firstname;
2687 $reparray[$i]['email'] = $obj->email;
2688 $reparray[$i]['phone'] = $obj->office_phone;
2689 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2690 $reparray[$i]['office_fax'] = $obj->office_fax;
2691 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2692 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2693 $reparray[$i]['job'] = $obj->job;
2694 $reparray[$i]['statut'] = $obj->status; // deprecated
2695 $reparray[$i]['status'] = $obj->status;
2696 $reparray[$i]['entity'] = $obj->entity;
2697 $reparray[$i]['login'] = $obj->login;
2698 $reparray[$i]['photo'] = $obj->photo;
2699 $reparray[$i]['gender'] = $obj->gender;
2700 } else {
2701 $reparray[] = $obj->rowid;
2702 }
2703 $i++;
2704 }
2705 return $reparray;
2706 } else {
2707 dol_print_error($this->db);
2708 return -1;
2709 }
2710 }
2711
2719 public function setPriceLevel($price_level, User $user)
2720 {
2721 if ($this->id) {
2722 $now = dol_now();
2723
2724 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2725 $sql .= " SET price_level = ".((int) $price_level);
2726 $sql .= " WHERE rowid = ".((int) $this->id);
2727
2728 if (!$this->db->query($sql)) {
2729 dol_print_error($this->db);
2730 return -1;
2731 }
2732
2733 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2734 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2735 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2736
2737 if (!$this->db->query($sql)) {
2738 dol_print_error($this->db);
2739 return -1;
2740 }
2741 return 1;
2742 }
2743 return -1;
2744 }
2745
2746 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2754 public function add_commercial(User $user, $commid)
2755 {
2756 // phpcs:enable
2757 $error = 0;
2758
2759 if ($this->id > 0 && $commid > 0) {
2760 $this->db->begin();
2761
2762 if (!$error) {
2763 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2764 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2765
2766 $resql = $this->db->query($sql);
2767 if (!$resql) {
2768 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2769 $error++;
2770 }
2771 }
2772
2773 if (!$error) {
2774 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2775 $sql .= " (fk_soc, fk_user)";
2776 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2777
2778 $resql = $this->db->query($sql);
2779 if (!$resql) {
2780 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2781 $error++;
2782 }
2783 }
2784
2785 if (!$error) {
2786 $this->context = array('commercial_modified' => $commid);
2787
2788 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2789 if ($result < 0) {
2790 $error++;
2791 }
2792 }
2793
2794 if (!$error) {
2795 $this->db->commit();
2796 return 1;
2797 } else {
2798 $this->db->rollback();
2799 return -1;
2800 }
2801 }
2802
2803 return 0;
2804 }
2805
2806 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2814 public function del_commercial(User $user, $commid)
2815 {
2816 // phpcs:enable
2817 $error = 0;
2818 $this->context = array('commercial_modified' => $commid);
2819
2820 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2821 if ($result < 0) {
2822 $error++;
2823 }
2824
2825 if ($this->id > 0 && $commid > 0) {
2826 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2827 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2828
2829 if (!$this->db->query($sql)) {
2830 $error++;
2831 dol_syslog(get_class($this)."::del_commercial Erreur");
2832 }
2833 }
2834
2835 if ($error) {
2836 return -1;
2837 } else {
2838 return 1;
2839 }
2840 }
2841
2849 public function getTooltipContentArray($params)
2850 {
2851 global $conf, $langs, $user;
2852
2853 $langs->loadLangs(['companies', 'commercial']);
2854
2855 $datas = array();
2856
2857 $option = $params['option'] ?? '';
2858 $nofetch = !empty($params['nofetch']);
2859
2860 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2861
2862 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2863 return ['optimize' => $langs->trans("ShowCompany")];
2864 }
2865
2866 if (!empty($this->logo) && class_exists('Form')) {
2867 $photo = '<div class="photointooltip floatright">';
2868 $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.
2869 $photo .= '</div>';
2870 $datas['photo'] = $photo;
2871 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2872 /*$label.= '<div class="photointooltip">';
2873 $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.
2874 $label.= '</div><div style="clear: both;"></div>';*/
2875 // }
2876
2877 $datas['divopen'] = '<div class="centpercent">';
2878
2879 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2880 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2881 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2882 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2883 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2884 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2885 } elseif ($option == 'agenda') {
2886 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2887 } elseif ($option == 'project') {
2888 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2889 } elseif ($option == 'margin') {
2890 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2891 } elseif ($option == 'contact') {
2892 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2893 } elseif ($option == 'ban') {
2894 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2895 }
2896
2897 // By default
2898 if (empty($datas['picto'])) {
2899 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2900 }
2901 if (isset($this->status)) {
2902 $datas['status'] = ' '.$this->getLibStatut(5);
2903 }
2904 if (isset($this->client) && isset($this->fournisseur)) {
2905 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2906 }
2907 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2908 if (!empty($this->name_alias) && empty($noaliasinname)) {
2909 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2910 }
2911 if (!empty($this->email)) {
2912 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2913 }
2914 if (!empty($this->url)) {
2915 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2916 }
2917 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2918 $phonelist = array();
2919 if ($this->phone) {
2920 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2921 }
2922 // deliberately not making new list because fax uses same list as phone
2923 if ($this->phone_mobile) {
2924 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2925 }
2926 if ($this->fax) {
2927 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2928 }
2929 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2930 }
2931
2932 if (!empty($this->address)) {
2933 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2934 } elseif (!empty($this->country_code)) {
2935 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2936 }
2937 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2938 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2939 }
2940
2941 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2942 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2943 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2944 }
2945 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2946 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2947 }
2948 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2949 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2950 }
2951 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2952 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2953 }
2954 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2955 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2956 }
2957 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2958 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2959 }
2960 }
2961
2962 $datas['separator'] = '<br>';
2963
2964 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2965 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2966 }
2967 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2968 $langs->load('compta');
2969 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
2970 }
2971 // show categories for this record only in ajax to not overload lists
2972 if (!$nofetch && isModEnabled('category') && $this->client) {
2973 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2974 $form = new Form($this->db);
2975 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2976 }
2977 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2978 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2979 }
2980 if (isModEnabled('accounting') && $this->fournisseur) {
2981 $langs->load('compta');
2982 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2983 }
2984 // show categories for this record only in ajax to not overload lists
2985 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2986 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2987 $form = new Form($this->db);
2988 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2989 }
2990
2991 $datas['divclose'] = '</div>';
2992
2993 return $datas;
2994 }
2995
3009 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3010 {
3011 global $conf, $langs, $hookmanager, $user;
3012
3013 if (!empty($conf->dol_no_mouse_hover)) {
3014 $notooltip = 1; // Force disable tooltips
3015 }
3016
3017 $name = $this->name ? $this->name : $this->nom;
3018
3019 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3020 if (empty($option) && $this->client > 0) {
3021 $option = 'customer';
3022 }
3023 if (empty($option) && $this->fournisseur > 0) {
3024 $option = 'supplier';
3025 }
3026 }
3027
3028 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3029 $code = '';
3030 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3031 $code = $this->code_client.' - ';
3032 }
3033
3034 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3035 $code .= $this->code_fournisseur.' - ';
3036 }
3037
3038 if ($code) {
3039 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3040 $name = $code.' '.$name;
3041 } else {
3042 $name = $code;
3043 }
3044 }
3045 }
3046
3047 if (!empty($this->name_alias) && empty($noaliasinname)) {
3048 $name .= ' ('.$this->name_alias.')';
3049 }
3050
3051 $result = '';
3052 $params = [
3053 'id' => $this->id,
3054 'objecttype' => $this->element,
3055 'option' => $option,
3056 'nofetch' => 1,
3057 ];
3058 $classfortooltip = 'classfortooltip';
3059 $dataparams = '';
3060 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3061 $classfortooltip = 'classforajaxtooltip';
3062 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3063 $label = '';
3064 } else {
3065 $label = implode($this->getTooltipContentArray($params));
3066 }
3067
3068 $linkstart = '';
3069 $linkend = '';
3070
3071 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3072 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3073 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3074 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3075 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3076 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3077 } elseif ($option == 'agenda') {
3078 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3079 } elseif ($option == 'project') {
3080 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3081 } elseif ($option == 'margin') {
3082 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3083 } elseif ($option == 'contact') {
3084 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3085 } elseif ($option == 'ban') {
3086 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3087 }
3088
3089 // By default
3090 if (empty($linkstart)) {
3091 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3092 }
3093
3094 // Add type of canvas
3095 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3096 // Add param to save lastsearch_values or not
3097 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3098 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3099 $add_save_lastsearch_values = 1;
3100 }
3101 if ($add_save_lastsearch_values) {
3102 $linkstart .= '&save_lastsearch_values=1';
3103 }
3104 $linkstart .= '"';
3105
3106 $linkclose = '';
3107 if (empty($notooltip)) {
3108 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3109 $label = $langs->trans("ShowCompany");
3110 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3111 }
3112 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3113 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3114 $target_value = array('_self', '_blank', '_parent', '_top');
3115 if (in_array($target, $target_value)) {
3116 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3117 }
3118 } else {
3119 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3120 }
3121 $linkstart .= $linkclose.'>';
3122 $linkend = '</a>';
3123
3124 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3125 $linkstart = '';
3126 $linkend = '';
3127 }
3128
3129 $result .= $linkstart;
3130 if ($withpicto) {
3131 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3132 }
3133 if ($withpicto != 2) {
3134 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3135 }
3136 $result .= $linkend;
3137
3138 global $action;
3139 $hookmanager->initHooks(array('thirdpartydao'));
3140 $parameters = array(
3141 'id' => $this->id,
3142 'getnomurl' => &$result,
3143 'withpicto ' => $withpicto,
3144 'option' => $option,
3145 'maxlen' => $maxlen,
3146 'notooltip' => $notooltip,
3147 'save_lastsearch_value' => $save_lastsearch_value
3148 );
3149 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3150 if ($reshook > 0) {
3151 $result = $hookmanager->resPrint;
3152 } else {
3153 $result .= $hookmanager->resPrint;
3154 }
3155
3156 return $result;
3157 }
3158
3168 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3169 {
3170 global $conf, $langs;
3171
3172 $s = '';
3173 if (empty($option) || preg_match('/prospect/', $option)) {
3174 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3175 $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.'>';
3176 }
3177 }
3178 if (empty($option) || preg_match('/customer/', $option)) {
3179 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3180 $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.'>';
3181 }
3182 }
3183 if (empty($option) || preg_match('/supplier/', $option)) {
3184 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3185 $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.'>';
3186 }
3187 }
3188 return $s;
3189 }
3190
3191
3198 public function getLibStatut($mode = 0)
3199 {
3200 return $this->LibStatut($this->status, $mode);
3201 }
3202
3203 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3211 public function LibStatut($status, $mode = 0)
3212 {
3213 // phpcs:enable
3214 global $langs;
3215 $langs->load('companies');
3216
3217 $statusType = 'status4';
3218 if ($status == 0) {
3219 $statusType = 'status6';
3220 }
3221
3222 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3223 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3224 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3225 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3226 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3227 }
3228
3229 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3230 }
3231
3232 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3239 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3240 {
3241 // phpcs:enable
3242 global $langs;
3243
3244 $contact_emails = $this->contact_property_array('email', 1);
3245
3246 if ($this->email && $addthirdparty) {
3247 if (empty($this->name)) {
3248 $this->name = $this->nom;
3249 }
3250 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3251 }
3252
3253 //var_dump($contact_emails)
3254 return $contact_emails;
3255 }
3256
3257 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3264 {
3265 // phpcs:enable
3266 global $langs;
3267
3268 $contact_phone = $this->contact_property_array('mobile');
3269
3270 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3271 if (empty($this->name)) {
3272 $this->name = $this->nom;
3273 }
3274 // TODO: Tester si tel non deja present dans tableau contact
3275 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3276 }
3277 return $contact_phone;
3278 }
3279
3280 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3288 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3289 {
3290 // phpcs:enable
3291 global $langs;
3292
3293 $contact_property = array();
3294
3295
3296 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3297 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3298 $sql .= " WHERE fk_soc = ".((int) $this->id);
3299 $sql .= " AND entity IN (".getEntity($this->element).")";
3300 $sql .= " ORDER BY lastname, firstname";
3301
3302 $resql = $this->db->query($sql);
3303 if ($resql) {
3304 $nump = $this->db->num_rows($resql);
3305 if ($nump) {
3306 $sepa = "(";
3307 $sepb = ")";
3308 if ($mode == 'email') {
3309 //$sepa="&lt;"; $sepb="&gt;";
3310 $sepa = "<";
3311 $sepb = ">";
3312 }
3313 $i = 0;
3314 while ($i < $nump) {
3315 $obj = $this->db->fetch_object($resql);
3316 if ($mode == 'email') {
3317 $property = $obj->email;
3318 } elseif ($mode == 'mobile') {
3319 $property = $obj->phone_mobile;
3320 } else {
3321 $property = $obj->$mode;
3322 }
3323
3324 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3325 if ($obj->status == 1 || empty($hidedisabled)) {
3326 if (empty($property)) {
3327 if ($mode == 'email') {
3328 $property = $langs->transnoentitiesnoconv("NoEMail");
3329 } elseif ($mode == 'mobile') {
3330 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3331 }
3332 }
3333
3334 if (!empty($obj->poste)) {
3335 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3336 } else {
3337 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3338 }
3339 }
3340 $i++;
3341 }
3342 }
3343 } else {
3344 dol_print_error($this->db);
3345 }
3346 return $contact_property;
3347 }
3348
3349
3350 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3356 public function contact_array()
3357 {
3358 // phpcs:enable
3359 $contacts = array();
3360
3361 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3362 $resql = $this->db->query($sql);
3363 if ($resql) {
3364 $nump = $this->db->num_rows($resql);
3365 if ($nump) {
3366 $i = 0;
3367 while ($i < $nump) {
3368 $obj = $this->db->fetch_object($resql);
3369 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3370 $i++;
3371 }
3372 }
3373 } else {
3374 dol_print_error($this->db);
3375 }
3376 return $contacts;
3377 }
3378
3379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3385 public function contact_array_objects()
3386 {
3387 // phpcs:enable
3388 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3389 $contacts = array();
3390
3391 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3392 $resql = $this->db->query($sql);
3393 if ($resql) {
3394 $nump = $this->db->num_rows($resql);
3395 if ($nump) {
3396 $i = 0;
3397 while ($i < $nump) {
3398 $obj = $this->db->fetch_object($resql);
3399 $contact = new Contact($this->db);
3400 $contact->fetch($obj->rowid);
3401 $contacts[] = $contact;
3402 $i++;
3403 }
3404 }
3405 } else {
3406 dol_print_error($this->db);
3407 }
3408 return $contacts;
3409 }
3410
3411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3419 public function contact_get_property($rowid, $mode)
3420 {
3421 // phpcs:enable
3422 $contact_property = '';
3423
3424 if (empty($rowid)) {
3425 return '';
3426 }
3427
3428 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3429 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3430 $sql .= " WHERE rowid = ".((int) $rowid);
3431
3432 $resql = $this->db->query($sql);
3433 if ($resql) {
3434 $nump = $this->db->num_rows($resql);
3435
3436 if ($nump) {
3437 $obj = $this->db->fetch_object($resql);
3438
3439 if ($mode == 'email') {
3440 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3441 } elseif ($mode == 'mobile') {
3442 $contact_property = $obj->phone_mobile;
3443 }
3444 }
3445 return $contact_property;
3446 } else {
3447 dol_print_error($this->db);
3448 }
3449
3450 return '';
3451 }
3452
3453
3454 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3461 public function display_rib($mode = 'label')
3462 {
3463 // phpcs:enable
3464 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3465
3466 $bac = new CompanyBankAccount($this->db);
3467 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3468 $bac->fetch(0, '', $this->id);
3469
3470 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3471 if ($mode == 'label') {
3472 return $bac->getRibLabel(true);
3473 } elseif ($mode == 'rum') {
3474 if (empty($bac->rum)) {
3475 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3476 $prelevement = new BonPrelevement($this->db);
3477 $bac->fetch_thirdparty();
3478 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3479 }
3480 return $bac->rum;
3481 } elseif ($mode == 'format') {
3482 return $bac->frstrecur;
3483 } else {
3484 return 'BadParameterToFunctionDisplayRib';
3485 }
3486 } else {
3487 return '';
3488 }
3489 }
3490
3491 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3497 public function get_all_rib()
3498 {
3499 // phpcs:enable
3500 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3501 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3502 $result = $this->db->query($sql);
3503 if (!$result) {
3504 $this->error = $this->db->lasterror();
3505 $this->errors[] = $this->db->lasterror();
3506 return 0;
3507 } else {
3508 $num_rows = $this->db->num_rows($result);
3509 $rib_array = array();
3510 if ($num_rows) {
3511 while ($obj = $this->db->fetch_object($result)) {
3512 $rib = new CompanyBankAccount($this->db);
3513 $rib->fetch($obj->rowid);
3514 $rib_array[] = $rib;
3515 }
3516 }
3517 return $rib_array;
3518 }
3519 }
3520
3521 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3530 public function get_codeclient($objsoc = null, $type = 0)
3531 {
3532 // phpcs:enable
3533 global $conf;
3534 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3535 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3536
3537 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3538 foreach ($dirsociete as $dirroot) {
3539 $res = dol_include_once($dirroot.$module.'.php');
3540 if ($res) {
3541 break;
3542 }
3543 }
3545 $mod = new $module($this->db);
3546 '@phan-var-force ModeleThirdPartyCode $mod';
3547
3548 $this->code_client = $mod->getNextValue($objsoc, $type);
3549 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3550
3551 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3552 }
3553 }
3554
3555 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3564 public function get_codefournisseur($objsoc = null, $type = 1)
3565 {
3566 // phpcs:enable
3567 global $conf;
3568 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3569 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3570
3571 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3572 foreach ($dirsociete as $dirroot) {
3573 $res = dol_include_once($dirroot.$module.'.php');
3574 if ($res) {
3575 break;
3576 }
3577 }
3579 $mod = new $module($this->db);
3580 '@phan-var-force ModeleThirdPartyCode $mod';
3581
3582 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3583
3584 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3585 }
3586 }
3587
3588 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3595 public function codeclient_modifiable()
3596 {
3597 // phpcs:enable
3598 global $conf;
3599 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3600 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3601
3602 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3603 foreach ($dirsociete as $dirroot) {
3604 $res = dol_include_once($dirroot.$module.'.php');
3605 if ($res) {
3606 break;
3607 }
3608 }
3609
3610 $mod = new $module($this->db);
3611 '@phan-var-force ModeleThirdPartyCode $mod';
3612
3613 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3614 if ($mod->code_modifiable_null && !$this->code_client) {
3615 return 1;
3616 }
3617 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3618 return 1;
3619 }
3620 if ($mod->code_modifiable) {
3621 return 1; // A mettre en dernier
3622 }
3623 return 0;
3624 } else {
3625 return 0;
3626 }
3627 }
3628
3629
3630 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3637 {
3638 // phpcs:enable
3639 global $conf;
3640 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3641 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3642
3643 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3644 foreach ($dirsociete as $dirroot) {
3645 $res = dol_include_once($dirroot.$module.'.php');
3646 if ($res) {
3647 break;
3648 }
3649 }
3650
3651 $mod = new $module($this->db);
3652 '@phan-var-force ModeleThirdPartyCode $mod';
3653
3654 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3655 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3656 return 1;
3657 }
3658 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3659 return 1;
3660 }
3661 if ($mod->code_modifiable) {
3662 return 1; // A mettre en dernier
3663 }
3664 return 0;
3665 } else {
3666 return 0;
3667 }
3668 }
3669
3670
3671 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3683 public function check_codeclient()
3684 {
3685 // phpcs:enable
3686 global $conf;
3687 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3688 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3689
3690 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3691 foreach ($dirsociete as $dirroot) {
3692 $res = dol_include_once($dirroot.$module.'.php');
3693 if ($res) {
3694 break;
3695 }
3696 }
3697
3698 $mod = new $module($this->db);
3699 '@phan-var-force ModeleThirdPartyCode $mod';
3700
3701 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3702 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3703 if ($result) { // If error
3704 $this->error = $mod->error;
3705 $this->errors = $mod->errors;
3706 }
3707 return $result;
3708 } else {
3709 return 0;
3710 }
3711 }
3712
3713 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3725 public function check_codefournisseur()
3726 {
3727 // phpcs:enable
3728 global $conf;
3729 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3730 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3731
3732 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3733 foreach ($dirsociete as $dirroot) {
3734 $res = dol_include_once($dirroot.$module.'.php');
3735 if ($res) {
3736 break;
3737 }
3738 }
3739
3740 $mod = new $module($this->db);
3741 '@phan-var-force ModeleThirdPartyCode $mod';
3742
3743 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3744 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3745 if ($result) { // If error
3746 $this->error = $mod->error;
3747 $this->errors = $mod->errors;
3748 }
3749 return $result;
3750 } else {
3751 return 0;
3752 }
3753 }
3754
3755 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3764 public function get_codecompta($type)
3765 {
3766 // phpcs:enable
3767 global $conf;
3768
3769 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3770 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3771 $res = false;
3772 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3773 foreach ($dirsociete as $dirroot) {
3774 $res = dol_include_once($dirroot.$module.'.php');
3775 if ($res) {
3776 break;
3777 }
3778 }
3779
3780 if ($res) {
3781 $mod = new $module();
3782 '@phan-var-force ModeleAccountancyCode $mod';
3783
3784 // Set code count in $mod->code
3785 $result = $mod->get_code($this->db, $this, $type);
3786
3787 if ($type == 'customer') {
3788 $this->code_compta_client = $mod->code;
3789 } elseif ($type == 'supplier') {
3790 $this->code_compta_fournisseur = $mod->code;
3791 }
3792
3793 return $result;
3794 } else {
3795 $this->error = 'ErrorAccountancyCodeNotDefined';
3796 return -1;
3797 }
3798 } else {
3799 if ($type == 'customer') {
3800 $this->code_compta_client = '';
3801 } elseif ($type == 'supplier') {
3802 $this->code_compta_fournisseur = '';
3803 }
3804
3805 return 0;
3806 }
3807 }
3808
3815 public function setParent($id)
3816 {
3817 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3818
3819 if ($this->id) {
3820 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3821 if ($id > 0) {
3822 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3823 if ($sameparent < 0) {
3824 return -1;
3825 }
3826 if ($sameparent == 1) {
3827 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3828 return -1;
3829 }
3830 }
3831
3832 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3833
3834 $resql = $this->db->query($sql);
3835 if ($resql) {
3836 $this->parent = $id;
3837 return 1;
3838 } else {
3839 return -1;
3840 }
3841 }
3842
3843 return -1;
3844 }
3845
3854 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3855 {
3856 if ($counter > 100) {
3857 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3858 }
3859
3860 $sql = 'SELECT s.parent';
3861 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3862 $sql .= ' WHERE rowid = '.((int) $idparent);
3863 $resql = $this->db->query($sql);
3864 if ($resql) {
3865 $obj = $this->db->fetch_object($resql);
3866
3867 if ($obj->parent == '') {
3868 return 0;
3869 } elseif ($obj->parent == $idchild) {
3870 return 1;
3871 } else {
3872 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3873 }
3874 return $sameparent;
3875 } else {
3876 return -1;
3877 }
3878 }
3879
3887 public function getParentsForCompany($company_id, $parents = array())
3888 {
3889 global $langs;
3890
3891 if ($company_id > 0) {
3892 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3893 $resql = $this->db->query($sql);
3894 if ($resql) {
3895 if ($obj = $this->db->fetch_object($resql)) {
3896 $parent = $obj->parent;
3897 if ($parent > 0 && !in_array($parent, $parents)) {
3898 $parents[] = $parent;
3899 return $this->getParentsForCompany($parent, $parents);
3900 } else {
3901 return $parents;
3902 }
3903 }
3904 $this->db->free($resql);
3905 } else {
3906 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3907 }
3908 }
3909 // Return a default value when $company_id is not greater than 0
3910 return array();
3911 }
3912
3913 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3920 public function id_prof_verifiable($idprof)
3921 {
3922 // phpcs:enable
3923 global $conf;
3924
3925 switch ($idprof) {
3926 case 1:
3927 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
3928 break;
3929 case 2:
3930 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
3931 break;
3932 case 3:
3933 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
3934 break;
3935 case 4:
3936 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
3937 break;
3938 case 5:
3939 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
3940 break;
3941 case 6:
3942 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
3943 break;
3944 default:
3945 $ret = false;
3946 }
3947
3948 return $ret;
3949 }
3950
3951 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3960 public function id_prof_exists($idprof, $value, $socid = 0)
3961 {
3962 // phpcs:enable
3963 $field = $idprof;
3964
3965 switch ($idprof) { // For backward compatibility
3966 case '1':
3967 case 'idprof1':
3968 $field = "siren";
3969 break;
3970 case '2':
3971 case 'idprof2':
3972 $field = "siret";
3973 break;
3974 case '3':
3975 case 'idprof3':
3976 $field = "ape";
3977 break;
3978 case '4':
3979 case 'idprof4':
3980 $field = "idprof4";
3981 break;
3982 case '5':
3983 $field = "idprof5";
3984 break;
3985 case '6':
3986 $field = "idprof6";
3987 break;
3988 }
3989
3990 //Verify duplicate entries
3991 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3992 if ($socid) {
3993 $sql .= " AND rowid <> ".$socid;
3994 }
3995 $resql = $this->db->query($sql);
3996 if ($resql) {
3997 $obj = $this->db->fetch_object($resql);
3998 $count = $obj->nb;
3999 } else {
4000 $count = 0;
4001 print $this->db->error();
4002 }
4003 $this->db->free($resql);
4004
4005 if ($count > 0) {
4006 return true;
4007 } else {
4008 return false;
4009 }
4010 }
4011
4012 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4021 public function id_prof_check($idprof, $soc)
4022 {
4023 // phpcs:enable
4024 global $conf;
4025
4026 // load the library necessary to check the professional identifiers
4027 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4028
4029 $ok = 1;
4030
4031 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4032 return 1;
4033 }
4034
4035 // Check SIREN
4036 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4037 return -1;
4038 }
4039
4040 // Check SIRET
4041 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4042 return -1;
4043 }
4044
4045 //Verify CIF/NIF/NIE if pays ES
4046 if ($idprof == 1 && $soc->country_code == 'ES') {
4047 return isValidTinForES($this->idprof1);
4048 }
4049
4050 //Verify NIF if country is PT
4051 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4052 return -1;
4053 }
4054
4055 //Verify NIF if country is DZ
4056 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4057 return -1;
4058 }
4059
4060 //Verify ID Prof 1 if country is BE
4061 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4062 return -1;
4063 }
4064
4065 return $ok;
4066 }
4067
4068 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4077 public function id_prof_url($idprof, $thirdparty)
4078 {
4079 // phpcs:enable
4080 global $conf, $langs, $hookmanager;
4081
4082 $url = '';
4083 $action = '';
4084
4085 $hookmanager->initHooks(array('idprofurl'));
4086 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4087 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4088 if (empty($reshook)) {
4089 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4090 return '';
4091 }
4092
4093 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4094 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4095 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4096 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4097 }
4098 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4099 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4100 }
4101 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4102 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4103 }
4104 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4105 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4106 }
4107 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4108 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4109 }
4110 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4111 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4112 }
4113
4114 if ($url) {
4115 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4116 }
4117 } else {
4118 return $hookmanager->resPrint;
4119 }
4120
4121 return '';
4122 }
4123
4124 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4130 public function has_projects()
4131 {
4132 // phpcs:enable
4133 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4134 $resql = $this->db->query($sql);
4135 if ($resql) {
4136 $obj = $this->db->fetch_object($resql);
4137 $count = $obj->numproj;
4138 } else {
4139 $count = 0;
4140 print $this->db->error();
4141 }
4142 $this->db->free($resql);
4143 return ($count > 0);
4144 }
4145
4146
4153 public function info($id)
4154 {
4155 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4156 $sql .= " fk_user_creat, fk_user_modif";
4157 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4158 $sql .= " WHERE s.rowid = ".((int) $id);
4159
4160 $result = $this->db->query($sql);
4161 if ($result) {
4162 if ($this->db->num_rows($result)) {
4163 $obj = $this->db->fetch_object($result);
4164
4165 $this->id = $obj->rowid;
4166
4167 $this->user_creation_id = $obj->fk_user_creat;
4168 $this->user_modification_id = $obj->fk_user_modif;
4169 $this->date_creation = $this->db->jdate($obj->datec);
4170 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4171
4172 $this->ref = $obj->name;
4173 }
4174
4175 $this->db->free($result);
4176 } else {
4177 dol_print_error($this->db);
4178 }
4179 }
4180
4186 public function isACompany()
4187 {
4188 // Define if third party is treated as company (or not) when nature is unknown
4189 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4190
4191 // Now try to guess using different tips
4192 if (!empty($this->tva_intra)) {
4193 $isACompany = 1;
4194 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4195 $isACompany = 1;
4196 } else {
4197 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4198 // TODO Add a field is_a_company into dictionary
4199 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4200 $isACompany = 0;
4201 } else {
4202 $isACompany = 1;
4203 }
4204 } else {
4205 $isACompany = 1;
4206 }
4207 }
4208
4209 return (bool) $isACompany;
4210 }
4211
4217 public function isInEEC()
4218 {
4219 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4220 return isInEEC($this);
4221 }
4222
4223 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4229 public function LoadSupplierCateg()
4230 {
4231 // phpcs:enable
4232 $this->SupplierCategories = array();
4233 $sql = "SELECT rowid, label";
4234 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4235 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4236
4237 $resql = $this->db->query($sql);
4238 if ($resql) {
4239 while ($obj = $this->db->fetch_object($resql)) {
4240 $this->SupplierCategories[$obj->rowid] = $obj->label;
4241 }
4242 return 0;
4243 } else {
4244 return -1;
4245 }
4246 }
4247
4248 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4255 public function AddFournisseurInCategory($categorie_id)
4256 {
4257 // phpcs:enable
4258 if ($categorie_id > 0 && $this->id > 0) {
4259 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4260 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4261
4262 if ($resql = $this->db->query($sql)) {
4263 return 0;
4264 }
4265 } else {
4266 return 0;
4267 }
4268 return -1;
4269 }
4270
4276 public function getNbOfEMailings()
4277 {
4278 $sql = "SELECT count(mc.email) as nb";
4279 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4280 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4281 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4282
4283 $resql = $this->db->query($sql);
4284 if ($resql) {
4285 $obj = $this->db->fetch_object($resql);
4286 $nb = $obj->nb;
4287
4288 $this->db->free($resql);
4289 return $nb;
4290 } else {
4291 $this->error = $this->db->error();
4292 return -1;
4293 }
4294 }
4295
4302 public function setNoEmail($no_email)
4303 {
4304 $error = 0;
4305
4306 // Update mass emailing flag into table mailing_unsubscribe
4307 if ($this->email) {
4308 $this->db->begin();
4309
4310 if ($no_email) {
4311 $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)."'";
4312 $resql = $this->db->query($sql);
4313 if ($resql) {
4314 $obj = $this->db->fetch_object($resql);
4315 $noemail = $obj->nb;
4316 if (empty($noemail)) {
4317 $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())."')";
4318 $resql = $this->db->query($sql);
4319 if (!$resql) {
4320 $error++;
4321 $this->error = $this->db->lasterror();
4322 $this->errors[] = $this->error;
4323 }
4324 }
4325 } else {
4326 $error++;
4327 $this->error = $this->db->lasterror();
4328 $this->errors[] = $this->error;
4329 }
4330 } else {
4331 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4332 $resql = $this->db->query($sql);
4333 if (!$resql) {
4334 $error++;
4335 $this->error = $this->db->lasterror();
4336 $this->errors[] = $this->error;
4337 }
4338 }
4339
4340 if (empty($error)) {
4341 $this->no_email = $no_email;
4342 $this->db->commit();
4343 return 1;
4344 } else {
4345 $this->db->rollback();
4346 return $error * -1;
4347 }
4348 }
4349
4350 return 0;
4351 }
4352
4359 public function getNoEmail()
4360 {
4361 if ($this->email) {
4362 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4363 $resql = $this->db->query($sql);
4364 if ($resql) {
4365 $obj = $this->db->fetch_object($resql);
4366 $this->no_email = $obj->nb;
4367 return 1;
4368 } else {
4369 $this->error = $this->db->lasterror();
4370 $this->errors[] = $this->error;
4371 return -1;
4372 }
4373 }
4374 return 0;
4375 }
4376
4377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4387 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4388 {
4389 // phpcs:enable
4390 global $conf, $user, $langs;
4391
4392 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4393 $fullname = $member->getFullName($langs);
4394
4395 if ($member->morphy == 'mor') {
4396 if (empty($socname)) {
4397 $socname = $member->company ? $member->company : $member->societe;
4398 }
4399 if (!empty($fullname) && empty($socalias)) {
4400 $socalias = $fullname;
4401 }
4402 } elseif (empty($socname) && $member->morphy == 'phy') {
4403 if (empty($socname)) {
4404 $socname = $fullname;
4405 }
4406 if (!empty($member->company) && empty($socalias)) {
4407 $socalias = $member->company;
4408 }
4409 }
4410
4411 $name = $socname;
4412 $alias = $socalias ? $socalias : '';
4413
4414 // Positionne parameters
4415 $this->nom = $name; // TODO deprecated
4416 $this->name = $name;
4417 $this->name_alias = $alias;
4418 $this->address = $member->address;
4419 $this->zip = $member->zip;
4420 $this->town = $member->town;
4421 $this->country_code = $member->country_code;
4422 $this->country_id = $member->country_id;
4423 $this->phone = $member->phone; // Prof phone
4424 $this->email = $member->email;
4425 $this->socialnetworks = $member->socialnetworks;
4426 $this->entity = $member->entity;
4427
4428 $this->client = 1; // A member is a customer by default
4429 $this->code_client = ($customercode ? $customercode : -1);
4430 $this->code_fournisseur = '-1';
4431 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4432 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4433
4434 $this->db->begin();
4435
4436 // Cree et positionne $this->id
4437 $result = $this->create($user);
4438
4439 if ($result >= 0) {
4440 // Auto-create contact on thirdparty creation
4441 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4442 // Fill fields needed by contact
4443 $this->name_bis = $member->lastname;
4444 $this->firstname = $member->firstname;
4445 $this->civility_id = $member->civility_id;
4446
4447 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4448 $result = $this->create_individual($user);
4449
4450 if ($result < 0) {
4451 setEventMessages($this->error, $this->errors, 'errors');
4452 $this->db->rollback();
4453 return -1;
4454 }
4455 }
4456
4457 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4458 $sql .= " SET fk_soc = ".((int) $this->id);
4459 $sql .= " WHERE rowid = ".((int) $member->id);
4460
4461 $resql = $this->db->query($sql);
4462 if ($resql) {
4463 $this->db->commit();
4464 return $this->id;
4465 } else {
4466 $this->error = $this->db->error();
4467
4468 $this->db->rollback();
4469 return -1;
4470 }
4471 } else {
4472 // $this->error deja positionne
4473 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4474
4475 $this->db->rollback();
4476 return $result;
4477 }
4478 }
4479
4486 public function setMysoc(Conf $conf)
4487 {
4488 global $langs;
4489
4490 $this->id = 0;
4491 $this->entity = $conf->entity;
4492 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4493 $this->nom = $this->name; // deprecated
4494 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4495 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4496 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4497 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4498
4499 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4500
4501 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4502
4503 // We define country_id, country_code and country
4504 $country_id = 0;
4505 $country_code = $country_label = '';
4506 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4507 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4508 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4509 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4510 $country_code = $tmp[1];
4511 $country_label = $tmp[2];
4512 } else {
4513 // For backward compatibility
4514 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4515 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4516 $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
4517 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4518 }
4519 }
4520 $this->country_id = $country_id;
4521 $this->country_code = $country_code;
4522 $this->country = $country_label;
4523 if (is_object($langs)) {
4524 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4525 }
4526
4527 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4528 // We define state_id, state_code and state
4529 $state_id = 0;
4530 $state_code = '';
4531 $state_label = '';
4532 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4533 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4534 $state_id = (int) $tmp[0];
4535 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4536 $state_code = $tmp[1];
4537 $state_label = $tmp[2];
4538 } else { // For backward compatibility
4539 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);
4540 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4541 $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
4542 $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
4543 }
4544 }
4545 $this->state_id = $state_id;
4546 $this->state_code = $state_code;
4547 $this->state = $state_label;
4548 if (is_object($langs)) {
4549 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4550 }
4551
4552 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4553 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4554 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4555 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4556
4557 // Social networks
4558 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4559 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4560 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4561 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4562 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4563 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4564 $this->socialnetworks = array();
4565 if (!empty($facebook_url)) {
4566 $this->socialnetworks['facebook'] = $facebook_url;
4567 }
4568 if (!empty($twitter_url)) {
4569 $this->socialnetworks['twitter'] = $twitter_url;
4570 }
4571 if (!empty($linkedin_url)) {
4572 $this->socialnetworks['linkedin'] = $linkedin_url;
4573 }
4574 if (!empty($instagram_url)) {
4575 $this->socialnetworks['instagram'] = $instagram_url;
4576 }
4577 if (!empty($youtube_url)) {
4578 $this->socialnetworks['youtube'] = $youtube_url;
4579 }
4580 if (!empty($github_url)) {
4581 $this->socialnetworks['github'] = $github_url;
4582 }
4583
4584 // Id prof generiques
4585 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4586 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4587 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4588 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4589 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4590 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4591 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4592 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4593 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4594 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4595 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4596 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4597 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4598 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4599 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4600 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4601 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4602 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4603
4604 // Define if company use vat or not
4605 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4606
4607 // Define if company use local taxes
4608 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4609 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4610 }
4611
4619 public function initAsSpecimen()
4620 {
4621 $now = dol_now();
4622
4623 // Initialize parameters
4624 $this->id = 0;
4625 $this->entity = 1;
4626 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4627 $this->nom = $this->name; // For backward compatibility
4628 $this->ref_ext = 'Ref ext';
4629 $this->specimen = 1;
4630 $this->address = '21 jump street';
4631 $this->zip = '99999';
4632 $this->town = 'MyTown';
4633 $this->state_id = 1;
4634 $this->state_code = 'AA';
4635 $this->state = 'MyState';
4636 $this->country_id = 1;
4637 $this->country_code = 'FR';
4638 $this->email = 'specimen@specimen.com';
4639 $this->socialnetworks = array(
4640 'skype' => 'skypepseudo',
4641 'twitter' => 'twitterpseudo',
4642 'facebook' => 'facebookpseudo',
4643 'linkedin' => 'linkedinpseudo',
4644 );
4645 $this->url = 'http://www.specimen.com';
4646
4647 $this->phone = '0909090901';
4648 $this->phone_mobile = '0909090901';
4649 $this->fax = '0909090909';
4650
4651 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4652 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4653 $this->typent_code = 'TE_OTHER';
4654 $this->capital = 10000;
4655 $this->client = 1;
4656 $this->prospect = 1;
4657 $this->fournisseur = 1;
4658 $this->tva_assuj = 1;
4659 $this->tva_intra = 'EU1234567';
4660 $this->note_public = 'This is a comment (public)';
4661 $this->note_private = 'This is a comment (private)';
4662
4663 $this->idprof1 = 'idprof1';
4664 $this->idprof2 = 'idprof2';
4665 $this->idprof3 = 'idprof3';
4666 $this->idprof4 = 'idprof4';
4667 $this->idprof5 = 'idprof5';
4668 $this->idprof6 = 'idprof6';
4669
4670 return 1;
4671 }
4672
4679 public function useLocalTax($localTaxNum = 0)
4680 {
4681 $sql = "SELECT t.localtax1, t.localtax2";
4682 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4683 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4684 $sql .= " AND t.active = 1";
4685 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4686 if (empty($localTaxNum)) {
4687 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4688 } elseif ($localTaxNum == 1) {
4689 $sql .= " AND t.localtax1_type <> '0'";
4690 } elseif ($localTaxNum == 2) {
4691 $sql .= " AND t.localtax2_type <> '0'";
4692 }
4693
4694 $resql = $this->db->query($sql);
4695 if ($resql) {
4696 return ($this->db->num_rows($resql) > 0);
4697 } else {
4698 return false;
4699 }
4700 }
4701
4707 public function useNPR()
4708 {
4709 $sql = "SELECT t.rowid";
4710 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4711 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4712 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4713 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4714
4715 dol_syslog("useNPR", LOG_DEBUG);
4716 $resql = $this->db->query($sql);
4717 if ($resql) {
4718 return ($this->db->num_rows($resql) > 0);
4719 } else {
4720 return false;
4721 }
4722 }
4723
4730 public function useRevenueStamp()
4731 {
4732 $sql = "SELECT COUNT(*) as nb";
4733 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4734 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4735 $sql .= " AND r.active = 1";
4736
4737 dol_syslog("useRevenueStamp", LOG_DEBUG);
4738 $resql = $this->db->query($sql);
4739 if ($resql) {
4740 $obj = $this->db->fetch_object($resql);
4741 return ($obj->nb > 0);
4742 } else {
4743 $this->error = $this->db->lasterror();
4744 return false;
4745 }
4746 }
4747
4753 public function getLibProspLevel()
4754 {
4755 return $this->LibProspLevel($this->fk_prospectlevel);
4756 }
4757
4758 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4765 public function LibProspLevel($fk_prospectlevel)
4766 {
4767 // phpcs:enable
4768 global $langs;
4769
4770 $label = '';
4771 if ($fk_prospectlevel != '') {
4772 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4773 // If label is not found in language file, we get label from cache/database
4774 if ($label == "ProspectLevel".$fk_prospectlevel) {
4775 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4776 }
4777 }
4778
4779 return $label;
4780 }
4781
4789 public function getLibProspCommStatut($mode = 0, $label = '')
4790 {
4791 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4792 }
4793
4794 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4808 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4809 {
4810 // phpcs:enable
4811 global $langs;
4812
4813 $langs->load('customers');
4814
4815 if ($mode == 2) {
4816 if ($status == '-1' || $status == 'ST_NO') {
4817 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4818 } elseif ($status == '0' || $status == 'ST_NEVER') {
4819 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4820 } elseif ($status == '1' || $status == 'ST_TODO') {
4821 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4822 } elseif ($status == '2' || $status == 'ST_PEND') {
4823 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4824 } elseif ($status == '3' || $status == 'ST_DONE') {
4825 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4826 } else {
4827 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);
4828 }
4829 } elseif ($mode == 3) {
4830 if ($status == '-1' || $status == 'ST_NO') {
4831 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
4832 } elseif ($status == '0' || $status == 'ST_NEVER') {
4833 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
4834 } elseif ($status == '1' || $status == 'ST_TODO') {
4835 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
4836 } elseif ($status == '2' || $status == 'ST_PEND') {
4837 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
4838 } elseif ($status == '3' || $status == 'ST_DONE') {
4839 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
4840 } else {
4841 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
4842 }
4843 } elseif ($mode == 4) {
4844 if ($status == '-1' || $status == 'ST_NO') {
4845 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4846 } elseif ($status == '0' || $status == 'ST_NEVER') {
4847 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4848 } elseif ($status == '1' || $status == 'ST_TODO') {
4849 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4850 } elseif ($status == '2' || $status == 'ST_PEND') {
4851 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4852 } elseif ($status == '3' || $status == 'ST_DONE') {
4853 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4854 } else {
4855 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);
4856 }
4857 }
4858
4859 return "Error, mode/status not found";
4860 }
4861
4868 public function getOutstandingProposals($mode = 'customer')
4869 {
4870 $table = 'propal';
4871 if ($mode == 'supplier') {
4872 $table = 'supplier_proposal';
4873 }
4874
4875 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4876 $sql .= " WHERE fk_soc = ".((int) $this->id);
4877 if ($mode == 'supplier') {
4878 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4879 } else {
4880 $sql .= " AND entity IN (".getEntity('propal').")";
4881 }
4882
4883 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4884
4885 $resql = $this->db->query($sql);
4886 if ($resql) {
4887 $outstandingOpened = 0;
4888 $outstandingTotal = 0;
4889 $outstandingTotalIncTax = 0;
4890 $arrayofref = array();
4891 while ($obj = $this->db->fetch_object($resql)) {
4892 $arrayofref[$obj->rowid] = $obj->ref;
4893 $outstandingTotal += $obj->total_ht;
4894 $outstandingTotalIncTax += $obj->total_ttc;
4895 if ($obj->status != 0) {
4896 // Not a draft
4897 $outstandingOpened += $obj->total_ttc;
4898 }
4899 }
4900 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4901 } else {
4902 return array();
4903 }
4904 }
4905
4912 public function getOutstandingOrders($mode = 'customer')
4913 {
4914 $table = 'commande';
4915 if ($mode == 'supplier') {
4916 $table = 'commande_fournisseur';
4917 }
4918
4919 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4920 $sql .= " WHERE fk_soc = ".((int) $this->id);
4921 if ($mode == 'supplier') {
4922 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4923 } else {
4924 $sql .= " AND entity IN (".getEntity('commande').")";
4925 }
4926
4927 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4928 $resql = $this->db->query($sql);
4929 if ($resql) {
4930 $outstandingOpened = 0;
4931 $outstandingTotal = 0;
4932 $outstandingTotalIncTax = 0;
4933 $arrayofref = array();
4934 while ($obj = $this->db->fetch_object($resql)) {
4935 $arrayofref[$obj->rowid] = $obj->ref;
4936 $outstandingTotal += $obj->total_ht;
4937 $outstandingTotalIncTax += $obj->total_ttc;
4938 if ($obj->status != 0) {
4939 // Not a draft
4940 $outstandingOpened += $obj->total_ttc;
4941 }
4942 }
4943 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4944 } else {
4945 return array();
4946 }
4947 }
4948
4956 public function getOutstandingBills($mode = 'customer', $late = 0)
4957 {
4958 $table = 'facture';
4959 if ($mode == 'supplier') {
4960 $table = 'facture_fourn';
4961 }
4962
4963 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4964 $paiement = $invoice->getSommePaiement();
4965 $creditnotes=$invoice->getSumCreditNotesUsed();
4966 $deposits=$invoice->getSumDepositsUsed();
4967 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4968 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4969 */
4970 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4971 $sql .= " WHERE fk_soc = ".((int) $this->id);
4972 if (!empty($late)) {
4973 $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4974 }
4975 if ($mode == 'supplier') {
4976 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4977 } else {
4978 $sql .= " AND entity IN (".getEntity('invoice').")";
4979 }
4980
4981 dol_syslog("getOutstandingBills", LOG_DEBUG);
4982 $resql = $this->db->query($sql);
4983 if ($resql) {
4984 $outstandingOpened = 0;
4985 $outstandingTotal = 0;
4986 $outstandingTotalIncTax = 0;
4987 $arrayofref = array();
4988 $arrayofrefopened = array();
4989 if ($mode == 'supplier') {
4990 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4991 $tmpobject = new FactureFournisseur($this->db);
4992 } else {
4993 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4994 $tmpobject = new Facture($this->db);
4995 }
4996 while ($obj = $this->db->fetch_object($resql)) {
4997 $arrayofref[$obj->rowid] = $obj->ref;
4998 $tmpobject->id = $obj->rowid;
4999
5000 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5001 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5002 ) {
5003 $outstandingTotal += $obj->total_ht;
5004 $outstandingTotalIncTax += $obj->total_ttc;
5005 }
5006
5007 $remaintopay = 0;
5008
5009 if ($obj->paye == 0
5010 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5011 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5012 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5013 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5014 $paiement = $tmpobject->getSommePaiement();
5015 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5016 $deposits = $tmpobject->getSumDepositsUsed();
5017
5018 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5019 $outstandingOpened += $remaintopay;
5020 }
5021
5022 //if credit note is converted but not used
5023 // TODO Do this also for customer ?
5024 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5025 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5026 $remaintopay -= $remainingcreditnote;
5027 $outstandingOpened -= $remainingcreditnote;
5028 }
5029
5030 if ($remaintopay) {
5031 $arrayofrefopened[$obj->rowid] = $obj->ref;
5032 }
5033 }
5034 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
5035 } else {
5036 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5037 return array();
5038 }
5039 }
5040
5047 public function getLibCustProspStatut()
5048 {
5049 return $this->LibCustProspStatut($this->client);
5050 }
5051
5052 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5059 public function LibCustProspStatut($status)
5060 {
5061 // phpcs:enable
5062 global $langs;
5063 $langs->load('companies');
5064
5065 if ($status == 0) {
5066 return $langs->trans("NorProspectNorCustomer");
5067 } elseif ($status == 1) {
5068 return $langs->trans("Customer");
5069 } elseif ($status == 2) {
5070 return $langs->trans("Prospect");
5071 } elseif ($status == 3) {
5072 return $langs->trans("ProspectCustomer");
5073 }
5074
5075 return '';
5076 }
5077
5078
5090 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5091 {
5092 global $langs;
5093
5094 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5095 $modelpath = "core/modules/bank/doc/";
5096
5097 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5098 $companybankaccount = new CompanyBankAccount($this->db);
5099 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5100 if (!$result) {
5101 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5102 }
5103 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5104 $this->last_main_doc = $companybankaccount->last_main_doc;
5105 } else {
5106 // Positionne le modele sur le nom du modele a utiliser
5107 if (!dol_strlen($modele)) {
5108 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5109 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5110 } else {
5111 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5112 return 0;
5113 }
5114 }
5115
5116 if (!isset($this->bank_account)) {
5117 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5118 $bac = new CompanyBankAccount($this->db);
5119 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5120 $result = $bac->fetch(0, '', $this->id);
5121 if ($result > 0) {
5122 $this->bank_account = $bac;
5123 } else {
5124 $this->bank_account = '';
5125 }
5126 }
5127
5128 $modelpath = "core/modules/societe/doc/";
5129
5130 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5131 }
5132
5133 return $result;
5134 }
5135
5136
5148 public function setCategories($categories, $type_categ)
5149 {
5150 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5151
5152 // Decode type
5153 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5154 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5155 return -1;
5156 }
5157
5158 return parent::setCategoriesCommon($categories, $type_categ);
5159 }
5160
5168 public function setSalesRep($salesrep, $onlyAdd = false)
5169 {
5170 global $user;
5171
5172 // Handle single user
5173 if (!is_array($salesrep)) {
5174 $salesrep = array($salesrep);
5175 }
5176
5177 $to_del = array(); // Nothing to delete
5178 $to_add = $salesrep;
5179 if ($onlyAdd === false) {
5180 // Get current users
5181 $existing = $this->getSalesRepresentatives($user, 1);
5182
5183 // Diff
5184 if (is_array($existing)) {
5185 $to_del = array_diff($existing, $salesrep);
5186 $to_add = array_diff($salesrep, $existing);
5187 }
5188 }
5189
5190 $error = 0;
5191
5192 // Process
5193 foreach ($to_del as $del) {
5194 $this->del_commercial($user, $del);
5195 }
5196 foreach ($to_add as $add) {
5197 $result = $this->add_commercial($user, $add);
5198 if ($result < 0) {
5199 $error++;
5200 break;
5201 }
5202 }
5203
5204 return $error ? -1 : 1;
5205 }
5206
5213 public function setThirdpartyType($typent_id)
5214 {
5215 global $user;
5216
5217 dol_syslog(__METHOD__, LOG_DEBUG);
5218
5219 if ($this->id) {
5220 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5221
5222 if ($result > 0) {
5223 $this->typent_id = $typent_id;
5224 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5225 return 1;
5226 } else {
5227 return -1;
5228 }
5229 } else {
5230 return -1;
5231 }
5232 }
5233
5243 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5244 {
5245 if ($origin_id == $dest_id) {
5246 dol_syslog('Error: Try to merge a thirdparty into itself');
5247 return false;
5248 }
5249
5250 // 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.
5251 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5252 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5253 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5254 $sql .= ' SELECT fk_user ';
5255 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5256 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5257
5258 $resql = $dbs->query($sql);
5259 while ($obj = $dbs->fetch_object($resql)) {
5260 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5261 }
5262
5263 // llx_societe_extrafields table must not be here because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5264 // Do not include llx_societe because it will be replaced later.
5265 $tables = array(
5266 'societe_account',
5267 'societe_commerciaux',
5268 'societe_prices',
5269 'societe_remise',
5270 'societe_remise_except',
5271 'societe_rib'
5272 );
5273
5274 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5275 }
5276
5285 public function setAccountancyCode($type, $value)
5286 {
5287 global $user, $langs, $conf;
5288
5289 $this->db->begin();
5290
5291 if ($type == 'buy') {
5292 $field = 'accountancy_code_buy';
5293 } elseif ($type == 'sell') {
5294 $field = 'accountancy_code_sell';
5295 } else {
5296 return -1;
5297 }
5298
5299 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5300 $sql .= $field." = '".$this->db->escape($value)."'";
5301 $sql .= " WHERE rowid = ".((int) $this->id);
5302
5303 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5304 $resql = $this->db->query($sql);
5305
5306 if ($resql) {
5307 // Call triggers
5308 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5309 $interface = new Interfaces($this->db);
5310 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5311 if ($result < 0) {
5312 $this->errors = $interface->errors;
5313 $this->db->rollback();
5314 return -1;
5315 }
5316 // End call triggers
5317
5318 $this->$field = $value;
5319
5320 $this->db->commit();
5321 return 1;
5322 } else {
5323 $this->error = $this->db->lasterror();
5324 $this->db->rollback();
5325 return -1;
5326 }
5327 }
5328
5335 public function fetchPartnerships($mode)
5336 {
5337 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5338
5339 $this->partnerships[] = array();
5340
5341 return 1;
5342 }
5343
5351 public function getKanbanView($option = '', $arraydata = array())
5352 {
5353 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5354
5355 $return = '<div class="box-flex-item box-flex-grow-zero">';
5356 $return .= '<div class="info-box info-box-sm">';
5357 $return .= '<span class="info-box-icon bg-infobox-action">';
5358 $return .= img_picto('', $this->picto);
5359 $return .= '</span>';
5360 $return .= '<div class="info-box-content">';
5361 $return .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref);
5362 $return .= '</div>';
5363 if (!empty($this->phone)) {
5364 $return .= '<div class="inline-block valignmiddle">';
5365 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5366 $return .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5367 $return .= '</div>';
5368 }
5369 if (!empty($this->email)) {
5370 $return .= '<div class="inline-block valignmiddle">';
5371 $return .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5372 $return .= '</div>';
5373 }
5374 if ($selected >= 0) {
5375 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5376 }
5377 if (property_exists($this, 'code_client')) {
5378 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5379 }
5380 if (method_exists($this, 'getLibStatut')) {
5381 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5382 }
5383 $return .= '</div>'; // end info-box-content
5384 $return .= '</div>';
5385 $return .= '</div>';
5386
5387 return $return;
5388 }
5389
5399 public function getContacts($list = 0, $code = '', $element = '')
5400 {
5401 // phpcs:enable
5402 global $langs;
5403
5404 $tab = array();
5405
5406 $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
5407 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5408 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5409 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5410 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5411 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5412 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5413 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5414 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5415 if (!empty($element)) {
5416 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5417 }
5418 if ($code) {
5419 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5420 }
5421 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5422 $sql .= " AND tc.source = 'external'";
5423 $sql .= " AND tc.active = 1";
5424
5425 $sql .= " ORDER BY t.lastname ASC";
5426
5427 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5428 $resql = $this->db->query($sql);
5429 if ($resql) {
5430 $num = $this->db->num_rows($resql);
5431 $i = 0;
5432 while ($i < $num) {
5433 $obj = $this->db->fetch_object($resql);
5434
5435 if (!$list) {
5436 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5437 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5438 $tab[$i] = array(
5439 'source' => $obj->source,
5440 'socid' => $obj->socid,
5441 'id' => $obj->id,
5442 'nom' => $obj->lastname, // For backward compatibility
5443 'civility' => $obj->civility,
5444 'lastname' => $obj->lastname,
5445 'firstname' => $obj->firstname,
5446 'email' => $obj->email,
5447 'login' => (empty($obj->login) ? '' : $obj->login),
5448 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5449 'statuscontact' => $obj->statuscontact,
5450 'rowid' => $obj->rowid,
5451 'code' => $obj->code,
5452 'element' => $obj->element,
5453 'libelle' => $libelle_type,
5454 'status' => $obj->statuslink,
5455 'fk_c_type_contact' => $obj->fk_c_type_contact
5456 );
5457 } else {
5458 $tab[$i] = $obj->id;
5459 }
5460
5461 $i++;
5462 }
5463
5464 return $tab;
5465 } else {
5466 $this->error = $this->db->lasterror();
5467 dol_print_error($this->db);
5468 return -1;
5469 }
5470 }
5471
5482 public function mergeCompany($soc_origin_id)
5483 {
5484 global $conf, $langs, $hookmanager, $user, $action;
5485
5486 $error = 0;
5487 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5488
5489 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5490
5491 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5492 $this->error = $langs->trans('ErrorRecordNotFound');
5493 $error++;
5494 }
5495
5496 if (!$error) {
5497 $this->db->begin();
5498
5499 // Recopy some data
5500 $this->client |= $soc_origin->client;
5501 $this->fournisseur |= $soc_origin->fournisseur;
5502 $listofproperties = array(
5503 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5504 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5505 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5506 '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',
5507 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5508 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5509 );
5510 foreach ($listofproperties as $property) {
5511 if (empty($this->$property)) {
5512 $this->$property = $soc_origin->$property;
5513 }
5514 }
5515
5516 if ($this->typent_id == -1) {
5517 $this->typent_id = $soc_origin->typent_id;
5518 }
5519
5520 // Concat some data
5521 $listofproperties = array(
5522 'note_public', 'note_private'
5523 );
5524 foreach ($listofproperties as $property) {
5525 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5526 }
5527
5528 // Merge extrafields
5529 if (is_array($soc_origin->array_options)) {
5530 foreach ($soc_origin->array_options as $key => $val) {
5531 if (empty($this->array_options[$key])) {
5532 $this->array_options[$key] = $val;
5533 }
5534 }
5535 }
5536
5537 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5538 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5539 $this->name_bis = $this->name;
5540 }
5541
5542 // Merge categories
5543 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5544 $static_cat = new Categorie($this->db);
5545
5546 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5547 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5548 $custcats = array_merge($custcats, $custcats_ori);
5549 $this->setCategories($custcats, 'customer');
5550
5551 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5552 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5553 $suppcats = array_merge($suppcats, $suppcats_ori);
5554 $this->setCategories($suppcats, 'supplier');
5555
5556 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5557 if ($soc_origin->code_client == $this->code_client
5558 || $soc_origin->code_fournisseur == $this->code_fournisseur
5559 || $soc_origin->barcode == $this->barcode) {
5560 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5561 $soc_origin->code_client = '';
5562 $soc_origin->code_fournisseur = '';
5563 $soc_origin->barcode = '';
5564 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5565 }
5566
5567 // Update
5568 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5569
5570 if ($result < 0) {
5571 $error++;
5572 }
5573
5574 // Move links
5575 if (!$error) {
5576 $objects = array(
5577 'Adherent' => '/adherents/class/adherent.class.php',
5578 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5579 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5580 'Propal' => '/comm/propal/class/propal.class.php',
5581 'Commande' => '/commande/class/commande.class.php',
5582 'Facture' => '/compta/facture/class/facture.class.php',
5583 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5584 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5585 'Contact' => '/contact/class/contact.class.php',
5586 'Contrat' => '/contrat/class/contrat.class.php',
5587 'Expedition' => '/expedition/class/expedition.class.php',
5588 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5589 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5590 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5591 'Reception' => '/reception/class/reception.class.php',
5592 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5593 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5594 'Product' => '/product/class/product.class.php',
5595 //'ProductThirparty' => '...', // for llx_product_thirdparty
5596 'Project' => '/projet/class/project.class.php',
5597 'User' => '/user/class/user.class.php',
5598 'Account' => '/compta/bank/class/account.class.php',
5599 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5600 'Societe' => '/societe/class/societe.class.php',
5601 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5602 );
5603 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5604 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5605 }
5606 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5607 $objects['Mo'] = '/mrp/class/mo.class.php';
5608 }
5609 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5610 $objects['Don'] = '/don/class/don.class.php';
5611 }
5612 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5613 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5614 }
5615 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5616 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5617 }
5618 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5619 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5620 }
5621
5622 //First, all core objects must update their tables
5623 foreach ($objects as $object_name => $object_file) {
5624 /* $object_file is never an array -> code commented
5625 if (is_array($object_file)) {
5626 if (empty($object_file['enabled'])) {
5627 continue;
5628 }
5629 $object_file = $object_file['file'];
5630 }
5631 */
5632
5633 require_once DOL_DOCUMENT_ROOT.$object_file;
5634
5635 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5636 $error++;
5637 $this->error = $this->db->lasterror();
5638 break;
5639 }
5640 }
5641 }
5642
5643 // External modules should update their ones too
5644 if (!$error) {
5645 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5646 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5647
5648 if ($reshook < 0) {
5649 $this->error = $hookmanager->error;
5650 $this->errors = $hookmanager->errors;
5651 $error++;
5652 }
5653 }
5654
5655
5656 if (!$error) {
5657 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5658
5659 // Call trigger
5660 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5661 if ($result < 0) {
5662 $error++;
5663 }
5664 // End call triggers
5665 }
5666
5667 if (!$error) {
5668 // Move files from the dir of the third party to delete into the dir of the third party to keep
5669 if (!empty($conf->societe->multidir_output[$this->entity])) {
5670 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5671 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5672
5673 if (dol_is_dir($srcdir)) {
5674 $dirlist = dol_dir_list($srcdir, 'files', 1);
5675 foreach ($dirlist as $filetomove) {
5676 $destfile = $destdir.'/'.$filetomove['relativename'];
5677 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5678 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5679 }
5680 //exit;
5681 }
5682 }
5683 }
5684
5685
5686 if (!$error) {
5687 // We finally remove the old thirdparty
5688 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5689 $this->error = $soc_origin->error;
5690 $this->errors = $soc_origin->errors;
5691 $error++;
5692 }
5693 }
5694
5695 if (!$error) {
5696 $this->db->commit();
5697 return 0;
5698 } else {
5699 $langs->load("errors");
5700 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5701 $this->db->rollback();
5702 return -1;
5703 }
5704 }
5705
5706 return -1;
5707 }
5708}
$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,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
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.
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.
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Search the thirdparty that match the most the provided parameters.
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()
Return 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.
deprecatedProperties()
Provide list of deprecated properties and replacements.
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 clickable link of object (with optional picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Return 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.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:162
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
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)
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
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.
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)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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, $attop=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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...
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
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 a Dolibarr global constant string value.
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...
div refaddress div address
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.
isValidSiren($siren)
Check the syntax validity of a SIREN.
isValidTinForPT($str)
Check the syntax validity of a Portuguese (PT) Tax Identification Number (TIN).
isValidSiret($siret)
Check the syntax validity of a SIRET.
isValidTinForES($str)
Check the syntax validity of a Spanish (ES) Tax Identification Number (TIN), where:
isValidTinForBE($str)
Check the syntax validity of a Belgium (BE) Tax Identification Number (TIN).
isValidTinForDZ($str)
Check the syntax validity of an Algerian (DZ) Tax Identification Number (TIN).
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140