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->multicurrency_amount_ttc = price2num($remise * (float) $discount->multicurrency_tx, 'MT');
2774 $discount->multicurrency_amount_ht = price2num(((float) $remise / (1 + (float) $vatrate / 100)) * (float) $discount->multicurrency_tx, 'MT');
2775 $discount->multicurrency_amount_tva = price2num(((float) $discount->amount_ttc - (float) $discount->amount_ht) * (float) $discount->multicurrency_tx, 'MT');
2776
2777 $discount->amount_ttc = price2num($remise, 'MT');
2778 $discount->amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2779 $discount->amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2780 } else {
2781 $discount->amount_ht = price2num($remise, 'MT');
2782 $discount->amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2783 $discount->amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2784
2785 $discount->multicurrency_amount_ht = price2num($remise * (float) $discount->multicurrency_tx, 'MT');
2786 $discount->multicurrency_amount_tva = price2num(((float) $remise * (float) $vatrate / 100) * (float) $discount->multicurrency_tx, 'MT');
2787 $discount->multicurrency_amount_ttc = price2num(((float) $discount->amount_ht + (float) $discount->amount_tva) * (float) $discount->multicurrency_tx, 'MT');
2788 }
2789
2790 $discount->tva_tx = (float) price2num($vatrate);
2791 $discount->vat_src_code = $vat_src_code;
2792
2793 $discount->description = $desc;
2794
2795 $result = $discount->create($user);
2796 if ($result > 0) {
2797 return $result;
2798 } else {
2799 $this->error = $discount->error;
2800 return -3;
2801 }
2802 } else {
2803 return 0;
2804 }
2805 }
2806
2816 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2817 {
2818 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2819
2820 $discountstatic = new DiscountAbsolute($this->db);
2821 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2822 if ($result >= 0) {
2823 return $result;
2824 } else {
2825 $this->error = $discountstatic->error;
2826 return -1;
2827 }
2828 }
2829
2830
2837 public function getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type = 0)
2838 {
2839 global $conf;
2840
2841 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ttc) as amount, SUM(f.multicurrency_total_ttc) as multicurrency_amount";
2842 if (!empty($discount_type)) {
2843 $sql .= " FROM ".$this->db->prefix()."facture_fourn as f";
2844 } else {
2845 $sql .= " FROM ".$this->db->prefix()."facture as f";
2846 }
2847 $sql .= " WHERE f.entity = ".$conf->entity;
2848 $sql .= " AND paye = 0 AND fk_statut = 1";
2849 $sql .= " AND f.type = ".CommonInvoice::TYPE_CREDIT_NOTE;
2850 $sql .= " AND NOT EXISTS (SELECT rowid FROM ".$this->db->prefix()."societe_remise_except as rc";
2851 $sql .= " WHERE rc.discount_type = ".((int) $discount_type);
2852 if (!empty($discount_type)) {
2853 $sql .= " AND rc.fk_invoice_supplier = f.rowid";
2854 } else {
2855 $sql .= " AND rc.fk_facture = f.rowid";
2856 }
2857 $sql .= " AND rc.fk_soc = ".((int) $this->id);
2858 $sql .= ")";
2859 $sql .= " AND f.fk_soc = ".((int) $this->id);
2860
2861 $resql = $this->db->query($sql);
2862 if ($resql) {
2863 $obj = $this->db->fetch_object($resql);
2864
2865 return $obj->nb;
2866 }
2867
2868 return -1;
2869 }
2870
2871
2881 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2882 {
2883 global $conf;
2884
2885 $reparray = array();
2886
2887 $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";
2888 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2889 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2890 // Condition here should be the same than into select_dolusers()
2891 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2892 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2893 } else {
2894 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
2895 }
2896
2897 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2898 if (empty($sortfield)) {
2899 $sortfield = 'u.lastname,u.firstname';
2900 }
2901 if (empty($sortorder)) {
2902 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
2903 }
2904 $sql .= $this->db->order($sortfield, $sortorder);
2905
2906 $resql = $this->db->query($sql);
2907 if ($resql) {
2908 $num = $this->db->num_rows($resql);
2909 $i = 0;
2910 while ($i < $num) {
2911 $obj = $this->db->fetch_object($resql);
2912
2913 if (empty($mode)) {
2914 $reparray[$i]['id'] = (int) $obj->rowid;
2915 $reparray[$i]['lastname'] = $obj->lastname;
2916 $reparray[$i]['firstname'] = $obj->firstname;
2917 $reparray[$i]['email'] = $obj->email;
2918 $reparray[$i]['phone'] = $obj->office_phone;
2919 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2920 $reparray[$i]['office_fax'] = $obj->office_fax;
2921 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2922 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2923 $reparray[$i]['job'] = $obj->job;
2924 $reparray[$i]['statut'] = $obj->status; // deprecated
2925 $reparray[$i]['status'] = $obj->status;
2926 $reparray[$i]['entity'] = $obj->entity;
2927 $reparray[$i]['login'] = $obj->login;
2928 $reparray[$i]['photo'] = $obj->photo;
2929 $reparray[$i]['gender'] = $obj->gender;
2930 } else {
2931 $reparray[] = (int) $obj->rowid;
2932 }
2933 $i++;
2934 }
2935 return $reparray;
2936 } else {
2937 dol_print_error($this->db);
2938 return -1;
2939 }
2940 }
2941
2949 public function setPriceLevel($price_level, User $user)
2950 {
2951 if ($this->id) {
2952 $now = dol_now();
2953
2954 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2955 $sql .= " SET price_level = ".((int) $price_level);
2956 $sql .= " WHERE rowid = ".((int) $this->id);
2957
2958 if (!$this->db->query($sql)) {
2959 dol_print_error($this->db);
2960 return -1;
2961 }
2962
2963 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2964 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2965 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2966
2967 if (!$this->db->query($sql)) {
2968 dol_print_error($this->db);
2969 return -1;
2970 }
2971 return 1;
2972 }
2973 return -1;
2974 }
2975
2976 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2984 public function add_commercial(User $user, $commid)
2985 {
2986 // phpcs:enable
2987 $error = 0;
2988
2989 if ($this->id > 0 && $commid > 0) {
2990 $this->db->begin();
2991
2992 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2993 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2994
2995 $resql = $this->db->query($sql);
2996 if (!$resql) {
2997 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2998 $error++;
2999 }
3000
3001 if (!$error) {
3002 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
3003 $sql .= " (fk_soc, fk_user)";
3004 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
3005
3006 $resql = $this->db->query($sql);
3007 if (!$resql) {
3008 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3009 $error++;
3010 }
3011 }
3012
3013 if (!$error) {
3014 $this->context = array('commercial_modified' => $commid);
3015
3016 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3017 if ($result < 0) {
3018 $error++;
3019 }
3020 }
3021
3022 if (!$error) {
3023 $this->db->commit();
3024 return 1;
3025 } else {
3026 $this->db->rollback();
3027 return -1;
3028 }
3029 }
3030
3031 return 0;
3032 }
3033
3034 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3042 public function del_commercial(User $user, $commid)
3043 {
3044 // phpcs:enable
3045 $error = 0;
3046 $this->context = array('commercial_modified' => $commid);
3047
3048 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3049 if ($result < 0) {
3050 $error++;
3051 }
3052
3053 if ($this->id > 0 && $commid > 0) {
3054 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3055 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3056
3057 if (!$this->db->query($sql)) {
3058 $error++;
3059 dol_syslog(get_class($this)."::del_commercial Erreur");
3060 }
3061 }
3062
3063 if ($error) {
3064 return -1;
3065 } else {
3066 return 1;
3067 }
3068 }
3069
3077 public function getTooltipContentArray($params)
3078 {
3079 global $conf, $langs, $user;
3080
3081 $langs->loadLangs(['companies', 'commercial']);
3082
3083 $datas = array();
3084
3085 $option = $params['option'] ?? '';
3086 $nofetch = !empty($params['nofetch']);
3087
3088 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3089
3090 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3091 return ['optimize' => $langs->trans("ShowCompany")];
3092 }
3093
3094 if (!empty($this->logo) && class_exists('Form')) {
3095 $photo = '<div class="photointooltip floatright">';
3096 $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.
3097 $photo .= '</div>';
3098 $datas['photo'] = $photo;
3099 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3100 /*$label.= '<div class="photointooltip">';
3101 $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.
3102 $label.= '</div><div style="clear: both;"></div>';*/
3103 // }
3104
3105 $datas['divopen'] = '<div class="centpercent">';
3106
3107 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3108 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3109 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3110 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3111 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3112 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3113 } elseif ($option == 'agenda') {
3114 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3115 } elseif ($option == 'project') {
3116 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3117 } elseif ($option == 'margin') {
3118 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3119 } elseif ($option == 'contact') {
3120 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3121 } elseif ($option == 'ban') {
3122 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3123 }
3124
3125 // By default
3126 if (empty($datas['picto'])) {
3127 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3128 }
3129 if (isset($this->status)) {
3130 $datas['status'] = ' '.$this->getLibStatut(5);
3131 }
3132 if (isset($this->client) && isset($this->fournisseur)) {
3133 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3134 }
3135 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3136 if (!empty($this->name_alias) && empty($noaliasinname)) {
3137 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3138 }
3139 if (!empty($this->email)) {
3140 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3141 }
3142 if (!empty($this->url)) {
3143 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3144 }
3145 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3146 $phonelist = array();
3147 if ($this->phone) {
3148 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3149 }
3150 // deliberately not making new list because fax uses same list as phone
3151 if ($this->phone_mobile) {
3152 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3153 }
3154 if ($this->fax) {
3155 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3156 }
3157 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3158 }
3159
3160 if (!empty($this->address)) {
3161 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3162 } elseif (!empty($this->country_code)) {
3163 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3164 }
3165 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3166 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3167 }
3168
3169 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3170 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3171 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3172 }
3173 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3174 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3175 }
3176 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3177 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3178 }
3179 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3180 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3181 }
3182 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3183 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3184 }
3185 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3186 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3187 }
3188 }
3189
3190 $datas['separator'] = '<br>';
3191
3192 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3193 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3194 }
3195 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3196 $langs->load('compta');
3197 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3198 }
3199 // show categories for this record only in ajax to not overload lists
3200 if (!$nofetch && isModEnabled('category') && $this->client) {
3201 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3202 $form = new Form($this->db);
3203 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3204 }
3205 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3206 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3207 }
3208 if (isModEnabled('accounting') && $this->fournisseur) {
3209 $langs->load('compta');
3210 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3211 }
3212 // show categories for this record only in ajax to not overload lists
3213 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3214 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3215 $form = new Form($this->db);
3216 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3217 }
3218
3219 $datas['divclose'] = '</div>';
3220
3221 return $datas;
3222 }
3223
3237 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3238 {
3239 global $conf, $langs, $hookmanager, $user;
3240
3241 if (!empty($conf->dol_no_mouse_hover)) {
3242 $notooltip = 1; // Force disable tooltips
3243 }
3244
3245 $name = $this->name ? $this->name : $this->nom;
3246
3247 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3248 if (empty($option) && $this->client > 0) {
3249 $option = 'customer';
3250 }
3251 if (empty($option) && $this->fournisseur > 0) {
3252 $option = 'supplier';
3253 }
3254 }
3255
3256 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3257 $code = '';
3258 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3259 $code = $this->code_client.' - ';
3260 }
3261
3262 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3263 $code .= $this->code_fournisseur.' - ';
3264 }
3265
3266 if ($code) {
3267 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3268 $name = $code.' '.$name;
3269 } else {
3270 $name = $code;
3271 }
3272 }
3273 }
3274
3275 if (!empty($this->name_alias) && empty($noaliasinname)) {
3276 $name .= ' ('.$this->name_alias.')';
3277 }
3278
3279 $result = '';
3280 $params = [
3281 'id' => $this->id,
3282 'objecttype' => $this->element,
3283 'option' => $option,
3284 'nofetch' => 1,
3285 ];
3286 $classfortooltip = 'classfortooltip';
3287 $dataparams = '';
3288 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3289 $classfortooltip = 'classforajaxtooltip';
3290 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3291 $label = '';
3292 } else {
3293 $label = implode($this->getTooltipContentArray($params));
3294 }
3295
3296 $linkstart = '';
3297 $linkend = '';
3298
3299 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3300 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3301 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3302 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3303 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3304 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3305 } elseif ($option == 'agenda') {
3306 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3307 } elseif ($option == 'project') {
3308 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3309 } elseif ($option == 'margin') {
3310 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3311 } elseif ($option == 'contact') {
3312 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3313 } elseif ($option == 'ban') {
3314 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3315 }
3316
3317 // By default
3318 if (empty($linkstart)) {
3319 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3320 }
3321
3322 // Add type of canvas
3323 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3324 // Add param to save lastsearch_values or not
3325 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3326 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3327 $add_save_lastsearch_values = 1;
3328 }
3329 if ($add_save_lastsearch_values) {
3330 $linkstart .= '&save_lastsearch_values=1';
3331 }
3332 $linkstart .= '"';
3333
3334 $linkclose = '';
3335 if (empty($notooltip)) {
3336 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3337 $label = $langs->trans("ShowCompany");
3338 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3339 }
3340 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3341 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3342 $target_value = array('_self', '_blank', '_parent', '_top');
3343 if (in_array($target, $target_value)) {
3344 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3345 }
3346 } else {
3347 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3348 }
3349 $linkstart .= $linkclose.'>';
3350 $linkend = '</a>';
3351
3352 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3353 $linkstart = '';
3354 $linkend = '';
3355 }
3356
3357 $result .= $linkstart;
3358 if ($withpicto) {
3359 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3360 }
3361 if ($withpicto != 2) {
3362 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3363 }
3364 $result .= $linkend;
3365
3366 global $action;
3367 $hookmanager->initHooks(array('thirdpartydao'));
3368 $parameters = array(
3369 'id' => $this->id,
3370 'getnomurl' => &$result,
3371 'withpicto ' => $withpicto,
3372 'option' => $option,
3373 'maxlen' => $maxlen,
3374 'notooltip' => $notooltip,
3375 'save_lastsearch_value' => $save_lastsearch_value
3376 );
3377 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3378 if ($reshook > 0) {
3379 $result = $hookmanager->resPrint;
3380 } else {
3381 $result .= $hookmanager->resPrint;
3382 }
3383
3384 return $result;
3385 }
3386
3396 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3397 {
3398 global $langs;
3399
3400 $s = '';
3401 if (empty($option) || preg_match('/prospect/', $option)) {
3402 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3403 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3404 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3405 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3406 }
3407 }
3408 if (empty($option) || preg_match('/customer/', $option)) {
3409 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3410 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3411 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3412 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3413 }
3414 }
3415 if (empty($option) || preg_match('/supplier/', $option)) {
3416 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3417 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3418 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3419 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3420 }
3421 }
3422
3423 return $s;
3424 }
3425
3426
3433 public function getLibStatut($mode = 0)
3434 {
3435 return $this->LibStatut($this->status, $mode);
3436 }
3437
3438 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3446 public function LibStatut($status, $mode = 0)
3447 {
3448 // phpcs:enable
3449 global $langs;
3450 $langs->load('companies');
3451
3452 $statusType = 'status4';
3453 if ($status == 0) {
3454 $statusType = 'status6';
3455 }
3456
3457 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3458 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3459 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3460 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3461 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3462 }
3463
3464 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3465 }
3466
3467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3474 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3475 {
3476 // phpcs:enable
3477 global $langs;
3478
3479 $contact_emails = $this->contact_property_array('email', 1);
3480
3481 if ($this->email && $addthirdparty) {
3482 if (empty($this->name)) {
3483 $this->name = $this->nom;
3484 }
3485 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3486 }
3487
3488 //var_dump($contact_emails)
3489 return $contact_emails;
3490 }
3491
3492 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3499 {
3500 // phpcs:enable
3501 global $langs;
3502
3503 $contact_phone = $this->contact_property_array('mobile');
3504
3505 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3506 if (empty($this->name)) {
3507 $this->name = $this->nom;
3508 }
3509 // TODO: Tester si tel non deja present dans tableau contact
3510 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3511 }
3512 return $contact_phone;
3513 }
3514
3515 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3523 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3524 {
3525 // phpcs:enable
3526 global $langs;
3527
3528 $contact_property = array();
3529
3530
3531 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3532 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3533 $sql .= " WHERE fk_soc = ".((int) $this->id);
3534 $sql .= " AND entity IN (".getEntity($this->element).")";
3535 $sql .= " ORDER BY lastname, firstname";
3536
3537 $resql = $this->db->query($sql);
3538 if ($resql) {
3539 $nump = $this->db->num_rows($resql);
3540 if ($nump) {
3541 $sepa = "(";
3542 $sepb = ")";
3543 if ($mode == 'email') {
3544 //$sepa="&lt;"; $sepb="&gt;";
3545 $sepa = "<";
3546 $sepb = ">";
3547 }
3548 $i = 0;
3549 while ($i < $nump) {
3550 $obj = $this->db->fetch_object($resql);
3551 if ($mode == 'email') {
3552 $property = $obj->email;
3553 } elseif ($mode == 'mobile') {
3554 $property = $obj->phone_mobile;
3555 } else {
3556 $property = $obj->$mode;
3557 }
3558
3559 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3560 if ($obj->status == 1 || empty($hidedisabled)) {
3561 if (empty($property)) {
3562 if ($mode == 'email') {
3563 $property = $langs->transnoentitiesnoconv("NoEMail");
3564 } elseif ($mode == 'mobile') {
3565 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3566 }
3567 }
3568
3569 if (!empty($obj->poste)) {
3570 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3571 } else {
3572 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3573 }
3574 }
3575 $i++;
3576 }
3577 }
3578 } else {
3579 dol_print_error($this->db);
3580 }
3581 return $contact_property;
3582 }
3583
3584
3585 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3591 public function contact_array()
3592 {
3593 // phpcs:enable
3594 $contacts = array();
3595
3596 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3597 $resql = $this->db->query($sql);
3598 if ($resql) {
3599 $nump = $this->db->num_rows($resql);
3600 if ($nump) {
3601 $i = 0;
3602 while ($i < $nump) {
3603 $obj = $this->db->fetch_object($resql);
3604 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3605 $i++;
3606 }
3607 }
3608 } else {
3609 dol_print_error($this->db);
3610 }
3611 return $contacts;
3612 }
3613
3614 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3620 public function contact_array_objects()
3621 {
3622 // phpcs:enable
3623 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3624 $contacts = array();
3625
3626 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3627 $resql = $this->db->query($sql);
3628 if ($resql) {
3629 $nump = $this->db->num_rows($resql);
3630 if ($nump) {
3631 $i = 0;
3632 while ($i < $nump) {
3633 $obj = $this->db->fetch_object($resql);
3634 $contact = new Contact($this->db);
3635 $contact->fetch($obj->rowid);
3636 $contacts[] = $contact;
3637 $i++;
3638 }
3639 }
3640 } else {
3641 dol_print_error($this->db);
3642 }
3643 return $contacts;
3644 }
3645
3646 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3654 public function contact_get_property($rowid, $mode)
3655 {
3656 // phpcs:enable
3657 $contact_property = '';
3658
3659 if (empty($rowid)) {
3660 return '';
3661 }
3662
3663 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3664 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3665 $sql .= " WHERE rowid = ".((int) $rowid);
3666
3667 $resql = $this->db->query($sql);
3668 if ($resql) {
3669 $nump = $this->db->num_rows($resql);
3670
3671 if ($nump) {
3672 $obj = $this->db->fetch_object($resql);
3673
3674 if ($mode == 'email') {
3675 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3676 } elseif ($mode == 'mobile') {
3677 $contact_property = $obj->phone_mobile;
3678 }
3679 }
3680 return $contact_property;
3681 } else {
3682 dol_print_error($this->db);
3683 }
3684
3685 return '';
3686 }
3687
3688
3689 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3696 public function display_rib($mode = 'label')
3697 {
3698 // phpcs:enable
3699 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3700
3701 $bac = new CompanyBankAccount($this->db);
3702 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3703 $bac->fetch(0, '', $this->id);
3704
3705 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3706 if ($mode == 'label') {
3707 return $bac->getRibLabel(true);
3708 } elseif ($mode == 'rum') {
3709 if (empty($bac->rum)) {
3710 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3711 $prelevement = new BonPrelevement($this->db);
3712 $bac->fetch_thirdparty();
3713 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3714 }
3715 return $bac->rum;
3716 } elseif ($mode == 'format') {
3717 return $bac->frstrecur;
3718 } else {
3719 return 'BadParameterToFunctionDisplayRib';
3720 }
3721 } else {
3722 return '';
3723 }
3724 }
3725
3726 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3732 public function get_all_rib()
3733 {
3734 // phpcs:enable
3735 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3736 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3737 $result = $this->db->query($sql);
3738 if (!$result) {
3739 $this->error = $this->db->lasterror();
3740 $this->errors[] = $this->db->lasterror();
3741 return 0;
3742 } else {
3743 $num_rows = $this->db->num_rows($result);
3744 $rib_array = array();
3745 if ($num_rows) {
3746 while ($obj = $this->db->fetch_object($result)) {
3747 $rib = new CompanyBankAccount($this->db);
3748 $rib->fetch($obj->rowid);
3749 $rib_array[] = $rib;
3750 }
3751 }
3752 return $rib_array;
3753 }
3754 }
3755
3759 public function getDefaultRib()
3760 {
3761 // phpcs:enable
3762 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3763 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3764 $resql = $this->db->query($sql);
3765 if (!$resql) {
3766 $this->error = $this->db->lasterror();
3767 $this->errors[] = $this->db->lasterror();
3768 return -1;
3769 } else {
3770 $num_rows = $this->db->num_rows($resql);
3771 $rib_array = array();
3772 if ($num_rows) {
3773 while ($obj = $this->db->fetch_object($resql)) {
3774 return $obj->rowid;
3775 }
3776 }
3777 return 0;
3778 }
3779 }
3780
3781
3782 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3791 public function get_codeclient($objsoc = null, $type = 0)
3792 {
3793 // phpcs:enable
3794 global $conf;
3795 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3796 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3797
3798 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3799 foreach ($dirsociete as $dirroot) {
3800 $res = dol_include_once($dirroot.$module.'.php');
3801 if ($res) {
3802 break;
3803 }
3804 }
3806 $mod = new $module($this->db);
3807 '@phan-var-force ModeleThirdPartyCode $mod';
3808
3809 $this->code_client = $mod->getNextValue($objsoc, $type);
3810 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3811
3812 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3813 }
3814 }
3815
3816 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3825 public function get_codefournisseur($objsoc = null, $type = 1)
3826 {
3827 // phpcs:enable
3828 global $conf;
3829 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3830 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3831
3832 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3833 foreach ($dirsociete as $dirroot) {
3834 $res = dol_include_once($dirroot.$module.'.php');
3835 if ($res) {
3836 break;
3837 }
3838 }
3840 $mod = new $module($this->db);
3841 '@phan-var-force ModeleThirdPartyCode $mod';
3842
3843 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3844
3845 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3846 }
3847 }
3848
3849 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3856 public function codeclient_modifiable()
3857 {
3858 // phpcs:enable
3859 global $conf;
3860 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3861 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3862
3863 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3864 foreach ($dirsociete as $dirroot) {
3865 $res = dol_include_once($dirroot.$module.'.php');
3866 if ($res) {
3867 break;
3868 }
3869 }
3870
3871 $mod = new $module($this->db);
3872 '@phan-var-force ModeleThirdPartyCode $mod';
3873
3874 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3875 if ($mod->code_modifiable_null && !$this->code_client) {
3876 return 1;
3877 }
3878 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3879 return 1;
3880 }
3881 if ($mod->code_modifiable) {
3882 return 1; // A mettre en dernier
3883 }
3884 return 0;
3885 } else {
3886 return 0;
3887 }
3888 }
3889
3890
3891 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3898 {
3899 // phpcs:enable
3900 global $conf;
3901 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3902 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3903
3904 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3905 foreach ($dirsociete as $dirroot) {
3906 $res = dol_include_once($dirroot.$module.'.php');
3907 if ($res) {
3908 break;
3909 }
3910 }
3911
3912 $mod = new $module($this->db);
3913 '@phan-var-force ModeleThirdPartyCode $mod';
3914
3915 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3916 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3917 return 1;
3918 }
3919 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3920 return 1;
3921 }
3922 if ($mod->code_modifiable) {
3923 return 1; // A mettre en dernier
3924 }
3925 return 0;
3926 } else {
3927 return 0;
3928 }
3929 }
3930
3931
3932 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3944 public function check_codeclient()
3945 {
3946 // phpcs:enable
3947 global $conf;
3948 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3949 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3950
3951 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3952 foreach ($dirsociete as $dirroot) {
3953 $res = dol_include_once($dirroot.$module.'.php');
3954 if ($res) {
3955 break;
3956 }
3957 }
3958
3959 $mod = new $module($this->db);
3960 '@phan-var-force ModeleThirdPartyCode $mod';
3961
3962 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3963 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3964 if ($result) { // If error
3965 $this->error = $mod->error;
3966 $this->errors = $mod->errors;
3967 }
3968 return $result;
3969 } else {
3970 return 0;
3971 }
3972 }
3973
3974 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3986 public function check_codefournisseur()
3987 {
3988 // phpcs:enable
3989 global $conf;
3990 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3991 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3992
3993 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3994 foreach ($dirsociete as $dirroot) {
3995 $res = dol_include_once($dirroot.$module.'.php');
3996 if ($res) {
3997 break;
3998 }
3999 }
4000
4001 $mod = new $module($this->db);
4002 '@phan-var-force ModeleThirdPartyCode $mod';
4003
4004 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4005 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
4006 if ($result) { // If error
4007 $this->error = $mod->error;
4008 $this->errors = $mod->errors;
4009 }
4010 return $result;
4011 } else {
4012 return 0;
4013 }
4014 }
4015
4016 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4025 public function get_codecompta($type)
4026 {
4027 // phpcs:enable
4028 global $conf;
4029
4030 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
4031 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
4032 $res = false;
4033 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4034 foreach ($dirsociete as $dirroot) {
4035 $res = dol_include_once($dirroot.$module.'.php');
4036 if ($res) {
4037 break;
4038 }
4039 }
4040
4041 if ($res) {
4042 $mod = new $module();
4043 '@phan-var-force ModeleAccountancyCode $mod';
4044
4045 // Set code count in $mod->code
4046 $result = $mod->get_code($this->db, $this, $type);
4047
4048 if ($type == 'customer') {
4049 $this->code_compta_client = $mod->code;
4050 } elseif ($type == 'supplier') {
4051 $this->code_compta_fournisseur = $mod->code;
4052 }
4053
4054 return $result;
4055 } else {
4056 $this->error = 'ErrorAccountancyCodeNotDefined';
4057 return -1;
4058 }
4059 } else {
4060 if ($type == 'customer') {
4061 $this->code_compta_client = '';
4062 } elseif ($type == 'supplier') {
4063 $this->code_compta_fournisseur = '';
4064 }
4065
4066 return 0;
4067 }
4068 }
4069
4076 public function setParent($id)
4077 {
4078 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4079
4080 if ($this->id) {
4081 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4082 if ($id > 0) {
4083 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4084 if ($sameparent < 0) {
4085 return -1;
4086 }
4087 if ($sameparent == 1) {
4088 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4089 return -1;
4090 }
4091 }
4092
4093 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
4094
4095 $resql = $this->db->query($sql);
4096 if ($resql) {
4097 $this->parent = $id;
4098 return 1;
4099 } else {
4100 return -1;
4101 }
4102 }
4103
4104 return -1;
4105 }
4106
4115 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4116 {
4117 if ($counter > 100) {
4118 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4119 }
4120
4121 $sql = 'SELECT s.parent';
4122 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4123 $sql .= ' WHERE rowid = '.((int) $idparent);
4124 $resql = $this->db->query($sql);
4125 if ($resql) {
4126 $obj = $this->db->fetch_object($resql);
4127
4128 if ($obj->parent == '') {
4129 return 0;
4130 } elseif ($obj->parent == $idchild) {
4131 return 1;
4132 } else {
4133 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4134 }
4135 return $sameparent;
4136 } else {
4137 return -1;
4138 }
4139 }
4140
4148 public function getParentsForCompany($company_id, $parents = array())
4149 {
4150 global $langs;
4151
4152 if ($company_id > 0) {
4153 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4154 $resql = $this->db->query($sql);
4155 if ($resql) {
4156 if ($obj = $this->db->fetch_object($resql)) {
4157 $parent = $obj->parent;
4158 if ($parent > 0 && !in_array($parent, $parents)) {
4159 $parents[] = $parent;
4160 return $this->getParentsForCompany($parent, $parents);
4161 } else {
4162 return $parents;
4163 }
4164 }
4165 $this->db->free($resql);
4166 } else {
4167 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4168 }
4169 }
4170 // Return a default value when $company_id is not greater than 0
4171 return array();
4172 }
4173
4174 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4181 public function id_prof_verifiable($idprof)
4182 {
4183 // phpcs:enable
4184 global $conf;
4185
4186 switch ($idprof) {
4187 case 1:
4188 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4189 break;
4190 case 2:
4191 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4192 break;
4193 case 3:
4194 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4195 break;
4196 case 4:
4197 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4198 break;
4199 case 5:
4200 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4201 break;
4202 case 6:
4203 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4204 break;
4205 default:
4206 $ret = false;
4207 }
4208
4209 return $ret;
4210 }
4211
4212 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4221 public function id_prof_exists($idprof, $value, $socid = 0)
4222 {
4223 // phpcs:enable
4224 $field = $idprof;
4225
4226 switch ($idprof) { // For backward compatibility
4227 case '1':
4228 case 'idprof1':
4229 $field = "siren";
4230 break;
4231 case '2':
4232 case 'idprof2':
4233 $field = "siret";
4234 break;
4235 case '3':
4236 case 'idprof3':
4237 $field = "ape";
4238 break;
4239 case '4':
4240 case 'idprof4':
4241 $field = "idprof4";
4242 break;
4243 case '5':
4244 $field = "idprof5";
4245 break;
4246 case '6':
4247 $field = "idprof6";
4248 break;
4249 }
4250
4251 //Verify duplicate entries
4252 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4253 if ($socid) {
4254 $sql .= " AND rowid <> ".$socid;
4255 }
4256 $resql = $this->db->query($sql);
4257 if ($resql) {
4258 $obj = $this->db->fetch_object($resql);
4259 $count = $obj->nb;
4260 } else {
4261 $count = 0;
4262 print $this->db->error();
4263 }
4264 $this->db->free($resql);
4265
4266 if ($count > 0) {
4267 return true;
4268 } else {
4269 return false;
4270 }
4271 }
4272
4273 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4282 public function id_prof_check($idprof, $soc)
4283 {
4284 // phpcs:enable
4285
4286 $ok = 1;
4287
4288 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4289 return 1;
4290 }
4291
4292 // load the library necessary to check the professional identifiers
4293 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4294
4295 // Check SIREN
4296 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4297 return -1;
4298 }
4299
4300 // Check SIRET
4301 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4302 return -1;
4303 }
4304
4305 //Verify CIF/NIF/NIE if pays ES
4306 if ($idprof == 1 && $soc->country_code == 'ES') {
4307 return isValidTinForES($this->idprof1);
4308 }
4309
4310 //Verify NIF if country is PT
4311 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4312 return -1;
4313 }
4314
4315 //Verify NIF if country is DZ
4316 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4317 return -1;
4318 }
4319
4320 //Verify ID Prof 1 if country is BE
4321 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4322 return -1;
4323 }
4324
4325 return $ok;
4326 }
4327
4328 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4337 public function id_prof_url($idprof, $thirdparty)
4338 {
4339 // phpcs:enable
4340 global $langs, $hookmanager;
4341
4342 $url = '';
4343 $action = '';
4344
4345 $hookmanager->initHooks(array('idprofurl'));
4346 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4347 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4348 if (empty($reshook)) {
4349 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4350 return '';
4351 }
4352
4353 // TODO Move links to validate professional ID into the dictionary table "country" + column "linkidprof1"
4354 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4355 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4356 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.urlencode($strippedIdProf1); // See also http://avis-situation-sirene.insee.fr/
4357 }
4358 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4359 $url = 'https://beta.companieshouse.gov.uk/company/'.urlencode($strippedIdProf1);
4360 }
4361 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4362 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.urlencode($strippedIdProf1);
4363 }
4364 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4365 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.urlencode($strippedIdProf1).';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4366 }
4367 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4368 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.urlencode($strippedIdProf1);
4369 }
4370 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4371 $url = 'http://www.nif.pt/'.urlencode($strippedIdProf1);
4372 }
4373
4374 if ($url) {
4375 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4376 }
4377 } else {
4378 return $hookmanager->resPrint;
4379 }
4380
4381 return '';
4382 }
4383
4384 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4390 public function has_projects()
4391 {
4392 // phpcs:enable
4393 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4394 $resql = $this->db->query($sql);
4395 if ($resql) {
4396 $obj = $this->db->fetch_object($resql);
4397 $count = $obj->numproj;
4398 } else {
4399 $count = 0;
4400 print $this->db->error();
4401 }
4402 $this->db->free($resql);
4403 return ($count > 0);
4404 }
4405
4406
4413 public function info($id)
4414 {
4415 $sql = "SELECT s.rowid, s.nom as name, s.datec, GREATEST(s.tms, sef.tms) as datem,";
4416 $sql .= " fk_user_creat, fk_user_modif";
4417 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4418 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as sef ON sef.fk_object=s.rowid";
4419 $sql .= " WHERE s.rowid = ".((int) $id);
4420
4421 $result = $this->db->query($sql);
4422 if ($result) {
4423 if ($this->db->num_rows($result)) {
4424 $obj = $this->db->fetch_object($result);
4425
4426 $this->id = $obj->rowid;
4427
4428 $this->user_creation_id = $obj->fk_user_creat;
4429 $this->user_modification_id = $obj->fk_user_modif;
4430 $this->date_creation = $this->db->jdate($obj->datec);
4431 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4432
4433 $this->ref = $obj->name;
4434 }
4435
4436 $this->db->free($result);
4437 } else {
4438 dol_print_error($this->db);
4439 }
4440 }
4441
4447 public function isACompany()
4448 {
4449 //global $mysoc;
4450
4451 // Define if third party is treated as company (or not) when nature is unknown
4452 //$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
4453 $defaultvalue = 1;
4454 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', $defaultvalue);
4455
4456 // Now try to guess using different tips
4457 if (!empty($this->tva_intra)) {
4458 $isACompany = 2;
4459 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4460 $isACompany = 3;
4461 } else {
4462 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4463 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4464 $isACompany = 0;
4465 }
4466 } else {
4467 $isACompany = 4;
4468 }
4469 }
4470
4471 return $isACompany;
4472 }
4473
4479 public function isInEEC()
4480 {
4481 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4482 return isInEEC($this);
4483 }
4484
4490 public function isInSEPA()
4491 {
4492 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4493 return isInSEPA($this);
4494 }
4495
4496 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4502 public function LoadSupplierCateg()
4503 {
4504 // phpcs:enable
4505 $this->SupplierCategories = array();
4506 $sql = "SELECT rowid, label";
4507 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4508 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4509
4510 $resql = $this->db->query($sql);
4511 if ($resql) {
4512 while ($obj = $this->db->fetch_object($resql)) {
4513 $this->SupplierCategories[$obj->rowid] = $obj->label;
4514 }
4515 return 0;
4516 } else {
4517 return -1;
4518 }
4519 }
4520
4521 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4528 public function AddFournisseurInCategory($categorie_id)
4529 {
4530 // phpcs:enable
4531 if ($categorie_id > 0 && $this->id > 0) {
4532 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4533 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4534
4535 if ($resql = $this->db->query($sql)) {
4536 return 0;
4537 }
4538 } else {
4539 return 0;
4540 }
4541 return -1;
4542 }
4543
4549 public function getNbOfEMailings()
4550 {
4551 $sql = "SELECT count(mc.email) as nb";
4552 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4553 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4554 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4555
4556 $resql = $this->db->query($sql);
4557 if ($resql) {
4558 $obj = $this->db->fetch_object($resql);
4559 $nb = (int) $obj->nb;
4560
4561 $this->db->free($resql);
4562 return $nb;
4563 } else {
4564 $this->error = $this->db->error();
4565 return -1;
4566 }
4567 }
4568
4576 public function setNoEmail($no_email, $unsubscribegroup = '')
4577 {
4578 $error = 0;
4579
4580 // Update mass emailing flag into table mailing_unsubscribe
4581 if ($this->email) {
4582 $this->db->begin();
4583
4584 if ($no_email) {
4585 // TODO Add $unsubscribegroup
4586 $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)."'";
4587 $resql = $this->db->query($sql);
4588 if ($resql) {
4589 $obj = $this->db->fetch_object($resql);
4590 $noemail = $obj->nb;
4591 if (empty($noemail)) {
4592 // TODO Add $unsubscribegroup
4593 $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())."')";
4594 $resql = $this->db->query($sql);
4595 if (!$resql) {
4596 $error++;
4597 $this->error = $this->db->lasterror();
4598 $this->errors[] = $this->error;
4599 }
4600 }
4601 } else {
4602 $error++;
4603 $this->error = $this->db->lasterror();
4604 $this->errors[] = $this->error;
4605 }
4606 } else {
4607 // TODO Add $unsubscribegroup
4608 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4609 $resql = $this->db->query($sql);
4610 if (!$resql) {
4611 $error++;
4612 $this->error = $this->db->lasterror();
4613 $this->errors[] = $this->error;
4614 }
4615 }
4616
4617 if (empty($error)) {
4618 $this->no_email = $no_email;
4619 $this->db->commit();
4620 return 1;
4621 } else {
4622 $this->db->rollback();
4623 return $error * -1;
4624 }
4625 }
4626
4627 return 0;
4628 }
4629
4636 public function getNoEmail()
4637 {
4638 if ($this->email) {
4639 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4640 $resql = $this->db->query($sql);
4641 if ($resql) {
4642 $obj = $this->db->fetch_object($resql);
4643 $this->no_email = $obj->nb;
4644 return 1;
4645 } else {
4646 $this->error = $this->db->lasterror();
4647 $this->errors[] = $this->error;
4648 return -1;
4649 }
4650 }
4651 return 0;
4652 }
4653
4654 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4664 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4665 {
4666 // phpcs:enable
4667 global $user, $langs;
4668
4669 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4670 $fullname = $member->getFullName($langs);
4671
4672 if ($member->morphy == 'mor') {
4673 if (empty($socname)) {
4674 $socname = $member->company ? $member->company : $member->societe;
4675 }
4676 if (!empty($fullname) && empty($socalias)) {
4677 $socalias = $fullname;
4678 }
4679 } elseif (empty($socname) && $member->morphy == 'phy') {
4680 if (empty($socname)) {
4681 $socname = $fullname;
4682 }
4683 if (!empty($member->company) && empty($socalias)) {
4684 $socalias = $member->company;
4685 }
4686 }
4687
4688 $name = $socname;
4689 $alias = $socalias ? $socalias : '';
4690
4691 // Positionne parameters
4692 $this->nom = $name; // TODO deprecated
4693 $this->name = $name;
4694 $this->name_alias = $alias;
4695 $this->address = $member->address;
4696 $this->zip = $member->zip;
4697 $this->town = $member->town;
4698 $this->country_code = $member->country_code;
4699 $this->country_id = $member->country_id;
4700 $this->phone = $member->phone; // Prof phone
4701 $this->email = $member->email;
4702 $this->socialnetworks = $member->socialnetworks;
4703 $this->entity = $member->entity;
4704
4705 $this->client = 1; // A member is a customer by default
4706 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4707 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4708 } else {
4709 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4710 }
4711 $this->code_fournisseur = '-1';
4712 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4713 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4714
4715 $this->db->begin();
4716
4717 // Cree et positionne $this->id
4718 $result = $this->create($user);
4719
4720 if ($result >= 0) {
4721 // Auto-create contact on thirdparty creation
4722 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4723 // Fill fields needed by contact
4724 $this->name_bis = $member->lastname;
4725 $this->firstname = $member->firstname;
4726 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4727 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4728
4729 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4730 $result = $this->create_individual($user);
4731
4732 if ($result < 0) {
4733 setEventMessages($this->error, $this->errors, 'errors');
4734 $this->db->rollback();
4735 return -1;
4736 }
4737 }
4738
4739 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4740 $sql .= " SET fk_soc = ".((int) $this->id);
4741 $sql .= " WHERE rowid = ".((int) $member->id);
4742
4743 $resql = $this->db->query($sql);
4744 if ($resql) {
4745 $this->db->commit();
4746 return $this->id;
4747 } else {
4748 $this->error = $this->db->error();
4749
4750 $this->db->rollback();
4751 return -1;
4752 }
4753 } else {
4754 // $this->error deja positionne
4755 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4756
4757 $this->db->rollback();
4758 return $result;
4759 }
4760 }
4761
4768 public function setMysoc(Conf $conf)
4769 {
4770 global $langs;
4771
4772 $this->id = 0;
4773 $this->entity = $conf->entity;
4774 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4775 $this->nom = $this->name; // deprecated
4776 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4777 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4778 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4779 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4780
4781 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4782
4783 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4784
4785 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4786
4787 // We define country_id, country_code and country
4788 $country_id = 0;
4789 $country_code = $country_label = '';
4790 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4791 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4792 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4793 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4794 $country_code = $tmp[1];
4795 $country_label = $tmp[2];
4796 } else {
4797 // For backward compatibility
4798 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4799 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4800 $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
4801 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4802 }
4803 }
4804 $this->country_id = $country_id;
4805 $this->country_code = $country_code;
4806 $this->country = $country_label;
4807 if (is_object($langs)) {
4808 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4809 }
4810
4811 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4812 // We define state_id, state_code and state
4813 $state_id = 0;
4814 $state_code = '';
4815 $state_label = '';
4816 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4817 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4818 $state_id = (int) $tmp[0];
4819 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4820 $state_code = $tmp[1];
4821 $state_label = $tmp[2];
4822 } else { // For backward compatibility
4823 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);
4824 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4825 $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
4826 $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
4827 }
4828 }
4829 $this->state_id = $state_id;
4830 $this->state_code = $state_code;
4831 $this->state = $state_label;
4832 if (is_object($langs)) {
4833 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4834 }
4835
4836 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4837 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4838 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4839 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4840
4841 // Social networks
4842 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4843 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4844 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4845 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4846 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4847 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4848 $this->socialnetworks = array();
4849 if (!empty($facebook_url)) {
4850 $this->socialnetworks['facebook'] = $facebook_url;
4851 }
4852 if (!empty($twitter_url)) {
4853 $this->socialnetworks['twitter'] = $twitter_url;
4854 }
4855 if (!empty($linkedin_url)) {
4856 $this->socialnetworks['linkedin'] = $linkedin_url;
4857 }
4858 if (!empty($instagram_url)) {
4859 $this->socialnetworks['instagram'] = $instagram_url;
4860 }
4861 if (!empty($youtube_url)) {
4862 $this->socialnetworks['youtube'] = $youtube_url;
4863 }
4864 if (!empty($github_url)) {
4865 $this->socialnetworks['github'] = $github_url;
4866 }
4867
4868 // Id prof generic
4869 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4870 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4871 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4872 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4873 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4874 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4875 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4876 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4877 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4878 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4879 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4880 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4881 $this->capital = is_numeric(price2num(getDolGlobalString('MAIN_INFO_CAPITAL'))) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : null;
4882 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4883 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4884 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4885 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4886 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4887 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4888 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4889 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4890 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4891
4892 // Define if company use vat or not
4893 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4894
4895 // Define if company use local taxes
4896 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4897 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4898
4899 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4900 }
4901
4909 public function initAsSpecimen()
4910 {
4911 $now = dol_now();
4912
4913 // Initialize parameters
4914 $this->id = 0;
4915 $this->entity = 1;
4916 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4917 $this->ref_ext = 'Ref ext';
4918 $this->specimen = 1;
4919 $this->address = '21 jump street';
4920 $this->zip = '99999';
4921 $this->town = 'MyTown';
4922 $this->state_id = 1;
4923 $this->state_code = 'AA';
4924 $this->state = 'MyState';
4925 $this->country_id = 1;
4926 $this->country_code = 'FR';
4927 $this->email = 'specimen@specimen.com';
4928 $this->socialnetworks = array(
4929 'skype' => 'skypepseudo',
4930 'twitter' => 'twitterpseudo',
4931 'facebook' => 'facebookpseudo',
4932 'linkedin' => 'linkedinpseudo',
4933 );
4934 $this->url = 'http://www.specimen.com';
4935
4936 $this->phone = '0909090901';
4937 $this->phone_mobile = '0909090901';
4938 $this->fax = '0909090909';
4939
4940 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4941 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4942 $this->typent_code = 'TE_OTHER';
4943 $this->capital = 10000;
4944 $this->client = 1;
4945 $this->prospect = 1;
4946 $this->fournisseur = 1;
4947 $this->tva_assuj = 1;
4948 $this->tva_intra = 'EU1234567';
4949 $this->note_public = 'This is a comment (public)';
4950 $this->note_private = 'This is a comment (private)';
4951
4952 $this->idprof1 = 'idprof1';
4953 $this->idprof2 = 'idprof2';
4954 $this->idprof3 = 'idprof3';
4955 $this->idprof4 = 'idprof4';
4956 $this->idprof5 = 'idprof5';
4957 $this->idprof6 = 'idprof6';
4958
4959 return 1;
4960 }
4961
4970 public function useLocalTax($localTaxNum = 0, $mode = 0, $thirdparty = null)
4971 {
4972 if ($mode == 1 && $thirdparty instanceof Societe) {
4973 if ($localTaxNum == -1) {
4974 return array(1 => ($thirdparty->localtax1_assuj ? true : false), 2 => ($thirdparty->localtax2_assuj ? true : false));
4975 } elseif ($localTaxNum == 1) {
4976 return $thirdparty->localtax1_assuj ? true : false;
4977 } elseif ($localTaxNum == 2) {
4978 return $thirdparty->localtax2_assuj ? true : false;
4979 }
4980 return false;
4981 } else {
4982 $sql = "SELECT t.localtax1, t.localtax2";
4983 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4984 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4985 $sql .= " AND t.active = 1";
4986 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4987 if (empty($localTaxNum) || $localTaxNum == -1) {
4988 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4989 } elseif ($localTaxNum == 1) {
4990 $sql .= " AND t.localtax1_type <> '0'";
4991 } elseif ($localTaxNum == 2) {
4992 $sql .= " AND t.localtax2_type <> '0'";
4993 }
4994
4995 $resql = $this->db->query($sql);
4996 if ($resql) {
4997 if ($localTaxNum == -1) {
4998 $obj = $this->db->fetch_object($resql);
4999 if ($obj) {
5000 return array(1 => ($obj->localtax1 ? true : false), 2 => ($obj->localtax2 ? true : false));
5001 }
5002 return array(1 => false, 2 => false);
5003 } else {
5004 return ($this->db->num_rows($resql) > 0);
5005 }
5006 } else {
5007 return false;
5008 }
5009 }
5010 }
5011
5017 public function useNPR()
5018 {
5019 $sql = "SELECT t.rowid";
5020 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5021 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5022 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
5023 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5024
5025 dol_syslog("useNPR", LOG_DEBUG);
5026 $resql = $this->db->query($sql);
5027 if ($resql) {
5028 return ($this->db->num_rows($resql) > 0);
5029 } else {
5030 return false;
5031 }
5032 }
5033
5040 public function useRevenueStamp()
5041 {
5042 $sql = "SELECT COUNT(*) as nb";
5043 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
5044 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5045 $sql .= " AND r.active = 1";
5046
5047 dol_syslog("useRevenueStamp", LOG_DEBUG);
5048 $resql = $this->db->query($sql);
5049 if ($resql) {
5050 $obj = $this->db->fetch_object($resql);
5051 return ($obj->nb > 0);
5052 } else {
5053 $this->error = $this->db->lasterror();
5054 return false;
5055 }
5056 }
5057
5063 public function getLibProspLevel()
5064 {
5065 return $this->LibProspLevel($this->fk_prospectlevel);
5066 }
5067
5068 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5075 public function LibProspLevel($fk_prospectlevel)
5076 {
5077 // phpcs:enable
5078 global $langs;
5079
5080 $label = '';
5081 if ($fk_prospectlevel != '') {
5082 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5083 // If label is not found in language file, we get label from cache/database
5084 if ($label == "ProspectLevel".$fk_prospectlevel) {
5085 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5086 }
5087 }
5088
5089 return $label;
5090 }
5091
5099 public function getLibProspCommStatut($mode = 0, $label = '')
5100 {
5101 return $this->LibProspCommStatut((int) $this->stcomm_id, $mode, $label, $this->stcomm_picto);
5102 }
5103
5104 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5118 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5119 {
5120 // phpcs:enable
5121 global $langs;
5122
5123 $langs->load('customers');
5124
5125 if ($mode == 2) {
5126 if ($status == '-1' || $status == 'ST_NO') {
5127 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5128 } elseif ($status == '0' || $status == 'ST_NEVER') {
5129 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5130 } elseif ($status == '1' || $status == 'ST_TODO') {
5131 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5132 } elseif ($status == '2' || $status == 'ST_PEND') {
5133 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5134 } elseif ($status == '3' || $status == 'ST_DONE') {
5135 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5136 } else {
5137 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);
5138 }
5139 } elseif ($mode == 3) {
5140 if ($status == '-1' || $status == 'ST_NO') {
5141 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5142 } elseif ($status == '0' || $status == 'ST_NEVER') {
5143 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5144 } elseif ($status == '1' || $status == 'ST_TODO') {
5145 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5146 } elseif ($status == '2' || $status == 'ST_PEND') {
5147 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5148 } elseif ($status == '3' || $status == 'ST_DONE') {
5149 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5150 } else {
5151 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5152 }
5153 } elseif ($mode == 4) {
5154 if ($status == '-1' || $status == 'ST_NO') {
5155 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5156 } elseif ($status == '0' || $status == 'ST_NEVER') {
5157 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5158 } elseif ($status == '1' || $status == 'ST_TODO') {
5159 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5160 } elseif ($status == '2' || $status == 'ST_PEND') {
5161 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5162 } elseif ($status == '3' || $status == 'ST_DONE') {
5163 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5164 } else {
5165 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);
5166 }
5167 }
5168
5169 return "Error, mode/status not found";
5170 }
5171
5178 public function getOutstandingProposals($mode = 'customer')
5179 {
5180 global $hookmanager;
5181 $table = 'propal';
5182 if ($mode == 'supplier') {
5183 $table = 'supplier_proposal';
5184 }
5185
5186 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5187 $sql .= " WHERE fk_soc = ".((int) $this->id);
5188 if ($mode == 'supplier') {
5189 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5190 } else {
5191 $sql .= " AND entity IN (".getEntity('propal').")";
5192 }
5193
5194 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5195
5196 // Add where from hooks
5197 $parameters = array('mode' => $mode, 'table' => $table);
5198 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5199 $sql .= $hookmanager->resPrint;
5200
5201 $resql = $this->db->query($sql);
5202 if ($resql) {
5203 $outstandingOpened = 0;
5204 $outstandingTotal = 0;
5205 $outstandingTotalIncTax = 0;
5206 $arrayofref = array();
5207 while ($obj = $this->db->fetch_object($resql)) {
5208 $arrayofref[$obj->rowid] = $obj->ref;
5209 $outstandingTotal += $obj->total_ht;
5210 $outstandingTotalIncTax += $obj->total_ttc;
5211 if ($obj->status != 0) {
5212 // Not a draft
5213 $outstandingOpened += $obj->total_ttc;
5214 }
5215 }
5216 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5217 } else {
5218 return array();
5219 }
5220 }
5221
5228 public function getOutstandingOrders($mode = 'customer')
5229 {
5230 global $hookmanager;
5231 $table = 'commande';
5232 if ($mode == 'supplier') {
5233 $table = 'commande_fournisseur';
5234 }
5235
5236 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5237 $sql .= " WHERE fk_soc = ".((int) $this->id);
5238 if ($mode == 'supplier') {
5239 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5240 } else {
5241 $sql .= " AND entity IN (".getEntity('commande').")";
5242 }
5243
5244 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5245 // Add where from hooks
5246 $parameters = array('mode' => $mode, 'table' => $table);
5247 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5248 $sql .= $hookmanager->resPrint;
5249 $resql = $this->db->query($sql);
5250 if ($resql) {
5251 $outstandingOpened = 0;
5252 $outstandingTotal = 0;
5253 $outstandingTotalIncTax = 0;
5254 $arrayofref = array();
5255 while ($obj = $this->db->fetch_object($resql)) {
5256 $arrayofref[$obj->rowid] = $obj->ref;
5257 $outstandingTotal += $obj->total_ht;
5258 $outstandingTotalIncTax += $obj->total_ttc;
5259 if ($obj->status != 0) {
5260 // Not a draft
5261 $outstandingOpened += $obj->total_ttc;
5262 }
5263 }
5264 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5265 } else {
5266 return array();
5267 }
5268 }
5269
5277 public function getOutstandingBills($mode = 'customer', $late = 0)
5278 {
5279 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5280
5281 $table = 'facture';
5282 if ($mode == 'supplier') {
5283 $table = 'facture_fourn';
5284 }
5285
5286 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5287 $paiement = $invoice->getSommePaiement();
5288 $creditnotes=$invoice->getSumCreditNotesUsed();
5289 $deposits=$invoice->getSumDepositsUsed();
5290 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5291 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5292 */
5293 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5294
5295 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5296 $sql .= " WHERE fk_soc = ".((int) $this->id);
5297 if (!empty($late)) {
5298 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5299 }
5300 if ($mode == 'supplier') {
5301 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5302 } else {
5303 $sql .= " AND entity IN (".getEntity('invoice').")";
5304 }
5305
5306 dol_syslog("getOutstandingBills", LOG_DEBUG);
5307 $resql = $this->db->query($sql);
5308 if ($resql) {
5309 $outstandingOpened = 0;
5310 $outstandingTotal = 0;
5311 $outstandingTotalIncTax = 0;
5312 $arrayofref = array();
5313 $arrayofrefopened = array();
5314 if ($mode == 'supplier') {
5315 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5316 $tmpobject = new FactureFournisseur($this->db);
5317 } else {
5318 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5319 $tmpobject = new Facture($this->db);
5320 }
5321 while ($obj = $this->db->fetch_object($resql)) {
5322 $arrayofref[$obj->rowid] = $obj->ref;
5323 $tmpobject->id = $obj->rowid;
5324
5325 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5326 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5327 ) {
5328 $outstandingTotal += $obj->total_ht;
5329 $outstandingTotalIncTax += $obj->total_ttc;
5330 }
5331
5332 $remaintopay = 0;
5333
5334 if ($obj->paye == 0
5335 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5336 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5337 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5338 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5339 $paiement = $tmpobject->getSommePaiement();
5340 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5341 $deposits = $tmpobject->getSumDepositsUsed();
5342
5343 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5344 $outstandingOpened += $remaintopay;
5345 }
5346
5347 //if credit note is converted but not used
5348 // TODO Do this also for customer ?
5349 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5350 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5351 $remaintopay -= $remainingcreditnote;
5352 $outstandingOpened -= $remainingcreditnote;
5353 }
5354
5355 if ($remaintopay) {
5356 $arrayofrefopened[$obj->rowid] = $obj->ref;
5357 }
5358 }
5359 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'amount incl taxes' > 0
5360 } else {
5361 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5362 return array();
5363 }
5364 }
5365
5372 public function getLibCustProspStatut()
5373 {
5374 return $this->LibCustProspStatut($this->client);
5375 }
5376
5377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5384 public function LibCustProspStatut($status)
5385 {
5386 // phpcs:enable
5387 global $langs;
5388 $langs->load('companies');
5389
5390 if ($status == 0) {
5391 return $langs->trans("NorProspectNorCustomer");
5392 } elseif ($status == 1) {
5393 return $langs->trans("Customer");
5394 } elseif ($status == 2) {
5395 return $langs->trans("Prospect");
5396 } elseif ($status == 3) {
5397 return $langs->trans("ProspectCustomer");
5398 }
5399
5400 return '';
5401 }
5402
5403
5415 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5416 {
5417 global $langs;
5418
5419 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5420 $modelpath = "core/modules/bank/doc/";
5421
5422 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5423 $companybankaccount = new CompanyBankAccount($this->db);
5424 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5425 if (!$result) {
5426 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5427 }
5428 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5429 $this->last_main_doc = $companybankaccount->last_main_doc;
5430 } else {
5431 // Positionne le modele sur le nom du modele a utiliser
5432 if (!dol_strlen($modele)) {
5433 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5434 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5435 } else {
5436 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5437 return 0;
5438 }
5439 }
5440
5441 if (!isset($this->bank_account)) {
5442 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5443 $bac = new CompanyBankAccount($this->db);
5444 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5445 $result = $bac->fetch(0, '', $this->id);
5446 if ($result > 0) {
5447 $this->bank_account = $bac;
5448 } else {
5449 $this->bank_account = '';
5450 }
5451 }
5452
5453 $modelpath = "core/modules/societe/doc/";
5454
5455 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5456 }
5457
5458 return $result;
5459 }
5460
5461
5474 public function setCategories($categories, $type_categ, $remove_existing = true)
5475 {
5476 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5477
5478 // Decode type
5479 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5480 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Nothing done.', LOG_ERR);
5481 return -1;
5482 }
5483
5484 return parent::setCategoriesCommon($categories, $type_categ, $remove_existing);
5485 }
5486
5494 public function setSalesRep($salesrep, $onlyAdd = false)
5495 {
5496 global $user;
5497
5498 // Handle single user
5499 if (!is_array($salesrep)) {
5500 $salesrep = array($salesrep);
5501 }
5502
5503 $to_del = array(); // Nothing to delete
5504 $to_add = $salesrep;
5505 if ($onlyAdd === false) {
5506 // Get current users
5507 $existing = $this->getSalesRepresentatives($user, 1);
5508
5509 // Diff
5510 if (is_array($existing)) {
5511 $to_del = array_diff($existing, $salesrep);
5512 $to_add = array_diff($salesrep, $existing);
5513 }
5514 }
5515
5516 $error = 0;
5517
5518 // Process
5519 foreach ($to_del as $del) {
5520 $this->del_commercial($user, $del);
5521 }
5522 foreach ($to_add as $add) {
5523 $result = $this->add_commercial($user, $add);
5524 if ($result < 0) {
5525 $error++;
5526 break;
5527 }
5528 }
5529
5530 return $error ? -1 : 1;
5531 }
5532
5539 public function setThirdpartyType($typent_id)
5540 {
5541 global $user;
5542
5543 dol_syslog(__METHOD__, LOG_DEBUG);
5544
5545 if ($this->id) {
5546 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5547
5548 if ($result > 0) {
5549 $this->typent_id = $typent_id;
5550 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5551 return 1;
5552 } else {
5553 return -1;
5554 }
5555 } else {
5556 return -1;
5557 }
5558 }
5559
5569 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5570 {
5571 if ($origin_id == $dest_id) {
5572 dol_syslog('Error: Try to merge a thirdparty into itself');
5573 return false;
5574 }
5575
5576 // 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.
5577 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5578 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5579 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5580 $sql .= ' SELECT fk_user ';
5581 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5582 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5583
5584 $resql = $dbs->query($sql);
5585 while ($obj = $dbs->fetch_object($resql)) {
5586 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5587 }
5588
5589 // 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.
5590 // Do not include llx_societe because it will be replaced later.
5591 $tables = array(
5592 'societe_account',
5593 'societe_commerciaux',
5594 'societe_prices',
5595 'societe_remise',
5596 'societe_remise_except',
5597 'societe_rib'
5598 );
5599
5600 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5601
5602 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5603 }
5604
5613 public function setAccountancyCode($type, $value)
5614 {
5615 global $user, $langs, $conf;
5616
5617 $this->db->begin();
5618
5619 if ($type == 'buy') {
5620 $field = 'accountancy_code_buy';
5621 } elseif ($type == 'sell') {
5622 $field = 'accountancy_code_sell';
5623 } else {
5624 return -1;
5625 }
5626
5627 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5628 $sql .= $field." = '".$this->db->escape($value)."'";
5629 $sql .= " WHERE rowid = ".((int) $this->id);
5630
5631 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5632 $resql = $this->db->query($sql);
5633
5634 if ($resql) {
5635 // Call triggers
5636 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5637 $interface = new Interfaces($this->db);
5638 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5639 if ($result < 0) {
5640 $this->errors = $interface->errors;
5641 $this->db->rollback();
5642 return -1;
5643 }
5644 // End call triggers
5645
5646 $this->$field = $value;
5647
5648 $this->db->commit();
5649 return 1;
5650 } else {
5651 $this->error = $this->db->lasterror();
5652 $this->db->rollback();
5653 return -1;
5654 }
5655 }
5656
5663 public function fetchPartnerships($mode)
5664 {
5665 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5666
5667 $this->partnerships[] = array();
5668
5669 return 1;
5670 }
5671
5679 public function getKanbanView($option = '', $arraydata = array())
5680 {
5681 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5682
5683 $out = '<div class="box-flex-item box-flex-grow-zero">';
5684 $out .= '<div class="info-box info-box-sm">';
5685 $out .= '<span class="info-box-icon bg-infobox-action">';
5686 if (!empty($this->logo) && class_exists('Form')) {
5687 $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.
5688 } else {
5689 $out .= img_picto('', $this->picto);
5690 }
5691 $out .= '</span>';
5692 $out .= '<div class="info-box-content">';
5693 $out .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">' . $this->getNomUrl(1);
5694 $out .= '</div>';
5695 if (!empty($this->phone)) {
5696 $out .= '<div class="inline-block valignmiddle">';
5697 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5698 $out .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5699 $out .= '</div>';
5700 }
5701 if (!empty($this->email)) {
5702 $out .= '<div class="inline-block valignmiddle">';
5703 $out .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5704 $out .= '</div>';
5705 }
5706 if ($selected >= 0) {
5707 $out .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5708 }
5709 if (!empty($this->code_client)) {
5710 $out .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5711 }
5712 $out .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
5713 $out .= '</div>'; // end info-box-content
5714 $out .= '</div>';
5715 $out .= '</div>';
5716
5717 return $out;
5718 }
5719
5728 public function getContacts($list = 0, $code = '', $element = '')
5729 {
5730 // phpcs:enable
5731 global $langs;
5732
5733 $tab = array();
5734
5735 $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
5736 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5737 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5738 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5739 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5740 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5741 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5742 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5743 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5744 if (!empty($element)) {
5745 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5746 }
5747 if ($code) {
5748 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5749 }
5750 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5751 $sql .= " AND tc.source = 'external'";
5752 $sql .= " AND tc.active = 1";
5753
5754 $sql .= " ORDER BY t.lastname ASC";
5755
5756 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5757 $resql = $this->db->query($sql);
5758 if ($resql) {
5759 $num = $this->db->num_rows($resql);
5760 $i = 0;
5761 while ($i < $num) {
5762 $obj = $this->db->fetch_object($resql);
5763
5764 if (!$list) {
5765 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5766 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5767 $tab[$obj->id] = array(
5768 'source' => $obj->source,
5769 'socid' => $obj->socid,
5770 'id' => $obj->id,
5771 'nom' => $obj->lastname, // For backward compatibility
5772 'civility' => $obj->civility,
5773 'lastname' => $obj->lastname,
5774 'firstname' => $obj->firstname,
5775 'email' => $obj->email,
5776 'login' => (empty($obj->login) ? '' : $obj->login),
5777 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5778 'statuscontact' => $obj->statuscontact,
5779 'rowid' => $obj->rowid,
5780 'code' => $obj->code,
5781 'element' => $obj->element,
5782 'libelle' => $libelle_type,
5783 'status' => $obj->statuslink,
5784 'fk_c_type_contact' => $obj->fk_c_type_contact
5785 );
5786 } else {
5787 $tab[$obj->id] = $obj->id;
5788 }
5789
5790 $i++;
5791 }
5792
5793 return $tab;
5794 } else {
5795 $this->error = $this->db->lasterror();
5796 dol_print_error($this->db);
5797 return -1;
5798 }
5799 }
5800
5811 public function mergeCompany($soc_origin_id)
5812 {
5813 global $conf, $langs, $hookmanager, $user, $action;
5814
5815 $error = 0;
5816 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5817
5818 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5819
5820 if ($soc_origin->fetch($soc_origin_id) < 1) {
5821 $this->error = $langs->trans('ErrorRecordNotFound');
5822 $error++;
5823 }
5824
5825 if (!$error) {
5826 $this->db->begin();
5827
5828 // Recopy some data
5829 $this->client |= $soc_origin->client;
5830 $this->fournisseur |= $soc_origin->fournisseur;
5831 $listofproperties = array(
5832 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5833 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5834 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5835 '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',
5836 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5837 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5838 );
5839 foreach ($listofproperties as $property) {
5840 if (empty($this->$property)) {
5841 $this->$property = $soc_origin->$property;
5842 }
5843 }
5844
5845 if ($this->typent_id == -1) {
5846 $this->typent_id = $soc_origin->typent_id;
5847 }
5848
5849 // Concat some data
5850 $listofproperties = array(
5851 'note_public', 'note_private'
5852 );
5853 foreach ($listofproperties as $property) {
5854 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5855 }
5856
5857 // Merge extrafields
5858 if (is_array($soc_origin->array_options)) {
5859 foreach ($soc_origin->array_options as $key => $val) {
5860 if (empty($this->array_options[$key])) {
5861 $this->array_options[$key] = $val;
5862 }
5863 }
5864 }
5865
5866 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5867 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5868 $this->name_bis = $this->name;
5869 }
5870
5871 // Merge categories
5872 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5873 $static_cat = new Categorie($this->db);
5874
5875 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5876 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5877 $custcats = array_merge($custcats, $custcats_ori);
5878 $this->setCategories($custcats, 'customer');
5879
5880 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5881 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5882 $suppcats = array_merge($suppcats, $suppcats_ori);
5883 $this->setCategories($suppcats, 'supplier');
5884
5885 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5886 if ($soc_origin->code_client == $this->code_client
5887 || $soc_origin->code_fournisseur == $this->code_fournisseur
5888 || $soc_origin->barcode == $this->barcode) {
5889 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5890 $soc_origin->code_client = '';
5891 $soc_origin->code_fournisseur = '';
5892 $soc_origin->barcode = '';
5893 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5894 }
5895
5896 // Update
5897 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5898
5899 if ($result < 0) {
5900 $error++;
5901 }
5902
5903 // Move links
5904 if (!$error) {
5905 $objects = array(
5906 'Adherent' => '/adherents/class/adherent.class.php',
5907 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5908 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5909 'Propal' => '/comm/propal/class/propal.class.php',
5910 'Commande' => '/commande/class/commande.class.php',
5911 'Facture' => '/compta/facture/class/facture.class.php',
5912 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5913 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5914 'Contact' => '/contact/class/contact.class.php',
5915 'Contrat' => '/contrat/class/contrat.class.php',
5916 'Expedition' => '/expedition/class/expedition.class.php',
5917 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5918 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5919 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5920 'Reception' => '/reception/class/reception.class.php',
5921 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5922 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5923 'Product' => '/product/class/product.class.php',
5924 //'ProductThirparty' => '...', // for llx_product_thirdparty
5925 'Project' => '/projet/class/project.class.php',
5926 'User' => '/user/class/user.class.php',
5927 'Account' => '/compta/bank/class/account.class.php',
5928 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5929 'Societe' => '/societe/class/societe.class.php',
5930 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5931 );
5932 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5933 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5934 }
5935 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5936 $objects['Mo'] = '/mrp/class/mo.class.php';
5937 }
5938 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5939 $objects['Don'] = '/don/class/don.class.php';
5940 }
5941 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5942 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5943 }
5944 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5945 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5946 }
5947 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5948 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5949 }
5950
5951 //First, all core objects must update their tables
5952 foreach ($objects as $object_name => $object_file) {
5953 /* $object_file is never an array -> code commented
5954 if (is_array($object_file)) {
5955 if (empty($object_file['enabled'])) {
5956 continue;
5957 }
5958 $object_file = $object_file['file'];
5959 }
5960 */
5961
5962 require_once DOL_DOCUMENT_ROOT.$object_file;
5963
5964 if (!$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5965 $error++;
5966 $this->error = $this->db->lasterror();
5967 break;
5968 }
5969 }
5970 }
5971
5972 // External modules should update their ones too
5973 if (!$error) {
5974 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5975 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5976
5977 if ($reshook < 0) {
5978 $this->error = $hookmanager->error;
5979 $this->errors = $hookmanager->errors;
5980 $error++;
5981 }
5982 }
5983
5984
5985 if (!$error) {
5986 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5987
5988 // Call trigger
5989 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5990 if ($result < 0) {
5991 $error++;
5992 }
5993 // End call triggers
5994 }
5995
5996 if (!$error) {
5997 // We finally remove the old thirdparty
5998 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5999 $this->error = $soc_origin->error;
6000 $this->errors = $soc_origin->errors;
6001 $error++;
6002 }
6003 }
6004
6005
6006 if (!$error) {
6007 // Move files from the dir of the third party to delete into the dir of the third party to keep
6008 if (!empty($conf->societe->multidir_output[$this->entity])) {
6009 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
6010 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
6011
6012 if (dol_is_dir($srcdir)) {
6013 $dirlist = dol_dir_list($srcdir, 'files', 1);
6014 foreach ($dirlist as $filetomove) {
6015 $destfile = $destdir.'/'.$filetomove['relativename'];
6016 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
6017 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
6018 }
6019 //exit;
6020 }
6021 }
6022 }
6023
6024 if (!$error) {
6025 $this->db->commit();
6026 return 0;
6027 } else {
6028 $langs->load("errors");
6029 $this->error = $langs->trans('ErrorsThirdpartyMerge');
6030 $this->db->rollback();
6031 return -1;
6032 }
6033 }
6034
6035 return -1;
6036 }
6037}
$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_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, ....
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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