dolibarr 23.0.3
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-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-2025 MDW <mdeweerd@users.noreply.github.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 */
38
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
49require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
50
51
55class Societe extends CommonObject
56{
57 use CommonIncoterm;
59 use CommonPeople;
60
65 public $TRIGGER_PREFIX = 'COMPANY'; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
66
70 public $module = 'societe';
71
75 public $element = 'societe';
76
80 public $table_element = 'societe';
81
85 public $fk_element = 'fk_soc';
86
90 public $fieldsforcombobox = 'nom,name_alias';
91
95 protected $childtables = array(
96 'supplier_proposal' => array('name' => 'SupplierProposal'),
97 'propal' => array('name' => 'Proposal'),
98 'commande' => array('name' => 'Order'),
99 'facture' => array('name' => 'Invoice'),
100 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
101 'contrat' => array('name' => 'Contract'),
102 'fichinter' => array('name' => 'Fichinter'),
103 'facture_fourn' => array('name' => 'SupplierInvoice'),
104 'commande_fournisseur' => array('name' => 'SupplierOrder'),
105 'projet' => array('name' => 'Project'),
106 'expedition' => array('name' => 'Shipment'),
107 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
108 );
109
114 protected $childtablesoncascade = array(
115 'societe_prices',
116 'product_fournisseur_price',
117 'product_customer_price_log',
118 'product_customer_price',
119 '@Contact:/contact/class/contact.class.php:fk_soc',
120 'adherent',
121 'societe_account',
122 'societe_rib',
123 'societe_remise',
124 'societe_remise_except',
125 'societe_commerciaux',
126 'categorie',
127 'notify',
128 'notify_def',
129 'actioncomm',
130 );
131
135 public $picto = 'company';
136
141 public $restrictiononfksoc = 1;
142
147 public $SupplierCategories = array();
148
153 public $prefixCustomerIsRequired;
154
184 public $fields = array(
185 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
186 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
187 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
188 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
189 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
190 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
191 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
192 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
193 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
194 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
195 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
196 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
197 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
198 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
199 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
200 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
201 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
202 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
203 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
204 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
205 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
206 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
207 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
208 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
209 'fk_typent' => array('type' => 'integer', 'label' => 'ThirdPartyType', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
210 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
211 'birth' => array('type' => 'date', 'label' => 'CompnanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182),
212 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
213 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
214 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
215 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
216 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
217 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
218 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
219 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
220 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
221 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
222 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
223 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
224 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
225 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
226 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
227 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
228 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
229 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
230 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
231 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
232 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
233 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
234 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
235 'mode_reglement' => array('type' => 'smallint(6)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
236 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
237 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
238 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
239 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
240 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
241 '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),
242 '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),
243 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMode', 'enabled' => 1, 'visible' => -1, 'position' => 330),
244 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'VATIsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 335),
245 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax1IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 340),
246 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
247 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax2IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 350),
248 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
249 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
250 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
251 '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),
252 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
253 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
254 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
255 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
256 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
257 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
258 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
259 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
260 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
261 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
262 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
263 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
264 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
265 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
266 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
267 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
268 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
269 );
270
277 public $nom;
278
282 public $name;
283
288 public $name_alias;
289
293 public $particulier;
294
299 public $status = 1;
300
304 public $region_code;
305
309 public $region;
310
314 public $country_id;
315
321 public $departement_code;
322
328 public $departement;
329
335 public $pays;
336
341 public $phone;
346 public $phone_mobile;
351 public $fax;
352
357 public $email;
358
363 public $no_email;
364
370 public $skype;
371
377 public $twitter;
378
384 public $facebook;
385
391 public $linkedin;
392
397 public $url;
398
403 public $barcode;
404
405 // 6 professional id (usage depends on country)
406
411 public $idprof1;
412
418 public $siren;
419
420
425 public $idprof2;
426
432 public $siret;
433
438 public $idprof3;
439
445 public $ape;
446
451 public $idprof4;
452
457 public $idprof5;
458
463 public $idprof6;
464
469 public $idprof7;
470
475 public $idprof8;
476
481 public $idprof9;
482
487 public $idprof10;
488
493 public $socialobject;
494
498 public $prefix_comm;
499
503 public $tva_assuj = 1;
504
508 public $tva_intra;
509
513 public $vat_reverse_charge = 0;
514
515 // Local taxes
519 public $localtax1_assuj;
523 public $localtax1_value;
527 public $localtax2_assuj;
531 public $localtax2_value;
532
536 public $managers;
537
541 public $capital;
542
546 public $typent_id = 0;
547
551 public $typent_code;
552
556 public $effectif;
557
561 public $effectif_id = 0;
565 public $forme_juridique_code = 0;
570 public $forme_juridique;
574 public $birth;
575
579 public $remise_percent;
583 public $remise_supplier_percent;
584
588 public $mode_reglement_id;
592 public $cond_reglement_id;
596 public $deposit_percent;
600 public $mode_reglement_supplier_id;
604 public $cond_reglement_supplier_id;
608 public $transport_mode_supplier_id;
609
613 public $fk_prospectlevel;
614
618 public $name_bis;
619
625 public $user_modification;
626
632 public $user_creation;
633
638 public $client = 0;
639
644 public $prospect = 0;
645
650 public $fournisseur;
651
656 public $code_client;
657
662 public $code_fournisseur;
663
668 public $code_compta_client;
669
674 public $accountancy_code_customer_general;
675
680 public $accountancy_code_customer;
681
686 public $code_compta_fournisseur;
687
692 public $accountancy_code_supplier_general;
693
698 public $accountancy_code_supplier;
699
704 public $code_compta_product;
705
711 public $note;
712
717 public $note_private;
718
723 public $note_public;
724
729 public $stcomm_id;
730
735 public $stcomm_picto;
736
741 public $status_prospect_label;
742
747 public $price_level;
748
752 public $outstanding_limit;
753
757 public $order_min_amount;
758
762 public $supplier_order_min_amount;
763
768 public $commercial_id;
769
774 public $parent;
775
780 public $default_lang;
781
785 public $ref;
786
792 public $ref_ext;
793
797 public $ip;
798
805 public $import_key;
806
811 public $webservices_url;
812
817 public $webservices_key;
818
822 public $logo;
823
827 public $logo_small;
828
832 public $logo_mini;
833
837 public $logo_squarred;
838
842 public $logo_squarred_small;
843
847 public $logo_squarred_mini;
848
852 public $accountancy_code_sell;
853
857 public $accountancy_code_buy;
858
862 public $currency_code;
863
864 // Multicurrency
868 public $fk_multicurrency;
869
873 public $multicurrency_code;
874
875 // Warehouse
879 public $fk_warehouse;
880
884 public $termsofsale;
885
886
887 // Fields loaded by fetchPartnerships()
888
892 public $partnerships = array();
893
894
898 public $bank_account;
899
905 public $code_compta;
906
907
908 const STATUS_CEASED = 0;
909 const STATUS_INACTIVITY = 1;
910
914 const NO_CUSTOMER = 0;
915
919 const CUSTOMER = 1;
920
924 const PROSPECT = 2;
925
930
934 const NO_SUPPLIER = 0;
935
939 const SUPPLIER = 1;
940
946 protected function deprecatedProperties()
947 {
948 return
949 array(
950 'code_compta' => 'code_compta_client',
951 )
952 + parent::deprecatedProperties();
953 }
954
955
956
962 public function __construct($db)
963 {
964 $this->db = $db;
965
966 $this->ismultientitymanaged = 1;
967 $this->isextrafieldmanaged = 1;
968 $this->client = 0;
969 $this->prospect = 0;
970 $this->fournisseur = 0;
971 $this->typent_id = 0;
972 $this->effectif_id = 0;
973 $this->forme_juridique_code = 0;
974 $this->tva_assuj = 1;
975 $this->vat_reverse_charge = 0;
976 $this->status = 1;
977
978 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
979 $this->fields['address']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
980 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
981 $this->fields['town']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
982 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
983 }
984 }
985
986
995 public function create(User $user, $notrigger = 0)
996 {
997 global $langs, $conf;
998
999 $error = 0;
1000
1001 // Clean parameters
1002 if (empty($this->status)) {
1003 $this->status = 0;
1004 }
1005 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1006 $this->setUpperOrLowerCase();
1007 $this->nom = $this->name; // For backward compatibility
1008
1009 if (empty($this->client)) {
1010 $this->client = 0;
1011 }
1012 if (empty($this->fournisseur)) {
1013 $this->fournisseur = 0;
1014 }
1015 $this->import_key = trim((string) $this->import_key);
1016
1017 $this->code_compta_client = trim($this->code_compta_client ?? '');
1018
1019 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general ?? '');
1020 if ($this->accountancy_code_customer_general === '-1') {
1021 $this->accountancy_code_customer_general = '';
1022 }
1023 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1024 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general ?? '');
1025 if ($this->accountancy_code_supplier_general === '-1') {
1026 $this->accountancy_code_supplier_general = '';
1027 }
1028 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1029 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1030 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1031
1032 if (!empty($this->multicurrency_code)) {
1033 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1034 }
1035 if (empty($this->fk_multicurrency)) {
1036 $this->multicurrency_code = '';
1037 $this->fk_multicurrency = 0;
1038 }
1039
1040 dol_syslog(get_class($this)."::create ".$this->name);
1041
1042 $now = dol_now();
1043
1044 if (empty($this->date_creation)) {
1045 $this->date_creation = $now;
1046 }
1047
1048 $this->db->begin();
1049
1050 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1051 if ($this->code_client == -1 || $this->code_client === 'auto') {
1052 $this->get_codeclient($this, 0);
1053 }
1054 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1055 $this->get_codefournisseur($this, 1);
1056 }
1057
1058 // Check more parameters (including mandatory setup
1059 // If error, this->errors[] is filled
1060 $result = $this->verify();
1061
1062 if ($result >= 0) {
1063 $this->entity = setEntity($this);
1064
1065 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1066 $sql .= "nom";
1067 $sql .= ", name_alias";
1068 $sql .= ", entity";
1069 $sql .= ", datec";
1070 $sql .= ", fk_user_creat";
1071 $sql .= ", fk_typent";
1072 $sql .= ", canvas";
1073 $sql .= ", status";
1074 $sql .= ", ref_ext";
1075 $sql .= ", fk_stcomm";
1076 $sql .= ", fk_incoterms";
1077 $sql .= ", location_incoterms";
1078 $sql .= ", import_key";
1079 $sql .= ", fk_multicurrency";
1080 $sql .= ", multicurrency_code";
1081 $sql .= ", ip";
1082 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1083 $sql .= ", vat_reverse_charge";
1084 $sql .= ", accountancy_code_buy";
1085 $sql .= ", accountancy_code_sell";
1086 }
1087 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1088 $sql .= " '".$this->db->escape($this->name_alias)."',";
1089 $sql .= " ".((int) $this->entity).",";
1090 $sql .= " '".$this->db->idate($this->date_creation)."'";
1091 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1092 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1093 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1094 $sql .= ", ".((int) $this->status);
1095 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1096 $sql .= ", 0";
1097 $sql .= ", ".(int) $this->fk_incoterms;
1098 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1099 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1100 $sql .= ", ".(int) $this->fk_multicurrency;
1101 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1102 $sql .= ", ".(empty($this->ip) ? "null" : "'".$this->db->escape($this->ip)."'");
1103 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1104 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1105 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1106 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1107 }
1108 $sql .= ")";
1109
1110 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1111
1112 $result = $this->db->query($sql);
1113 if ($result) {
1114 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1115
1116 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1117
1118 // update accountancy for this entity
1119 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1120 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1121
1122 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1123 $sql .= " fk_soc";
1124 $sql .= ", entity";
1125 $sql .= ", vat_reverse_charge";
1126 $sql .= ", accountancy_code_customer_general";
1127 $sql .= ", accountancy_code_customer";
1128 $sql .= ", accountancy_code_supplier_general";
1129 $sql .= ", accountancy_code_supplier";
1130 $sql .= ", accountancy_code_buy";
1131 $sql .= ", accountancy_code_sell";
1132 $sql .= ") VALUES (";
1133 $sql .= $this->id;
1134 $sql .= ", ".((int) $conf->entity);
1135 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1136 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1137 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1138 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1139 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1140 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1141 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1142 $sql .= ")";
1143 $result = $this->db->query($sql);
1144 if (!$result) {
1145 $error++;
1146 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1147 }
1148 }
1149
1150 // Ajout du commercial affecte
1151 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1152 $this->add_commercial($user, $this->commercial_id);
1153 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1154 // si un commercial cree un client il lui est affecte automatiquement
1155 $this->add_commercial($user, $user->id);
1156 }
1157
1158 if ($ret >= 0) {
1159 if (! $notrigger) {
1160 // Call trigger
1161 $result = $this->call_trigger('COMPANY_CREATE', $user);
1162 if ($result < 0) {
1163 $error++;
1164 }
1165 // End call triggers
1166 }
1167 } else {
1168 $error++;
1169 }
1170
1171 if (!$error) {
1172 dol_syslog(get_class($this)."::Create success id=".$this->id);
1173 $this->db->commit();
1174 return $this->id;
1175 } else {
1176 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1177 $this->db->rollback();
1178 return -4;
1179 }
1180 } else {
1181 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1182 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1183 $result = -1;
1184 } else {
1185 $this->error = $this->db->lasterror();
1186 $result = -2;
1187 }
1188 $this->db->rollback();
1189 return $result;
1190 }
1191 } else {
1192 $this->db->rollback();
1193 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1194 return -3;
1195 }
1196 }
1197
1198
1199 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1209 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1210 {
1211 $error = 0;
1212
1213 $this->db->begin();
1214
1215 // phpcs:enable
1216 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1217 $contact = new Contact($this->db);
1218
1219 $contact->name = $this->name_bis;
1220 $contact->firstname = $this->firstname;
1221 $contact->civility_id = $this->civility_id;
1222 $contact->socid = $this->id; // fk_soc
1223 $contact->statut = 1; // deprecated
1224 $contact->status = 1;
1225 $contact->priv = 0;
1226 $contact->country_id = $this->country_id;
1227 $contact->state_id = $this->state_id;
1228 $contact->address = $this->address;
1229 $contact->email = $this->email;
1230 $contact->zip = $this->zip;
1231 $contact->town = $this->town;
1232 $this->setUpperOrLowerCase();
1233 $contact->phone_pro = $this->phone;
1234 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1235 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1236 }
1237
1238 $contactId = $contact->create($user, $notrigger);
1239 if ($contactId < 0) {
1240 $error++;
1241 $this->setErrorsFromObject($contact);
1242 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1243 }
1244
1245 if (empty($error) && is_array($tags) && !empty($tags)) {
1246 $result = $contact->setCategories($tags);
1247 if ($result < 0) {
1248 $error++;
1249 $this->setErrorsFromObject($contact);
1250 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1251 $contactId = $result;
1252 }
1253 }
1254
1255 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1256 $result = $contact->setNoEmail($no_email);
1257 if ($result < 0) {
1258 $this->setErrorsFromObject($contact);
1259 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1260 $contactId = $result;
1261 }
1262 }
1263
1264 if (empty($error)) {
1265 dol_syslog(get_class($this)."::create_individual success");
1266 $this->db->commit();
1267 } else {
1268 $this->db->rollback();
1269 }
1270
1271 return $contactId;
1272 }
1273
1280 public function verify()
1281 {
1282 global $langs, $mysoc;
1283
1284 $error = 0;
1285 $this->errors = array();
1286
1287 $result = 0;
1288 $this->name = trim($this->name);
1289 $this->nom = $this->name; // For backward compatibility
1290
1291 if (!$this->name) {
1292 $this->errors[] = 'ErrorBadThirdPartyName';
1293 $result = -2;
1294 }
1295
1296 if ($this->client) {
1297 $rescode = $this->check_codeclient();
1298 if ($rescode != 0 && $rescode != -5) {
1299 if ($rescode == -1) {
1300 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1301 } elseif ($rescode == -2) {
1302 $this->errors[] = 'ErrorCustomerCodeRequired';
1303 } elseif ($rescode == -3) {
1304 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1305 } elseif ($rescode == -4) {
1306 $this->errors[] = 'ErrorPrefixRequired';
1307 } else {
1308 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1309 }
1310
1311 $result = -3;
1312 }
1313 }
1314
1315 if ($this->fournisseur) {
1316 $rescode = $this->check_codefournisseur();
1317 if ($rescode != 0 && $rescode != -5) {
1318 if ($rescode == -1) {
1319 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1320 } elseif ($rescode == -2) {
1321 $this->errors[] = 'ErrorSupplierCodeRequired';
1322 } elseif ($rescode == -3) {
1323 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1324 } elseif ($rescode == -4) {
1325 $this->errors[] = 'ErrorPrefixRequired';
1326 } else {
1327 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1328 }
1329 $result = -3;
1330 }
1331 }
1332
1333 // Check for duplicate or mandatory fields defined into setup
1334 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1335 foreach ($array_to_check as $key) {
1336 $keymin = strtolower($key);
1337 $keyfield_db = $keymin;
1338 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1339 $keymin = 'code_compta_client';
1340 $keyfield_db = 'code_compta';
1341 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1342 $keymin = 'code_compta_fournisseur';
1343 $keyfield_db = 'code_compta_fournisseur';
1344 }
1345 $i = (int) preg_replace('/[^0-9]/', '', $key);
1346 $vallabel = $this->$keymin;
1347
1348 if ($i > 0) {
1349 if ($mysoc != null && $this->isACompany()) {
1350 // Check for mandatory prof id (but only if country is same than ours)
1351 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1352 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1353 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1354 $langs->load("errors");
1355 $error++;
1356 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1357 }
1358 }
1359 }
1360
1361 // Check for unicity on profid
1362 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1363 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1364 $langs->load("errors");
1365 $error++;
1366 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1367 }
1368 }
1369 } else {
1370 if ($key == 'EMAIL') {
1371 // Check for mandatory
1372 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1373 $langs->load("errors");
1374 $error++;
1375 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1376 }
1377
1378 // Check for unicity
1379 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1380 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1381 $langs->load("errors");
1382 $error++;
1383 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1384 }
1385 }
1386 } elseif ($key == 'TVA_INTRA') {
1387 // Check for unicity
1388 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1389 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1390 $langs->load("errors");
1391 $error++;
1392 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1393 }
1394 }
1395 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1396 $langs->load("errors");
1397 $error++;
1398 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1399 }
1400 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1401 // Check for unicity
1402 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1403 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1404 $langs->loadLangs(array("errors", 'compta'));
1405 $error++;
1406 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1407 }
1408 }
1409
1410 // Check for mandatory
1411 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1412 $langs->loadLangs(array("errors", 'compta'));
1413 $error++;
1414 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1415 }
1416 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1417 // Check for unicity
1418 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1419 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1420 $langs->loadLangs(array("errors", 'compta'));
1421 $error++;
1422 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1423 }
1424 }
1425
1426 // Check for mandatory
1427 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1428 $langs->loadLangs(array("errors", 'compta'));
1429 $error++;
1430 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1431 }
1432 }
1433 }
1434 }
1435
1436 if ($error) {
1437 $result = -4;
1438 }
1439
1440 return $result;
1441 }
1442
1455 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1456 {
1457 global $langs, $conf, $hookmanager;
1458
1459 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1460
1461 if (empty($id)) {
1462 $id = $this->id;
1463 }
1464 if (empty($this->country_id) && !empty($this->country_code)) {
1465 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1466 }
1467
1468 if (empty($this->country_id) && !empty($this->country_code)) {
1469 $country_id = getCountry($this->country_code, '3');
1470 $this->country_id = is_int($country_id) ? $country_id : 0;
1471 }
1472
1473 $error = 0;
1474
1475 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1476
1477 $now = dol_now();
1478
1479 // Clean parameters
1480 $this->id = $id;
1481 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1482 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1483 $this->nom = $this->name; // For backward compatibility
1484 $this->name_alias = trim((string) $this->name_alias);
1485 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1486 $this->address = trim((string) $this->address);
1487 $this->zip = trim((string) $this->zip);
1488 $this->town = trim((string) $this->town);
1489 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1490 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1491 $this->phone = trim((string) $this->phone);
1492 $this->phone = preg_replace("/\s/", "", $this->phone);
1493 $this->phone = preg_replace("/\./", "", $this->phone);
1494 $this->phone_mobile = trim((string) $this->phone_mobile);
1495 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1496 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1497 $this->fax = trim((string) $this->fax);
1498 $this->fax = preg_replace("/\s/", "", $this->fax);
1499 $this->fax = preg_replace("/\./", "", $this->fax);
1500 $this->email = trim((string) $this->email);
1501 $this->url = $this->url ? clean_url($this->url, 0) : '';
1502 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1503 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1504 $this->idprof1 = trim((string) $this->idprof1);
1505 $this->idprof2 = trim((string) $this->idprof2);
1506 $this->idprof3 = trim((string) $this->idprof3);
1507 $this->idprof4 = trim((string) $this->idprof4);
1508 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1509 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1510 $this->prefix_comm = trim((string) $this->prefix_comm);
1511 $this->outstanding_limit = price2num($this->outstanding_limit);
1512 $this->order_min_amount = price2num($this->order_min_amount);
1513 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1514
1515 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1516 $this->tva_intra = trim((string) $this->tva_intra);
1517 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1518 if (empty($this->status)) {
1519 $this->status = 0;
1520 }
1521
1522 if (!empty($this->multicurrency_code)) {
1523 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1524 }
1525 if (empty($this->fk_multicurrency)) {
1526 $this->multicurrency_code = '';
1527 $this->fk_multicurrency = 0;
1528 }
1529
1530 // Local taxes
1531 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1532 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1533
1534 $this->localtax1_value = trim($this->localtax1_value);
1535 $this->localtax2_value = trim($this->localtax2_value);
1536
1537 $this->capital = (!is_null($this->capital) && (string) $this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1538
1539 $this->effectif_id = (int) $this->effectif_id;
1540 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1541
1542 //Gencod
1543 $this->barcode = trim((string) $this->barcode);
1544
1545 // For automatic creation
1546 if ($this->code_client == -1 || $this->code_client === 'auto') {
1547 $this->get_codeclient($this, 0);
1548 }
1549 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1550 $this->get_codefournisseur($this, 1);
1551 }
1552
1553 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1554 if ($this->accountancy_code_customer_general === '-1') {
1555 $this->accountancy_code_customer_general = '';
1556 }
1557 $this->code_compta_client = trim((string) $this->code_compta_client);
1558 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1559 if ($this->accountancy_code_supplier_general === '-1') {
1560 $this->accountancy_code_supplier_general = '';
1561 }
1562 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1563
1564 // Check parameters. More tests are done later in the ->verify()
1565 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1566 $langs->load("errors");
1567 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1568 return -1;
1569 }
1570
1571 $customer = false;
1572 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1573 // If $allowmodcodeclient is set and value is not set, we generate it
1574 if (empty($this->code_compta_client)) {
1575 $ret = $this->get_codecompta('customer');
1576 if ($ret < 0) {
1577 return -1;
1578 }
1579 }
1580
1581 $customer = true;
1582 }
1583
1584 $supplier = false;
1585 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1586 // If $allowmodcodefournisseur is set and value is not set, we generate it
1587 if (empty($this->code_compta_fournisseur)) {
1588 $ret = $this->get_codecompta('supplier');
1589 if ($ret < 0) {
1590 return -1;
1591 }
1592 }
1593
1594 $supplier = true;
1595 }
1596
1597 //Web services
1598 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1599 $this->webservices_key = trim((string) $this->webservices_key);
1600
1601 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1602 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1603
1604 //Incoterms
1605 $this->fk_incoterms = (int) $this->fk_incoterms;
1606 $this->location_incoterms = trim((string) $this->location_incoterms);
1607
1608 $this->db->begin();
1609
1610 // Check name is required and codes are ok or unique.
1611 // If error, this->errors[] is filled
1612 $result = 0;
1613 if ($action != 'add' && $action != 'merge') {
1614 // We don't check when update called during a create because verify was already done.
1615 // 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
1616 $result = $this->verify();
1617
1618 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1619 // So we can update record that were using and old numbering rule.
1620 if (is_array($this->errors)) {
1621 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1622 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1623 unset($this->errors[$key]); // Remove error message
1624 }
1625 }
1626 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1627 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1628 unset($this->errors[$key]); // Remove error message
1629 }
1630 }
1631 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1632 $result = 0;
1633 }
1634 }
1635 }
1636 $this->setUpperOrLowerCase();
1637 if ($result >= 0) {
1638 dol_syslog(get_class($this)."::update verify ok or not done");
1639
1640 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1641 $sql .= "entity = ".((int) $this->entity);
1642 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1643 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1644 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1645 $sql .= ",address = '".$this->db->escape($this->address)."'";
1646
1647 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1648 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1649
1650 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1651 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1652
1653 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1654 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1655 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1656 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1657 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1658 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1659
1660 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1661
1662 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1663 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1664
1665 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1666 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1667 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1668 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1669 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1670 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1671
1672 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape((string) $this->tva_assuj)."'" : "null");
1673 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1674 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1675 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape((string) $this->vat_reverse_charge) . "'" : 0);
1676 }
1677 $sql .= ",status = ".((int) $this->status);
1678
1679 // Local taxes
1680 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape((string) $this->localtax1_assuj)."'" : "null");
1681 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape((string) $this->localtax2_assuj)."'" : "null");
1682 if ($this->localtax1_assuj == 1) {
1683 if ($this->localtax1_value != '') {
1684 $sql .= ", localtax1_value = ".((float) $this->localtax1_value);
1685 } else {
1686 $sql .= ", localtax1_value = 0.000";
1687 }
1688 } else {
1689 $sql .= ",localtax1_value =0.000";
1690 }
1691
1692 if ($this->localtax2_assuj == 1) {
1693 if ($this->localtax2_value != '') {
1694 $sql .= ",localtax2_value = ".((float) $this->localtax2_value);
1695 } else {
1696 $sql .= ",localtax2_value = 0.000";
1697 }
1698 } else {
1699 $sql .= ",localtax2_value = 0.000";
1700 }
1701
1702 $sql .= ",capital = ".($this->capital === null ? "null" : (float) $this->capital);
1703
1704 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1705
1706 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1707 if (isset($this->stcomm_id)) {
1708 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1709 }
1710 if (isset($this->typent_id)) {
1711 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1712 }
1713
1714 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape((string) $this->forme_juridique_code)."'" : "null");
1715 $sql .= ",birth = ".(!empty($this->birth) ? "'".$this->db->idate($this->birth)."'" : "null");
1716
1717 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape((string) $this->mode_reglement_id)."'" : "null");
1718 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape((string) $this->cond_reglement_id)."'" : "null");
1719 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null");
1720 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape((string) $this->transport_mode_id)."'" : "null");
1721 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape((string) $this->mode_reglement_supplier_id)."'" : "null");
1722 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape((string) $this->cond_reglement_supplier_id)."'" : "null");
1723 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape((string) $this->transport_mode_supplier_id)."'" : "null");
1724 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape((string) $this->shipping_method_id)."'" : "null");
1725
1726 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1727 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1728 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1729 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1730 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1731 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1732 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1733 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1734 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1735 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1736 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1737 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1738 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1739 if ($customer) {
1740 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1741 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1742 }
1743
1744 if ($supplier) {
1745 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1746 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1747 }
1748 }
1749 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1750 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1751
1752 //Incoterms
1753 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1754 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1755
1756 if ($customer) {
1757 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1758 }
1759
1760 if ($supplier) {
1761 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1762 }
1763 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1764 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1765 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1766 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1767 $sql .= " WHERE rowid = ".(int) $id;
1768
1769 $resql = $this->db->query($sql);
1770 if ($resql) {
1771 if (is_object($this->oldcopy)) { // If we have information on old values
1772 if ($this->oldcopy->country_id != $this->country_id) {
1773 unset($this->country_code);
1774 unset($this->country);
1775 }
1776 if ($this->oldcopy->state_id != $this->state_id) {
1777 unset($this->state_code);
1778 unset($this->state);
1779 }
1780 } else {
1781 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1782 unset($this->country);
1783 unset($this->state_code);
1784 unset($this->state);
1785 }
1786
1787 $nbrowsaffected = $this->db->affected_rows($resql);
1788
1789 if ($nbrowsaffected) {
1790 // Update information on linked member if it is an update
1791 if (!$nosyncmember && isModEnabled('member')) {
1792 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1793
1794 dol_syslog(get_class($this)."::update update linked member");
1795
1796 $lmember = new Adherent($this->db);
1797 $result = $lmember->fetch(0, '0', $this->id);
1798
1799 if ($result > 0) {
1800 $lmember->company = $this->name;
1801 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1802 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1803 $lmember->address = $this->address;
1804 $lmember->zip = $this->zip;
1805 $lmember->town = $this->town;
1806 $lmember->email = $this->email;
1807 $lmember->socialnetworks = $this->socialnetworks;
1808 $lmember->phone = $this->phone;
1809 $lmember->state_id = $this->state_id;
1810 $lmember->country_id = $this->country_id;
1811 $lmember->default_lang = $this->default_lang;
1812
1813 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1814 if ($result < 0) {
1815 $this->setErrorsFromObject($lmember);
1816 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1817 $error++;
1818 }
1819 } elseif ($result < 0) {
1820 $this->error = $lmember->error;
1821 $error++;
1822 }
1823 }
1824 }
1825
1826 $action = 'update';
1827
1828 // update accountancy for this entity
1829 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1830 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1831
1832 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1833 $sql .= " fk_soc";
1834 $sql .= ", entity";
1835 $sql .= ", vat_reverse_charge";
1836 $sql .= ", accountancy_code_customer_general";
1837 $sql .= ", accountancy_code_customer";
1838 $sql .= ", accountancy_code_supplier_general";
1839 $sql .= ", accountancy_code_supplier";
1840 $sql .= ", accountancy_code_buy";
1841 $sql .= ", accountancy_code_sell";
1842 $sql .= ") VALUES (";
1843 $sql .= $this->id;
1844 $sql .= ", ".((int) $conf->entity);
1845 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1846 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1847 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1848 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1849 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1850 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1851 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1852 $sql .= ")";
1853 $result = $this->db->query($sql);
1854 if (!$result) {
1855 $error++;
1856 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1857 }
1858 }
1859
1860 // Actions on extra fields
1861 if (!$error) {
1862 $result = $this->insertExtraFields();
1863 if ($result < 0) {
1864 $error++;
1865 }
1866 }
1867 // Actions on extra languages
1868 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1869 $result = $this->insertExtraLanguages();
1870 if ($result < 0) {
1871 $error++;
1872 }
1873 }
1874
1875 if (!$error && $call_trigger) {
1876 // Call trigger
1877 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1878 if ($result < 0) {
1879 $error++;
1880 }
1881 // End call triggers
1882 }
1883
1884 if (!$error) {
1885 dol_syslog(get_class($this)."::Update success");
1886 $this->db->commit();
1887 return 1;
1888 } else {
1889 $this->db->rollback();
1890 return -1;
1891 }
1892 } else {
1893 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1894 // Doublon
1895 $this->error = $langs->trans("ErrorDuplicateField");
1896 $result = -1;
1897 } else {
1898 $this->error = $this->db->lasterror();
1899 $result = -2;
1900 }
1901 $this->db->rollback();
1902 return $result;
1903 }
1904 } else {
1905 $this->db->rollback();
1906 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1907 return -3;
1908 }
1909 }
1910
1930 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1931 {
1932 global $langs;
1933 global $conf;
1934
1935 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)) {
1936 return -1;
1937 }
1938
1939 $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';
1940 $sql .= ', s.status, s.fk_warehouse';
1941 $sql .= ', s.price_level';
1942 $sql .= ', GREATEST(s.tms, sef.tms) as date_modification, s.fk_user_creat, s.fk_user_modif';
1943 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1944 $sql .= ', s.socialnetworks';
1945 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1946 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1947 $sql .= ', s.capital, s.tva_intra';
1948 $sql .= ', s.fk_typent as typent_id';
1949 $sql .= ', s.fk_effectif as effectif_id';
1950 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1951 $sql .= ', s.birth';
1952 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1953 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1954 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1955 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1956 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1957 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1958 } else {
1959 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1960 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1961 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1962 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1963 }
1964 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1965 $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';
1966 $sql .= ', s.fk_account, s.tva_assuj';
1967 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1968 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1969 $sql .= ', s.fk_shipping_method';
1970 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1971 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1972 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1973 $sql .= ', fj.libelle as forme_juridique';
1974 $sql .= ', e.libelle as effectif';
1975 $sql .= ', c.code as country_code, c.label as country';
1976 $sql .= ', d.code_departement as state_code, d.nom as state';
1977 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1978 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1979 $sql .= ', te.code as typent_code';
1980 $sql .= ', i.libelle as label_incoterms';
1981 if (!isModEnabled('multicompany')) {
1982 $sql .= ', s.remise_client, s.remise_supplier';
1983 } else {
1984 $sql .= ', sr.remise_client, sr2.remise_supplier';
1985 }
1986 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1987 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_extrafields as sef ON sef.fk_object=s.rowid';
1988 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1989 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1990 }
1991 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1992 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1993 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1994 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1995 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1996 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1997 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1998 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1999 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
2000 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
2001 if (isModEnabled('multicompany')) {
2002 $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').'))';
2003 $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').'))';
2004 }
2005 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2006
2007 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
2008 if ($is_client) {
2009 $sql .= ' AND s.client > 0';
2010 }
2011 if ($is_supplier) {
2012 $sql .= ' AND s.fournisseur > 0';
2013 } // if both false, no test (the thirdparty can be client and/or supplier)
2014
2015 if ($rowid) {
2016 $sql .= ' AND s.rowid = '.((int) $rowid);
2017 }
2018 if ($ref) {
2019 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
2020 }
2021 if ($ref_alias) {
2022 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
2023 }
2024 if ($ref_ext) {
2025 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
2026 }
2027 if ($barcode) {
2028 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
2029 }
2030 if ($idprof1) {
2031 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2032 }
2033 if ($idprof2) {
2034 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2035 }
2036 if ($idprof3) {
2037 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2038 }
2039 if ($idprof4) {
2040 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2041 }
2042 if ($idprof5) {
2043 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2044 }
2045 if ($idprof6) {
2046 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2047 }
2048 if ($email) {
2049 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2050 }
2051
2052 $resql = $this->db->query($sql);
2053 if ($resql) {
2054 $num = $this->db->num_rows($resql);
2055 if ($num > 1) {
2056 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2057 dol_syslog($this->error, LOG_WARNING);
2058 $result = -2;
2059 } elseif ($num) { // $num = 1
2060 $obj = $this->db->fetch_object($resql);
2061
2062 $this->id = $obj->rowid;
2063 $this->entity = $obj->entity;
2064 $this->canvas = $obj->canvas;
2065
2066 $this->ref = $obj->name;
2067 $this->name = $obj->name;
2068 $this->nom = $obj->name; // deprecated
2069 $this->name_alias = $obj->name_alias;
2070 $this->ref_ext = $obj->ref_ext;
2071
2072 $this->date_creation = $this->db->jdate($obj->date_creation);
2073 $this->date_modification = $this->db->jdate($obj->date_modification);
2074 $this->user_creation_id = $obj->fk_user_creat;
2075 $this->user_modification_id = $obj->fk_user_modif;
2076
2077 $this->address = $obj->address;
2078 $this->zip = $obj->zip;
2079 $this->town = $obj->town;
2080
2081 $this->country_id = $obj->country_id;
2082 $this->country_code = $obj->country_id ? $obj->country_code : '';
2083 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2084
2085 $this->state_id = $obj->state_id;
2086 $this->state_code = $obj->state_code;
2087 $this->region_id = $obj->region_id;
2088 $this->region_code = $obj->region_code;
2089 $this->state = ($obj->state != '-' ? $obj->state : '');
2090
2091 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2092 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2093 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2094 $this->status_prospect_label = $label; // label status prospect
2095 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2096
2097 $this->email = $obj->email;
2098 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2099
2100 $this->url = $obj->url;
2101 $this->phone = $obj->phone;
2102 $this->phone_mobile = $obj->phone_mobile;
2103 $this->fax = $obj->fax;
2104
2105 $this->parent = $obj->parent;
2106
2107 $this->idprof1 = $obj->idprof1;
2108 $this->idprof2 = $obj->idprof2;
2109 $this->idprof3 = $obj->idprof3;
2110 $this->idprof4 = $obj->idprof4;
2111 $this->idprof5 = $obj->idprof5;
2112 $this->idprof6 = $obj->idprof6;
2113
2114 $this->capital = $obj->capital;
2115
2116 $this->code_client = $obj->code_client;
2117 $this->code_fournisseur = $obj->code_fournisseur;
2118
2119 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2120 $this->code_compta_client = $obj->code_compta;
2121 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2122 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2123
2124 $this->barcode = $obj->barcode;
2125
2126 $this->tva_assuj = $obj->tva_assuj;
2127 $this->tva_intra = $obj->tva_intra;
2128
2129 if (!empty($obj->spe_vat_reverse_charge)) {
2130 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2131 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2132 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2133 } else {
2134 $this->vat_reverse_charge = 0;
2135 }
2136
2137 $this->status = $obj->status;
2138
2139 // Local Taxes
2140 $this->localtax1_assuj = $obj->localtax1_assuj;
2141 $this->localtax2_assuj = $obj->localtax2_assuj;
2142
2143 $this->localtax1_value = $obj->localtax1_value;
2144 $this->localtax2_value = $obj->localtax2_value;
2145
2146 $this->typent_id = $obj->typent_id;
2147 $this->typent_code = $obj->typent_code;
2148
2149 $this->effectif_id = $obj->effectif_id;
2150 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2151
2152 $this->forme_juridique_code = $obj->forme_juridique_code;
2153 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2154 $this->birth = $this->db->jdate($obj->birth);
2155
2156 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2157
2158 $this->prefix_comm = $obj->prefix_comm;
2159
2160 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2161 $this->remise_supplier_percent = $obj->remise_supplier;
2162
2163 $this->mode_reglement_id = $obj->mode_reglement;
2164 $this->cond_reglement_id = $obj->cond_reglement;
2165 $this->deposit_percent = $obj->deposit_percent;
2166 $this->transport_mode_id = $obj->transport_mode;
2167 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2168 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2169 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2170 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2171 $this->fk_account = $obj->fk_account;
2172
2173 $this->client = $obj->client;
2174 $this->fournisseur = $obj->fournisseur;
2175
2176 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2177 $this->note_private = $obj->note_private;
2178 $this->note_public = $obj->note_public;
2179 $this->model_pdf = $obj->model_pdf;
2180 $this->default_lang = $obj->default_lang;
2181 $this->logo = $obj->logo;
2182 $this->logo_squarred = $obj->logo_squarred;
2183
2184 $this->webservices_url = $obj->webservices_url;
2185 $this->webservices_key = $obj->webservices_key;
2186
2187 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2188 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2189
2190 $this->outstanding_limit = $obj->outstanding_limit;
2191 $this->order_min_amount = $obj->order_min_amount;
2192 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2193
2194 // multiprix
2195 $this->price_level = $obj->price_level;
2196
2197 // warehouse
2198 $this->fk_warehouse = $obj->fk_warehouse;
2199
2200 $this->import_key = $obj->import_key;
2201
2202 //Incoterms
2203 $this->fk_incoterms = $obj->fk_incoterms;
2204 $this->location_incoterms = $obj->location_incoterms;
2205 $this->label_incoterms = $obj->label_incoterms;
2206
2207 // multicurrency
2208 $this->fk_multicurrency = $obj->fk_multicurrency;
2209 $this->multicurrency_code = $obj->multicurrency_code;
2210
2211 // pdf
2212 $this->model_pdf = $obj->model_pdf;
2213 $this->last_main_doc = $obj->last_main_doc;
2214
2215 $result = $this->id;
2216
2217 // fetch optionals attributes and labels
2218 $this->fetch_optionals();
2219 } else {
2220 $result = 0;
2221 }
2222
2223 $this->db->free($resql);
2224 } else {
2225 $this->error = $this->db->lasterror();
2226 $this->errors[] = $this->db->lasterror();
2227 $result = -3;
2228 }
2229
2230 // Use first price level if level not defined for third party
2231 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2232 $this->price_level = 1;
2233 }
2234
2235 return $result;
2236 }
2237
2258 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2259 {
2260 // A rowid is known, it is a unique key so we found it
2261 if ($rowid) {
2262 return $rowid;
2263 }
2264
2265 dol_syslog(get_class($this)."::findNearest", LOG_DEBUG);
2266 $tmpthirdparty = new Societe($this->db);
2267
2268 // We try to find the thirdparty with exact matching on all fields
2269 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2270 if ($result != 0) {
2271 return $result;
2272 }
2273
2274 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2275 dol_syslog("Thirdparty not found with exact match so we try barcode search", LOG_DEBUG);
2276 if ($barcode) {
2277 $result = $tmpthirdparty->fetch(0, '', '', $barcode, '', '', '', '', '', '', '', '', $is_client, $is_supplier);
2278 if ($result != 0) {
2279 return $result;
2280 }
2281 }
2282
2283 $sqlstart = "SELECT s.rowid as id FROM ".MAIN_DB_PREFIX."societe as s";
2284 $sqlstart .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2285 if ($is_client) {
2286 $sqlstart .= ' AND s.client > 0';
2287 }
2288 if ($is_supplier) {
2289 $sqlstart .= ' AND s.fournisseur > 0';
2290 } // if both false, no test (the thirdparty can be client and/or supplier)
2291
2292 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2293 dol_syslog("Thirdparty not found with barcode search so we try profids search", LOG_DEBUG);
2294 $sqlprof = "";
2295 if ($idprof1) {
2296 $sqlprof .= " s.siren = '".$this->db->escape($idprof1)."'";
2297 }
2298 if ($idprof2) {
2299 if ($sqlprof) {
2300 $sqlprof .= " OR";
2301 }
2302 $sqlprof .= " s.siret = '".$this->db->escape($idprof2)."'";
2303 }
2304 if ($idprof3) {
2305 if ($sqlprof) {
2306 $sqlprof .= " OR";
2307 }
2308 $sqlprof .= " s.ape = '".$this->db->escape($idprof3)."'";
2309 }
2310 if ($idprof4) {
2311 if ($sqlprof) {
2312 $sqlprof .= " OR";
2313 }
2314 $sqlprof .= " s.idprof4 = '".$this->db->escape($idprof4)."'";
2315 }
2316 if ($idprof5) {
2317 if ($sqlprof) {
2318 $sqlprof .= " OR";
2319 }
2320 $sqlprof .= " s.idprof5 = '".$this->db->escape($idprof5)."'";
2321 }
2322 if ($idprof6) {
2323 if ($sqlprof) {
2324 $sqlprof .= " OR";
2325 }
2326 $sqlprof .= " s.idprof6 = '".$this->db->escape($idprof6)."'";
2327 }
2328
2329 if ($sqlprof) {
2330 $sqlprofquery = $sqlstart . " AND (".$sqlprof." )";
2331 $resql = $this->db->query($sqlprofquery);
2332 if ($resql) {
2333 $num = $this->db->num_rows($resql);
2334 if ($num > 1) {
2335 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2336 dol_syslog($this->error, LOG_WARNING);
2337 $result = -2;
2338 } elseif ($num) {
2339 $obj = $this->db->fetch_object($resql);
2340 $result = $obj->id;
2341 } else {
2342 $result = 0;
2343 }
2344 } else {
2345 $this->error = $this->db->lasterror();
2346 $this->errors[] = $this->db->lasterror();
2347 $result = -3;
2348 }
2349 if ($result != 0) {
2350 return $result;
2351 }
2352 }
2353
2354 // Then search on email (+ restriction on is_client and is_supplier)
2355 dol_syslog("Thirdparty not found with profids search so we try email search", LOG_DEBUG);
2356 if ($email) {
2357 $result = $tmpthirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email, '', $is_client, $is_supplier);
2358 if ($result != 0) {
2359 return $result;
2360 }
2361 }
2362
2363 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2364 dol_syslog("Thirdparty not found with email search so we try ref, ref_ext or ref_alias search", LOG_DEBUG);
2365 $sqlref = "";
2366 if ($ref) {
2367 $sqlref .= " s.nom = '".$this->db->escape($ref)."'";
2368 }
2369 if ($ref_alias) {
2370 if ($sqlref) {
2371 $sqlref .= " OR";
2372 }
2373 $sqlref .= " s.name_alias = '".$this->db->escape($ref_alias)."'";
2374 }
2375 if ($ref_ext) {
2376 if ($sqlref) {
2377 $sqlref .= " OR";
2378 }
2379 $sqlref .= " s.ref_ext = '".$this->db->escape($ref_ext)."'";
2380 }
2381
2382 if ($sqlref) {
2383 $sqlrefquery = $sqlstart . " AND (".$sqlref." )";
2384 $resql = $this->db->query($sqlrefquery);
2385 if ($resql) {
2386 $num = $this->db->num_rows($resql);
2387 if ($num > 1) {
2388 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2389 dol_syslog($this->error, LOG_WARNING);
2390 $result = -2;
2391 } elseif ($num) {
2392 $obj = $this->db->fetch_object($resql);
2393 $result = $obj->id;
2394 } else {
2395 $result = 0;
2396 }
2397 } else {
2398 $this->error = $this->db->lasterror();
2399 $this->errors[] = $this->db->lasterror();
2400 $result = -3;
2401 }
2402 }
2403 return $result;
2404 }
2405
2414 public function delete($id, $fuser = null, $call_trigger = 1)
2415 {
2416 global $conf, $user;
2417
2418 if (empty($fuser)) {
2419 $fuser = $user;
2420 }
2421
2422 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2423
2424 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2425
2426 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2427 $error = 0;
2428
2429 // Test if child exists
2430 $objectisused = $this->isObjectUsed($id);
2431 if (empty($objectisused)) {
2432 $this->db->begin();
2433
2434 // User is mandatory for trigger call
2435 if ($call_trigger) {
2436 // Call trigger
2437 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2438 if ($result < 0) {
2439 $error++;
2440 }
2441 // End call triggers
2442 }
2443
2444 if (!$error) {
2445 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2446 $static_cat = new Categorie($this->db);
2447 $toute_categs = array();
2448
2449 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2450 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2451 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2452
2453 // Remove each "Categorie"
2454 foreach ($toute_categs as $type => $categs_type) {
2455 foreach ($categs_type as $cat) {
2456 $cat->del_type($this, $type);
2457 }
2458 }
2459 }
2460
2461 if (!$error) {
2462 foreach ($this->childtablesoncascade as $tabletodelete) {
2463 $deleteFromObject = explode(':', $tabletodelete, 4);
2464 if (count($deleteFromObject) >= 2) {
2465 $className = str_replace('@', '', $deleteFromObject[0]);
2466 $filepath = $deleteFromObject[1];
2467 $columnName = $deleteFromObject[2];
2468 if (dol_include_once($filepath)) {
2469 $child_object = new $className($this->db);
2470 '@phan-var-force CommonObject $child_object';
2471 $result = $child_object->deleteByParentField($id, $columnName);
2472 if ($result < 0) {
2473 $error++;
2474 $this->errors[] = $child_object->error;
2475 break;
2476 }
2477 } else {
2478 $error++;
2479 $this->errors[] = 'Cannot include child class file '.$filepath;
2480 break;
2481 }
2482 } else {
2483 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2484 $sql .= " WHERE fk_soc = ".((int) $id);
2485 if (!$this->db->query($sql)) {
2486 $error++;
2487 $this->errors[] = $this->db->lasterror();
2488 break;
2489 }
2490 }
2491 }
2492 }
2493
2494 // Removed extrafields
2495 if (!$error) {
2496 $result = $this->deleteExtraFields();
2497 if ($result < 0) {
2498 $error++;
2499 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2500 }
2501 }
2502
2503 // Remove links to subsidiaries companies
2504 if (!$error) {
2505 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2506 $sql .= " SET parent = NULL";
2507 $sql .= " WHERE parent = ".((int) $id);
2508 if (!$this->db->query($sql)) {
2509 $error++;
2510 $this->errors[] = $this->db->lasterror();
2511 }
2512 }
2513
2514 // Remove third party
2515 if (!$error) {
2516 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2517 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2518 $sql .= " WHERE fk_soc = ".((int) $id);
2519 if (!$this->db->query($sql)) {
2520 $error++;
2521 $this->errors[] = $this->db->lasterror();
2522 }
2523 }
2524
2525 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2526 $sql .= " WHERE rowid = ".((int) $id);
2527 if (!$this->db->query($sql)) {
2528 $error++;
2529 $this->errors[] = $this->db->lasterror();
2530 }
2531 }
2532
2533 if (!$error) {
2534 $this->db->commit();
2535
2536 // Delete directory
2537 if (!empty($conf->societe->multidir_output[$entity])) {
2538 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2539 if (dol_is_dir($docdir)) {
2540 dol_delete_dir_recursive($docdir);
2541 }
2542 }
2543
2544 return 1;
2545 } else {
2546 dol_syslog($this->error, LOG_ERR);
2547 $this->db->rollback();
2548 return -1;
2549 }
2550 } else {
2551 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2552 }
2553 return 0;
2554 }
2555
2556 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2564 public function set_as_client()
2565 {
2566 // phpcs:enable
2567 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2568 return $this->setAsCustomer();
2569 }
2570
2577 public function setAsCustomer()
2578 {
2579 if ($this->id) {
2580 $newclient = 1;
2581 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2582 $newclient = 3; //If prospect, we keep prospect tag
2583 }
2584 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2585 $sql .= " SET client = ".((int) $newclient);
2586 $sql .= " WHERE rowid = ".((int) $this->id);
2587
2588 $resql = $this->db->query($sql);
2589 if ($resql) {
2590 $this->client = $newclient;
2591 return 1;
2592 } else {
2593 return -1;
2594 }
2595 }
2596 return 0;
2597 }
2598
2599 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2608 public function set_remise_client($remise, $note, User $user)
2609 {
2610 // phpcs:enable
2611 global $conf, $langs;
2612
2613 // Parameter cleaning
2614 $note = trim($note);
2615 if (!$note) {
2616 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2617 return -2;
2618 }
2619
2620 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2621
2622 if ($this->id) {
2623 $this->db->begin();
2624
2625 $now = dol_now();
2626
2627 // Position current discount
2628 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2629 $sql .= " SET remise_client = '".$this->db->escape((string) $remise)."'";
2630 $sql .= " WHERE rowid = ".((int) $this->id);
2631 $resql = $this->db->query($sql);
2632 if (!$resql) {
2633 $this->db->rollback();
2634 $this->error = $this->db->error();
2635 return -1;
2636 }
2637
2638 // Writes trace in discount history
2639 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2640 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2641 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape((string) $remise)."',";
2642 $sql .= " '".$this->db->escape($note)."',";
2643 $sql .= " ".((int) $user->id);
2644 $sql .= ")";
2645
2646 $resql = $this->db->query($sql);
2647 if (!$resql) {
2648 $this->db->rollback();
2649 $this->error = $this->db->lasterror();
2650 return -1;
2651 }
2652
2653 $this->db->commit();
2654
2655 return 1;
2656 }
2657 return -1;
2658 }
2659
2660 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2669 public function set_remise_supplier($remise, $note, User $user)
2670 {
2671 // phpcs:enable
2672 global $conf, $langs;
2673
2674 // Parameter cleaning
2675 $note = trim($note);
2676 if (!$note) {
2677 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2678 return -2;
2679 }
2680
2681 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2682
2683 if ($this->id) {
2684 $this->db->begin();
2685
2686 $now = dol_now();
2687
2688 // Position current discount
2689 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2690 $sql .= " SET remise_supplier = ".((float) $remise);
2691 $sql .= " WHERE rowid = ".((int) $this->id);
2692 $resql = $this->db->query($sql);
2693 if (!$resql) {
2694 $this->db->rollback();
2695 $this->error = $this->db->error();
2696 return -1;
2697 }
2698
2699 // Writes trace in discount history
2700 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2701 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2702 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((float) $remise).",";
2703 $sql .= " '".$this->db->escape($note)."',";
2704 $sql .= " ".((int) $user->id);
2705 $sql .= ")";
2706
2707 $resql = $this->db->query($sql);
2708 if (!$resql) {
2709 $this->db->rollback();
2710 $this->error = $this->db->lasterror();
2711 return -1;
2712 }
2713
2714 $this->db->commit();
2715 return 1;
2716 }
2717
2718 return -1;
2719 }
2720
2721 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2733 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2734 {
2735 // phpcs:enable
2736 global $langs;
2737
2738 // Clean parameters
2739 $remise = (float) price2num($remise);
2740 $desc = trim($desc);
2741
2742 // Check parameters
2743 if (!($remise > 0)) {
2744 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2745 return -1;
2746 }
2747 if (!$desc) {
2748 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2749 return -2;
2750 }
2751
2752 if ($this->id > 0) {
2753 // Clean vat code
2754 $reg = array();
2755 $vat_src_code = '';
2756 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2757 $vat_src_code = $reg[1];
2758 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2759 }
2760
2761 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2762
2763 $discount = new DiscountAbsolute($this->db);
2764 $discount->fk_soc = $this->id;
2765 $discount->socid = $this->id;
2766
2767 $discount->discount_type = $discount_type;
2768 $discount->multicurrency_code = $this->multicurrency_code;
2769 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2770 $discount->multicurrency_tx = $this->multicurrency_tx;
2771
2772 if ($price_base_type == 'TTC') {
2773 $discount->total_ttc = (float) price2num($remise, 'MT');
2774 $discount->total_ht = (float) price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2775 $discount->total_tva = (float) price2num((float) $discount->total_ttc - (float) $discount->total_ht, 'MT');
2776
2777 $discount->multicurrency_total_ttc = (float) price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2778 $discount->multicurrency_total_ht = (float) price2num(((float) $remise / (1 + (float) $vatrate / 100)) * (float) $discount->multicurrency_tx, 'MT');
2779 $discount->multicurrency_total_tva = (float) price2num(((float) $discount->total_ttc - (float) $discount->total_ht) * (float) $discount->multicurrency_tx, 'MT');
2780 } else {
2781 $discount->total_ht = (float) price2num($remise, 'MT');
2782 $discount->total_tva = (float) price2num((float) $remise * (float) $vatrate / 100, 'MT');
2783 $discount->total_ttc = (float) price2num((float) $discount->total_ht + (float) $discount->total_tva, 'MT');
2784
2785 $discount->multicurrency_total_ht = (float) price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2786 $discount->multicurrency_total_tva = (float) price2num(((float) $remise * (float) $vatrate / 100) * (float) $discount->multicurrency_tx, 'MT');
2787 $discount->multicurrency_total_ttc = (float) price2num(((float) $discount->total_ht + (float) $discount->total_tva) * (float) $discount->multicurrency_tx, 'MT');
2788 }
2789
2790 // For backward compatibility
2791 $discount->amount_ht = $discount->total_ht;
2792 $discount->amount_tva = $discount->total_tva;
2793 $discount->amount_ttc = $discount->total_ttc;
2794 $discount->multicurrency_amount_ht = $discount->multicurrency_total_ht;
2795 $discount->multicurrency_amount_tva = $discount->multicurrency_total_tva;
2796 $discount->multicurrency_amount_ttc = $discount->multicurrency_total_ttc;
2797
2798
2799 $discount->tva_tx = (float) price2num($vatrate);
2800 $discount->vat_src_code = $vat_src_code;
2801
2802 $discount->description = $desc;
2803
2804 $result = $discount->create($user);
2805 if ($result > 0) {
2806 return $result;
2807 } else {
2808 $this->error = $discount->error;
2809 return -3;
2810 }
2811 } else {
2812 return 0;
2813 }
2814 }
2815
2825 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2826 {
2827 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2828
2829 $discountstatic = new DiscountAbsolute($this->db);
2830 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2831 if ($result >= 0) {
2832 return $result;
2833 } else {
2834 $this->error = $discountstatic->error;
2835 return -1;
2836 }
2837 }
2838
2839
2846 public function getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type = 0)
2847 {
2848 global $conf;
2849
2850 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ttc) as amount, SUM(f.multicurrency_total_ttc) as multicurrency_amount";
2851 if (!empty($discount_type)) {
2852 $sql .= " FROM ".$this->db->prefix()."facture_fourn as f";
2853 } else {
2854 $sql .= " FROM ".$this->db->prefix()."facture as f";
2855 }
2856 $sql .= " WHERE f.entity = ".$conf->entity;
2857 $sql .= " AND paye = 0 AND fk_statut = 1";
2858 $sql .= " AND f.type = ".CommonInvoice::TYPE_CREDIT_NOTE;
2859 $sql .= " AND NOT EXISTS (SELECT rowid FROM ".$this->db->prefix()."societe_remise_except as rc";
2860 $sql .= " WHERE rc.discount_type = ".((int) $discount_type);
2861 if (!empty($discount_type)) {
2862 $sql .= " AND rc.fk_invoice_supplier = f.rowid";
2863 } else {
2864 $sql .= " AND rc.fk_facture = f.rowid";
2865 }
2866 $sql .= " AND rc.fk_soc = ".((int) $this->id);
2867 $sql .= ")";
2868 $sql .= " AND f.fk_soc = ".((int) $this->id);
2869
2870 $resql = $this->db->query($sql);
2871 if ($resql) {
2872 $obj = $this->db->fetch_object($resql);
2873
2874 return $obj->nb;
2875 }
2876
2877 return -1;
2878 }
2879
2880
2890 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2891 {
2892 global $conf;
2893
2894 $reparray = array();
2895
2896 $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";
2897 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2898 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2899 // Condition here should be the same than into select_dolusers()
2900 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2901 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2902 } else {
2903 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
2904 }
2905
2906 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2907 if (empty($sortfield)) {
2908 $sortfield = 'u.lastname,u.firstname';
2909 }
2910 if (empty($sortorder)) {
2911 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
2912 }
2913 $sql .= $this->db->order($sortfield, $sortorder);
2914
2915 $resql = $this->db->query($sql);
2916 if ($resql) {
2917 $num = $this->db->num_rows($resql);
2918 $i = 0;
2919 while ($i < $num) {
2920 $obj = $this->db->fetch_object($resql);
2921
2922 if (empty($mode)) {
2923 $reparray[$i]['id'] = (int) $obj->rowid;
2924 $reparray[$i]['lastname'] = $obj->lastname;
2925 $reparray[$i]['firstname'] = $obj->firstname;
2926 $reparray[$i]['email'] = $obj->email;
2927 $reparray[$i]['phone'] = $obj->office_phone;
2928 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2929 $reparray[$i]['office_fax'] = $obj->office_fax;
2930 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2931 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2932 $reparray[$i]['job'] = $obj->job;
2933 $reparray[$i]['statut'] = $obj->status; // deprecated
2934 $reparray[$i]['status'] = $obj->status;
2935 $reparray[$i]['entity'] = $obj->entity;
2936 $reparray[$i]['login'] = $obj->login;
2937 $reparray[$i]['photo'] = $obj->photo;
2938 $reparray[$i]['gender'] = $obj->gender;
2939 } else {
2940 $reparray[] = (int) $obj->rowid;
2941 }
2942 $i++;
2943 }
2944 return $reparray;
2945 } else {
2946 dol_print_error($this->db);
2947 return -1;
2948 }
2949 }
2950
2958 public function setPriceLevel($price_level, User $user)
2959 {
2960 if ($this->id) {
2961 $now = dol_now();
2962
2963 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2964 $sql .= " SET price_level = ".((int) $price_level);
2965 $sql .= " WHERE rowid = ".((int) $this->id);
2966
2967 if (!$this->db->query($sql)) {
2968 dol_print_error($this->db);
2969 return -1;
2970 }
2971
2972 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2973 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2974 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2975
2976 if (!$this->db->query($sql)) {
2977 dol_print_error($this->db);
2978 return -1;
2979 }
2980 return 1;
2981 }
2982 return -1;
2983 }
2984
2985 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2993 public function add_commercial(User $user, $commid)
2994 {
2995 // phpcs:enable
2996 $error = 0;
2997
2998 if ($this->id > 0 && $commid > 0) {
2999 $this->db->begin();
3000
3001 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
3002 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3003
3004 $resql = $this->db->query($sql);
3005 if (!$resql) {
3006 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3007 $error++;
3008 }
3009
3010 if (!$error) {
3011 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
3012 $sql .= " (fk_soc, fk_user)";
3013 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
3014
3015 $resql = $this->db->query($sql);
3016 if (!$resql) {
3017 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3018 $error++;
3019 }
3020 }
3021
3022 if (!$error) {
3023 $this->context = array('commercial_modified' => $commid);
3024
3025 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3026 if ($result < 0) {
3027 $error++;
3028 }
3029 }
3030
3031 if (!$error) {
3032 $this->db->commit();
3033 return 1;
3034 } else {
3035 $this->db->rollback();
3036 return -1;
3037 }
3038 }
3039
3040 return 0;
3041 }
3042
3043 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3051 public function del_commercial(User $user, $commid)
3052 {
3053 // phpcs:enable
3054 $error = 0;
3055 $this->context = array('commercial_modified' => $commid);
3056
3057 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3058 if ($result < 0) {
3059 $error++;
3060 }
3061
3062 if ($this->id > 0 && $commid > 0) {
3063 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3064 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3065
3066 if (!$this->db->query($sql)) {
3067 $error++;
3068 dol_syslog(get_class($this)."::del_commercial Erreur");
3069 }
3070 }
3071
3072 if ($error) {
3073 return -1;
3074 } else {
3075 return 1;
3076 }
3077 }
3078
3086 public function getTooltipContentArray($params)
3087 {
3088 global $conf, $langs, $user;
3089
3090 $langs->loadLangs(['companies', 'commercial']);
3091
3092 $datas = array();
3093
3094 $option = $params['option'] ?? '';
3095 $nofetch = !empty($params['nofetch']);
3096
3097 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3098
3099 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3100 return ['optimize' => $langs->trans("ShowCompany")];
3101 }
3102
3103 if (!empty($this->logo) && class_exists('Form')) {
3104 $photo = '<div class="photointooltip floatright">';
3105 $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.
3106 $photo .= '</div>';
3107 $datas['photo'] = $photo;
3108 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3109 /*$label.= '<div class="photointooltip">';
3110 $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.
3111 $label.= '</div><div style="clear: both;"></div>';*/
3112 // }
3113
3114 $datas['divopen'] = '<div class="centpercent">';
3115
3116 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3117 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3118 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3119 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3120 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3121 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3122 } elseif ($option == 'agenda') {
3123 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3124 } elseif ($option == 'project') {
3125 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3126 } elseif ($option == 'margin') {
3127 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3128 } elseif ($option == 'contact') {
3129 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3130 } elseif ($option == 'ban') {
3131 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3132 }
3133
3134 // By default
3135 if (empty($datas['picto'])) {
3136 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3137 }
3138 if (isset($this->status)) {
3139 $datas['status'] = ' '.$this->getLibStatut(5);
3140 }
3141 if (isset($this->client) && isset($this->fournisseur)) {
3142 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3143 }
3144 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3145 if (!empty($this->name_alias) && empty($noaliasinname)) {
3146 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3147 }
3148 if (!empty($this->email)) {
3149 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3150 }
3151 if (!empty($this->url)) {
3152 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3153 }
3154 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3155 $phonelist = array();
3156 if ($this->phone) {
3157 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3158 }
3159 // deliberately not making new list because fax uses same list as phone
3160 if ($this->phone_mobile) {
3161 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3162 }
3163 if ($this->fax) {
3164 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3165 }
3166 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3167 }
3168
3169 if (!empty($this->address)) {
3170 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3171 } elseif (!empty($this->country_code)) {
3172 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3173 }
3174 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3175 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3176 }
3177
3178 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3179 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3180 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3181 }
3182 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3183 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3184 }
3185 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3186 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3187 }
3188 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3189 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3190 }
3191 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3192 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3193 }
3194 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3195 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3196 }
3197 }
3198
3199 $datas['separator'] = '<br>';
3200
3201 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3202 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3203 }
3204 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3205 $langs->load('compta');
3206 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3207 }
3208 // show categories for this record only in ajax to not overload lists
3209 if (!$nofetch && isModEnabled('category') && $this->client) {
3210 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3211 $form = new Form($this->db);
3212 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3213 }
3214 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3215 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3216 }
3217 if (isModEnabled('accounting') && $this->fournisseur) {
3218 $langs->load('compta');
3219 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3220 }
3221 // show categories for this record only in ajax to not overload lists
3222 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3223 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3224 $form = new Form($this->db);
3225 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3226 }
3227
3228 $datas['divclose'] = '</div>';
3229
3230 return $datas;
3231 }
3232
3246 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3247 {
3248 global $conf, $langs, $hookmanager, $user;
3249
3250 if (!empty($conf->dol_no_mouse_hover)) {
3251 $notooltip = 1; // Force disable tooltips
3252 }
3253
3254 $name = $this->name ? $this->name : $this->nom;
3255
3256 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3257 if (empty($option) && $this->client > 0) {
3258 $option = 'customer';
3259 }
3260 if (empty($option) && $this->fournisseur > 0) {
3261 $option = 'supplier';
3262 }
3263 }
3264
3265 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3266 $code = '';
3267 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3268 $code = $this->code_client.' - ';
3269 }
3270
3271 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3272 $code .= $this->code_fournisseur.' - ';
3273 }
3274
3275 if ($code) {
3276 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3277 $name = $code.' '.$name;
3278 } else {
3279 $name = $code;
3280 }
3281 }
3282 }
3283
3284 if (!empty($this->name_alias) && empty($noaliasinname)) {
3285 $name .= ' ('.$this->name_alias.')';
3286 }
3287
3288 $result = '';
3289 $params = [
3290 'id' => $this->id,
3291 'objecttype' => $this->element,
3292 'option' => $option,
3293 'nofetch' => 1,
3294 ];
3295 $classfortooltip = 'classfortooltip';
3296 $dataparams = '';
3297 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3298 $classfortooltip = 'classforajaxtooltip';
3299 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3300 $label = '';
3301 } else {
3302 $label = implode($this->getTooltipContentArray($params));
3303 }
3304
3305 $linkstart = '';
3306 $linkend = '';
3307
3308 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3309 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3310 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3311 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3312 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3313 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3314 } elseif ($option == 'agenda') {
3315 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3316 } elseif ($option == 'project') {
3317 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3318 } elseif ($option == 'margin') {
3319 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3320 } elseif ($option == 'contact') {
3321 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3322 } elseif ($option == 'ban') {
3323 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3324 }
3325
3326 // By default
3327 if (empty($linkstart)) {
3328 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3329 }
3330
3331 // Add type of canvas
3332 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3333 // Add param to save lastsearch_values or not
3334 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3335 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3336 $add_save_lastsearch_values = 1;
3337 }
3338 if ($add_save_lastsearch_values) {
3339 $linkstart .= '&save_lastsearch_values=1';
3340 }
3341 $linkstart .= '"';
3342
3343 $linkclose = '';
3344 if (empty($notooltip)) {
3345 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3346 $label = $langs->trans("ShowCompany");
3347 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3348 }
3349 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3350 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3351 $target_value = array('_self', '_blank', '_parent', '_top');
3352 if (in_array($target, $target_value)) {
3353 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3354 }
3355 } else {
3356 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3357 }
3358 $linkstart .= $linkclose.'>';
3359 $linkend = '</a>';
3360
3361 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3362 $linkstart = '';
3363 $linkend = '';
3364 }
3365
3366 $result .= $linkstart;
3367 if ($withpicto) {
3368 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3369 }
3370 if ($withpicto != 2) {
3371 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3372 }
3373 $result .= $linkend;
3374
3375 global $action;
3376 $hookmanager->initHooks(array('thirdpartydao'));
3377 $parameters = array(
3378 'id' => $this->id,
3379 'getnomurl' => &$result,
3380 'withpicto ' => $withpicto,
3381 'option' => $option,
3382 'maxlen' => $maxlen,
3383 'notooltip' => $notooltip,
3384 'save_lastsearch_value' => $save_lastsearch_value
3385 );
3386 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3387 if ($reshook > 0) {
3388 $result = $hookmanager->resPrint;
3389 } else {
3390 $result .= $hookmanager->resPrint;
3391 }
3392
3393 return $result;
3394 }
3395
3405 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3406 {
3407 global $langs;
3408
3409 $s = '';
3410 if (empty($option) || preg_match('/prospect/', $option)) {
3411 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3412 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3413 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3414 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3415 }
3416 }
3417 if (empty($option) || preg_match('/customer/', $option)) {
3418 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3419 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3420 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3421 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3422 }
3423 }
3424 if (empty($option) || preg_match('/supplier/', $option)) {
3425 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3426 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3427 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3428 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3429 }
3430 }
3431
3432 return $s;
3433 }
3434
3435
3442 public function getLibStatut($mode = 0)
3443 {
3444 return $this->LibStatut($this->status, $mode);
3445 }
3446
3447 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3455 public function LibStatut($status, $mode = 0)
3456 {
3457 // phpcs:enable
3458 global $langs;
3459 $langs->load('companies');
3460
3461 $statusType = 'status4';
3462 if ($status == 0) {
3463 $statusType = 'status6';
3464 }
3465
3466 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3467 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3468 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3469 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3470 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3471 }
3472
3473 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3474 }
3475
3476 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3483 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3484 {
3485 // phpcs:enable
3486 global $langs;
3487
3488 $contact_emails = $this->contact_property_array('email', 1);
3489
3490 if ($this->email && $addthirdparty) {
3491 if (empty($this->name)) {
3492 $this->name = $this->nom;
3493 }
3494 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3495 }
3496
3497 //var_dump($contact_emails)
3498 return $contact_emails;
3499 }
3500
3501 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3508 {
3509 // phpcs:enable
3510 global $langs;
3511
3512 $contact_phone = $this->contact_property_array('mobile');
3513
3514 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3515 if (empty($this->name)) {
3516 $this->name = $this->nom;
3517 }
3518 // TODO: Tester si tel non deja present dans tableau contact
3519 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3520 }
3521 return $contact_phone;
3522 }
3523
3524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3532 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3533 {
3534 // phpcs:enable
3535 global $langs;
3536
3537 $contact_property = array();
3538
3539
3540 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3541 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3542 $sql .= " WHERE fk_soc = ".((int) $this->id);
3543 $sql .= " AND entity IN (".getEntity($this->element).")";
3544 $sql .= " ORDER BY lastname, firstname";
3545
3546 $resql = $this->db->query($sql);
3547 if ($resql) {
3548 $nump = $this->db->num_rows($resql);
3549 if ($nump) {
3550 $sepa = "(";
3551 $sepb = ")";
3552 if ($mode == 'email') {
3553 //$sepa="&lt;"; $sepb="&gt;";
3554 $sepa = "<";
3555 $sepb = ">";
3556 }
3557 $i = 0;
3558 while ($i < $nump) {
3559 $obj = $this->db->fetch_object($resql);
3560 if ($mode == 'email') {
3561 $property = $obj->email;
3562 } elseif ($mode == 'mobile') {
3563 $property = $obj->phone_mobile;
3564 } else {
3565 $property = $obj->$mode;
3566 }
3567
3568 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3569 if ($obj->status == 1 || empty($hidedisabled)) {
3570 if (empty($property)) {
3571 if ($mode == 'email') {
3572 $property = $langs->transnoentitiesnoconv("NoEMail");
3573 } elseif ($mode == 'mobile') {
3574 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3575 }
3576 }
3577
3578 if (!empty($obj->poste)) {
3579 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3580 } else {
3581 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3582 }
3583 }
3584 $i++;
3585 }
3586 }
3587 } else {
3588 dol_print_error($this->db);
3589 }
3590 return $contact_property;
3591 }
3592
3593
3594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3600 public function contact_array()
3601 {
3602 // phpcs:enable
3603 $contacts = array();
3604
3605 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3606 $resql = $this->db->query($sql);
3607 if ($resql) {
3608 $nump = $this->db->num_rows($resql);
3609 if ($nump) {
3610 $i = 0;
3611 while ($i < $nump) {
3612 $obj = $this->db->fetch_object($resql);
3613 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3614 $i++;
3615 }
3616 }
3617 } else {
3618 dol_print_error($this->db);
3619 }
3620 return $contacts;
3621 }
3622
3623 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3629 public function contact_array_objects()
3630 {
3631 // phpcs:enable
3632 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3633 $contacts = array();
3634
3635 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3636 $resql = $this->db->query($sql);
3637 if ($resql) {
3638 $nump = $this->db->num_rows($resql);
3639 if ($nump) {
3640 $i = 0;
3641 while ($i < $nump) {
3642 $obj = $this->db->fetch_object($resql);
3643 $contact = new Contact($this->db);
3644 $contact->fetch($obj->rowid);
3645 $contacts[] = $contact;
3646 $i++;
3647 }
3648 }
3649 } else {
3650 dol_print_error($this->db);
3651 }
3652 return $contacts;
3653 }
3654
3655 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3663 public function contact_get_property($rowid, $mode)
3664 {
3665 // phpcs:enable
3666 $contact_property = '';
3667
3668 if (empty($rowid)) {
3669 return '';
3670 }
3671
3672 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3673 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3674 $sql .= " WHERE rowid = ".((int) $rowid);
3675
3676 $resql = $this->db->query($sql);
3677 if ($resql) {
3678 $nump = $this->db->num_rows($resql);
3679
3680 if ($nump) {
3681 $obj = $this->db->fetch_object($resql);
3682
3683 if ($mode == 'email') {
3684 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3685 } elseif ($mode == 'mobile') {
3686 $contact_property = $obj->phone_mobile;
3687 }
3688 }
3689 return $contact_property;
3690 } else {
3691 dol_print_error($this->db);
3692 }
3693
3694 return '';
3695 }
3696
3697
3698 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3705 public function display_rib($mode = 'label')
3706 {
3707 // phpcs:enable
3708 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3709
3710 $bac = new CompanyBankAccount($this->db);
3711 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3712 $bac->fetch(0, '', $this->id);
3713
3714 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3715 if ($mode == 'label') {
3716 return $bac->getRibLabel(true);
3717 } elseif ($mode == 'rum') {
3718 if (empty($bac->rum)) {
3719 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3720 $prelevement = new BonPrelevement($this->db);
3721 $bac->fetch_thirdparty();
3722 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3723 }
3724 return $bac->rum;
3725 } elseif ($mode == 'format') {
3726 return $bac->frstrecur;
3727 } else {
3728 return 'BadParameterToFunctionDisplayRib';
3729 }
3730 } else {
3731 return '';
3732 }
3733 }
3734
3735 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3741 public function get_all_rib()
3742 {
3743 // phpcs:enable
3744 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3745 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3746 $result = $this->db->query($sql);
3747 if (!$result) {
3748 $this->error = $this->db->lasterror();
3749 $this->errors[] = $this->db->lasterror();
3750 return 0;
3751 } else {
3752 $num_rows = $this->db->num_rows($result);
3753 $rib_array = array();
3754 if ($num_rows) {
3755 while ($obj = $this->db->fetch_object($result)) {
3756 $rib = new CompanyBankAccount($this->db);
3757 $rib->fetch($obj->rowid);
3758 $rib_array[] = $rib;
3759 }
3760 }
3761 return $rib_array;
3762 }
3763 }
3764
3768 public function getDefaultRib()
3769 {
3770 // phpcs:enable
3771 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3772 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3773 $resql = $this->db->query($sql);
3774 if (!$resql) {
3775 $this->error = $this->db->lasterror();
3776 $this->errors[] = $this->db->lasterror();
3777 return -1;
3778 } else {
3779 $num_rows = $this->db->num_rows($resql);
3780 $rib_array = array();
3781 if ($num_rows) {
3782 while ($obj = $this->db->fetch_object($resql)) {
3783 return $obj->rowid;
3784 }
3785 }
3786 return 0;
3787 }
3788 }
3789
3790
3791 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3800 public function get_codeclient($objsoc = null, $type = 0)
3801 {
3802 // phpcs:enable
3803 global $conf;
3804 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3805 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3806
3807 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3808 foreach ($dirsociete as $dirroot) {
3809 $res = dol_include_once($dirroot.$module.'.php');
3810 if ($res) {
3811 break;
3812 }
3813 }
3815 $mod = new $module($this->db);
3816 '@phan-var-force ModeleThirdPartyCode $mod';
3817
3818 $this->code_client = $mod->getNextValue($objsoc, $type);
3819 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3820
3821 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3822 }
3823 }
3824
3825 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3834 public function get_codefournisseur($objsoc = null, $type = 1)
3835 {
3836 // phpcs:enable
3837 global $conf;
3838 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3839 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3840
3841 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3842 foreach ($dirsociete as $dirroot) {
3843 $res = dol_include_once($dirroot.$module.'.php');
3844 if ($res) {
3845 break;
3846 }
3847 }
3849 $mod = new $module($this->db);
3850 '@phan-var-force ModeleThirdPartyCode $mod';
3851
3852 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3853
3854 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3855 }
3856 }
3857
3858 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3865 public function codeclient_modifiable()
3866 {
3867 // phpcs:enable
3868 global $conf;
3869 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3870 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3871
3872 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3873 foreach ($dirsociete as $dirroot) {
3874 $res = dol_include_once($dirroot.$module.'.php');
3875 if ($res) {
3876 break;
3877 }
3878 }
3879
3880 $mod = new $module($this->db);
3881 '@phan-var-force ModeleThirdPartyCode $mod';
3882
3883 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3884 if ($mod->code_modifiable_null && !$this->code_client) {
3885 return 1;
3886 }
3887 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3888 return 1;
3889 }
3890 if ($mod->code_modifiable) {
3891 return 1; // A mettre en dernier
3892 }
3893 return 0;
3894 } else {
3895 return 0;
3896 }
3897 }
3898
3899
3900 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3907 {
3908 // phpcs:enable
3909 global $conf;
3910 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3911 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3912
3913 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3914 foreach ($dirsociete as $dirroot) {
3915 $res = dol_include_once($dirroot.$module.'.php');
3916 if ($res) {
3917 break;
3918 }
3919 }
3920
3921 $mod = new $module($this->db);
3922 '@phan-var-force ModeleThirdPartyCode $mod';
3923
3924 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3925 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3926 return 1;
3927 }
3928 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3929 return 1;
3930 }
3931 if ($mod->code_modifiable) {
3932 return 1; // A mettre en dernier
3933 }
3934 return 0;
3935 } else {
3936 return 0;
3937 }
3938 }
3939
3940
3941 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3953 public function check_codeclient()
3954 {
3955 // phpcs:enable
3956 global $conf;
3957 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3958 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3959
3960 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3961 foreach ($dirsociete as $dirroot) {
3962 $res = dol_include_once($dirroot.$module.'.php');
3963 if ($res) {
3964 break;
3965 }
3966 }
3967
3968 $mod = new $module($this->db);
3969 '@phan-var-force ModeleThirdPartyCode $mod';
3970
3971 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3972 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3973 if ($result) { // If error
3974 $this->error = $mod->error;
3975 $this->errors = $mod->errors;
3976 }
3977 return $result;
3978 } else {
3979 return 0;
3980 }
3981 }
3982
3983 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3995 public function check_codefournisseur()
3996 {
3997 // phpcs:enable
3998 global $conf;
3999 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4000 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4001
4002 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4003 foreach ($dirsociete as $dirroot) {
4004 $res = dol_include_once($dirroot.$module.'.php');
4005 if ($res) {
4006 break;
4007 }
4008 }
4009
4010 $mod = new $module($this->db);
4011 '@phan-var-force ModeleThirdPartyCode $mod';
4012
4013 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4014 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
4015 if ($result) { // If error
4016 $this->error = $mod->error;
4017 $this->errors = $mod->errors;
4018 }
4019 return $result;
4020 } else {
4021 return 0;
4022 }
4023 }
4024
4025 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4034 public function get_codecompta($type)
4035 {
4036 // phpcs:enable
4037 global $conf;
4038
4039 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
4040 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
4041 $res = false;
4042 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4043 foreach ($dirsociete as $dirroot) {
4044 $res = dol_include_once($dirroot.$module.'.php');
4045 if ($res) {
4046 break;
4047 }
4048 }
4049
4050 if ($res) {
4051 $mod = new $module();
4052 '@phan-var-force ModeleAccountancyCode $mod';
4053
4054 // Set code count in $mod->code
4055 $result = $mod->get_code($this->db, $this, $type);
4056
4057 if ($type == 'customer') {
4058 $this->code_compta_client = $mod->code;
4059 } elseif ($type == 'supplier') {
4060 $this->code_compta_fournisseur = $mod->code;
4061 }
4062
4063 return $result;
4064 } else {
4065 $this->error = 'ErrorAccountancyCodeNotDefined';
4066 return -1;
4067 }
4068 } else {
4069 if ($type == 'customer') {
4070 $this->code_compta_client = '';
4071 } elseif ($type == 'supplier') {
4072 $this->code_compta_fournisseur = '';
4073 }
4074
4075 return 0;
4076 }
4077 }
4078
4085 public function setParent($id)
4086 {
4087 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4088
4089 if ($this->id) {
4090 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4091 if ($id > 0) {
4092 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4093 if ($sameparent < 0) {
4094 return -1;
4095 }
4096 if ($sameparent == 1) {
4097 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4098 return -1;
4099 }
4100 }
4101
4102 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
4103
4104 $resql = $this->db->query($sql);
4105 if ($resql) {
4106 $this->parent = $id;
4107 return 1;
4108 } else {
4109 return -1;
4110 }
4111 }
4112
4113 return -1;
4114 }
4115
4124 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4125 {
4126 if ($counter > 100) {
4127 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4128 }
4129
4130 $sql = 'SELECT s.parent';
4131 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4132 $sql .= ' WHERE rowid = '.((int) $idparent);
4133 $resql = $this->db->query($sql);
4134 if ($resql) {
4135 $obj = $this->db->fetch_object($resql);
4136
4137 if ($obj->parent == '') {
4138 return 0;
4139 } elseif ($obj->parent == $idchild) {
4140 return 1;
4141 } else {
4142 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4143 }
4144 return $sameparent;
4145 } else {
4146 return -1;
4147 }
4148 }
4149
4157 public function getParentsForCompany($company_id, $parents = array())
4158 {
4159 global $langs;
4160
4161 if ($company_id > 0) {
4162 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4163 $resql = $this->db->query($sql);
4164 if ($resql) {
4165 if ($obj = $this->db->fetch_object($resql)) {
4166 $parent = $obj->parent;
4167 if ($parent > 0 && !in_array($parent, $parents)) {
4168 $parents[] = $parent;
4169 return $this->getParentsForCompany($parent, $parents);
4170 } else {
4171 return $parents;
4172 }
4173 }
4174 $this->db->free($resql);
4175 } else {
4176 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4177 }
4178 }
4179 // Return a default value when $company_id is not greater than 0
4180 return array();
4181 }
4182
4183 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4190 public function id_prof_verifiable($idprof)
4191 {
4192 // phpcs:enable
4193 global $conf;
4194
4195 switch ($idprof) {
4196 case 1:
4197 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4198 break;
4199 case 2:
4200 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4201 break;
4202 case 3:
4203 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4204 break;
4205 case 4:
4206 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4207 break;
4208 case 5:
4209 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4210 break;
4211 case 6:
4212 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4213 break;
4214 default:
4215 $ret = false;
4216 }
4217
4218 return $ret;
4219 }
4220
4221 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4230 public function id_prof_exists($idprof, $value, $socid = 0)
4231 {
4232 // phpcs:enable
4233 $field = $idprof;
4234
4235 switch ($idprof) { // For backward compatibility
4236 case '1':
4237 case 'idprof1':
4238 $field = "siren";
4239 break;
4240 case '2':
4241 case 'idprof2':
4242 $field = "siret";
4243 break;
4244 case '3':
4245 case 'idprof3':
4246 $field = "ape";
4247 break;
4248 case '4':
4249 case 'idprof4':
4250 $field = "idprof4";
4251 break;
4252 case '5':
4253 $field = "idprof5";
4254 break;
4255 case '6':
4256 $field = "idprof6";
4257 break;
4258 }
4259
4260 //Verify duplicate entries
4261 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4262 if ($socid) {
4263 $sql .= " AND rowid <> ".$socid;
4264 }
4265 $resql = $this->db->query($sql);
4266 if ($resql) {
4267 $obj = $this->db->fetch_object($resql);
4268 $count = $obj->nb;
4269 } else {
4270 $count = 0;
4271 print $this->db->error();
4272 }
4273 $this->db->free($resql);
4274
4275 if ($count > 0) {
4276 return true;
4277 } else {
4278 return false;
4279 }
4280 }
4281
4282 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4291 public function id_prof_check($idprof, $soc)
4292 {
4293 // phpcs:enable
4294
4295 $ok = 1;
4296
4297 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4298 return 1;
4299 }
4300
4301 // load the library necessary to check the professional identifiers
4302 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4303
4304 // Check SIREN
4305 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4306 return -1;
4307 }
4308
4309 // Check SIRET
4310 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4311 return -1;
4312 }
4313
4314 //Verify CIF/NIF/NIE if pays ES
4315 if ($idprof == 1 && $soc->country_code == 'ES') {
4316 return isValidTinForES($this->idprof1);
4317 }
4318
4319 //Verify NIF if country is PT
4320 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4321 return -1;
4322 }
4323
4324 //Verify NIF if country is DZ
4325 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4326 return -1;
4327 }
4328
4329 //Verify ID Prof 1 if country is BE
4330 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4331 return -1;
4332 }
4333
4334 return $ok;
4335 }
4336
4337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4346 public function id_prof_url($idprof, $thirdparty)
4347 {
4348 // phpcs:enable
4349 global $langs, $hookmanager;
4350
4351 $url = '';
4352 $action = '';
4353
4354 $hookmanager->initHooks(array('idprofurl'));
4355 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4356 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4357 if (empty($reshook)) {
4358 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4359 return '';
4360 }
4361
4362 // TODO Move links to validate professional ID into the dictionary table "country" + column "linkidprof1"
4363 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4364 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4365 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.urlencode($strippedIdProf1); // See also http://avis-situation-sirene.insee.fr/
4366 }
4367 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4368 $url = 'https://beta.companieshouse.gov.uk/company/'.urlencode($strippedIdProf1);
4369 }
4370 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4371 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.urlencode($strippedIdProf1);
4372 }
4373 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4374 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.urlencode($strippedIdProf1).';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4375 }
4376 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4377 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.urlencode($strippedIdProf1);
4378 }
4379 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4380 $url = 'http://www.nif.pt/'.urlencode($strippedIdProf1);
4381 }
4382
4383 if ($url) {
4384 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4385 }
4386 } else {
4387 return $hookmanager->resPrint;
4388 }
4389
4390 return '';
4391 }
4392
4393 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4399 public function has_projects()
4400 {
4401 // phpcs:enable
4402 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4403 $resql = $this->db->query($sql);
4404 if ($resql) {
4405 $obj = $this->db->fetch_object($resql);
4406 $count = $obj->numproj;
4407 } else {
4408 $count = 0;
4409 print $this->db->error();
4410 }
4411 $this->db->free($resql);
4412 return ($count > 0);
4413 }
4414
4415
4422 public function info($id)
4423 {
4424 $sql = "SELECT s.rowid, s.nom as name, s.datec, GREATEST(s.tms, sef.tms) as datem,";
4425 $sql .= " fk_user_creat, fk_user_modif";
4426 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4427 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as sef ON sef.fk_object=s.rowid";
4428 $sql .= " WHERE s.rowid = ".((int) $id);
4429
4430 $result = $this->db->query($sql);
4431 if ($result) {
4432 if ($this->db->num_rows($result)) {
4433 $obj = $this->db->fetch_object($result);
4434
4435 $this->id = $obj->rowid;
4436
4437 $this->user_creation_id = $obj->fk_user_creat;
4438 $this->user_modification_id = $obj->fk_user_modif;
4439 $this->date_creation = $this->db->jdate($obj->datec);
4440 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4441
4442 $this->ref = $obj->name;
4443 }
4444
4445 $this->db->free($result);
4446 } else {
4447 dol_print_error($this->db);
4448 }
4449 }
4450
4456 public function isACompany()
4457 {
4458 //global $mysoc;
4459
4460 // Define if third party is treated as company (or not) when nature is unknown
4461 //$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
4462 $defaultvalue = 1;
4463 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', $defaultvalue);
4464
4465 // Now try to guess using different tips
4466 if (!empty($this->tva_intra)) {
4467 $isACompany = 2;
4468 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4469 $isACompany = 3;
4470 } else {
4471 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4472 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4473 $isACompany = 0;
4474 }
4475 } else {
4476 $isACompany = 4;
4477 }
4478 }
4479
4480 return $isACompany;
4481 }
4482
4488 public function isInEEC()
4489 {
4490 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4491 return isInEEC($this);
4492 }
4493
4499 public function isInSEPA()
4500 {
4501 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4502 return isInSEPA($this);
4503 }
4504
4505 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4511 public function LoadSupplierCateg()
4512 {
4513 // phpcs:enable
4514 $this->SupplierCategories = array();
4515 $sql = "SELECT rowid, label";
4516 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4517 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4518
4519 $resql = $this->db->query($sql);
4520 if ($resql) {
4521 while ($obj = $this->db->fetch_object($resql)) {
4522 $this->SupplierCategories[$obj->rowid] = $obj->label;
4523 }
4524 return 0;
4525 } else {
4526 return -1;
4527 }
4528 }
4529
4530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4537 public function AddFournisseurInCategory($categorie_id)
4538 {
4539 // phpcs:enable
4540 if ($categorie_id > 0 && $this->id > 0) {
4541 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4542 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4543
4544 if ($resql = $this->db->query($sql)) {
4545 return 0;
4546 }
4547 } else {
4548 return 0;
4549 }
4550 return -1;
4551 }
4552
4558 public function getNbOfEMailings()
4559 {
4560 $sql = "SELECT count(mc.email) as nb";
4561 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4562 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4563 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4564
4565 $resql = $this->db->query($sql);
4566 if ($resql) {
4567 $obj = $this->db->fetch_object($resql);
4568 $nb = (int) $obj->nb;
4569
4570 $this->db->free($resql);
4571 return $nb;
4572 } else {
4573 $this->error = $this->db->error();
4574 return -1;
4575 }
4576 }
4577
4585 public function setNoEmail($no_email, $unsubscribegroup = '')
4586 {
4587 $error = 0;
4588
4589 // Update mass emailing flag into table mailing_unsubscribe
4590 if ($this->email) {
4591 $this->db->begin();
4592
4593 if ($no_email) {
4594 // TODO Add $unsubscribegroup
4595 $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)."'";
4596 $resql = $this->db->query($sql);
4597 if ($resql) {
4598 $obj = $this->db->fetch_object($resql);
4599 $noemail = $obj->nb;
4600 if (empty($noemail)) {
4601 // TODO Add $unsubscribegroup
4602 $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())."')";
4603 $resql = $this->db->query($sql);
4604 if (!$resql) {
4605 $error++;
4606 $this->error = $this->db->lasterror();
4607 $this->errors[] = $this->error;
4608 }
4609 }
4610 } else {
4611 $error++;
4612 $this->error = $this->db->lasterror();
4613 $this->errors[] = $this->error;
4614 }
4615 } else {
4616 // TODO Add $unsubscribegroup
4617 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4618 $resql = $this->db->query($sql);
4619 if (!$resql) {
4620 $error++;
4621 $this->error = $this->db->lasterror();
4622 $this->errors[] = $this->error;
4623 }
4624 }
4625
4626 if (empty($error)) {
4627 $this->no_email = $no_email;
4628 $this->db->commit();
4629 return 1;
4630 } else {
4631 $this->db->rollback();
4632 return $error * -1;
4633 }
4634 }
4635
4636 return 0;
4637 }
4638
4645 public function getNoEmail()
4646 {
4647 if ($this->email) {
4648 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4649 $resql = $this->db->query($sql);
4650 if ($resql) {
4651 $obj = $this->db->fetch_object($resql);
4652 $this->no_email = $obj->nb;
4653 return 1;
4654 } else {
4655 $this->error = $this->db->lasterror();
4656 $this->errors[] = $this->error;
4657 return -1;
4658 }
4659 }
4660 return 0;
4661 }
4662
4663 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4673 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4674 {
4675 // phpcs:enable
4676 global $user, $langs;
4677
4678 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4679 $fullname = $member->getFullName($langs);
4680
4681 if ($member->morphy == 'mor') {
4682 if (empty($socname)) {
4683 $socname = $member->company ? $member->company : $member->societe;
4684 }
4685 if (!empty($fullname) && empty($socalias)) {
4686 $socalias = $fullname;
4687 }
4688 } elseif (empty($socname) && $member->morphy == 'phy') {
4689 if (empty($socname)) {
4690 $socname = $fullname;
4691 }
4692 if (!empty($member->company) && empty($socalias)) {
4693 $socalias = $member->company;
4694 }
4695 }
4696
4697 $name = $socname;
4698 $alias = $socalias ? $socalias : '';
4699
4700 // Positionne parameters
4701 $this->nom = $name; // TODO deprecated
4702 $this->name = $name;
4703 $this->name_alias = $alias;
4704 $this->address = $member->address;
4705 $this->zip = $member->zip;
4706 $this->town = $member->town;
4707 $this->country_code = $member->country_code;
4708 $this->country_id = $member->country_id;
4709 $this->phone = $member->phone; // Prof phone
4710 $this->email = $member->email;
4711 $this->socialnetworks = $member->socialnetworks;
4712 $this->entity = $member->entity;
4713
4714 $this->client = 1; // A member is a customer by default
4715 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4716 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4717 } else {
4718 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4719 }
4720 $this->code_fournisseur = '-1';
4721 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4722 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4723
4724 $this->db->begin();
4725
4726 // Cree et positionne $this->id
4727 $result = $this->create($user);
4728
4729 if ($result >= 0) {
4730 // Auto-create contact on thirdparty creation
4731 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4732 // Fill fields needed by contact
4733 $this->name_bis = $member->lastname;
4734 $this->firstname = $member->firstname;
4735 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4736 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4737
4738 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4739 $result = $this->create_individual($user);
4740
4741 if ($result < 0) {
4742 setEventMessages($this->error, $this->errors, 'errors');
4743 $this->db->rollback();
4744 return -1;
4745 }
4746 }
4747
4748 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4749 $sql .= " SET fk_soc = ".((int) $this->id);
4750 $sql .= " WHERE rowid = ".((int) $member->id);
4751
4752 $resql = $this->db->query($sql);
4753 if ($resql) {
4754 $this->db->commit();
4755 return $this->id;
4756 } else {
4757 $this->error = $this->db->error();
4758
4759 $this->db->rollback();
4760 return -1;
4761 }
4762 } else {
4763 // $this->error deja positionne
4764 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4765
4766 $this->db->rollback();
4767 return $result;
4768 }
4769 }
4770
4777 public function setMysoc(Conf $conf)
4778 {
4779 global $langs;
4780
4781 $this->id = 0;
4782 $this->entity = $conf->entity;
4783 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4784 $this->nom = $this->name; // deprecated
4785 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4786 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4787 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4788 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4789
4790 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4791
4792 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4793
4794 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4795
4796 // We define country_id, country_code and country
4797 $country_id = 0;
4798 $country_code = $country_label = '';
4799 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4800 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4801 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4802 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4803 $country_code = $tmp[1];
4804 $country_label = $tmp[2];
4805 } else {
4806 // For backward compatibility
4807 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4808 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4809 $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
4810 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4811 }
4812 }
4813 $this->country_id = $country_id;
4814 $this->country_code = $country_code;
4815 $this->country = $country_label;
4816 if (is_object($langs)) {
4817 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4818 }
4819
4820 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4821 // We define state_id, state_code and state
4822 $state_id = 0;
4823 $state_code = '';
4824 $state_label = '';
4825 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4826 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4827 $state_id = (int) $tmp[0];
4828 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4829 $state_code = $tmp[1];
4830 $state_label = $tmp[2];
4831 } else { // For backward compatibility
4832 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);
4833 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4834 $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
4835 $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
4836 }
4837 }
4838 $this->state_id = $state_id;
4839 $this->state_code = $state_code;
4840 $this->state = $state_label;
4841 if (is_object($langs)) {
4842 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4843 }
4844
4845 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4846 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4847 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4848 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4849
4850 // Social networks
4851 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4852 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4853 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4854 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4855 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4856 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4857 $this->socialnetworks = array();
4858 if (!empty($facebook_url)) {
4859 $this->socialnetworks['facebook'] = $facebook_url;
4860 }
4861 if (!empty($twitter_url)) {
4862 $this->socialnetworks['twitter'] = $twitter_url;
4863 }
4864 if (!empty($linkedin_url)) {
4865 $this->socialnetworks['linkedin'] = $linkedin_url;
4866 }
4867 if (!empty($instagram_url)) {
4868 $this->socialnetworks['instagram'] = $instagram_url;
4869 }
4870 if (!empty($youtube_url)) {
4871 $this->socialnetworks['youtube'] = $youtube_url;
4872 }
4873 if (!empty($github_url)) {
4874 $this->socialnetworks['github'] = $github_url;
4875 }
4876
4877 // Id prof generic
4878 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4879 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4880 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4881 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4882 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4883 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4884 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4885 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4886 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4887 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4888 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4889 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4890 $this->capital = is_numeric(price2num(getDolGlobalString('MAIN_INFO_CAPITAL'))) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : null;
4891 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4892 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4893 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4894 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4895 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4896 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4897 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4898 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4899 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4900
4901 // Define if company use vat or not
4902 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4903
4904 // Define if company use local taxes
4905 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4906 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4907
4908 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4909 }
4910
4918 public function initAsSpecimen()
4919 {
4920 $now = dol_now();
4921
4922 // Initialize parameters
4923 $this->id = 0;
4924 $this->entity = 1;
4925 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4926 $this->ref_ext = 'Ref ext';
4927 $this->specimen = 1;
4928 $this->address = '21 jump street';
4929 $this->zip = '99999';
4930 $this->town = 'MyTown';
4931 $this->state_id = 1;
4932 $this->state_code = 'AA';
4933 $this->state = 'MyState';
4934 $this->country_id = 1;
4935 $this->country_code = 'FR';
4936 $this->email = 'specimen@specimen.com';
4937 $this->socialnetworks = array(
4938 'skype' => 'skypepseudo',
4939 'twitter' => 'twitterpseudo',
4940 'facebook' => 'facebookpseudo',
4941 'linkedin' => 'linkedinpseudo',
4942 );
4943 $this->url = 'http://www.specimen.com';
4944
4945 $this->phone = '0909090901';
4946 $this->phone_mobile = '0909090901';
4947 $this->fax = '0909090909';
4948
4949 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4950 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4951 $this->typent_code = 'TE_OTHER';
4952 $this->capital = 10000;
4953 $this->client = 1;
4954 $this->prospect = 1;
4955 $this->fournisseur = 1;
4956 $this->tva_assuj = 1;
4957 $this->tva_intra = 'EU1234567';
4958 $this->note_public = 'This is a comment (public)';
4959 $this->note_private = 'This is a comment (private)';
4960
4961 $this->idprof1 = 'idprof1';
4962 $this->idprof2 = 'idprof2';
4963 $this->idprof3 = 'idprof3';
4964 $this->idprof4 = 'idprof4';
4965 $this->idprof5 = 'idprof5';
4966 $this->idprof6 = 'idprof6';
4967
4968 return 1;
4969 }
4970
4979 public function useLocalTax($localTaxNum = 0, $mode = 0, $thirdparty = null)
4980 {
4981 if ($mode == 1 && $thirdparty instanceof Societe) {
4982 if ($localTaxNum == -1) {
4983 return array(1 => ($thirdparty->localtax1_assuj ? true : false), 2 => ($thirdparty->localtax2_assuj ? true : false));
4984 } elseif ($localTaxNum == 1) {
4985 return $thirdparty->localtax1_assuj ? true : false;
4986 } elseif ($localTaxNum == 2) {
4987 return $thirdparty->localtax2_assuj ? true : false;
4988 }
4989 return false;
4990 } else {
4991 $sql = "SELECT t.localtax1, t.localtax2";
4992 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4993 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4994 $sql .= " AND t.active = 1";
4995 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4996 if (empty($localTaxNum) || $localTaxNum == -1) {
4997 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4998 } elseif ($localTaxNum == 1) {
4999 $sql .= " AND t.localtax1_type <> '0'";
5000 } elseif ($localTaxNum == 2) {
5001 $sql .= " AND t.localtax2_type <> '0'";
5002 }
5003
5004 $resql = $this->db->query($sql);
5005 if ($resql) {
5006 if ($localTaxNum == -1) {
5007 $obj = $this->db->fetch_object($resql);
5008 if ($obj) {
5009 return array(1 => ($obj->localtax1 ? true : false), 2 => ($obj->localtax2 ? true : false));
5010 }
5011 return array(1 => false, 2 => false);
5012 } else {
5013 return ($this->db->num_rows($resql) > 0);
5014 }
5015 } else {
5016 return false;
5017 }
5018 }
5019 }
5020
5026 public function useNPR()
5027 {
5028 $sql = "SELECT t.rowid";
5029 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5030 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5031 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
5032 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5033
5034 dol_syslog("useNPR", LOG_DEBUG);
5035 $resql = $this->db->query($sql);
5036 if ($resql) {
5037 return ($this->db->num_rows($resql) > 0);
5038 } else {
5039 return false;
5040 }
5041 }
5042
5049 public function useRevenueStamp()
5050 {
5051 $sql = "SELECT COUNT(*) as nb";
5052 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
5053 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5054 $sql .= " AND r.active = 1";
5055
5056 dol_syslog("useRevenueStamp", LOG_DEBUG);
5057 $resql = $this->db->query($sql);
5058 if ($resql) {
5059 $obj = $this->db->fetch_object($resql);
5060 return ($obj->nb > 0);
5061 } else {
5062 $this->error = $this->db->lasterror();
5063 return false;
5064 }
5065 }
5066
5072 public function getLibProspLevel()
5073 {
5074 return $this->LibProspLevel($this->fk_prospectlevel);
5075 }
5076
5077 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5084 public function LibProspLevel($fk_prospectlevel)
5085 {
5086 // phpcs:enable
5087 global $langs;
5088
5089 $label = '';
5090 if ($fk_prospectlevel != '') {
5091 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5092 // If label is not found in language file, we get label from cache/database
5093 if ($label == "ProspectLevel".$fk_prospectlevel) {
5094 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5095 }
5096 }
5097
5098 return $label;
5099 }
5100
5108 public function getLibProspCommStatut($mode = 0, $label = '')
5109 {
5110 return $this->LibProspCommStatut((int) $this->stcomm_id, $mode, $label, $this->stcomm_picto);
5111 }
5112
5113 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5127 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5128 {
5129 // phpcs:enable
5130 global $langs;
5131
5132 $langs->load('customers');
5133
5134 if ($mode == 2) {
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 } elseif ($mode == 3) {
5149 if ($status == '-1' || $status == 'ST_NO') {
5150 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5151 } elseif ($status == '0' || $status == 'ST_NEVER') {
5152 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5153 } elseif ($status == '1' || $status == 'ST_TODO') {
5154 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5155 } elseif ($status == '2' || $status == 'ST_PEND') {
5156 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5157 } elseif ($status == '3' || $status == 'ST_DONE') {
5158 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5159 } else {
5160 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5161 }
5162 } elseif ($mode == 4) {
5163 if ($status == '-1' || $status == 'ST_NO') {
5164 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5165 } elseif ($status == '0' || $status == 'ST_NEVER') {
5166 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5167 } elseif ($status == '1' || $status == 'ST_TODO') {
5168 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5169 } elseif ($status == '2' || $status == 'ST_PEND') {
5170 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5171 } elseif ($status == '3' || $status == 'ST_DONE') {
5172 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5173 } else {
5174 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);
5175 }
5176 }
5177
5178 return "Error, mode/status not found";
5179 }
5180
5187 public function getOutstandingProposals($mode = 'customer')
5188 {
5189 global $hookmanager;
5190 $table = 'propal';
5191 if ($mode == 'supplier') {
5192 $table = 'supplier_proposal';
5193 }
5194
5195 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5196 $sql .= " WHERE fk_soc = ".((int) $this->id);
5197 if ($mode == 'supplier') {
5198 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5199 } else {
5200 $sql .= " AND entity IN (".getEntity('propal').")";
5201 }
5202
5203 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5204
5205 // Add where from hooks
5206 $parameters = array('mode' => $mode, 'table' => $table);
5207 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5208 $sql .= $hookmanager->resPrint;
5209
5210 $resql = $this->db->query($sql);
5211 if ($resql) {
5212 $outstandingOpened = 0;
5213 $outstandingTotal = 0;
5214 $outstandingTotalIncTax = 0;
5215 $arrayofref = array();
5216 while ($obj = $this->db->fetch_object($resql)) {
5217 $arrayofref[$obj->rowid] = $obj->ref;
5218 $outstandingTotal += $obj->total_ht;
5219 $outstandingTotalIncTax += $obj->total_ttc;
5220 if ($obj->status != 0) {
5221 // Not a draft
5222 $outstandingOpened += $obj->total_ttc;
5223 }
5224 }
5225 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5226 } else {
5227 return array();
5228 }
5229 }
5230
5237 public function getOutstandingOrders($mode = 'customer')
5238 {
5239 global $hookmanager;
5240 $table = 'commande';
5241 if ($mode == 'supplier') {
5242 $table = 'commande_fournisseur';
5243 }
5244
5245 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5246 $sql .= " WHERE fk_soc = ".((int) $this->id);
5247 if ($mode == 'supplier') {
5248 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5249 } else {
5250 $sql .= " AND entity IN (".getEntity('commande').")";
5251 }
5252
5253 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5254 // Add where from hooks
5255 $parameters = array('mode' => $mode, 'table' => $table);
5256 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5257 $sql .= $hookmanager->resPrint;
5258 $resql = $this->db->query($sql);
5259 if ($resql) {
5260 $outstandingOpened = 0;
5261 $outstandingTotal = 0;
5262 $outstandingTotalIncTax = 0;
5263 $arrayofref = array();
5264 while ($obj = $this->db->fetch_object($resql)) {
5265 $arrayofref[$obj->rowid] = $obj->ref;
5266 $outstandingTotal += $obj->total_ht;
5267 $outstandingTotalIncTax += $obj->total_ttc;
5268 if ($obj->status != 0) {
5269 // Not a draft
5270 $outstandingOpened += $obj->total_ttc;
5271 }
5272 }
5273 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5274 } else {
5275 return array();
5276 }
5277 }
5278
5286 public function getOutstandingBills($mode = 'customer', $late = 0)
5287 {
5288 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5289
5290 $table = 'facture';
5291 if ($mode == 'supplier') {
5292 $table = 'facture_fourn';
5293 }
5294
5295 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5296 $paiement = $invoice->getSommePaiement();
5297 $creditnotes=$invoice->getSumCreditNotesUsed();
5298 $deposits=$invoice->getSumDepositsUsed();
5299 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5300 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5301 */
5302 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5303
5304 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5305 $sql .= " WHERE fk_soc = ".((int) $this->id);
5306 if (!empty($late)) {
5307 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5308 }
5309 if ($mode == 'supplier') {
5310 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5311 } else {
5312 $sql .= " AND entity IN (".getEntity('invoice').")";
5313 }
5314
5315 dol_syslog("getOutstandingBills", LOG_DEBUG);
5316 $resql = $this->db->query($sql);
5317 if ($resql) {
5318 $outstandingOpened = 0;
5319 $outstandingTotal = 0;
5320 $outstandingTotalIncTax = 0;
5321 $arrayofref = array();
5322 $arrayofrefopened = array();
5323 if ($mode == 'supplier') {
5324 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5325 $tmpobject = new FactureFournisseur($this->db);
5326 } else {
5327 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5328 $tmpobject = new Facture($this->db);
5329 }
5330 while ($obj = $this->db->fetch_object($resql)) {
5331 $arrayofref[$obj->rowid] = $obj->ref;
5332 $tmpobject->id = $obj->rowid;
5333
5334 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5335 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5336 ) {
5337 $outstandingTotal += $obj->total_ht;
5338 $outstandingTotalIncTax += $obj->total_ttc;
5339 }
5340
5341 $remaintopay = 0;
5342
5343 if ($obj->paye == 0
5344 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5345 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5346 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5347 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5348 $paiement = $tmpobject->getSommePaiement();
5349 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5350 $deposits = $tmpobject->getSumDepositsUsed();
5351
5352 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5353 $outstandingOpened += $remaintopay;
5354 }
5355
5356 //if credit note is converted but not used
5357 // TODO Do this also for customer ?
5358 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5359 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5360 $remaintopay -= $remainingcreditnote;
5361 $outstandingOpened -= $remainingcreditnote;
5362 }
5363
5364 if ($remaintopay) {
5365 $arrayofrefopened[$obj->rowid] = $obj->ref;
5366 }
5367 }
5368 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'amount incl taxes' > 0
5369 } else {
5370 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5371 return array();
5372 }
5373 }
5374
5381 public function getLibCustProspStatut()
5382 {
5383 return $this->LibCustProspStatut($this->client);
5384 }
5385
5386 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5393 public function LibCustProspStatut($status)
5394 {
5395 // phpcs:enable
5396 global $langs;
5397 $langs->load('companies');
5398
5399 if ($status == 0) {
5400 return $langs->trans("NorProspectNorCustomer");
5401 } elseif ($status == 1) {
5402 return $langs->trans("Customer");
5403 } elseif ($status == 2) {
5404 return $langs->trans("Prospect");
5405 } elseif ($status == 3) {
5406 return $langs->trans("ProspectCustomer");
5407 }
5408
5409 return '';
5410 }
5411
5412
5424 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5425 {
5426 global $langs;
5427
5428 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5429 $modelpath = "core/modules/bank/doc/";
5430
5431 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5432 $companybankaccount = new CompanyBankAccount($this->db);
5433 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5434 if (!$result) {
5435 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5436 }
5437 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5438 $this->last_main_doc = $companybankaccount->last_main_doc;
5439 } else {
5440 // Positionne le modele sur le nom du modele a utiliser
5441 if (!dol_strlen($modele)) {
5442 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5443 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5444 } else {
5445 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5446 return 0;
5447 }
5448 }
5449
5450 if (!isset($this->bank_account)) {
5451 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5452 $bac = new CompanyBankAccount($this->db);
5453 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5454 $result = $bac->fetch(0, '', $this->id);
5455 if ($result > 0) {
5456 $this->bank_account = $bac;
5457 } else {
5458 $this->bank_account = '';
5459 }
5460 }
5461
5462 $modelpath = "core/modules/societe/doc/";
5463
5464 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5465 }
5466
5467 return $result;
5468 }
5469
5470
5483 public function setCategories($categories, $type_categ, $remove_existing = true)
5484 {
5485 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5486
5487 // Decode type
5488 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5489 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Nothing done.', LOG_ERR);
5490 return -1;
5491 }
5492
5493 return parent::setCategoriesCommon($categories, $type_categ, $remove_existing);
5494 }
5495
5503 public function setSalesRep($salesrep, $onlyAdd = false)
5504 {
5505 global $user;
5506
5507 // Handle single user
5508 if (!is_array($salesrep)) {
5509 $salesrep = array($salesrep);
5510 }
5511
5512 $to_del = array(); // Nothing to delete
5513 $to_add = $salesrep;
5514 if ($onlyAdd === false) {
5515 // Get current users
5516 $existing = $this->getSalesRepresentatives($user, 1);
5517
5518 // Diff
5519 if (is_array($existing)) {
5520 $to_del = array_diff($existing, $salesrep);
5521 $to_add = array_diff($salesrep, $existing);
5522 }
5523 }
5524
5525 $error = 0;
5526
5527 // Process
5528 foreach ($to_del as $del) {
5529 $this->del_commercial($user, $del);
5530 }
5531 foreach ($to_add as $add) {
5532 $result = $this->add_commercial($user, $add);
5533 if ($result < 0) {
5534 $error++;
5535 break;
5536 }
5537 }
5538
5539 return $error ? -1 : 1;
5540 }
5541
5548 public function setThirdpartyType($typent_id)
5549 {
5550 global $user;
5551
5552 dol_syslog(__METHOD__, LOG_DEBUG);
5553
5554 if ($this->id) {
5555 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5556
5557 if ($result > 0) {
5558 $this->typent_id = $typent_id;
5559 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5560 return 1;
5561 } else {
5562 return -1;
5563 }
5564 } else {
5565 return -1;
5566 }
5567 }
5568
5578 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5579 {
5580 if ($origin_id == $dest_id) {
5581 dol_syslog('Error: Try to merge a thirdparty into itself');
5582 return false;
5583 }
5584
5585 // 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.
5586 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5587 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5588 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5589 $sql .= ' SELECT fk_user ';
5590 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5591 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5592
5593 $resql = $dbs->query($sql);
5594 while ($obj = $dbs->fetch_object($resql)) {
5595 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5596 }
5597
5598 // 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.
5599 // Do not include llx_societe because it will be replaced later.
5600 $tables = array(
5601 'societe_account',
5602 'societe_commerciaux',
5603 'societe_prices',
5604 'societe_remise',
5605 'societe_remise_except',
5606 'societe_rib'
5607 );
5608
5609 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5610
5611 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5612 }
5613
5622 public function setAccountancyCode($type, $value)
5623 {
5624 global $user, $langs, $conf;
5625
5626 $this->db->begin();
5627
5628 if ($type == 'buy') {
5629 $field = 'accountancy_code_buy';
5630 } elseif ($type == 'sell') {
5631 $field = 'accountancy_code_sell';
5632 } else {
5633 return -1;
5634 }
5635
5636 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5637 $sql .= $field." = '".$this->db->escape($value)."'";
5638 $sql .= " WHERE rowid = ".((int) $this->id);
5639
5640 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5641 $resql = $this->db->query($sql);
5642
5643 if ($resql) {
5644 // Call triggers
5645 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5646 $interface = new Interfaces($this->db);
5647 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5648 if ($result < 0) {
5649 $this->errors = $interface->errors;
5650 $this->db->rollback();
5651 return -1;
5652 }
5653 // End call triggers
5654
5655 $this->$field = $value;
5656
5657 $this->db->commit();
5658 return 1;
5659 } else {
5660 $this->error = $this->db->lasterror();
5661 $this->db->rollback();
5662 return -1;
5663 }
5664 }
5665
5672 public function fetchPartnerships($mode)
5673 {
5674 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5675
5676 $this->partnerships[] = array();
5677
5678 return 1;
5679 }
5680
5688 public function getKanbanView($option = '', $arraydata = array())
5689 {
5690 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5691
5692 $out = '<div class="box-flex-item box-flex-grow-zero">';
5693 $out .= '<div class="info-box info-box-sm">';
5694 $out .= '<span class="info-box-icon bg-infobox-action">';
5695 if (!empty($this->logo) && class_exists('Form')) {
5696 $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.
5697 } else {
5698 $out .= img_picto('', $this->picto);
5699 }
5700 $out .= '</span>';
5701 $out .= '<div class="info-box-content">';
5702 $out .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">' . $this->getNomUrl(1);
5703 $out .= '</div>';
5704 if (!empty($this->phone)) {
5705 $out .= '<div class="inline-block valignmiddle">';
5706 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5707 $out .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5708 $out .= '</div>';
5709 }
5710 if (!empty($this->email)) {
5711 $out .= '<div class="inline-block valignmiddle">';
5712 $out .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5713 $out .= '</div>';
5714 }
5715 if ($selected >= 0) {
5716 $out .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5717 }
5718 if (!empty($this->code_client)) {
5719 $out .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5720 }
5721 $out .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
5722 $out .= '</div>'; // end info-box-content
5723 $out .= '</div>';
5724 $out .= '</div>';
5725
5726 return $out;
5727 }
5728
5737 public function getContacts($list = 0, $code = '', $element = '')
5738 {
5739 // phpcs:enable
5740 global $langs;
5741
5742 $tab = array();
5743
5744 $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
5745 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5746 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5747 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5748 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5749 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5750 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5751 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5752 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5753 if (!empty($element)) {
5754 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5755 }
5756 if ($code) {
5757 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5758 }
5759 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5760 $sql .= " AND tc.source = 'external'";
5761 $sql .= " AND tc.active = 1";
5762
5763 $sql .= " ORDER BY t.lastname ASC";
5764
5765 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5766 $resql = $this->db->query($sql);
5767 if ($resql) {
5768 $num = $this->db->num_rows($resql);
5769 $i = 0;
5770 while ($i < $num) {
5771 $obj = $this->db->fetch_object($resql);
5772
5773 if (!$list) {
5774 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5775 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5776 $tab[$obj->id] = array(
5777 'source' => $obj->source,
5778 'socid' => $obj->socid,
5779 'id' => $obj->id,
5780 'nom' => $obj->lastname, // For backward compatibility
5781 'civility' => $obj->civility,
5782 'lastname' => $obj->lastname,
5783 'firstname' => $obj->firstname,
5784 'email' => $obj->email,
5785 'login' => (empty($obj->login) ? '' : $obj->login),
5786 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5787 'statuscontact' => $obj->statuscontact,
5788 'rowid' => $obj->rowid,
5789 'code' => $obj->code,
5790 'element' => $obj->element,
5791 'libelle' => $libelle_type,
5792 'status' => $obj->statuslink,
5793 'fk_c_type_contact' => $obj->fk_c_type_contact
5794 );
5795 } else {
5796 $tab[$obj->id] = $obj->id;
5797 }
5798
5799 $i++;
5800 }
5801
5802 return $tab;
5803 } else {
5804 $this->error = $this->db->lasterror();
5805 dol_print_error($this->db);
5806 return -1;
5807 }
5808 }
5809
5820 public function mergeCompany($soc_origin_id)
5821 {
5822 global $conf, $langs, $hookmanager, $user, $action;
5823
5824 $error = 0;
5825 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5826
5827 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5828
5829 if ($soc_origin->fetch($soc_origin_id) < 1) {
5830 $this->error = $langs->trans('ErrorRecordNotFound');
5831 $error++;
5832 }
5833
5834 if (!$error) {
5835 $this->db->begin();
5836
5837 // Recopy some data
5838 $this->client |= $soc_origin->client;
5839 $this->fournisseur |= $soc_origin->fournisseur;
5840 $listofproperties = array(
5841 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5842 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5843 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5844 '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',
5845 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5846 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5847 );
5848 foreach ($listofproperties as $property) {
5849 if (empty($this->$property)) {
5850 $this->$property = $soc_origin->$property;
5851 }
5852 }
5853
5854 if ($this->typent_id == -1) {
5855 $this->typent_id = $soc_origin->typent_id;
5856 }
5857
5858 // Concat some data
5859 $listofproperties = array(
5860 'note_public', 'note_private'
5861 );
5862 foreach ($listofproperties as $property) {
5863 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5864 }
5865
5866 // Merge extrafields
5867 if (is_array($soc_origin->array_options)) {
5868 foreach ($soc_origin->array_options as $key => $val) {
5869 if (empty($this->array_options[$key])) {
5870 $this->array_options[$key] = $val;
5871 }
5872 }
5873 }
5874
5875 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5876 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5877 $this->name_bis = $this->name;
5878 }
5879
5880 // Merge categories
5881 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5882 $static_cat = new Categorie($this->db);
5883
5884 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5885 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5886 $custcats = array_merge($custcats, $custcats_ori);
5887 $this->setCategories($custcats, 'customer');
5888
5889 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5890 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5891 $suppcats = array_merge($suppcats, $suppcats_ori);
5892 $this->setCategories($suppcats, 'supplier');
5893
5894 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5895 if ($soc_origin->code_client == $this->code_client
5896 || $soc_origin->code_fournisseur == $this->code_fournisseur
5897 || $soc_origin->barcode == $this->barcode) {
5898 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5899 $soc_origin->code_client = '';
5900 $soc_origin->code_fournisseur = '';
5901 $soc_origin->barcode = '';
5902 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5903 }
5904
5905 // Update
5906 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5907
5908 if ($result < 0) {
5909 $error++;
5910 }
5911
5912 // Move links
5913 if (!$error) {
5914 $objects = array(
5915 'Adherent' => '/adherents/class/adherent.class.php',
5916 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5917 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5918 'Propal' => '/comm/propal/class/propal.class.php',
5919 'Commande' => '/commande/class/commande.class.php',
5920 'Facture' => '/compta/facture/class/facture.class.php',
5921 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5922 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5923 'Contact' => '/contact/class/contact.class.php',
5924 'Contrat' => '/contrat/class/contrat.class.php',
5925 'Expedition' => '/expedition/class/expedition.class.php',
5926 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5927 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5928 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5929 'Reception' => '/reception/class/reception.class.php',
5930 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5931 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5932 'Product' => '/product/class/product.class.php',
5933 //'ProductThirparty' => '...', // for llx_product_thirdparty
5934 'Project' => '/projet/class/project.class.php',
5935 'User' => '/user/class/user.class.php',
5936 'Account' => '/compta/bank/class/account.class.php',
5937 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5938 'Societe' => '/societe/class/societe.class.php',
5939 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5940 );
5941 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5942 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5943 }
5944 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5945 $objects['Mo'] = '/mrp/class/mo.class.php';
5946 }
5947 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5948 $objects['Don'] = '/don/class/don.class.php';
5949 }
5950 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5951 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5952 }
5953 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5954 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5955 }
5956 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5957 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5958 }
5959
5960 //First, all core objects must update their tables
5961 foreach ($objects as $object_name => $object_file) {
5962 /* $object_file is never an array -> code commented
5963 if (is_array($object_file)) {
5964 if (empty($object_file['enabled'])) {
5965 continue;
5966 }
5967 $object_file = $object_file['file'];
5968 }
5969 */
5970
5971 require_once DOL_DOCUMENT_ROOT.$object_file;
5972
5973 if (!$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5974 $error++;
5975 $this->error = $this->db->lasterror();
5976 break;
5977 }
5978 }
5979 }
5980
5981 // External modules should update their ones too
5982 if (!$error) {
5983 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5984 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5985
5986 if ($reshook < 0) {
5987 $this->error = $hookmanager->error;
5988 $this->errors = $hookmanager->errors;
5989 $error++;
5990 }
5991 }
5992
5993
5994 if (!$error) {
5995 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5996
5997 // Call trigger
5998 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5999 if ($result < 0) {
6000 $error++;
6001 }
6002 // End call triggers
6003 }
6004
6005 if (!$error) {
6006 // We finally remove the old thirdparty
6007 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
6008 $this->error = $soc_origin->error;
6009 $this->errors = $soc_origin->errors;
6010 $error++;
6011 }
6012 }
6013
6014
6015 if (!$error) {
6016 // Move files from the dir of the third party to delete into the dir of the third party to keep
6017 if (!empty($conf->societe->multidir_output[$this->entity])) {
6018 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
6019 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
6020
6021 if (dol_is_dir($srcdir)) {
6022 $dirlist = dol_dir_list($srcdir, 'files', 1);
6023 foreach ($dirlist as $filetomove) {
6024 $destfile = $destdir.'/'.$filetomove['relativename'];
6025 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
6026 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
6027 }
6028 //exit;
6029 }
6030 }
6031 }
6032
6033 if (!$error) {
6034 $this->db->commit();
6035 return 0;
6036 } else {
6037 $langs->load("errors");
6038 $this->error = $langs->trans('ErrorsThirdpartyMerge');
6039 $this->db->rollback();
6040 return -1;
6041 }
6042 }
6043
6044 return -1;
6045 }
6046}
$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)
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
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_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Return the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
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.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='')
Return a link on thirdparty (with picto)
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
deprecatedProperties()
Provide list of deprecated properties and replacements.
getTooltipContentArray($params)
getTooltipContentArray
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
getKanbanView($option='', $arraydata=array())
Return clickable link of object (with optional picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Return the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
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:663
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_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_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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.
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, ....
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
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.
isValidSiren($siren)
Check the syntax validity of a SIREN.
isValidTinForPT($str)
Check the syntax validity of a Portuguese (PT) Tax Identification Number (TIN).
isValidSiret($siret)
Check the syntax validity of a SIRET.
isValidTinForES($str)
Check the syntax validity of a Spanish (ES) Tax Identification Number (TIN), where:
isValidTinForBE($str)
Check the syntax validity of a Belgium (BE) Tax Identification Number (TIN).
isValidTinForDZ($str)
Check the syntax validity of an Algerian (DZ) Tax Identification Number (TIN).
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:128