dolibarr 24.0.0-beta
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-2026 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-2025 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-2026 MDW <mdeweerd@users.noreply.github.com>
24 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
49require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
50require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
51
52
56class Societe extends CommonObject
57{
58 use CommonIncoterm;
60 use CommonPeople;
61
66 public $TRIGGER_PREFIX = 'COMPANY'; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
67
71 public $module = 'societe';
72
76 public $element = 'societe';
77
81 public $table_element = 'societe';
82
86 public $fk_element = 'fk_soc';
87
91 public $fieldsforcombobox = 'nom,name_alias';
92
96 protected $childtables = array(
97 'supplier_proposal' => array('name' => 'SupplierProposal'),
98 'propal' => array('name' => 'Proposal'),
99 'commande' => array('name' => 'Order'),
100 'facture' => array('name' => 'Invoice'),
101 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
102 'contrat' => array('name' => 'Contract'),
103 'fichinter' => array('name' => 'Fichinter'),
104 'facture_fourn' => array('name' => 'SupplierInvoice'),
105 'commande_fournisseur' => array('name' => 'SupplierOrder'),
106 'projet' => array('name' => 'Project'),
107 'expedition' => array('name' => 'Shipment'),
108 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
109 'adherent' => array('name' => 'Member')
110 );
111
116 protected $childtablesoncascade = array(
117 'societe_prices',
118 'product_fournisseur_price',
119 'product_customer_price_log',
120 'product_customer_price',
121 '@Contact:/contact/class/contact.class.php:fk_soc',
122 'adherent',
123 'societe_account',
124 'societe_rib',
125 'societe_remise',
126 'societe_remise_except',
127 'societe_commerciaux',
128 'categorie',
129 'notify',
130 'notify_def',
131 'actioncomm',
132 );
133
137 public $picto = 'company';
138
143 public $restrictiononfksoc = 1;
144
149 public $SupplierCategories = array();
150
155 public $prefixCustomerIsRequired;
156
186 public $fields = array(
187 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
188 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
189 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
190 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
191 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
192 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
193 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
194 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
195 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
196 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
197 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
198 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
199 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
200 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
201 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
202 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
203 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
204 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
205 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
206 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
207 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
208 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
209 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
210 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
211 'fk_typent' => array('type' => 'integer', 'label' => 'ThirdPartyType', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
212 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
213 'birth' => array('type' => 'date', 'label' => 'CompanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182),
214 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
215 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
216 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
217 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
218 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
219 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
220 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
221 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'VATIntra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
222 'euid' => array('type' => 'varchar(20)', 'label' => 'EUIDShort', 'enabled' => 1, 'visible' => -1, 'position' => 213),
223 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
224 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
225 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
226 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
227 'client' => array('type' => 'tinyint(4)', 'label' => 'Customer', 'enabled' => 1, 'visible' => -1, 'position' => 240),
228 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Supplier', 'enabled' => 1, 'visible' => -1, 'position' => 245),
229 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
230 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
231 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
232 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
233 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
234 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
235 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
236 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
237 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
238 'mode_reglement' => array('type' => 'smallint(6)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
239 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
240 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
241 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
242 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
243 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
244 'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
245 'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
246 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMode', 'enabled' => 1, 'visible' => -1, 'position' => 330),
247 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'VATIsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 335),
248 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax1IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 340),
249 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
250 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax2IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 350),
251 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
252 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
253 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
254 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => 'getDolGlobalString("PRODUIT_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
255 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
256 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
257 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
258 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
259 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
260 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
261 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
262 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
263 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
264 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
265 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
266 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
267 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
268 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
269 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
270 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
271 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
272 );
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 $euid;
517
521 public $vat_reverse_charge = 0;
522
523 // Local taxes
527 public $localtax1_assuj;
531 public $localtax1_value;
535 public $localtax2_assuj;
539 public $localtax2_value;
540
544 public $managers;
545
549 public $capital;
550
554 public $typent_id = 0;
555
559 public $typent_code;
560
564 public $effectif;
565
569 public $effectif_id = 0;
573 public $forme_juridique_code = 0;
578 public $forme_juridique;
582 public $birth;
583
587 public $remise_percent;
591 public $remise_supplier_percent;
592
596 public $mode_reglement_id;
600 public $cond_reglement_id;
604 public $deposit_percent;
608 public $mode_reglement_supplier_id;
612 public $cond_reglement_supplier_id;
616 public $transport_mode_supplier_id;
617
621 public $fk_prospectlevel;
622
626 public $name_bis;
627
633 public $user_modification;
634
640 public $user_creation;
641
646 public $client = 0;
647
652 public $prospect = 0;
653
658 public $fournisseur;
659
664 public $code_client;
665
670 public $code_fournisseur;
671
676 public $code_compta_client;
677
682 public $accountancy_code_customer_general;
683
688 public $accountancy_code_customer;
689
694 public $code_compta_fournisseur;
695
700 public $accountancy_code_supplier_general;
701
706 public $accountancy_code_supplier;
707
712 public $code_compta_product;
713
719 public $note;
720
725 public $note_private;
726
731 public $note_public;
732
737 public $stcomm_id;
738
743 public $stcomm_picto;
744
749 public $status_prospect_label;
750
755 public $price_level;
756
760 public $outstanding_limit;
761
765 public $order_min_amount;
766
770 public $supplier_order_min_amount;
771
776 public $commercial_id;
777
782 public $parent;
783
788 public $default_lang;
789
793 public $ref;
794
800 public $ref_ext;
801
805 public $ip;
806
813 public $import_key;
814
819 public $webservices_url;
820
825 public $webservices_key;
826
830 public $logo;
831
835 public $logo_small;
836
840 public $logo_mini;
841
845 public $logo_squarred;
846
850 public $logo_squarred_small;
851
855 public $logo_squarred_mini;
856
860 public $accountancy_code_sell;
861
865 public $accountancy_code_buy;
866
870 public $currency_code;
871
872 // Multicurrency
876 public $fk_multicurrency;
877
881 public $multicurrency_code;
882
883 // Warehouse
887 public $fk_warehouse;
888
892 public $termsofsale;
893
894
895 // Fields loaded by fetchPartnerships()
896
900 public $partnerships = array();
901
902
906 public $bank_account;
907
913 public $code_compta;
914
915
916 const STATUS_CEASED = 0;
917 const STATUS_INACTIVITY = 1;
918
922 const NO_CUSTOMER = 0;
923
927 const CUSTOMER = 1;
928
932 const PROSPECT = 2;
933
938
942 const NO_SUPPLIER = 0;
943
947 const SUPPLIER = 1;
948
954 protected function deprecatedProperties()
955 {
956 return
957 array(
958 'code_compta' => 'code_compta_client',
959 )
960 + parent::deprecatedProperties();
961 }
962
963
964
970 public function __construct($db)
971 {
972 $this->db = $db;
973
974 $this->ismultientitymanaged = 1;
975 $this->isextrafieldmanaged = 1;
976 $this->client = 0;
977 $this->prospect = 0;
978 $this->fournisseur = 0;
979 $this->typent_id = 0;
980 $this->effectif_id = 0;
981 $this->forme_juridique_code = 0;
982 $this->tva_assuj = 1;
983 $this->vat_reverse_charge = 0;
984 $this->status = 1;
985
986 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
987 $this->fields['address']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
988 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
989 $this->fields['town']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
990 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
991 }
992 }
993
994
1003 public function create(User $user, $notrigger = 0)
1004 {
1005 global $langs, $conf;
1006
1007 $error = 0;
1008
1009 // Clean parameters
1010 if (empty($this->status)) {
1011 $this->status = 0;
1012 }
1013 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1014 $this->setUpperOrLowerCase();
1015 $this->nom = $this->name; // For backward compatibility
1016
1017 if (empty($this->client)) {
1018 $this->client = 0;
1019 }
1020 if (empty($this->fournisseur)) {
1021 $this->fournisseur = 0;
1022 }
1023 $this->import_key = trim((string) $this->import_key);
1024
1025 $this->code_compta_client = trim($this->code_compta_client ?? '');
1026
1027 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general ?? '');
1028 if ($this->accountancy_code_customer_general === '-1') {
1029 $this->accountancy_code_customer_general = '';
1030 }
1031 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1032 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general ?? '');
1033 if ($this->accountancy_code_supplier_general === '-1') {
1034 $this->accountancy_code_supplier_general = '';
1035 }
1036 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1037 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1038 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1039
1040 if (!empty($this->multicurrency_code)) {
1041 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1042 }
1043 if (empty($this->fk_multicurrency)) {
1044 $this->multicurrency_code = '';
1045 $this->fk_multicurrency = 0;
1046 }
1047
1048 dol_syslog(get_class($this)."::create ".$this->name);
1049
1050 $now = dol_now();
1051
1052 if (empty($this->date_creation)) {
1053 $this->date_creation = $now;
1054 }
1055
1056 $this->db->begin();
1057
1058 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1059 if ($this->code_client == -1 || $this->code_client === 'auto') {
1060 $this->get_codeclient($this, 0);
1061 }
1062 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1063 $this->get_codefournisseur($this, 1);
1064 }
1065
1066 // Check more parameters (including mandatory setup
1067 // If error, this->errors[] is filled
1068 $result = $this->verify();
1069
1070 if ($result >= 0) {
1071 $this->entity = setEntity($this);
1072
1073 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1074 $sql .= "nom";
1075 $sql .= ", name_alias";
1076 $sql .= ", entity";
1077 $sql .= ", datec";
1078 $sql .= ", fk_user_creat";
1079 $sql .= ", fk_typent";
1080 $sql .= ", canvas";
1081 $sql .= ", status";
1082 $sql .= ", ref_ext";
1083 $sql .= ", fk_stcomm";
1084 $sql .= ", fk_incoterms";
1085 $sql .= ", location_incoterms";
1086 $sql .= ", import_key";
1087 $sql .= ", fk_multicurrency";
1088 $sql .= ", multicurrency_code";
1089 $sql .= ", ip";
1090 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1091 $sql .= ", vat_reverse_charge";
1092 $sql .= ", accountancy_code_buy";
1093 $sql .= ", accountancy_code_sell";
1094 }
1095 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1096 $sql .= " '".$this->db->escape($this->name_alias)."',";
1097 $sql .= " ".((int) $this->entity).",";
1098 $sql .= " '".$this->db->idate($this->date_creation)."'";
1099 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1100 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1101 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1102 $sql .= ", ".((int) $this->status);
1103 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1104 $sql .= ", 0";
1105 $sql .= ", ".(int) $this->fk_incoterms;
1106 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1107 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1108 $sql .= ", ".(int) $this->fk_multicurrency;
1109 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1110 $sql .= ", ".(empty($this->ip) ? "null" : "'".$this->db->escape($this->ip)."'");
1111 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1112 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1113 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1114 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1115 }
1116 $sql .= ")";
1117
1118 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1119
1120 $result = $this->db->query($sql);
1121 if ($result) {
1122 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1123
1124 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1125
1126 // Addition of the assigned sales representative
1127 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1128 $this->add_commercial($user, $this->commercial_id);
1129 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1130 // If a sales representative creates a customer, they are automatically assigned to them.
1131 $this->add_commercial($user, $user->id);
1132 }
1133
1134 if ($ret >= 0) {
1135 if (! $notrigger) {
1136 // Call trigger
1137 $result = $this->call_trigger('COMPANY_CREATE', $user);
1138 if ($result < 0) {
1139 $error++;
1140 }
1141 // End call triggers
1142 }
1143 } else {
1144 $error++;
1145 }
1146
1147 if (!$error) {
1148 dol_syslog(get_class($this)."::Create success id=".$this->id);
1149 $this->db->commit();
1150 return $this->id;
1151 } else {
1152 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1153 $this->db->rollback();
1154 return -4;
1155 }
1156 } else {
1157 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1158 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1159 $result = -1;
1160 } else {
1161 $this->error = $this->db->lasterror();
1162 $result = -2;
1163 }
1164 $this->db->rollback();
1165 return $result;
1166 }
1167 } else {
1168 $this->db->rollback();
1169 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1170 return -3;
1171 }
1172 }
1173
1174
1175 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1185 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1186 {
1187 $error = 0;
1188
1189 $this->db->begin();
1190
1191 // phpcs:enable
1192 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1193 $contact = new Contact($this->db);
1194
1195 $contact->name = $this->name_bis;
1196 $contact->firstname = $this->firstname;
1197 $contact->civility_id = $this->civility_id;
1198 $contact->socid = $this->id; // fk_soc
1199 $contact->statut = 1; // deprecated
1200 $contact->status = 1;
1201 $contact->priv = 0;
1202 $contact->country_id = $this->country_id;
1203 $contact->state_id = $this->state_id;
1204 $contact->address = $this->address;
1205 $contact->email = $this->email;
1206 $contact->zip = $this->zip;
1207 $contact->town = $this->town;
1208 $this->setUpperOrLowerCase();
1209 $contact->phone_pro = $this->phone;
1210 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1211 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1212 }
1213
1214 $contactId = $contact->create($user, $notrigger);
1215 if ($contactId < 0) {
1216 $error++;
1217 $this->setErrorsFromObject($contact);
1218 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1219 }
1220
1221 if (empty($error) && is_array($tags) && !empty($tags)) {
1222 $result = $contact->setCategories($tags);
1223 if ($result < 0) {
1224 $error++;
1225 $this->setErrorsFromObject($contact);
1226 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1227 $contactId = $result;
1228 }
1229 }
1230
1231 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1232 $result = $contact->setNoEmail($no_email);
1233 if ($result < 0) {
1234 $this->setErrorsFromObject($contact);
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 $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', 'EUID', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1311 foreach ($array_to_check as $key) {
1312 $keymin = strtolower($key);
1313 $keyfield_db = $keymin;
1314 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1315 $keymin = 'code_compta_client';
1316 $keyfield_db = 'code_compta';
1317 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1318 $keymin = 'code_compta_fournisseur';
1319 $keyfield_db = 'code_compta_fournisseur';
1320 }
1321 $i = (int) preg_replace('/[^0-9]/', '', $key);
1322 $vallabel = $this->$keymin;
1323
1324 if ($i > 0) {
1325 if ($mysoc != null && $this->isACompany()) {
1326 // Check for mandatory prof id (but only if country is same than ours)
1327 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1328 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1329 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1330 $langs->load("errors");
1331 $error++;
1332 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1333 }
1334 }
1335 }
1336
1337 // Check for unicity on profid
1338 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1339 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1340 $langs->load("errors");
1341 $error++;
1342 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1343 }
1344 }
1345 } else {
1346 if ($key == 'EMAIL') {
1347 // Check for mandatory
1348 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1349 $langs->load("errors");
1350 $error++;
1351 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1352 }
1353
1354 // Check for unicity
1355 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1356 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1357 $langs->load("errors");
1358 $error++;
1359 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1360 }
1361 }
1362 } elseif ($key == 'TVA_INTRA') {
1363 // Check for unicity
1364 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1365 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1366 $langs->load("errors");
1367 $error++;
1368 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1369 }
1370 }
1371 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1372 $langs->load("errors");
1373 $error++;
1374 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1375 }
1376 } elseif ($key == 'EUID') {
1377 // Check for unicity
1378 if ($vallabel && getDolGlobalString('SOCIETE_EUID_UNIQUE')) {
1379 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1380 $langs->load("errors");
1381 $error++;
1382 $this->errors[] = $langs->trans('EUIDShort')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1383 }
1384 }
1385
1386 // Check for mandatory
1387 if (getDolGlobalString('SOCIETE_EUID_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1388 $langs->load("errors");
1389 $error++;
1390 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('EUIDShort')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1391 }
1392 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1393 // Check for unicity
1394 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1395 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1396 $langs->loadLangs(array("errors", 'compta'));
1397 $error++;
1398 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1399 }
1400 }
1401
1402 // Check for mandatory
1403 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1404 $langs->loadLangs(array("errors", 'compta'));
1405 $error++;
1406 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1407 }
1408 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1409 // Check for unicity
1410 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1411 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1412 $langs->loadLangs(array("errors", 'compta'));
1413 $error++;
1414 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1415 }
1416 }
1417
1418 // Check for mandatory
1419 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1420 $langs->loadLangs(array("errors", 'compta'));
1421 $error++;
1422 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1423 }
1424 }
1425 }
1426 }
1427
1428 if ($error) {
1429 $result = -4;
1430 }
1431
1432 return $result;
1433 }
1434
1447 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1448 {
1449 global $langs, $conf, $hookmanager;
1450
1451 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1452
1453 if (empty($id)) {
1454 $id = $this->id;
1455 }
1456 if (empty($this->country_id) && !empty($this->country_code)) {
1457 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1458 }
1459
1460 if (empty($this->country_id) && !empty($this->country_code)) {
1461 $country_id = getCountry($this->country_code, '3');
1462 $this->country_id = is_int($country_id) ? $country_id : 0;
1463 }
1464
1465 $error = 0;
1466
1467 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1468
1469 $now = dol_now();
1470
1471 // Clean parameters
1472 $this->id = $id;
1473 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1474 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1475 $this->nom = $this->name; // For backward compatibility
1476 $this->name_alias = trim((string) $this->name_alias);
1477 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1478 $this->address = trim((string) $this->address);
1479 $this->zip = trim((string) $this->zip);
1480 $this->town = trim((string) $this->town);
1481 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1482 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1483 $this->phone = trim((string) $this->phone);
1484 $this->phone = preg_replace("/\s/", "", $this->phone);
1485 $this->phone = preg_replace("/\./", "", $this->phone);
1486 $this->phone_mobile = trim((string) $this->phone_mobile);
1487 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1488 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1489 $this->fax = trim((string) $this->fax);
1490 $this->fax = preg_replace("/\s/", "", $this->fax);
1491 $this->fax = preg_replace("/\./", "", $this->fax);
1492 $this->email = trim((string) $this->email);
1493 $this->url = $this->url ? clean_url($this->url, 0) : '';
1494 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1495 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1496 $this->idprof1 = trim((string) $this->idprof1);
1497 $this->idprof2 = trim((string) $this->idprof2);
1498 $this->idprof3 = trim((string) $this->idprof3);
1499 $this->idprof4 = trim((string) $this->idprof4);
1500 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1501 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1502 $this->prefix_comm = trim((string) $this->prefix_comm);
1503 $this->outstanding_limit = price2num($this->outstanding_limit);
1504 $this->order_min_amount = price2num($this->order_min_amount);
1505 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1506 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1507 $this->tva_intra = trim((string) $this->tva_intra);
1508 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1509 $this->euid = trim((string) $this->euid);
1510
1511 if (empty($this->status)) {
1512 $this->status = 0;
1513 }
1514
1515 if (!empty($this->multicurrency_code)) {
1516 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1517 }
1518 if (empty($this->fk_multicurrency)) {
1519 $this->multicurrency_code = '';
1520 $this->fk_multicurrency = 0;
1521 }
1522
1523 // Local taxes
1524 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1525 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1526
1527 $this->localtax1_value = trim($this->localtax1_value);
1528 $this->localtax2_value = trim($this->localtax2_value);
1529
1530 $this->capital = (!is_null($this->capital) && (string) $this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1531
1532 $this->effectif_id = (int) $this->effectif_id;
1533 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1534
1535 //Gencod
1536 $this->barcode = trim((string) $this->barcode);
1537
1538 // For automatic creation
1539 if ($this->code_client == -1 || $this->code_client === 'auto') {
1540 $this->get_codeclient($this, 0);
1541 }
1542 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1543 $this->get_codefournisseur($this, 1);
1544 }
1545
1546 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1547 if ($this->accountancy_code_customer_general === '-1') {
1548 $this->accountancy_code_customer_general = '';
1549 }
1550 $this->code_compta_client = trim((string) $this->code_compta_client);
1551 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1552 if ($this->accountancy_code_supplier_general === '-1') {
1553 $this->accountancy_code_supplier_general = '';
1554 }
1555 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1556
1557 // Check parameters. More tests are done later in the ->verify()
1558 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1559 $langs->load("errors");
1560 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1561 return -1;
1562 }
1563
1564 $customer = false;
1565 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1566 // If $allowmodcodeclient is set and value is not set, we generate it
1567 if (empty($this->code_compta_client)) {
1568 $ret = $this->get_codecompta('customer');
1569 if ($ret < 0) {
1570 return -1;
1571 }
1572 }
1573
1574 $customer = true;
1575 }
1576
1577 $supplier = false;
1578 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1579 // If $allowmodcodefournisseur is set and value is not set, we generate it
1580 if (empty($this->code_compta_fournisseur)) {
1581 $ret = $this->get_codecompta('supplier');
1582 if ($ret < 0) {
1583 return -1;
1584 }
1585 }
1586
1587 $supplier = true;
1588 }
1589
1590 //Web services
1591 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1592 $this->webservices_key = trim((string) $this->webservices_key);
1593
1594 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1595 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1596
1597 //Incoterms
1598 $this->fk_incoterms = (int) $this->fk_incoterms;
1599 $this->location_incoterms = trim((string) $this->location_incoterms);
1600
1601 $this->db->begin();
1602
1603 // Check name is required and codes are ok or unique.
1604 // If error, this->errors[] is filled
1605 $result = 0;
1606 if ($action != 'add' && $action != 'merge') {
1607 // We don't check when update called during a create because verify was already done.
1608 // 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
1609 $result = $this->verify();
1610
1611 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1612 // So we can update record that were using and old numbering rule.
1613 if (is_array($this->errors)) {
1614 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1615 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1616 unset($this->errors[$key]); // Remove error message
1617 }
1618 }
1619 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1620 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1621 unset($this->errors[$key]); // Remove error message
1622 }
1623 }
1624 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1625 $result = 0;
1626 }
1627 }
1628 }
1629 $this->setUpperOrLowerCase();
1630 if ($result >= 0) {
1631 dol_syslog(get_class($this)."::update verify ok or not done");
1632
1633 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1634 $sql .= "entity = ".((int) $this->entity);
1635 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1636 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1637 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1638 $sql .= ",address = '".$this->db->escape($this->address)."'";
1639
1640 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1641 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1642
1643 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1644 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1645
1646 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1647 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1648 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1649 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1650 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1651 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1652
1653 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1654
1655 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1656 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1657
1658 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1659 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1660 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1661 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1662 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1663 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1664
1665 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape((string) $this->tva_assuj)."'" : "null");
1666 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1667 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1668 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape((string) $this->vat_reverse_charge) . "'" : 0);
1669 }
1670 $sql .= ",euid = '".$this->db->escape($this->euid)."'";
1671 $sql .= ",status = ".((int) $this->status);
1672
1673 // Local taxes
1674 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape((string) $this->localtax1_assuj)."'" : "null");
1675 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape((string) $this->localtax2_assuj)."'" : "null");
1676 if ($this->localtax1_assuj == 1) {
1677 if ($this->localtax1_value != '') {
1678 $sql .= ", localtax1_value = ".((float) $this->localtax1_value);
1679 } else {
1680 $sql .= ", localtax1_value = 0.000";
1681 }
1682 } else {
1683 $sql .= ",localtax1_value =0.000";
1684 }
1685
1686 if ($this->localtax2_assuj == 1) {
1687 if ($this->localtax2_value != '') {
1688 $sql .= ",localtax2_value = ".((float) $this->localtax2_value);
1689 } else {
1690 $sql .= ",localtax2_value = 0.000";
1691 }
1692 } else {
1693 $sql .= ",localtax2_value = 0.000";
1694 }
1695
1696 $sql .= ",capital = ".($this->capital === null ? "null" : (float) $this->capital);
1697
1698 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1699
1700 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1701 if (isset($this->stcomm_id)) {
1702 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1703 }
1704 if (isset($this->typent_id)) {
1705 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1706 }
1707
1708 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape((string) $this->forme_juridique_code)."'" : "null");
1709 $sql .= ",birth = ".(!empty($this->birth) ? "'".$this->db->idate($this->birth)."'" : "null");
1710
1711 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape((string) $this->mode_reglement_id)."'" : "null");
1712 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape((string) $this->cond_reglement_id)."'" : "null");
1713 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null");
1714 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape((string) $this->transport_mode_id)."'" : "null");
1715 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape((string) $this->mode_reglement_supplier_id)."'" : "null");
1716 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape((string) $this->cond_reglement_supplier_id)."'" : "null");
1717 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape((string) $this->transport_mode_supplier_id)."'" : "null");
1718 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape((string) $this->shipping_method_id)."'" : "null");
1719 $sql .= ",fk_account = ".($this->fk_account > 0 ? (int) $this->fk_account : "null");
1720
1721 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1722 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1723 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1724 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1725 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1726 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1727 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1728 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1729 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1730 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1731 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1732 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1733 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1734 if ($customer) {
1735 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1736 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1737 }
1738
1739 if ($supplier) {
1740 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1741 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1742 }
1743 }
1744 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1745 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1746
1747 //Incoterms
1748 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1749 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1750
1751 if ($customer) {
1752 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1753 }
1754
1755 if ($supplier) {
1756 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1757 }
1758 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1759 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1760 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1761 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1762 $sql .= " WHERE rowid = ".(int) $id;
1763
1764 $resql = $this->db->query($sql);
1765 if ($resql) {
1766 if (is_object($this->oldcopy)) { // If we have information on old values
1767 if ($this->oldcopy->country_id != $this->country_id) {
1768 unset($this->country_code);
1769 unset($this->country);
1770 }
1771 if ($this->oldcopy->state_id != $this->state_id) {
1772 unset($this->state_code);
1773 unset($this->state);
1774 }
1775 } else {
1776 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1777 unset($this->country);
1778 unset($this->state_code);
1779 unset($this->state);
1780 }
1781
1782 $nbrowsaffected = $this->db->affected_rows($resql);
1783
1784 if ($nbrowsaffected) {
1785 // Update information on linked member if it is an update
1786 if (!$nosyncmember && isModEnabled('member')) {
1787 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1788
1789 dol_syslog(get_class($this)."::update update linked member");
1790
1791 $lmember = new Adherent($this->db);
1792 $result = $lmember->fetch(0, '0', $this->id);
1793
1794 if ($result > 0) {
1795 $lmember->company = $this->name;
1796 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1797 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1798 $lmember->address = $this->address;
1799 $lmember->zip = $this->zip;
1800 $lmember->town = $this->town;
1801 $lmember->email = $this->email;
1802 $lmember->socialnetworks = $this->socialnetworks;
1803 $lmember->phone = $this->phone;
1804 $lmember->state_id = $this->state_id;
1805 $lmember->country_id = $this->country_id;
1806 $lmember->default_lang = $this->default_lang;
1807
1808 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1809 if ($result < 0) {
1810 $this->setErrorsFromObject($lmember);
1811 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1812 $error++;
1813 }
1814 } elseif ($result < 0) {
1815 $this->error = $lmember->error;
1816 $error++;
1817 }
1818 }
1819 }
1820
1821 $action = 'update';
1822
1823 // update accountancy for this entity
1824 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1825 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1826
1827 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1828 $sql .= " fk_soc";
1829 $sql .= ", entity";
1830 $sql .= ", vat_reverse_charge";
1831 $sql .= ", accountancy_code_customer_general";
1832 $sql .= ", accountancy_code_customer";
1833 $sql .= ", accountancy_code_supplier_general";
1834 $sql .= ", accountancy_code_supplier";
1835 $sql .= ", accountancy_code_buy";
1836 $sql .= ", accountancy_code_sell";
1837 $sql .= ") VALUES (";
1838 $sql .= $this->id;
1839 $sql .= ", ".((int) $conf->entity);
1840 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1841 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1842 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1843 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1844 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1845 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1846 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1847 $sql .= ")";
1848 $result = $this->db->query($sql);
1849 if (!$result) {
1850 $error++;
1851 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1852 }
1853 }
1854
1855 // Actions on extra fields
1856 if (!$error) {
1857 $result = $this->insertExtraFields();
1858 if ($result < 0) {
1859 $error++;
1860 }
1861 }
1862 // Actions on extra languages
1863 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1864 $result = $this->insertExtraLanguages();
1865 if ($result < 0) {
1866 $error++;
1867 }
1868 }
1869
1870 if (!$error && $call_trigger) {
1871 // Call trigger
1872 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1873 if ($result < 0) {
1874 $error++;
1875 }
1876 // End call triggers
1877 }
1878
1879 if (!$error) {
1880 dol_syslog(get_class($this)."::Update success");
1881 $this->db->commit();
1882 return 1;
1883 } else {
1884 $this->db->rollback();
1885 return -1;
1886 }
1887 } else {
1888 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1889 // Duplicate
1890 $this->error = $langs->trans("ErrorDuplicateField");
1891 $result = -1;
1892 } else {
1893 $this->error = $this->db->lasterror();
1894 $result = -2;
1895 }
1896 $this->db->rollback();
1897 return $result;
1898 }
1899 } else {
1900 $this->db->rollback();
1901 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1902 return -3;
1903 }
1904 }
1905
1925 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1926 {
1927 global $langs;
1928 global $conf;
1929
1930 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)) {
1931 return -1;
1932 }
1933
1934 $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';
1935 $sql .= ', s.status, s.fk_warehouse';
1936 $sql .= ', s.price_level';
1937 $sql .= ', GREATEST(s.tms, sef.tms) as date_modification, s.fk_user_creat, s.fk_user_modif';
1938 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1939 $sql .= ', s.socialnetworks';
1940 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1941 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1942 $sql .= ', s.capital, s.tva_intra, s.euid';
1943 $sql .= ', s.fk_typent as typent_id';
1944 $sql .= ', s.fk_effectif as effectif_id';
1945 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1946 $sql .= ', s.birth';
1947 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1948 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1949 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1950 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1951 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1952 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1953 } else {
1954 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1955 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1956 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1957 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1958 }
1959 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1960 $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';
1961 $sql .= ', s.fk_account, s.tva_assuj';
1962 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1963 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1964 $sql .= ', s.fk_shipping_method';
1965 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1966 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1967 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1968 $sql .= ', fj.libelle as forme_juridique';
1969 $sql .= ', e.libelle as effectif';
1970 $sql .= ', c.code as country_code, c.label as country';
1971 $sql .= ', d.code_departement as state_code, d.nom as state';
1972 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1973 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1974 $sql .= ', te.code as typent_code';
1975 $sql .= ', i.libelle as label_incoterms';
1976 if (!isModEnabled('multicompany')) {
1977 $sql .= ', s.remise_client, s.remise_supplier';
1978 } else {
1979 $sql .= ', sr.remise_client, sr2.remise_supplier';
1980 }
1981 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1982 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_extrafields as sef ON sef.fk_object=s.rowid';
1983 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1984 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1985 }
1986 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1987 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1988 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1989 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1990 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1991 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1992 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1993 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1994 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1995 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1996 if (isModEnabled('multicompany')) {
1997 $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').'))';
1998 $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').'))';
1999 }
2000 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2001
2002 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
2003 if ($is_client) {
2004 $sql .= ' AND s.client > 0';
2005 }
2006 if ($is_supplier) {
2007 $sql .= ' AND s.fournisseur > 0';
2008 } // if both false, no test (the thirdparty can be client and/or supplier)
2009
2010 if ($rowid) {
2011 $sql .= ' AND s.rowid = '.((int) $rowid);
2012 }
2013 if ($ref) {
2014 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
2015 }
2016 if ($ref_alias) {
2017 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
2018 }
2019 if ($ref_ext) {
2020 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
2021 }
2022 if ($barcode) {
2023 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
2024 }
2025 if ($idprof1) {
2026 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2027 }
2028 if ($idprof2) {
2029 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2030 }
2031 if ($idprof3) {
2032 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2033 }
2034 if ($idprof4) {
2035 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2036 }
2037 if ($idprof5) {
2038 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2039 }
2040 if ($idprof6) {
2041 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2042 }
2043 if ($email) {
2044 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2045 }
2046
2047 $resql = $this->db->query($sql);
2048 if ($resql) {
2049 $num = $this->db->num_rows($resql);
2050 if ($num > 1) {
2051 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2052 dol_syslog($this->error, LOG_WARNING);
2053 $result = -2;
2054 } elseif ($num) { // $num = 1
2055 $obj = $this->db->fetch_object($resql);
2056
2057 $this->id = $obj->rowid;
2058 $this->entity = $obj->entity;
2059 $this->canvas = $obj->canvas;
2060
2061 $this->ref = $obj->name;
2062 $this->name = $obj->name;
2063 $this->nom = $obj->name; // deprecated
2064 $this->name_alias = $obj->name_alias;
2065 $this->ref_ext = $obj->ref_ext;
2066
2067 $this->date_creation = $this->db->jdate($obj->date_creation);
2068 $this->date_modification = $this->db->jdate($obj->date_modification);
2069 $this->user_creation_id = $obj->fk_user_creat;
2070 $this->user_modification_id = $obj->fk_user_modif;
2071
2072 $this->address = $obj->address;
2073 $this->zip = $obj->zip;
2074 $this->town = $obj->town;
2075
2076 $this->country_id = $obj->country_id;
2077 $this->country_code = $obj->country_id ? $obj->country_code : '';
2078 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2079
2080 $this->state_id = $obj->state_id;
2081 $this->state_code = $obj->state_code;
2082 $this->region_id = $obj->region_id;
2083 $this->region_code = $obj->region_code;
2084 $this->state = ($obj->state != '-' ? $obj->state : '');
2085
2086 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2087 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2088 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2089 $this->status_prospect_label = $label; // label status prospect
2090 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2091
2092 $this->email = $obj->email;
2093 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2094
2095 $this->url = $obj->url;
2096 $this->phone = $obj->phone;
2097 $this->phone_mobile = $obj->phone_mobile;
2098 $this->fax = $obj->fax;
2099
2100 $this->parent = $obj->parent;
2101
2102 $this->idprof1 = $obj->idprof1;
2103 $this->idprof2 = $obj->idprof2;
2104 $this->idprof3 = $obj->idprof3;
2105 $this->idprof4 = $obj->idprof4;
2106 $this->idprof5 = $obj->idprof5;
2107 $this->idprof6 = $obj->idprof6;
2108
2109 $this->capital = $obj->capital;
2110
2111 $this->code_client = $obj->code_client;
2112 $this->code_fournisseur = $obj->code_fournisseur;
2113
2114 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2115 $this->code_compta_client = $obj->code_compta;
2116 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2117 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2118
2119 $this->barcode = $obj->barcode;
2120
2121 $this->tva_assuj = $obj->tva_assuj;
2122 $this->tva_intra = $obj->tva_intra;
2123
2124 if (!empty($obj->spe_vat_reverse_charge)) {
2125 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2126 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2127 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2128 } else {
2129 $this->vat_reverse_charge = 0;
2130 }
2131 $this->euid = $obj->euid;
2132
2133 $this->status = $obj->status;
2134
2135 // Local Taxes
2136 $this->localtax1_assuj = $obj->localtax1_assuj;
2137 $this->localtax2_assuj = $obj->localtax2_assuj;
2138
2139 $this->localtax1_value = $obj->localtax1_value;
2140 $this->localtax2_value = $obj->localtax2_value;
2141
2142 $this->typent_id = $obj->typent_id;
2143 $this->typent_code = $obj->typent_code;
2144
2145 $this->effectif_id = $obj->effectif_id;
2146 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2147
2148 $this->forme_juridique_code = $obj->forme_juridique_code;
2149 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2150 $this->birth = $this->db->jdate($obj->birth);
2151
2152 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2153
2154 $this->prefix_comm = $obj->prefix_comm;
2155
2156 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2157 $this->remise_supplier_percent = $obj->remise_supplier;
2158
2159 $this->mode_reglement_id = $obj->mode_reglement;
2160 $this->cond_reglement_id = $obj->cond_reglement;
2161 $this->deposit_percent = $obj->deposit_percent;
2162 $this->transport_mode_id = $obj->transport_mode;
2163 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2164 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2165 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2166 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2167 $this->fk_account = $obj->fk_account;
2168
2169 $this->client = $obj->client;
2170 $this->fournisseur = $obj->fournisseur;
2171
2172 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2173 $this->note_private = $obj->note_private;
2174 $this->note_public = $obj->note_public;
2175 $this->model_pdf = $obj->model_pdf;
2176 $this->default_lang = $obj->default_lang;
2177 $this->logo = $obj->logo;
2178 $this->logo_squarred = $obj->logo_squarred;
2179
2180 $this->webservices_url = $obj->webservices_url;
2181 $this->webservices_key = $obj->webservices_key;
2182
2183 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2184 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2185
2186 $this->outstanding_limit = $obj->outstanding_limit;
2187 $this->order_min_amount = $obj->order_min_amount;
2188 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2189
2190 // multi price
2191 $this->price_level = $obj->price_level;
2192
2193 // warehouse
2194 $this->fk_warehouse = $obj->fk_warehouse;
2195
2196 $this->import_key = $obj->import_key;
2197
2198 //Incoterms
2199 $this->fk_incoterms = $obj->fk_incoterms;
2200 $this->location_incoterms = $obj->location_incoterms;
2201 $this->label_incoterms = $obj->label_incoterms;
2202
2203 // multicurrency
2204 $this->fk_multicurrency = $obj->fk_multicurrency;
2205 $this->multicurrency_code = $obj->multicurrency_code;
2206
2207 // pdf
2208 $this->model_pdf = $obj->model_pdf;
2209 $this->last_main_doc = $obj->last_main_doc;
2210
2211 $result = $this->id;
2212
2213 // fetch optionals attributes and labels
2214 $this->fetch_optionals();
2215 } else {
2216 $result = 0;
2217 }
2218
2219 $this->db->free($resql);
2220 } else {
2221 $this->error = $this->db->lasterror();
2222 $this->errors[] = $this->db->lasterror();
2223 $result = -3;
2224 }
2225
2226 // Use first price level if level not defined for third party
2227 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2228 $this->price_level = 1;
2229 }
2230
2231 return $result;
2232 }
2233
2254 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2255 {
2256 // A rowid is known, it is a unique key so we found it
2257 if ($rowid) {
2258 return $rowid;
2259 }
2260
2261 dol_syslog(get_class($this)."::findNearest", LOG_DEBUG);
2262 $tmpthirdparty = new Societe($this->db);
2263
2264 // We try to find the thirdparty with exact matching on all fields
2265 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2266 if ($result != 0) {
2267 return $result;
2268 }
2269
2270 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2271 dol_syslog("Thirdparty not found with exact match so we try barcode search", LOG_DEBUG);
2272 if ($barcode) {
2273 $result = $tmpthirdparty->fetch(0, '', '', $barcode, '', '', '', '', '', '', '', '', $is_client, $is_supplier);
2274 if ($result != 0) {
2275 return $result;
2276 }
2277 }
2278
2279 $sqlstart = "SELECT s.rowid as id FROM ".MAIN_DB_PREFIX."societe as s";
2280 $sqlstart .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2281 if ($is_client) {
2282 $sqlstart .= ' AND s.client > 0';
2283 }
2284 if ($is_supplier) {
2285 $sqlstart .= ' AND s.fournisseur > 0';
2286 } // if both false, no test (the thirdparty can be client and/or supplier)
2287
2288 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2289 dol_syslog("Thirdparty not found with barcode search so we try profids search", LOG_DEBUG);
2290 $sqlprof = "";
2291 if ($idprof1) {
2292 $sqlprof .= " s.siren = '".$this->db->escape($idprof1)."'";
2293 }
2294 if ($idprof2) {
2295 if ($sqlprof) {
2296 $sqlprof .= " OR";
2297 }
2298 $sqlprof .= " s.siret = '".$this->db->escape($idprof2)."'";
2299 }
2300 if ($idprof3) {
2301 if ($sqlprof) {
2302 $sqlprof .= " OR";
2303 }
2304 $sqlprof .= " s.ape = '".$this->db->escape($idprof3)."'";
2305 }
2306 if ($idprof4) {
2307 if ($sqlprof) {
2308 $sqlprof .= " OR";
2309 }
2310 $sqlprof .= " s.idprof4 = '".$this->db->escape($idprof4)."'";
2311 }
2312 if ($idprof5) {
2313 if ($sqlprof) {
2314 $sqlprof .= " OR";
2315 }
2316 $sqlprof .= " s.idprof5 = '".$this->db->escape($idprof5)."'";
2317 }
2318 if ($idprof6) {
2319 if ($sqlprof) {
2320 $sqlprof .= " OR";
2321 }
2322 $sqlprof .= " s.idprof6 = '".$this->db->escape($idprof6)."'";
2323 }
2324
2325 if ($sqlprof) {
2326 $sqlprofquery = $sqlstart . " AND (".$sqlprof." )";
2327 $resql = $this->db->query($sqlprofquery);
2328 if ($resql) {
2329 $num = $this->db->num_rows($resql);
2330 if ($num > 1) {
2331 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2332 dol_syslog($this->error, LOG_WARNING);
2333 $result = -2;
2334 } elseif ($num) {
2335 $obj = $this->db->fetch_object($resql);
2336 $result = $obj->id;
2337 } else {
2338 $result = 0;
2339 }
2340 } else {
2341 $this->error = $this->db->lasterror();
2342 $this->errors[] = $this->db->lasterror();
2343 $result = -3;
2344 }
2345 if ($result != 0) {
2346 return $result;
2347 }
2348 }
2349
2350 // Then search on email (+ restriction on is_client and is_supplier)
2351 dol_syslog("Thirdparty not found with profids search so we try email search", LOG_DEBUG);
2352 if ($email) {
2353 $result = $tmpthirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email, '', $is_client, $is_supplier);
2354 if ($result != 0) {
2355 return $result;
2356 }
2357 }
2358
2359 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2360 dol_syslog("Thirdparty not found with email search so we try ref, ref_ext or ref_alias search", LOG_DEBUG);
2361 $sqlref = "";
2362 if ($ref) {
2363 $sqlref .= " s.nom = '".$this->db->escape($ref)."'";
2364 }
2365 if ($ref_alias) {
2366 if ($sqlref) {
2367 $sqlref .= " OR";
2368 }
2369 $sqlref .= " s.name_alias = '".$this->db->escape($ref_alias)."'";
2370 }
2371 if ($ref_ext) {
2372 if ($sqlref) {
2373 $sqlref .= " OR";
2374 }
2375 $sqlref .= " s.ref_ext = '".$this->db->escape($ref_ext)."'";
2376 }
2377
2378 if ($sqlref) {
2379 $sqlrefquery = $sqlstart . " AND (".$sqlref." )";
2380 $resql = $this->db->query($sqlrefquery);
2381 if ($resql) {
2382 $num = $this->db->num_rows($resql);
2383 if ($num > 1) {
2384 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2385 dol_syslog($this->error, LOG_WARNING);
2386 $result = -2;
2387 } elseif ($num) {
2388 $obj = $this->db->fetch_object($resql);
2389 $result = $obj->id;
2390 } else {
2391 $result = 0;
2392 }
2393 } else {
2394 $this->error = $this->db->lasterror();
2395 $this->errors[] = $this->db->lasterror();
2396 $result = -3;
2397 }
2398 }
2399 return $result;
2400 }
2401
2410 public function delete($id, $fuser = null, $call_trigger = 1)
2411 {
2412 global $conf, $user;
2413
2414 if (empty($fuser)) {
2415 $fuser = $user;
2416 }
2417
2418 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2419
2420 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2421
2422 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2423 $error = 0;
2424
2425 // Test if child exists
2426 $objectisused = $this->isObjectUsed($id);
2427 if (empty($objectisused)) {
2428 $this->db->begin();
2429
2430 // User is mandatory for trigger call
2431 if ($call_trigger) {
2432 // Call trigger
2433 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2434 if ($result < 0) {
2435 $error++;
2436 }
2437 // End call triggers
2438 }
2439
2440 if (!$error) {
2441 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2442 $static_cat = new Categorie($this->db);
2443 $toute_categs = array();
2444
2445 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2446 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2447 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2448
2449 // Remove each "Categorie"
2450 foreach ($toute_categs as $type => $categs_type) {
2451 foreach ($categs_type as $cat) {
2452 $cat->del_type($this, $type);
2453 }
2454 }
2455 }
2456
2457 if (!$error) {
2458 foreach ($this->childtablesoncascade as $tabletodelete) {
2459 $deleteFromObject = explode(':', $tabletodelete, 4);
2460 if (count($deleteFromObject) >= 2) {
2461 $className = str_replace('@', '', $deleteFromObject[0]);
2462 $filepath = $deleteFromObject[1];
2463 $columnName = $deleteFromObject[2];
2464 if (dol_include_once($filepath)) {
2465 $child_object = new $className($this->db);
2466 '@phan-var-force CommonObject $child_object';
2467 $result = $child_object->deleteByParentField($id, $columnName);
2468 if ($result < 0) {
2469 $error++;
2470 $this->errors[] = $child_object->error;
2471 break;
2472 }
2473 } else {
2474 $error++;
2475 $this->errors[] = 'Cannot include child class file '.$filepath;
2476 break;
2477 }
2478 } else {
2479 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2480 $sql .= " WHERE fk_soc = ".((int) $id);
2481 if (!$this->db->query($sql)) {
2482 $error++;
2483 $this->errors[] = $this->db->lasterror();
2484 break;
2485 }
2486 }
2487 }
2488 }
2489
2490 // Removed extrafields
2491 if (!$error) {
2492 $result = $this->deleteExtraFields();
2493 if ($result < 0) {
2494 $error++;
2495 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2496 }
2497 }
2498
2499 // Remove links to subsidiaries companies
2500 if (!$error) {
2501 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2502 $sql .= " SET parent = NULL";
2503 $sql .= " WHERE parent = ".((int) $id);
2504 if (!$this->db->query($sql)) {
2505 $error++;
2506 $this->errors[] = $this->db->lasterror();
2507 }
2508 }
2509
2510 // Remove third party
2511 if (!$error) {
2512 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2513 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2514 $sql .= " WHERE fk_soc = ".((int) $id);
2515 if (!$this->db->query($sql)) {
2516 $error++;
2517 $this->errors[] = $this->db->lasterror();
2518 }
2519 }
2520
2521 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2522 $sql .= " WHERE rowid = ".((int) $id);
2523 if (!$this->db->query($sql)) {
2524 $error++;
2525 $this->errors[] = $this->db->lasterror();
2526 }
2527 }
2528
2529 if (!$error) {
2530 $this->db->commit();
2531
2532 // Delete directory
2533 if (!empty($conf->societe->multidir_output[$entity])) {
2534 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2535 if (dol_is_dir($docdir)) {
2536 dol_delete_dir_recursive($docdir);
2537 }
2538 }
2539
2540 return 1;
2541 } else {
2542 dol_syslog($this->error, LOG_ERR);
2543 $this->db->rollback();
2544 return -1;
2545 }
2546 } else {
2547 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2548 }
2549 return 0;
2550 }
2551
2552 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2560 public function set_as_client()
2561 {
2562 // phpcs:enable
2563 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2564 return $this->setAsCustomer();
2565 }
2566
2573 public function setAsCustomer()
2574 {
2575 if ($this->id) {
2576 $newclient = 1;
2577 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2578 $newclient = 3; // If prospected, we keep prospect tag
2579 }
2580 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2581 $sql .= " SET client = ".((int) $newclient);
2582 $sql .= " WHERE rowid = ".((int) $this->id);
2583
2584 $resql = $this->db->query($sql);
2585 if ($resql) {
2586 $this->client = $newclient;
2587 return 1;
2588 } else {
2589 return -1;
2590 }
2591 }
2592 return 0;
2593 }
2594
2595 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2604 public function set_remise_client($remise, $note, User $user)
2605 {
2606 // phpcs:enable
2607 global $conf, $langs;
2608
2609 // Parameter cleaning
2610 $note = trim($note);
2611 if (!$note) {
2612 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2613 return -2;
2614 }
2615
2616 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2617
2618 if ($this->id) {
2619 $this->db->begin();
2620
2621 $now = dol_now();
2622
2623 // Position current discount
2624 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2625 $sql .= " SET remise_client = '".$this->db->escape((string) $remise)."'";
2626 $sql .= " WHERE rowid = ".((int) $this->id);
2627 $resql = $this->db->query($sql);
2628 if (!$resql) {
2629 $this->db->rollback();
2630 $this->error = $this->db->error();
2631 return -1;
2632 }
2633
2634 // Writes trace in discount history
2635 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2636 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2637 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape((string) $remise)."',";
2638 $sql .= " '".$this->db->escape($note)."',";
2639 $sql .= " ".((int) $user->id);
2640 $sql .= ")";
2641
2642 $resql = $this->db->query($sql);
2643 if (!$resql) {
2644 $this->db->rollback();
2645 $this->error = $this->db->lasterror();
2646 return -1;
2647 }
2648
2649 $this->db->commit();
2650
2651 return 1;
2652 }
2653 return -1;
2654 }
2655
2656 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2665 public function set_remise_supplier($remise, $note, User $user)
2666 {
2667 // phpcs:enable
2668 global $conf, $langs;
2669
2670 // Parameter cleaning
2671 $note = trim($note);
2672 if (!$note) {
2673 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2674 return -2;
2675 }
2676
2677 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2678
2679 if ($this->id) {
2680 $this->db->begin();
2681
2682 $now = dol_now();
2683
2684 // Position current discount
2685 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2686 $sql .= " SET remise_supplier = ".((float) $remise);
2687 $sql .= " WHERE rowid = ".((int) $this->id);
2688 $resql = $this->db->query($sql);
2689 if (!$resql) {
2690 $this->db->rollback();
2691 $this->error = $this->db->error();
2692 return -1;
2693 }
2694
2695 // Writes trace in discount history
2696 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2697 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2698 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((float) $remise).",";
2699 $sql .= " '".$this->db->escape($note)."',";
2700 $sql .= " ".((int) $user->id);
2701 $sql .= ")";
2702
2703 $resql = $this->db->query($sql);
2704 if (!$resql) {
2705 $this->db->rollback();
2706 $this->error = $this->db->lasterror();
2707 return -1;
2708 }
2709
2710 $this->db->commit();
2711 return 1;
2712 }
2713
2714 return -1;
2715 }
2716
2717 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2729 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2730 {
2731 // phpcs:enable
2732 global $langs, $mysoc;
2733
2734 // Clean parameters
2735 $remise = (float) price2num($remise);
2736 $desc = trim($desc);
2737
2738 // Check parameters
2739 if (!($remise > 0)) {
2740 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2741 return -1;
2742 }
2743 if (!$desc) {
2744 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2745 return -2;
2746 }
2747
2748 if ($this->id > 0) {
2749 // Separate VAT code from VAT rate string
2750 // Discount type determines who is buyer and seller
2751 $taxes = getTaxesFromId($vatrate, ($discount_type == 0 ? $this : $mysoc), ($discount_type == 0 ? $mysoc : $this), 0);
2752 $reg = array();
2753 $vat_src_code = '';
2754 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2755 $vat_src_code = $reg[1];
2756 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2757 }
2758
2759 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2760
2761 $discount = new DiscountAbsolute($this->db);
2762 $discount->fk_soc = $this->id;
2763 $discount->socid = $this->id;
2764
2765 $discount->discount_type = $discount_type;
2766 $discount->multicurrency_code = $this->multicurrency_code;
2767 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2768 $discount->multicurrency_tx = $this->multicurrency_tx;
2769
2770 $vat_tx = (float) price2num($vatrate);
2771
2772 $discount->generateFromAmount($remise, ($price_base_type == 'TTC' ? 1 : 0), $vat_tx, $taxes['localtax1'], $taxes['localtax2'], (int) $taxes['localtax1_type'], (int) $taxes['localtax2_type']);
2773
2774 $discount->vat_src_code = $vat_src_code;
2775
2776 $discount->description = $desc;
2777
2778 $result = $discount->create($user);
2779 if ($result > 0) {
2780 return $result;
2781 } else {
2782 $this->error = $discount->error;
2783 return -3;
2784 }
2785 } else {
2786 return 0;
2787 }
2788 }
2789
2799 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2800 {
2801 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2802
2803 $discountstatic = new DiscountAbsolute($this->db);
2804 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2805 if ($result >= 0) {
2806 return $result;
2807 } else {
2808 $this->error = $discountstatic->error;
2809 return -1;
2810 }
2811 }
2812
2813
2820 public function getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type = 0)
2821 {
2822 global $conf;
2823
2824 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ttc) as amount, SUM(f.multicurrency_total_ttc) as multicurrency_amount";
2825 if (!empty($discount_type)) {
2826 $sql .= " FROM ".$this->db->prefix()."facture_fourn as f";
2827 } else {
2828 $sql .= " FROM ".$this->db->prefix()."facture as f";
2829 }
2830 $sql .= " WHERE f.entity = ".$conf->entity;
2831 $sql .= " AND paye = 0 AND fk_statut = 1";
2832 $sql .= " AND f.type = ".CommonInvoice::TYPE_CREDIT_NOTE;
2833 $sql .= " AND NOT EXISTS (SELECT rowid FROM ".$this->db->prefix()."societe_remise_except as rc";
2834 $sql .= " WHERE rc.discount_type = ".((int) $discount_type);
2835 if (!empty($discount_type)) {
2836 $sql .= " AND rc.fk_invoice_supplier = f.rowid";
2837 } else {
2838 $sql .= " AND rc.fk_facture = f.rowid";
2839 }
2840 $sql .= " AND rc.fk_soc = ".((int) $this->id);
2841 $sql .= ")";
2842 $sql .= " AND f.fk_soc = ".((int) $this->id);
2843
2844 $resql = $this->db->query($sql);
2845 if ($resql) {
2846 $obj = $this->db->fetch_object($resql);
2847
2848 return $obj->nb;
2849 }
2850
2851 return -1;
2852 }
2853
2854
2864 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2865 {
2866 global $conf;
2867
2868 $reparray = array();
2869
2870 $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";
2871 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2872 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2873 // Condition here should be the same than into select_dolusers()
2874 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2875 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2876 } else {
2877 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
2878 }
2879
2880 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2881 if (empty($sortfield)) {
2882 $sortfield = 'u.lastname,u.firstname';
2883 }
2884 if (empty($sortorder)) {
2885 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
2886 }
2887 $sql .= $this->db->order($sortfield, $sortorder);
2888
2889 $resql = $this->db->query($sql);
2890 if ($resql) {
2891 $num = $this->db->num_rows($resql);
2892 $i = 0;
2893 while ($i < $num) {
2894 $obj = $this->db->fetch_object($resql);
2895
2896 if (empty($mode)) {
2897 $reparray[$i]['id'] = (int) $obj->rowid;
2898 $reparray[$i]['lastname'] = $obj->lastname;
2899 $reparray[$i]['firstname'] = $obj->firstname;
2900 $reparray[$i]['email'] = $obj->email;
2901 $reparray[$i]['phone'] = $obj->office_phone;
2902 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2903 $reparray[$i]['office_fax'] = $obj->office_fax;
2904 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2905 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2906 $reparray[$i]['job'] = $obj->job;
2907 $reparray[$i]['statut'] = $obj->status; // deprecated
2908 $reparray[$i]['status'] = $obj->status;
2909 $reparray[$i]['entity'] = $obj->entity;
2910 $reparray[$i]['login'] = $obj->login;
2911 $reparray[$i]['photo'] = $obj->photo;
2912 $reparray[$i]['gender'] = $obj->gender;
2913 } else {
2914 $reparray[] = (int) $obj->rowid;
2915 }
2916 $i++;
2917 }
2918 return $reparray;
2919 } else {
2920 dol_print_error($this->db);
2921 return -1;
2922 }
2923 }
2924
2932 public function setPriceLevel($price_level, User $user)
2933 {
2934 if ($this->id) {
2935 $now = dol_now();
2936
2937 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2938 $sql .= " SET price_level = ".((int) $price_level);
2939 $sql .= " WHERE rowid = ".((int) $this->id);
2940
2941 if (!$this->db->query($sql)) {
2942 dol_print_error($this->db);
2943 return -1;
2944 }
2945
2946 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2947 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2948 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2949
2950 if (!$this->db->query($sql)) {
2951 dol_print_error($this->db);
2952 return -1;
2953 }
2954 return 1;
2955 }
2956 return -1;
2957 }
2958
2959 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2967 public function add_commercial(User $user, $commid)
2968 {
2969 // phpcs:enable
2970 $error = 0;
2971
2972 if ($this->id > 0 && $commid > 0) {
2973 $this->db->begin();
2974
2975 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2976 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2977
2978 $resql = $this->db->query($sql);
2979 if (!$resql) {
2980 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2981 $error++;
2982 }
2983
2984 if (!$error) {
2985 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2986 $sql .= " (fk_soc, fk_user)";
2987 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2988
2989 $resql = $this->db->query($sql);
2990 if (!$resql) {
2991 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2992 $error++;
2993 }
2994 }
2995
2996 if (!$error) {
2997 $this->context = array('commercial_modified' => $commid);
2998
2999 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3000 if ($result < 0) {
3001 $error++;
3002 }
3003 }
3004
3005 if (!$error) {
3006 $this->db->commit();
3007 return 1;
3008 } else {
3009 $this->db->rollback();
3010 return -1;
3011 }
3012 }
3013
3014 return 0;
3015 }
3016
3017 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3025 public function del_commercial(User $user, $commid)
3026 {
3027 // phpcs:enable
3028 $error = 0;
3029 $this->context = array('commercial_modified' => $commid);
3030
3031 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3032 if ($result < 0) {
3033 $error++;
3034 }
3035
3036 if ($this->id > 0 && $commid > 0) {
3037 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3038 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3039
3040 if (!$this->db->query($sql)) {
3041 $error++;
3042 dol_syslog(get_class($this)."::del_commercial Erreur");
3043 }
3044 }
3045
3046 if ($error) {
3047 return -1;
3048 } else {
3049 return 1;
3050 }
3051 }
3052
3060 public function getTooltipContentArray($params)
3061 {
3062 global $conf, $langs, $user;
3063
3064 $langs->loadLangs(['companies', 'commercial']);
3065
3066 $datas = array();
3067
3068 $option = $params['option'] ?? '';
3069 $nofetch = !empty($params['nofetch']);
3070
3071 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3072
3073 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3074 return ['optimize' => $langs->trans("ShowCompany")];
3075 }
3076
3077 if (!empty($this->logo) && class_exists('Form')) {
3078 $photo = '<div class="photointooltip floatright">';
3079 $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.
3080 $photo .= '</div>';
3081 $datas['photo'] = $photo;
3082 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3083 /*$label.= '<div class="photointooltip">';
3084 $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.
3085 $label.= '</div><div style="clear: both;"></div>';*/
3086 // }
3087
3088 $datas['divopen'] = '<div class="centpercent">';
3089
3090 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3091 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3092 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3093 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3094 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3095 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3096 } elseif ($option == 'agenda') {
3097 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3098 } elseif ($option == 'project') {
3099 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3100 } elseif ($option == 'margin') {
3101 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3102 } elseif ($option == 'contact') {
3103 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3104 } elseif ($option == 'ban') {
3105 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3106 }
3107
3108 // By default
3109 if (empty($datas['picto'])) {
3110 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3111 }
3112 if (isset($this->status)) {
3113 $datas['status'] = ' '.$this->getLibStatut(5);
3114 }
3115 if (isset($this->client) && isset($this->fournisseur)) {
3116 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3117 }
3118 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3119 if (!empty($this->name_alias) && empty($noaliasinname)) {
3120 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3121 }
3122 if (!empty($this->email)) {
3123 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3124 }
3125 if (!empty($this->url)) {
3126 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3127 }
3128 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3129 $phonelist = array();
3130 if ($this->phone) {
3131 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3132 }
3133 // deliberately not making new list because fax uses same list as phone
3134 if ($this->phone_mobile) {
3135 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3136 }
3137 if ($this->fax) {
3138 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3139 }
3140 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3141 }
3142
3143 if (!empty($this->address)) {
3144 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3145 } elseif (!empty($this->country_code)) {
3146 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3147 }
3148 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3149 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3150 }
3151
3152 if (!empty($this->euid) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'euid') !== false)) {
3153 $datas['euid'] = '<br><b>'.$langs->trans('EUIDShort').':</b> '.dol_escape_htmltag($this->euid);
3154 }
3155
3156 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3157 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3158 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3159 }
3160 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3161 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3162 }
3163 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3164 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3165 }
3166 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3167 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3168 }
3169 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3170 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3171 }
3172 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3173 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3174 }
3175 }
3176
3177 $datas['separator'] = '<br>';
3178
3179 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3180 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3181 }
3182 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3183 $langs->load('compta');
3184 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3185 }
3186 // show categories for this record only in ajax to not overload lists
3187 if (!$nofetch && isModEnabled('category') && $this->client) {
3188 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3189 $form = new Form($this->db);
3190 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3191 }
3192 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3193 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3194 }
3195 if (isModEnabled('accounting') && $this->fournisseur) {
3196 $langs->load('compta');
3197 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3198 }
3199 // show categories for this record only in ajax to not overload lists
3200 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3201 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3202 $form = new Form($this->db);
3203 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3204 }
3205
3206 $datas['divclose'] = '</div>';
3207
3208 return $datas;
3209 }
3210
3224 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3225 {
3226 global $conf, $langs, $hookmanager, $user;
3227
3228 if (!empty($conf->dol_no_mouse_hover)) {
3229 $notooltip = 1; // Force disable tooltips
3230 }
3231
3232 $name = $this->name ? $this->name : $this->nom;
3233
3234 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3235 if (empty($option) && $this->client > 0) {
3236 $option = 'customer';
3237 }
3238 if (empty($option) && $this->fournisseur > 0) {
3239 $option = 'supplier';
3240 }
3241 }
3242
3243 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3244 $code = '';
3245 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3246 $code = $this->code_client.' - ';
3247 }
3248
3249 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3250 $code .= $this->code_fournisseur.' - ';
3251 }
3252
3253 if ($code) {
3254 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3255 $name = $code.' '.$name;
3256 } else {
3257 $name = $code;
3258 }
3259 }
3260 }
3261
3262 if (!empty($this->name_alias) && empty($noaliasinname)) {
3263 $name .= ' ('.$this->name_alias.')';
3264 }
3265
3266 $result = '';
3267 $params = [
3268 'id' => $this->id,
3269 'objecttype' => $this->element,
3270 'option' => $option,
3271 'nofetch' => 1,
3272 ];
3273 $classfortooltip = 'classfortooltip';
3274 $dataparams = '';
3275 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3276 $classfortooltip = 'classforajaxtooltip';
3277 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3278 $label = '';
3279 } else {
3280 $label = implode($this->getTooltipContentArray($params));
3281 }
3282
3283 $linkstart = '';
3284 $linkend = '';
3285
3286 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3287 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3288 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3289 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3290 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3291 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3292 } elseif ($option == 'agenda') {
3293 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3294 } elseif ($option == 'project') {
3295 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3296 } elseif ($option == 'margin') {
3297 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3298 } elseif ($option == 'contact') {
3299 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3300 } elseif ($option == 'ban') {
3301 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3302 }
3303
3304 // By default
3305 if (empty($linkstart)) {
3306 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3307 }
3308
3309 // Add type of canvas
3310 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3311 // Add param to save lastsearch_values or not
3312 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3313 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3314 $add_save_lastsearch_values = 1;
3315 }
3316 if ($add_save_lastsearch_values) {
3317 $linkstart .= '&save_lastsearch_values=1';
3318 }
3319 $linkstart .= '"';
3320
3321 $linkclose = '';
3322 if (empty($notooltip)) {
3323 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3324 $label = $langs->trans("ShowCompany");
3325 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3326 }
3327 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3328 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl'.($withpicto ? ' valignmiddle' : '').'"';
3329 $target_value = array('_self', '_blank', '_parent', '_top');
3330 if (in_array($target, $target_value)) {
3331 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3332 }
3333 } else {
3334 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3335 }
3336 $linkstart .= $linkclose.'>';
3337 $linkend = '</a>';
3338
3339 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3340 $linkstart = '';
3341 $linkend = '';
3342 }
3343
3344 $result .= $linkstart;
3345 if ($withpicto) {
3346 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3347 }
3348 if ($withpicto != 2) {
3349 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3350 }
3351 $result .= $linkend;
3352
3353 global $action;
3354 $hookmanager->initHooks(array('thirdpartydao'));
3355 $parameters = array(
3356 'id' => $this->id,
3357 'getnomurl' => &$result,
3358 'withpicto ' => $withpicto,
3359 'option' => $option,
3360 'maxlen' => $maxlen,
3361 'notooltip' => $notooltip,
3362 'save_lastsearch_value' => $save_lastsearch_value
3363 );
3364 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3365 if ($reshook > 0) {
3366 $result = $hookmanager->resPrint;
3367 } else {
3368 $result .= $hookmanager->resPrint;
3369 }
3370
3371 return $result;
3372 }
3373
3383 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3384 {
3385 global $langs;
3386
3387 $s = '';
3388 if (empty($option) || preg_match('/prospect/', $option)) {
3389 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3390 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3391 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3392 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3393 }
3394 }
3395 if (empty($option) || preg_match('/customer/', $option)) {
3396 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3397 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3398 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3399 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3400 }
3401 }
3402 if (empty($option) || preg_match('/supplier/', $option)) {
3403 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3404 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3405 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3406 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3407 }
3408 }
3409
3410 return $s;
3411 }
3412
3413
3420 public function getLibStatut($mode = 0)
3421 {
3422 return $this->LibStatut($this->status, $mode);
3423 }
3424
3425 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3433 public function LibStatut($status, $mode = 0)
3434 {
3435 // phpcs:enable
3436 global $langs;
3437 $langs->load('companies');
3438
3439 $statusType = 'status4';
3440 if ($status == 0) {
3441 $statusType = 'status6';
3442 }
3443
3444 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3445 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3446 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3447 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3448 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3449 }
3450
3451 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3452 }
3453
3454 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3461 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3462 {
3463 // phpcs:enable
3464 global $langs;
3465
3466 $contact_emails = $this->contact_property_array('email', 1);
3467
3468 if ($this->email && $addthirdparty) {
3469 if (empty($this->name)) {
3470 $this->name = $this->nom;
3471 }
3472 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3473 }
3474
3475 //var_dump($contact_emails)
3476 return $contact_emails;
3477 }
3478
3479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3486 {
3487 // phpcs:enable
3488 global $langs;
3489
3490 $contact_phone = $this->contact_property_array('mobile');
3491
3492 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3493 if (empty($this->name)) {
3494 $this->name = $this->nom;
3495 }
3496 // TODO: Tester si tel non deja present dans tableau contact
3497 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3498 }
3499 return $contact_phone;
3500 }
3501
3502 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3510 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3511 {
3512 // phpcs:enable
3513 global $langs;
3514
3515 $contact_property = array();
3516
3517
3518 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3519 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3520 $sql .= " WHERE fk_soc = ".((int) $this->id);
3521 $sql .= " AND entity IN (".getEntity($this->element).")";
3522 $sql .= " ORDER BY lastname, firstname";
3523
3524 $resql = $this->db->query($sql);
3525 if ($resql) {
3526 $nump = $this->db->num_rows($resql);
3527 if ($nump) {
3528 $sepa = "(";
3529 $sepb = ")";
3530 if ($mode == 'email') {
3531 //$sepa="&lt;"; $sepb="&gt;";
3532 $sepa = "<";
3533 $sepb = ">";
3534 }
3535 $i = 0;
3536 while ($i < $nump) {
3537 $obj = $this->db->fetch_object($resql);
3538 if ($mode == 'email') {
3539 $property = $obj->email;
3540 } elseif ($mode == 'mobile') {
3541 $property = $obj->phone_mobile;
3542 } else {
3543 $property = $obj->$mode;
3544 }
3545
3546 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3547 if ($obj->status == 1 || empty($hidedisabled)) {
3548 if (empty($property)) {
3549 if ($mode == 'email') {
3550 $property = $langs->transnoentitiesnoconv("NoEMail");
3551 } elseif ($mode == 'mobile') {
3552 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3553 }
3554 }
3555
3556 if (!empty($obj->poste)) {
3557 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3558 } else {
3559 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3560 }
3561 }
3562 $i++;
3563 }
3564 }
3565 } else {
3566 dol_print_error($this->db);
3567 }
3568 return $contact_property;
3569 }
3570
3571
3572 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3578 public function contact_array()
3579 {
3580 // phpcs:enable
3581 $contacts = array();
3582
3583 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3584 $resql = $this->db->query($sql);
3585 if ($resql) {
3586 $nump = $this->db->num_rows($resql);
3587 if ($nump) {
3588 $i = 0;
3589 while ($i < $nump) {
3590 $obj = $this->db->fetch_object($resql);
3591 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3592 $i++;
3593 }
3594 }
3595 } else {
3596 dol_print_error($this->db);
3597 }
3598 return $contacts;
3599 }
3600
3601 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3607 public function contact_array_objects()
3608 {
3609 // phpcs:enable
3610 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3611 $contacts = array();
3612
3613 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3614 $resql = $this->db->query($sql);
3615 if ($resql) {
3616 $nump = $this->db->num_rows($resql);
3617 if ($nump) {
3618 $i = 0;
3619 while ($i < $nump) {
3620 $obj = $this->db->fetch_object($resql);
3621 $contact = new Contact($this->db);
3622 $contact->fetch($obj->rowid);
3623 $contacts[] = $contact;
3624 $i++;
3625 }
3626 }
3627 } else {
3628 dol_print_error($this->db);
3629 }
3630 return $contacts;
3631 }
3632
3633 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3641 public function contact_get_property($rowid, $mode)
3642 {
3643 // phpcs:enable
3644 $contact_property = '';
3645
3646 if (empty($rowid)) {
3647 return '';
3648 }
3649
3650 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3651 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3652 $sql .= " WHERE rowid = ".((int) $rowid);
3653
3654 $resql = $this->db->query($sql);
3655 if ($resql) {
3656 $nump = $this->db->num_rows($resql);
3657
3658 if ($nump) {
3659 $obj = $this->db->fetch_object($resql);
3660
3661 if ($mode == 'email') {
3662 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3663 } elseif ($mode == 'mobile') {
3664 $contact_property = $obj->phone_mobile;
3665 }
3666 }
3667 return $contact_property;
3668 } else {
3669 dol_print_error($this->db);
3670 }
3671
3672 return '';
3673 }
3674
3675
3676 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3683 public function display_rib($mode = 'label')
3684 {
3685 // phpcs:enable
3686 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3687
3688 $bac = new CompanyBankAccount($this->db);
3689 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3690 $bac->fetch(0, '', $this->id);
3691
3692 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3693 if ($mode == 'label') {
3694 return $bac->getRibLabel(true);
3695 } elseif ($mode == 'rum') {
3696 if (empty($bac->rum)) {
3697 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3698 $prelevement = new BonPrelevement($this->db);
3699 $bac->fetch_thirdparty();
3700 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3701 }
3702 return $bac->rum;
3703 } elseif ($mode == 'format') {
3704 return $bac->frstrecur;
3705 } else {
3706 return 'BadParameterToFunctionDisplayRib';
3707 }
3708 } else {
3709 return '';
3710 }
3711 }
3712
3713 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3719 public function get_all_rib()
3720 {
3721 // phpcs:enable
3722 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3723 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3724 $result = $this->db->query($sql);
3725 if (!$result) {
3726 $this->error = $this->db->lasterror();
3727 $this->errors[] = $this->db->lasterror();
3728 return 0;
3729 } else {
3730 $num_rows = $this->db->num_rows($result);
3731 $rib_array = array();
3732 if ($num_rows) {
3733 while ($obj = $this->db->fetch_object($result)) {
3734 $rib = new CompanyBankAccount($this->db);
3735 $rib->fetch($obj->rowid);
3736 $rib_array[] = $rib;
3737 }
3738 }
3739 return $rib_array;
3740 }
3741 }
3742
3746 public function getDefaultRib()
3747 {
3748 // phpcs:enable
3749 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3750 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3751 $resql = $this->db->query($sql);
3752 if (!$resql) {
3753 $this->error = $this->db->lasterror();
3754 $this->errors[] = $this->db->lasterror();
3755 return -1;
3756 } else {
3757 $num_rows = $this->db->num_rows($resql);
3758 $rib_array = array();
3759 if ($num_rows) {
3760 while ($obj = $this->db->fetch_object($resql)) {
3761 return $obj->rowid;
3762 }
3763 }
3764 return 0;
3765 }
3766 }
3767
3768
3769 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3778 public function get_codeclient($objsoc = null, $type = 0)
3779 {
3780 // phpcs:enable
3781 global $conf;
3782 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3783 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3784
3785 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3786 foreach ($dirsociete as $dirroot) {
3787 $res = dol_include_once($dirroot.$module.'.php');
3788 if ($res) {
3789 break;
3790 }
3791 }
3793 $mod = new $module($this->db);
3794 '@phan-var-force ModeleThirdPartyCode $mod';
3795
3796 $this->code_client = $mod->getNextValue($objsoc, $type);
3797 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3798
3799 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3800 }
3801 }
3802
3803 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3812 public function get_codefournisseur($objsoc = null, $type = 1)
3813 {
3814 // phpcs:enable
3815 global $conf;
3816 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3817 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3818
3819 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3820 foreach ($dirsociete as $dirroot) {
3821 $res = dol_include_once($dirroot.$module.'.php');
3822 if ($res) {
3823 break;
3824 }
3825 }
3827 $mod = new $module($this->db);
3828 '@phan-var-force ModeleThirdPartyCode $mod';
3829
3830 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3831
3832 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3833 }
3834 }
3835
3836 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3843 public function codeclient_modifiable()
3844 {
3845 // phpcs:enable
3846 global $conf;
3847 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3848 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3849
3850 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3851 foreach ($dirsociete as $dirroot) {
3852 $res = dol_include_once($dirroot.$module.'.php');
3853 if ($res) {
3854 break;
3855 }
3856 }
3857
3858 $mod = new $module($this->db);
3859 '@phan-var-force ModeleThirdPartyCode $mod';
3860
3861 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3862 if ($mod->code_modifiable_null && !$this->code_client) {
3863 return 1;
3864 }
3865 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3866 return 1;
3867 }
3868 if ($mod->code_modifiable) {
3869 return 1; // To be put last
3870 }
3871 return 0;
3872 } else {
3873 return 0;
3874 }
3875 }
3876
3877
3878 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3885 {
3886 // phpcs:enable
3887 global $conf;
3888 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3889 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3890
3891 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3892 foreach ($dirsociete as $dirroot) {
3893 $res = dol_include_once($dirroot.$module.'.php');
3894 if ($res) {
3895 break;
3896 }
3897 }
3898
3899 $mod = new $module($this->db);
3900 '@phan-var-force ModeleThirdPartyCode $mod';
3901
3902 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3903 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3904 return 1;
3905 }
3906 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3907 return 1;
3908 }
3909 if ($mod->code_modifiable) {
3910 return 1; // To be put last
3911 }
3912 return 0;
3913 } else {
3914 return 0;
3915 }
3916 }
3917
3918
3919 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3931 public function check_codeclient()
3932 {
3933 // phpcs:enable
3934 global $conf;
3935 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3936 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3937
3938 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3939 foreach ($dirsociete as $dirroot) {
3940 $res = dol_include_once($dirroot.$module.'.php');
3941 if ($res) {
3942 break;
3943 }
3944 }
3945
3946 $mod = new $module($this->db);
3947 '@phan-var-force ModeleThirdPartyCode $mod';
3948
3949 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3950 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3951 if ($result) { // If error
3952 $this->error = $mod->error;
3953 $this->errors = $mod->errors;
3954 }
3955 return $result;
3956 } else {
3957 return 0;
3958 }
3959 }
3960
3961 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3973 public function check_codefournisseur()
3974 {
3975 // phpcs:enable
3976 global $conf;
3977 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3978 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3979
3980 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3981 foreach ($dirsociete as $dirroot) {
3982 $res = dol_include_once($dirroot.$module.'.php');
3983 if ($res) {
3984 break;
3985 }
3986 }
3987
3988 $mod = new $module($this->db);
3989 '@phan-var-force ModeleThirdPartyCode $mod';
3990
3991 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3992 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3993 if ($result) { // If error
3994 $this->error = $mod->error;
3995 $this->errors = $mod->errors;
3996 }
3997 return $result;
3998 } else {
3999 return 0;
4000 }
4001 }
4002
4003 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4012 public function get_codecompta($type)
4013 {
4014 // phpcs:enable
4015 global $conf;
4016
4017 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
4018 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
4019 $res = false;
4020 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4021 foreach ($dirsociete as $dirroot) {
4022 $res = dol_include_once($dirroot.$module.'.php');
4023 if ($res) {
4024 break;
4025 }
4026 }
4027
4028 if ($res) {
4029 $mod = new $module();
4030 '@phan-var-force ModeleAccountancyCode $mod';
4031
4032 // Set code count in $mod->code
4033 $result = $mod->get_code($this->db, $this, $type);
4034
4035 if ($type == 'customer') {
4036 $this->code_compta_client = $mod->code;
4037 } elseif ($type == 'supplier') {
4038 $this->code_compta_fournisseur = $mod->code;
4039 }
4040
4041 return $result;
4042 } else {
4043 $this->error = 'ErrorAccountancyCodeNotDefined';
4044 return -1;
4045 }
4046 } else {
4047 if ($type == 'customer') {
4048 $this->code_compta_client = '';
4049 } elseif ($type == 'supplier') {
4050 $this->code_compta_fournisseur = '';
4051 }
4052
4053 return 0;
4054 }
4055 }
4056
4063 public function setParent($id)
4064 {
4065 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4066
4067 if ($this->id) {
4068 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4069 if ($id > 0) {
4070 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4071 if ($sameparent < 0) {
4072 return -1;
4073 }
4074 if ($sameparent == 1) {
4075 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4076 return -1;
4077 }
4078 }
4079
4080 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
4081
4082 $resql = $this->db->query($sql);
4083 if ($resql) {
4084 $this->parent = $id;
4085 return 1;
4086 } else {
4087 return -1;
4088 }
4089 }
4090
4091 return -1;
4092 }
4093
4102 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4103 {
4104 if ($counter > 100) {
4105 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4106 }
4107
4108 $sql = 'SELECT s.parent';
4109 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4110 $sql .= ' WHERE rowid = '.((int) $idparent);
4111 $resql = $this->db->query($sql);
4112 if ($resql) {
4113 $obj = $this->db->fetch_object($resql);
4114
4115 if ($obj->parent == '') {
4116 return 0;
4117 } elseif ($obj->parent == $idchild) {
4118 return 1;
4119 } else {
4120 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4121 }
4122 return $sameparent;
4123 } else {
4124 return -1;
4125 }
4126 }
4127
4135 public function getParentsForCompany($company_id, $parents = array())
4136 {
4137 global $langs;
4138
4139 if ($company_id > 0) {
4140 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4141 $resql = $this->db->query($sql);
4142 if ($resql) {
4143 if ($obj = $this->db->fetch_object($resql)) {
4144 $parent = $obj->parent;
4145 if ($parent > 0 && !in_array($parent, $parents)) {
4146 $parents[] = $parent;
4147 return $this->getParentsForCompany($parent, $parents);
4148 } else {
4149 return $parents;
4150 }
4151 }
4152 $this->db->free($resql);
4153 } else {
4154 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4155 }
4156 }
4157 // Return a default value when $company_id is not greater than 0
4158 return array();
4159 }
4160
4167 public function getChildrenForCompany($company_id)
4168 {
4169 global $langs;
4170
4171 $children = array();
4172 if ($company_id > 0) {
4173 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "societe WHERE parent = ".((int) $company_id);
4174 $resql = $this->db->query($sql);
4175 if ($resql) {
4176 while ($obj = $this->db->fetch_object($resql)) {
4177 $child = $obj->rowid;
4178 if ($child > 0 && !in_array($child, $children)) {
4179 $children[] = $child;
4180 }
4181 }
4182 $this->db->free($resql);
4183 } else {
4184 setEventMessage($this->db->lasterror(), 'errors');
4185 }
4186 }
4187 // Return a default value when $company_id is not greater than 0
4188 return $children;
4189 }
4190
4191 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4198 public function id_prof_verifiable($idprof)
4199 {
4200 // phpcs:enable
4201 global $conf;
4202
4203 switch ($idprof) {
4204 case 1:
4205 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4206 break;
4207 case 2:
4208 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4209 break;
4210 case 3:
4211 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4212 break;
4213 case 4:
4214 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4215 break;
4216 case 5:
4217 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4218 break;
4219 case 6:
4220 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4221 break;
4222 default:
4223 $ret = false;
4224 }
4225
4226 return $ret;
4227 }
4228
4229 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4238 public function id_prof_exists($idprof, $value, $socid = 0)
4239 {
4240 // phpcs:enable
4241 $field = $idprof;
4242
4243 switch ($idprof) { // For backward compatibility
4244 case '1':
4245 case 'idprof1':
4246 $field = "siren";
4247 break;
4248 case '2':
4249 case 'idprof2':
4250 $field = "siret";
4251 break;
4252 case '3':
4253 case 'idprof3':
4254 $field = "ape";
4255 break;
4256 case '4':
4257 case 'idprof4':
4258 $field = "idprof4";
4259 break;
4260 case '5':
4261 $field = "idprof5";
4262 break;
4263 case '6':
4264 $field = "idprof6";
4265 break;
4266 }
4267
4268 //Verify duplicate entries
4269 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4270 if ($socid) {
4271 $sql .= " AND rowid <> ".$socid;
4272 }
4273 $resql = $this->db->query($sql);
4274 if ($resql) {
4275 $obj = $this->db->fetch_object($resql);
4276 $count = $obj->nb;
4277 } else {
4278 $count = 0;
4279 print $this->db->error();
4280 }
4281 $this->db->free($resql);
4282
4283 if ($count > 0) {
4284 return true;
4285 } else {
4286 return false;
4287 }
4288 }
4289
4290 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4297 public function id_prof_check($idprof)
4298 {
4299 // phpcs:enable
4300
4301 // Load the library necessary to check the professional identifiers
4302 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4303
4304 return isValidProfIds($idprof, $this);
4305 }
4306
4307 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4316 public function id_prof_url($idprof, $thirdparty)
4317 {
4318 // phpcs:enable
4319 global $langs, $hookmanager;
4320
4321 $url = '';
4322 $action = '';
4323
4324 $hookmanager->initHooks(array('idprofurl'));
4325 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4326 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4327 if (empty($reshook)) {
4328 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4329 return '';
4330 }
4331
4332 // TODO Move links to validate professional ID into the dictionary table "country" + column "linkidprof1"
4333 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4334 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4335 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.urlencode($strippedIdProf1); // See also http://avis-situation-sirene.insee.fr/
4336 }
4337 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4338 $url = 'https://beta.companieshouse.gov.uk/company/'.urlencode($strippedIdProf1);
4339 }
4340 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4341 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.urlencode($strippedIdProf1);
4342 }
4343 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4344 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.urlencode($strippedIdProf1).';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4345 }
4346 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4347 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.urlencode($strippedIdProf1);
4348 }
4349 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4350 $url = 'http://www.nif.pt/'.urlencode($strippedIdProf1);
4351 }
4352
4353 if ($url) {
4354 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4355 }
4356 } else {
4357 return $hookmanager->resPrint;
4358 }
4359
4360 return '';
4361 }
4362
4363 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4369 public function has_projects()
4370 {
4371 // phpcs:enable
4372 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4373 $resql = $this->db->query($sql);
4374 if ($resql) {
4375 $obj = $this->db->fetch_object($resql);
4376 $count = $obj->numproj;
4377 } else {
4378 $count = 0;
4379 print $this->db->error();
4380 }
4381 $this->db->free($resql);
4382 return ($count > 0);
4383 }
4384
4385
4392 public function info($id)
4393 {
4394 $sql = "SELECT s.rowid, s.nom as name, s.datec, GREATEST(s.tms, sef.tms) as datem,";
4395 $sql .= " fk_user_creat, fk_user_modif";
4396 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4397 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as sef ON sef.fk_object=s.rowid";
4398 $sql .= " WHERE s.rowid = ".((int) $id);
4399
4400 $result = $this->db->query($sql);
4401 if ($result) {
4402 if ($this->db->num_rows($result)) {
4403 $obj = $this->db->fetch_object($result);
4404
4405 $this->id = $obj->rowid;
4406
4407 $this->user_creation_id = $obj->fk_user_creat;
4408 $this->user_modification_id = $obj->fk_user_modif;
4409 $this->date_creation = $this->db->jdate($obj->datec);
4410 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4411
4412 $this->ref = $obj->name;
4413 }
4414
4415 $this->db->free($result);
4416 } else {
4417 dol_print_error($this->db);
4418 }
4419 }
4420
4426 public function isACompany()
4427 {
4428 // Define if third party is treated as company (or not) when nature is unknown
4429 //$defaultvalue = in_array($mysoc->country_code, array('FR')) ? 0 : 1; // TODO On old version, default was 1 for everybody, move this to defaultvalue = 0 for everybody
4430 $defaultvalue = 0;
4431 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', $defaultvalue);
4432
4433 // Now try to guess using different tips
4434 if (!empty($this->tva_intra)) {
4435 $isACompany = 2;
4436 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6) || !empty($this->euid)) {
4437 $isACompany = 3;
4438 } else {
4439 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4440 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4441 $isACompany = 0;
4442 }
4443 } else {
4444 $isACompany = 4;
4445 }
4446 }
4447
4448 return $isACompany;
4449 }
4450
4456 public function isInEEC()
4457 {
4458 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4459 return isInEEC($this);
4460 }
4461
4467 public function isInSEPA()
4468 {
4469 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4470 return isInSEPA($this);
4471 }
4472
4473 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4479 public function LoadSupplierCateg()
4480 {
4481 // phpcs:enable
4482 $this->SupplierCategories = array();
4483 $sql = "SELECT rowid, label";
4484 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4485 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4486
4487 $resql = $this->db->query($sql);
4488 if ($resql) {
4489 while ($obj = $this->db->fetch_object($resql)) {
4490 $this->SupplierCategories[$obj->rowid] = $obj->label;
4491 }
4492 return 0;
4493 } else {
4494 return -1;
4495 }
4496 }
4497
4498 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4505 public function AddFournisseurInCategory($categorie_id)
4506 {
4507 // phpcs:enable
4508 if ($categorie_id > 0 && $this->id > 0) {
4509 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4510 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4511
4512 if ($resql = $this->db->query($sql)) {
4513 return 0;
4514 }
4515 } else {
4516 return 0;
4517 }
4518 return -1;
4519 }
4520
4526 public function getNbOfEMailings()
4527 {
4528 $sql = "SELECT count(mc.email) as nb";
4529 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4530 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4531 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4532
4533 $resql = $this->db->query($sql);
4534 if ($resql) {
4535 $obj = $this->db->fetch_object($resql);
4536 $nb = (int) $obj->nb;
4537
4538 $this->db->free($resql);
4539 return $nb;
4540 } else {
4541 $this->error = $this->db->error();
4542 return -1;
4543 }
4544 }
4545
4553 public function setNoEmail($no_email, $unsubscribegroup = '')
4554 {
4555 $error = 0;
4556
4557 // Update mass emailing flag into table mailing_unsubscribe
4558 if ($this->email) {
4559 $this->db->begin();
4560
4561 if ($no_email) {
4562 // TODO Add $unsubscribegroup
4563 $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)."'";
4564 $resql = $this->db->query($sql);
4565 if ($resql) {
4566 $obj = $this->db->fetch_object($resql);
4567 $noemail = $obj->nb;
4568 if (empty($noemail)) {
4569 // TODO Add $unsubscribegroup
4570 $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())."')";
4571 $resql = $this->db->query($sql);
4572 if (!$resql) {
4573 $error++;
4574 $this->error = $this->db->lasterror();
4575 $this->errors[] = $this->error;
4576 }
4577 }
4578 } else {
4579 $error++;
4580 $this->error = $this->db->lasterror();
4581 $this->errors[] = $this->error;
4582 }
4583 } else {
4584 // TODO Add $unsubscribegroup
4585 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4586 $resql = $this->db->query($sql);
4587 if (!$resql) {
4588 $error++;
4589 $this->error = $this->db->lasterror();
4590 $this->errors[] = $this->error;
4591 }
4592 }
4593
4594 if (empty($error)) {
4595 $this->no_email = $no_email;
4596 $this->db->commit();
4597 return 1;
4598 } else {
4599 $this->db->rollback();
4600 return $error * -1;
4601 }
4602 }
4603
4604 return 0;
4605 }
4606
4613 public function getNoEmail()
4614 {
4615 if ($this->email) {
4616 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4617 $resql = $this->db->query($sql);
4618 if ($resql) {
4619 $obj = $this->db->fetch_object($resql);
4620 $this->no_email = $obj->nb;
4621 return 1;
4622 } else {
4623 $this->error = $this->db->lasterror();
4624 $this->errors[] = $this->error;
4625 return -1;
4626 }
4627 }
4628 return 0;
4629 }
4630
4631 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4641 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4642 {
4643 // phpcs:enable
4644 global $user, $langs;
4645
4646 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4647 $fullname = $member->getFullName($langs);
4648
4649 if ($member->morphy == 'mor') {
4650 if (empty($socname)) {
4651 $socname = $member->company ? $member->company : $member->societe;
4652 }
4653 if (!empty($fullname) && empty($socalias)) {
4654 $socalias = $fullname;
4655 }
4656 } elseif (empty($socname) && $member->morphy == 'phy') {
4657 if (empty($socname)) {
4658 $socname = $fullname;
4659 }
4660 if (!empty($member->company) && empty($socalias)) {
4661 $socalias = $member->company;
4662 }
4663 }
4664
4665 $name = (string) $socname;
4666 $alias = $socalias ? $socalias : '';
4667
4668 // Positionne parameters
4669 $this->nom = $name; // TODO deprecated
4670 $this->name = $name;
4671 $this->name_alias = $alias;
4672 $this->address = $member->address;
4673 $this->zip = $member->zip;
4674 $this->town = $member->town;
4675 $this->country_code = $member->country_code;
4676 $this->country_id = $member->country_id;
4677 $this->phone = $member->phone; // Prof phone
4678 $this->email = $member->email;
4679 $this->socialnetworks = $member->socialnetworks;
4680 $this->entity = $member->entity;
4681
4682 $this->client = 1; // A member is a customer by default
4683 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4684 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4685 } else {
4686 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4687 }
4688 $this->code_fournisseur = '-1';
4689 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4690 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4691
4692 $this->db->begin();
4693
4694 // Creates and positions $this->id
4695 $result = $this->create($user);
4696
4697 if ($result >= 0) {
4698 // Auto-create contact on thirdparty creation
4699 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4700 // Fill fields needed by contact
4701 $this->name_bis = $member->lastname;
4702 $this->firstname = $member->firstname;
4703 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4704 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4705
4706 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4707 $result = $this->create_individual($user);
4708
4709 if ($result < 0) {
4710 setEventMessages($this->error, $this->errors, 'errors');
4711 $this->db->rollback();
4712 return -1;
4713 }
4714 }
4715
4716 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4717 $sql .= " SET fk_soc = ".((int) $this->id);
4718 $sql .= " WHERE rowid = ".((int) $member->id);
4719
4720 $resql = $this->db->query($sql);
4721 if ($resql) {
4722 $this->db->commit();
4723 return $this->id;
4724 } else {
4725 $this->error = $this->db->error();
4726
4727 $this->db->rollback();
4728 return -1;
4729 }
4730 } else {
4731 // $this->error already positioned
4732 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4733
4734 $this->db->rollback();
4735 return $result;
4736 }
4737 }
4738
4745 public function setMysoc(Conf $conf)
4746 {
4747 global $langs;
4748
4749 $this->id = 0;
4750 $this->entity = $conf->entity;
4751 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4752 $this->nom = $this->name; // deprecated
4753 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4754 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4755 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4756 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4757
4758 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4759
4760 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4761
4762 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4763
4764 // We define country_id, country_code and country
4765 $country_id = 0;
4766 $country_code = $country_label = '';
4767 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4768 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4769 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4770 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4771 $country_code = $tmp[1];
4772 $country_label = $tmp[2];
4773 } else {
4774 // For backward compatibility
4775 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4776 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4777 $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
4778 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4779 }
4780 }
4781 $this->country_id = $country_id;
4782 $this->country_code = $country_code;
4783 $this->country = $country_label;
4784 if (is_object($langs)) {
4785 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4786 }
4787
4788 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4789 // We define state_id, state_code and state
4790 $state_id = 0;
4791 $state_code = '';
4792 $state_label = '';
4793 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4794 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4795 $state_id = (int) $tmp[0];
4796 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4797 $state_code = $tmp[1];
4798 $state_label = $tmp[2];
4799 } else { // For backward compatibility
4800 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);
4801 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4802 $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
4803 $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
4804 }
4805 }
4806 $this->state_id = $state_id;
4807 $this->state_code = $state_code;
4808 $this->state = $state_label;
4809 if (is_object($langs)) {
4810 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4811 }
4812
4813 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4814 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4815 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4816 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4817
4818 // Social networks
4819 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4820 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4821 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4822 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4823 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4824 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4825 $this->socialnetworks = array();
4826 if (!empty($facebook_url)) {
4827 $this->socialnetworks['facebook'] = $facebook_url;
4828 }
4829 if (!empty($twitter_url)) {
4830 $this->socialnetworks['twitter'] = $twitter_url;
4831 }
4832 if (!empty($linkedin_url)) {
4833 $this->socialnetworks['linkedin'] = $linkedin_url;
4834 }
4835 if (!empty($instagram_url)) {
4836 $this->socialnetworks['instagram'] = $instagram_url;
4837 }
4838 if (!empty($youtube_url)) {
4839 $this->socialnetworks['youtube'] = $youtube_url;
4840 }
4841 if (!empty($github_url)) {
4842 $this->socialnetworks['github'] = $github_url;
4843 }
4844
4845 // Id prof generic
4846 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4847 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4848 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4849 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4850 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4851 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4852 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4853 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4854 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4855 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4856 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4857 $this->euid = getDolGlobalString('MAIN_INFO_EUID');
4858 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4859 $this->capital = is_numeric(price2num(getDolGlobalString('MAIN_INFO_CAPITAL'))) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : null;
4860 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4861 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4862 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4863 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4864 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4865 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4866 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4867 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4868 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4869
4870 // Define if company use vat or not
4871 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4872
4873 // Define if company use local taxes
4874 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4875 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4876
4877 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4878 }
4879
4887 public function initAsSpecimen()
4888 {
4889 $now = dol_now();
4890
4891 // Initialize parameters
4892 $this->id = 0;
4893 $this->entity = 1;
4894 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4895 $this->ref_ext = 'Ref ext';
4896 $this->specimen = 1;
4897 $this->address = '21 jump street';
4898 $this->zip = '99999';
4899 $this->town = 'MyTown';
4900 $this->state_id = 1;
4901 $this->state_code = 'AA';
4902 $this->state = 'MyState';
4903 $this->country_id = 1;
4904 $this->country_code = 'FR';
4905 $this->email = 'specimen@specimen.com';
4906 $this->socialnetworks = array(
4907 'skype' => 'skypepseudo',
4908 'twitter' => 'twitterpseudo',
4909 'facebook' => 'facebookpseudo',
4910 'linkedin' => 'linkedinpseudo',
4911 );
4912 $this->url = 'https://www.specimen.com';
4913
4914 $this->phone = '0909090901';
4915 $this->phone_mobile = '0909090901';
4916 $this->fax = '0909090909';
4917
4918 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4919 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4920 $this->typent_code = 'TE_OTHER';
4921 $this->capital = 10000;
4922 $this->client = 1;
4923 $this->prospect = 1;
4924 $this->fournisseur = 1;
4925 $this->tva_assuj = 1;
4926 //$this->tva_intra = 'EU1234567';
4927 $this->tva_intra = 'FR1234567';
4928 $this->note_public = 'This is a comment (public)';
4929 $this->note_private = 'This is a comment (private)';
4930
4931 $this->idprof1 = 'idprof1';
4932 $this->idprof2 = 'idprof2';
4933 $this->idprof3 = 'idprof3';
4934 $this->idprof4 = 'idprof4';
4935 $this->idprof5 = 'idprof5';
4936 $this->idprof6 = 'idprof6';
4937
4938 $this->euid = 'FR-RCSXXXX-idprof1';
4939
4940 return 1;
4941 }
4942
4951 public function useLocalTax($localTaxNum = 0, $mode = 0, $thirdparty = null)
4952 {
4953 if ($mode == 1 && $thirdparty instanceof Societe) {
4954 if ($localTaxNum == -1) {
4955 return array(1 => ($thirdparty->localtax1_assuj ? true : false), 2 => ($thirdparty->localtax2_assuj ? true : false));
4956 } elseif ($localTaxNum == 1) {
4957 return $thirdparty->localtax1_assuj ? true : false;
4958 } elseif ($localTaxNum == 2) {
4959 return $thirdparty->localtax2_assuj ? true : false;
4960 }
4961 return false;
4962 } else {
4963 $sql = "SELECT t.localtax1, t.localtax2";
4964 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4965 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4966 $sql .= " AND t.active = 1";
4967 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4968 if (empty($localTaxNum) || $localTaxNum == -1) {
4969 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4970 } elseif ($localTaxNum == 1) {
4971 $sql .= " AND t.localtax1_type <> '0'";
4972 } elseif ($localTaxNum == 2) {
4973 $sql .= " AND t.localtax2_type <> '0'";
4974 }
4975
4976 $resql = $this->db->query($sql);
4977 if ($resql) {
4978 if ($localTaxNum == -1) {
4979 $obj = $this->db->fetch_object($resql);
4980 if ($obj) {
4981 return array(1 => ($obj->localtax1 ? true : false), 2 => ($obj->localtax2 ? true : false));
4982 }
4983 return array(1 => false, 2 => false);
4984 } else {
4985 return ($this->db->num_rows($resql) > 0);
4986 }
4987 } else {
4988 return false;
4989 }
4990 }
4991 }
4992
4998 public function useNPR()
4999 {
5000 $sql = "SELECT t.rowid";
5001 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5002 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5003 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
5004 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5005
5006 dol_syslog("useNPR", LOG_DEBUG);
5007 $resql = $this->db->query($sql);
5008 if ($resql) {
5009 return ($this->db->num_rows($resql) > 0);
5010 } else {
5011 return false;
5012 }
5013 }
5014
5021 public function useRevenueStamp()
5022 {
5023 $sql = "SELECT COUNT(*) as nb";
5024 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
5025 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5026 $sql .= " AND r.active = 1";
5027
5028 dol_syslog("useRevenueStamp", LOG_DEBUG);
5029 $resql = $this->db->query($sql);
5030 if ($resql) {
5031 $obj = $this->db->fetch_object($resql);
5032 return ($obj->nb > 0);
5033 } else {
5034 $this->error = $this->db->lasterror();
5035 return false;
5036 }
5037 }
5038
5044 public function getLibProspLevel()
5045 {
5046 return $this->LibProspLevel($this->fk_prospectlevel);
5047 }
5048
5049 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5056 public function LibProspLevel($fk_prospectlevel)
5057 {
5058 // phpcs:enable
5059 global $langs;
5060
5061 $label = '';
5062 if ($fk_prospectlevel != '') {
5063 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5064 // If label is not found in language file, we get label from cache/database
5065 if ($label == "ProspectLevel".$fk_prospectlevel) {
5066 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5067 }
5068 }
5069
5070 return $label;
5071 }
5072
5080 public function getLibProspCommStatut($mode = 0, $label = '')
5081 {
5082 return $this->LibProspCommStatut((int) $this->stcomm_id, $mode, $label, $this->stcomm_picto);
5083 }
5084
5085 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5099 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5100 {
5101 // phpcs:enable
5102 global $langs;
5103
5104 $langs->load('customers');
5105
5106 if ($mode == 2) {
5107 if ($status == '-1' || $status == 'ST_NO') {
5108 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5109 } elseif ($status == '0' || $status == 'ST_NEVER') {
5110 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5111 } elseif ($status == '1' || $status == 'ST_TODO') {
5112 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5113 } elseif ($status == '2' || $status == 'ST_PEND') {
5114 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5115 } elseif ($status == '3' || $status == 'ST_DONE') {
5116 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5117 } else {
5118 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);
5119 }
5120 } elseif ($mode == 3) {
5121 if ($status == '-1' || $status == 'ST_NO') {
5122 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5123 } elseif ($status == '0' || $status == 'ST_NEVER') {
5124 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5125 } elseif ($status == '1' || $status == 'ST_TODO') {
5126 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5127 } elseif ($status == '2' || $status == 'ST_PEND') {
5128 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5129 } elseif ($status == '3' || $status == 'ST_DONE') {
5130 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5131 } else {
5132 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5133 }
5134 } elseif ($mode == 4) {
5135 if ($status == '-1' || $status == 'ST_NO') {
5136 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5137 } elseif ($status == '0' || $status == 'ST_NEVER') {
5138 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5139 } elseif ($status == '1' || $status == 'ST_TODO') {
5140 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5141 } elseif ($status == '2' || $status == 'ST_PEND') {
5142 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5143 } elseif ($status == '3' || $status == 'ST_DONE') {
5144 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5145 } else {
5146 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);
5147 }
5148 }
5149
5150 return "Error, mode/status not found";
5151 }
5152
5159 public function getOutstandingProposals($mode = 'customer')
5160 {
5161 global $hookmanager;
5162 $table = 'propal';
5163 if ($mode == 'supplier') {
5164 $table = 'supplier_proposal';
5165 }
5166
5167 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5168 $sql .= " WHERE fk_soc = ".((int) $this->id);
5169 if ($mode == 'supplier') {
5170 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5171 } else {
5172 $sql .= " AND entity IN (".getEntity('propal').")";
5173 }
5174
5175 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5176
5177 // Add where from hooks
5178 $parameters = array('mode' => $mode, 'table' => $table);
5179 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5180 $sql .= $hookmanager->resPrint;
5181
5182 $resql = $this->db->query($sql);
5183 if ($resql) {
5184 $outstandingOpened = 0;
5185 $outstandingTotal = 0;
5186 $outstandingTotalIncTax = 0;
5187 $arrayofref = array();
5188 while ($obj = $this->db->fetch_object($resql)) {
5189 $arrayofref[$obj->rowid] = $obj->ref;
5190 $outstandingTotal += $obj->total_ht;
5191 $outstandingTotalIncTax += $obj->total_ttc;
5192 if ($obj->status != 0) {
5193 // Not a draft
5194 $outstandingOpened += $obj->total_ttc;
5195 }
5196 }
5197 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5198 } else {
5199 return array();
5200 }
5201 }
5202
5209 public function getOutstandingOrders($mode = 'customer')
5210 {
5211 global $hookmanager;
5212 $table = 'commande';
5213 if ($mode == 'supplier') {
5214 $table = 'commande_fournisseur';
5215 }
5216
5217 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5218 $sql .= " WHERE fk_soc = ".((int) $this->id);
5219 if ($mode == 'supplier') {
5220 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5221 } else {
5222 $sql .= " AND entity IN (".getEntity('commande').")";
5223 }
5224
5225 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5226 // Add where from hooks
5227 $parameters = array('mode' => $mode, 'table' => $table);
5228 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5229 $sql .= $hookmanager->resPrint;
5230 $resql = $this->db->query($sql);
5231 if ($resql) {
5232 $outstandingOpened = 0;
5233 $outstandingTotal = 0;
5234 $outstandingTotalIncTax = 0;
5235 $arrayofref = array();
5236 while ($obj = $this->db->fetch_object($resql)) {
5237 $arrayofref[$obj->rowid] = $obj->ref;
5238 $outstandingTotal += $obj->total_ht;
5239 $outstandingTotalIncTax += $obj->total_ttc;
5240 if ($obj->status != 0) {
5241 // Not a draft
5242 $outstandingOpened += $obj->total_ttc;
5243 }
5244 }
5245 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5246 } else {
5247 return array();
5248 }
5249 }
5250
5258 public function getOutstandingBills($mode = 'customer', $late = 0)
5259 {
5260 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5261
5262 $table = 'facture';
5263 if ($mode == 'supplier') {
5264 $table = 'facture_fourn';
5265 }
5266
5267 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5268 $paiement = $invoice->getSommePaiement();
5269 $creditnotes=$invoice->getSumCreditNotesUsed();
5270 $deposits=$invoice->getSumDepositsUsed();
5271 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5272 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5273 */
5274 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5275
5276 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5277 $sql .= " WHERE fk_soc = ".((int) $this->id);
5278 if (!empty($late)) {
5279 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5280 }
5281 if ($mode == 'supplier') {
5282 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5283 } else {
5284 $sql .= " AND entity IN (".getEntity('invoice').")";
5285 }
5286
5287 dol_syslog("getOutstandingBills", LOG_DEBUG);
5288 $resql = $this->db->query($sql);
5289 if ($resql) {
5290 $outstandingOpened = 0;
5291 $outstandingTotal = 0;
5292 $outstandingTotalIncTax = 0;
5293 $arrayofref = array();
5294 $arrayofrefopened = array();
5295 if ($mode == 'supplier') {
5296 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5297 $tmpobject = new FactureFournisseur($this->db);
5298 } else {
5299 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5300 $tmpobject = new Facture($this->db);
5301 }
5302 while ($obj = $this->db->fetch_object($resql)) {
5303 $arrayofref[$obj->rowid] = $obj->ref;
5304 $tmpobject->id = $obj->rowid;
5305
5306 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5307 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5308 ) {
5309 $outstandingTotal += $obj->total_ht;
5310 $outstandingTotalIncTax += $obj->total_ttc;
5311 }
5312
5313 $remaintopay = 0;
5314
5315 if ($obj->paye == 0
5316 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5317 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5318 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5319 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5320 $paiement = $tmpobject->getSommePaiement();
5321 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5322 $deposits = $tmpobject->getSumDepositsUsed();
5323
5324 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5325 $outstandingOpened += $remaintopay;
5326 }
5327
5328 //if credit note is converted but not used
5329 // TODO Do this also for customer ?
5330 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5331 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5332 $remaintopay -= $remainingcreditnote;
5333 $outstandingOpened -= $remainingcreditnote;
5334 }
5335
5336 if ($remaintopay) {
5337 $arrayofrefopened[$obj->rowid] = $obj->ref;
5338 }
5339 }
5340 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'amount incl taxes' > 0
5341 } else {
5342 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5343 return array();
5344 }
5345 }
5346
5353 public function getLibCustProspStatut()
5354 {
5355 return $this->LibCustProspStatut($this->client);
5356 }
5357
5358 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5365 public function LibCustProspStatut($status)
5366 {
5367 // phpcs:enable
5368 global $langs;
5369 $langs->load('companies');
5370
5371 if ($status == 0) {
5372 return $langs->trans("NorProspectNorCustomer");
5373 } elseif ($status == 1) {
5374 return $langs->trans("Customer");
5375 } elseif ($status == 2) {
5376 return $langs->trans("Prospect");
5377 } elseif ($status == 3) {
5378 return $langs->trans("ProspectCustomer");
5379 }
5380
5381 return '';
5382 }
5383
5384
5391 public function calculateVATNumberFromProperties($thirdparty)
5392 {
5393 if ($thirdparty->country_code == 'FR' && empty($thirdparty->tva_intra) && !empty($thirdparty->tva_assuj)) {
5394 $siren = trim($thirdparty->idprof1);
5395 if (empty($siren)) {
5396 $siren = (int) substr(str_replace(' ', '', $thirdparty->idprof2), 0, 9);
5397 }
5398 if (!empty($siren)) {
5399 // [FR + code clé + numéro SIREN ]
5400 // Key VAT = [12 + 3 × (SIREN modulo 97)] modulo 97
5401 $cle = (12 + 3 * $siren % 97) % 97;
5402 $tva_intra = 'FR' . $cle . $siren;
5403 }
5404 }
5405
5406 return $tva_intra ?? '';
5407 }
5408
5409
5421 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5422 {
5423 global $langs;
5424
5425 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5426 $modelpath = "core/modules/bank/doc/";
5427
5428 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5429 $companybankaccount = new CompanyBankAccount($this->db);
5430 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5431 if (!$result) {
5432 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5433 }
5434 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5435 $this->last_main_doc = $companybankaccount->last_main_doc;
5436 } else {
5437 // Set the model to the name of the model to be used
5438 if (!dol_strlen($modele)) {
5439 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5440 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5441 } else {
5442 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5443 return 0;
5444 }
5445 }
5446
5447 if (!isset($this->bank_account)) {
5448 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5449 $bac = new CompanyBankAccount($this->db);
5450 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5451 $result = $bac->fetch(0, '', $this->id);
5452 if ($result > 0) {
5453 $this->bank_account = $bac;
5454 } else {
5455 $this->bank_account = '';
5456 }
5457 }
5458
5459 $modelpath = "core/modules/societe/doc/";
5460
5461 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5462 }
5463
5464 return $result;
5465 }
5466
5467
5480 public function setCategories($categories, $type_categ, $remove_existing = true)
5481 {
5482 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5483
5484 // Decode type
5485 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5486 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Nothing done.', LOG_ERR);
5487 return -1;
5488 }
5489
5490 return parent::setCategoriesCommon($categories, $type_categ, $remove_existing);
5491 }
5492
5500 public function setSalesRep($salesrep, $onlyAdd = false)
5501 {
5502 global $user;
5503
5504 // Handle single user
5505 if (!is_array($salesrep)) {
5506 $salesrep = array($salesrep);
5507 }
5508
5509 $to_del = array(); // Nothing to delete
5510 $to_add = $salesrep;
5511 if ($onlyAdd === false) {
5512 // Get current users
5513 $existing = $this->getSalesRepresentatives($user, 1);
5514
5515 // Diff
5516 if (is_array($existing)) {
5517 $to_del = array_diff($existing, $salesrep);
5518 $to_add = array_diff($salesrep, $existing);
5519 }
5520 }
5521
5522 $error = 0;
5523
5524 // Process
5525 foreach ($to_del as $del) {
5526 $this->del_commercial($user, $del);
5527 }
5528 foreach ($to_add as $add) {
5529 $result = $this->add_commercial($user, $add);
5530 if ($result < 0) {
5531 $error++;
5532 break;
5533 }
5534 }
5535
5536 return $error ? -1 : 1;
5537 }
5538
5545 public function setThirdpartyType($typent_id)
5546 {
5547 global $user;
5548
5549 dol_syslog(__METHOD__, LOG_DEBUG);
5550
5551 if ($this->id) {
5552 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5553
5554 if ($result > 0) {
5555 $this->typent_id = $typent_id;
5556 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5557 return 1;
5558 } else {
5559 return -1;
5560 }
5561 } else {
5562 return -1;
5563 }
5564 }
5565
5575 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5576 {
5577 if ($origin_id == $dest_id) {
5578 dol_syslog('Error: Try to merge a thirdparty into itself');
5579 return false;
5580 }
5581
5582 // 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.
5583 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5584 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5585 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5586 $sql .= ' SELECT fk_user ';
5587 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5588 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5589
5590 $resql = $dbs->query($sql);
5591 while ($obj = $dbs->fetch_object($resql)) {
5592 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5593 }
5594
5595 // The table llx_societe_extrafields must NOT be in this list because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5596 // Do not include llx_societe because it will be replaced later.
5597 $tables = array(
5598 'societe_account',
5599 'societe_commerciaux',
5600 'societe_prices',
5601 'societe_remise',
5602 'societe_remise_except',
5603 'societe_rib'
5604 );
5605
5606 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5607
5608 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5609 }
5610
5619 public function setAccountancyCode($type, $value)
5620 {
5621 global $user, $langs, $conf;
5622
5623 $this->db->begin();
5624
5625 if ($type == 'buy') {
5626 $field = 'accountancy_code_buy';
5627 } elseif ($type == 'sell') {
5628 $field = 'accountancy_code_sell';
5629 } else {
5630 return -1;
5631 }
5632
5633 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5634 $sql .= $field." = '".$this->db->escape($value)."'";
5635 $sql .= " WHERE rowid = ".((int) $this->id);
5636
5637 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5638 $resql = $this->db->query($sql);
5639
5640 if ($resql) {
5641 // Call triggers
5642 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5643 $interface = new Interfaces($this->db);
5644 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5645 if ($result < 0) {
5646 $this->errors = $interface->errors;
5647 $this->db->rollback();
5648 return -1;
5649 }
5650 // End call triggers
5651
5652 $this->$field = $value;
5653
5654 $this->db->commit();
5655 return 1;
5656 } else {
5657 $this->error = $this->db->lasterror();
5658 $this->db->rollback();
5659 return -1;
5660 }
5661 }
5662
5669 public function fetchPartnerships($mode)
5670 {
5671 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5672
5673 $this->partnerships[] = array();
5674
5675 return 1;
5676 }
5677
5685 public function getKanbanView($option = '', $arraydata = array())
5686 {
5687 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5688
5689 $out = '<div class="box-flex-item box-flex-grow-zero">';
5690 $out .= '<div class="info-box info-box-sm">';
5691 $out .= '<span class="info-box-icon bg-infobox-action">';
5692 if (!empty($this->logo) && class_exists('Form')) {
5693 $out .= Form::showphoto('societe', $this, 0, 40, 0, 'photokanban', '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.
5694 } else {
5695 $out .= img_picto('', $this->picto);
5696 }
5697 $out .= '</span>';
5698 $out .= '<div class="info-box-content">';
5699 $out .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">' . $this->getNomUrl(1);
5700 $out .= '</div>';
5701 if (!empty($this->phone)) {
5702 $out .= '<div class="inline-block valignmiddle">';
5703 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5704 $out .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5705 $out .= '</div>';
5706 }
5707 if (!empty($this->email)) {
5708 $out .= '<div class="inline-block valignmiddle">';
5709 $out .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5710 $out .= '</div>';
5711 }
5712 if ($selected >= 0) {
5713 $out .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5714 }
5715 if (!empty($this->code_client)) {
5716 $out .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5717 }
5718 $out .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
5719 $out .= '</div>'; // end info-box-content
5720 $out .= '</div>';
5721 $out .= '</div>';
5722
5723 return $out;
5724 }
5725
5735 public function getContacts($list = 0, $code = '', $element = '', $status = -1)
5736 {
5737 // phpcs:enable
5738 global $langs;
5739
5740 $tab = array();
5741
5742 $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
5743 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5744 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5745 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5746 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5747 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5748 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5749 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5750 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5751
5752 // Add status filter if requested
5753 if ($status >= 0) {
5754 $sql .= " AND t.statut = " . ((int) $status);
5755 }
5756 if (!empty($element)) {
5757 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5758 }
5759 if ($code) {
5760 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5761 }
5762 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5763 $sql .= " AND tc.source = 'external'";
5764 $sql .= " AND tc.active = 1";
5765
5766 $sql .= " ORDER BY t.lastname ASC";
5767
5768 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5769 $resql = $this->db->query($sql);
5770 if ($resql) {
5771 $num = $this->db->num_rows($resql);
5772 $i = 0;
5773 while ($i < $num) {
5774 $obj = $this->db->fetch_object($resql);
5775
5776 if (!$list) {
5777 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5778 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5779 $tab[$obj->id] = array(
5780 'source' => $obj->source,
5781 'socid' => (int) $obj->socid,
5782 'id' => (int) $obj->id,
5783 'nom' => $obj->lastname, // For backward compatibility
5784 'civility' => $obj->civility,
5785 'lastname' => $obj->lastname,
5786 'firstname' => $obj->firstname,
5787 'email' => $obj->email,
5788 'login' => (empty($obj->login) ? '' : $obj->login),
5789 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5790 'statuscontact' => $obj->statuscontact,
5791 'rowid' => (int) $obj->rowid,
5792 'code' => $obj->code,
5793 'element' => $obj->element,
5794 'libelle' => $libelle_type,
5795 'status' => $obj->statuslink,
5796 'fk_c_type_contact' => (int) $obj->fk_c_type_contact
5797 );
5798 } else {
5799 $tab[$obj->id] = (int) $obj->id;
5800 }
5801 $i++;
5802 }
5803
5804 return $tab;
5805 } else {
5806 $this->error = $this->db->lasterror();
5807 dol_print_error($this->db);
5808 return -1;
5809 }
5810 }
5811
5822 public function mergeCompany($soc_origin_id)
5823 {
5824 global $conf, $langs, $hookmanager, $user, $action;
5825
5826 $error = 0;
5827 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5828
5829 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5830
5831 if ($soc_origin->fetch($soc_origin_id) < 1) {
5832 $this->error = $langs->trans('ErrorRecordNotFound');
5833 $error++;
5834 }
5835
5836 if (!$error) {
5837 $this->db->begin();
5838
5839 // Recopy some data
5840 $this->client |= $soc_origin->client;
5841 $this->fournisseur |= $soc_origin->fournisseur;
5842 $listofproperties = array(
5843 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5844 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5845 'tva_intra', 'euid', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5846 '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',
5847 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5848 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5849 );
5850 foreach ($listofproperties as $property) {
5851 if (empty($this->$property)) {
5852 $this->$property = $soc_origin->$property;
5853 }
5854 }
5855
5856 if ($this->typent_id == -1) {
5857 $this->typent_id = $soc_origin->typent_id;
5858 }
5859
5860 // Concat some data
5861 $listofproperties = array(
5862 'note_public', 'note_private'
5863 );
5864 foreach ($listofproperties as $property) {
5865 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5866 }
5867
5868 // Merge extrafields
5869 if (is_array($soc_origin->array_options)) {
5870 foreach ($soc_origin->array_options as $key => $val) {
5871 if (empty($this->array_options[$key])) {
5872 $this->array_options[$key] = $val;
5873 }
5874 }
5875 }
5876
5877 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5878 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5879 $this->name_bis = $this->name;
5880 }
5881
5882 // Merge categories
5883 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5884 $static_cat = new Categorie($this->db);
5885
5886 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5887 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5888 $custcats = array_merge($custcats, $custcats_ori);
5889 $this->setCategories($custcats, 'customer');
5890
5891 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5892 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5893 $suppcats = array_merge($suppcats, $suppcats_ori);
5894 $this->setCategories($suppcats, 'supplier');
5895
5896 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5897 if ($soc_origin->code_client == $this->code_client
5898 || $soc_origin->code_fournisseur == $this->code_fournisseur
5899 || $soc_origin->barcode == $this->barcode) {
5900 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5901 $soc_origin->code_client = '';
5902 $soc_origin->code_fournisseur = '';
5903 $soc_origin->barcode = '';
5904 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5905 }
5906
5907 // Children companies
5908 if (!getDolGlobalString('SOCIETE_DISABLE_PARENTCOMPANY')) {
5909 // Children
5910 $children_ori = $this->getChildrenForCompany($soc_origin->id);
5911 if (count($children_ori)) {
5912 foreach ($children_ori as $child_id) {
5913 $child = new Societe($this->db);
5914 $child->id = $child_id;
5915 $child->setParent($this->id);
5916 }
5917 }
5918 }
5919
5920 // Update
5921 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5922
5923 if ($result < 0) {
5924 $error++;
5925 }
5926
5927 // Move links
5928 if (!$error) {
5929 $objects = array(
5930 'Adherent' => '/adherents/class/adherent.class.php',
5931 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5932 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5933 'Propal' => '/comm/propal/class/propal.class.php',
5934 'Commande' => '/commande/class/commande.class.php',
5935 'Facture' => '/compta/facture/class/facture.class.php',
5936 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5937 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5938 'Contact' => '/contact/class/contact.class.php',
5939 'Contrat' => '/contrat/class/contrat.class.php',
5940 'Expedition' => '/expedition/class/expedition.class.php',
5941 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5942 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5943 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5944 'Reception' => '/reception/class/reception.class.php',
5945 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5946 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5947 'Product' => '/product/class/product.class.php',
5948 //'ProductThirparty' => '...', // for llx_product_thirdparty
5949 'Project' => '/projet/class/project.class.php',
5950 'User' => '/user/class/user.class.php',
5951 'Account' => '/compta/bank/class/account.class.php',
5952 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5953 'Societe' => '/societe/class/societe.class.php',
5954 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5955 );
5956 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'delivery')) {
5957 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5958 }
5959 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'mrp_mo')) {
5960 $objects['Mo'] = '/mrp/class/mo.class.php';
5961 }
5962 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'don')) {
5963 $objects['Don'] = '/don/class/don.class.php';
5964 }
5965 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'partnership')) {
5966 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5967 }
5968 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'fichinter')) {
5969 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5970 }
5971 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'ticket')) {
5972 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5973 }
5974
5975 //First, all core objects must update their tables
5976 foreach ($objects as $object_name => $object_file) {
5977 /* $object_file is never an array -> code commented
5978 if (is_array($object_file)) {
5979 if (empty($object_file['enabled'])) {
5980 continue;
5981 }
5982 $object_file = $object_file['file'];
5983 }
5984 */
5985
5986 require_once DOL_DOCUMENT_ROOT.$object_file;
5987
5988 if (!$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5989 $error++;
5990 $this->error = $this->db->lasterror();
5991 break;
5992 }
5993 }
5994 }
5995
5996 // External modules should update their ones too
5997 if (!$error) {
5998 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5999 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
6000
6001 if ($reshook < 0) {
6002 $this->error = $hookmanager->error;
6003 $this->errors = $hookmanager->errors;
6004 $error++;
6005 }
6006 }
6007
6008
6009 if (!$error) {
6010 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
6011
6012 // Call trigger
6013 $result = $this->call_trigger('COMPANY_MODIFY', $user);
6014 if ($result < 0) {
6015 $error++;
6016 }
6017 // End call triggers
6018 }
6019
6020 if (!$error) {
6021 // We finally remove the old thirdparty
6022 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
6023 $this->error = $soc_origin->error;
6024 $this->errors = $soc_origin->errors;
6025 $error++;
6026 }
6027 }
6028
6029
6030 if (!$error) {
6031 // Move files from the dir of the third party to delete into the dir of the third party to keep
6032 if (!empty($conf->societe->multidir_output[$this->entity])) {
6033 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
6034 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
6035
6036 if (dol_is_dir($srcdir)) {
6037 $dirlist = dol_dir_list($srcdir, 'files', 1);
6038 foreach ($dirlist as $filetomove) {
6039 $destfile = $destdir.'/'.$filetomove['relativename'];
6040 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
6041 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
6042 }
6043 //exit;
6044 }
6045 }
6046 }
6047
6048 if (!$error) {
6049 $this->db->commit();
6050 return 0;
6051 } else {
6052 $langs->load("errors");
6053 $this->error = $langs->trans('ErrorsThirdpartyMerge');
6054 $this->db->rollback();
6055 return -1;
6056 }
6057 }
6058
6059 return -1;
6060 }
6061}
$object ref
Definition info.php:90
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.
setErrorsFromObject($object)
setErrorsFromObject
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 languages 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.
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, $usesharelinkifavailable=0)
Return HTML code to output a photo.
Class to manage triggers.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
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...
isInSEPA()
Return if a company is inside the SEPA zone (Single Euro Payment Area)
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.
useLocalTax($localTaxNum=0, $mode=0, $thirdparty=null)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
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.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysoc in most ca...
id_prof_check($idprof)
Check the validity of a professional identifier according to the properties (country) of the thirdpar...
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.
getContacts($list=0, $code='', $element='', $status=-1)
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
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)
setCategories($categories, $type_categ, $remove_existing=true)
Sets object to supplied categories.
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.
setNoEmail($no_email, $unsubscribegroup='')
Set "blacklist" mailing status.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type=0)
Return amount (with tax) of discounts currently available for a company, user or other criteria.
getChildrenForCompany($company_id)
Get children for company.
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.
calculateVATNumberFromProperties($thirdparty)
Calculate VAT intracommunity number for a thirdparty if missing, from the professional ID.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
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.
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:168
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.
global $mysoc
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:664
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").
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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:64
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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...
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
isValidProfIds($idprof, $thirdparty, $lenghtonly=0)
Check the validity of a professional identifier according to the properties (country) of the company ...
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:133