dolibarr 25.0.0-alpha
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2026 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023-2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
24 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
49require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
50require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
51
52
56class Societe extends CommonObject
57{
58 use CommonIncoterm;
60 use CommonPeople;
61
66 public $TRIGGER_PREFIX = 'COMPANY'; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
67
71 public $module = 'societe';
72
76 public $element = 'societe';
77
81 public $table_element = 'societe';
82
86 public $fk_element = 'fk_soc';
87
91 public $fieldsforcombobox = 'nom,name_alias';
92
96 protected $childtables = array(
97 'supplier_proposal' => array('name' => 'SupplierProposal'),
98 'propal' => array('name' => 'Proposal'),
99 'commande' => array('name' => 'Order'),
100 'facture' => array('name' => 'Invoice'),
101 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
102 'contrat' => array('name' => 'Contract'),
103 'fichinter' => array('name' => 'Fichinter'),
104 'facture_fourn' => array('name' => 'SupplierInvoice'),
105 'commande_fournisseur' => array('name' => 'SupplierOrder'),
106 'projet' => array('name' => 'Project'),
107 'expedition' => array('name' => 'Shipment'),
108 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
109 'adherent' => array('name' => 'Member')
110 );
111
116 protected $childtablesoncascade = array(
117 'societe_prices',
118 'product_fournisseur_price',
119 'product_customer_price_log',
120 'product_customer_price',
121 '@Contact:/contact/class/contact.class.php:fk_soc',
122 'adherent',
123 'societe_account',
124 'societe_rib',
125 'societe_remise',
126 'societe_remise_except',
127 'societe_commerciaux',
128 'categorie',
129 'notify',
130 'notify_def',
131 'actioncomm',
132 );
133
137 public $picto = 'company';
138
143 public $restrictiononfksoc = 1;
144
149 public $SupplierCategories = array();
150
155 public $prefixCustomerIsRequired;
156
186 public $fields = array(
187 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
188 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
189 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
190 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
191 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
192 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
193 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
194 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
195 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
196 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
197 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
198 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
199 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
200 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
201 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
202 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
203 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
204 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
205 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
206 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
207 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
208 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
209 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
210 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
211 'fk_typent' => array('type' => 'integer', 'label' => 'ThirdPartyType', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
212 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
213 'birth' => array('type' => 'date', 'label' => 'CompanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182),
214 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
215 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
216 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
217 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
218 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
219 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
220 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
221 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'VATIntra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
222 'euid' => array('type' => 'varchar(20)', 'label' => 'EUIDShort', 'enabled' => 1, 'visible' => -1, 'position' => 213),
223 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
224 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
225 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
226 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
227 'client' => array('type' => 'tinyint(4)', 'label' => 'Customer', 'enabled' => 1, 'visible' => -1, 'position' => 240),
228 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Supplier', 'enabled' => 1, 'visible' => -1, 'position' => 245),
229 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
230 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
231 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
232 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
233 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
234 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
235 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
236 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
237 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
238 'mode_reglement' => array('type' => 'smallint(6)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
239 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
240 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
241 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
242 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
243 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
244 'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
245 'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
246 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMode', 'enabled' => 1, 'visible' => -1, 'position' => 330),
247 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'VATIsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 335),
248 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax1IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 340),
249 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
250 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax2IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 350),
251 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
252 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
253 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
254 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => 'getDolGlobalString("PRODUIT_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
255 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
256 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
257 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
258 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
259 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
260 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
261 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
262 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
263 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
264 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
265 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
266 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
267 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
268 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
269 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
270 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
271 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
272 );
273
280 public $nom;
281
285 public $name;
286
291 public $name_alias;
292
296 public $particulier;
297
302 public $status = 1;
303
307 public $region_code;
308
312 public $region;
313
317 public $country_id;
318
324 public $departement_code;
325
331 public $departement;
332
338 public $pays;
339
344 public $phone;
349 public $phone_mobile;
354 public $fax;
355
360 public $email;
361
366 public $no_email;
367
373 public $skype;
374
380 public $twitter;
381
387 public $facebook;
388
394 public $linkedin;
395
400 public $url;
401
406 public $barcode;
407
408 // 6 professional id (usage depends on country)
409
414 public $idprof1;
415
421 public $siren;
422
423
428 public $idprof2;
429
435 public $siret;
436
441 public $idprof3;
442
448 public $ape;
449
454 public $idprof4;
455
460 public $idprof5;
461
466 public $idprof6;
467
472 public $idprof7;
473
478 public $idprof8;
479
484 public $idprof9;
485
490 public $idprof10;
491
496 public $socialobject;
497
501 public $prefix_comm;
502
506 public $tva_assuj = 1;
507
511 public $tva_intra;
512
516 public $euid;
517
521 public $vat_reverse_charge = 0;
522
523 // Local taxes
527 public $localtax1_assuj;
531 public $localtax1_value;
535 public $localtax2_assuj;
539 public $localtax2_value;
540
544 public $managers;
545
549 public $capital;
550
554 public $typent_id = 0;
555
559 public $typent_code;
560
564 public $effectif;
565
569 public $effectif_id = 0;
573 public $forme_juridique_code = 0;
578 public $forme_juridique;
582 public $birth;
583
587 public $remise_percent;
591 public $remise_supplier_percent;
592
596 public $mode_reglement_id;
600 public $cond_reglement_id;
604 public $deposit_percent;
608 public $mode_reglement_supplier_id;
612 public $cond_reglement_supplier_id;
616 public $transport_mode_supplier_id;
617
621 public $fk_prospectlevel;
622
626 public $name_bis;
627
633 public $user_modification;
634
640 public $user_creation;
641
646 public $client = 0;
647
652 public $prospect = 0;
653
658 public $fournisseur;
659
664 public $code_client;
665
670 public $code_fournisseur;
671
676 public $code_compta_client;
677
682 public $accountancy_code_customer_general;
683
688 public $accountancy_code_customer;
689
694 public $code_compta_fournisseur;
695
700 public $accountancy_code_supplier_general;
701
706 public $accountancy_code_supplier;
707
712 public $code_compta_product;
713
719 public $note;
720
725 public $note_private;
726
731 public $note_public;
732
737 public $stcomm_id;
738
743 public $stcomm_picto;
744
749 public $status_prospect_label;
750
755 public $price_level;
756
760 public $outstanding_limit;
761
765 public $order_min_amount;
766
770 public $supplier_order_min_amount;
771
776 public $commercial_id;
777
782 public $parent;
783
788 public $default_lang;
789
793 public $ref;
794
800 public $ref_ext;
801
805 public $ip;
806
813 public $import_key;
814
819 public $webservices_url;
820
825 public $webservices_key;
826
830 public $logo;
831
835 public $logo_small;
836
840 public $logo_mini;
841
845 public $logo_squarred;
846
850 public $logo_squarred_small;
851
855 public $logo_squarred_mini;
856
860 public $accountancy_code_sell;
861
865 public $accountancy_code_buy;
866
870 public $currency_code;
871
872 // Multicurrency
876 public $fk_multicurrency;
877
881 public $multicurrency_code;
882
883 // Warehouse
887 public $fk_warehouse;
888
892 public $termsofsale;
893
894
895 // Fields loaded by fetchPartnerships()
896
900 public $partnerships = array();
901
902
906 public $bank_account;
907
913 public $code_compta;
914
915
916 const STATUS_CEASED = 0;
917 const STATUS_INACTIVITY = 1;
918
922 const NO_CUSTOMER = 0;
923
927 const CUSTOMER = 1;
928
932 const PROSPECT = 2;
933
938
942 const NO_SUPPLIER = 0;
943
947 const SUPPLIER = 1;
948
954 protected function deprecatedProperties()
955 {
956 return
957 array(
958 'code_compta' => 'code_compta_client',
959 )
960 + parent::deprecatedProperties();
961 }
962
963
964
970 public function __construct($db)
971 {
972 $this->db = $db;
973
974 $this->ismultientitymanaged = 1;
975 $this->isextrafieldmanaged = 1;
976 $this->client = 0;
977 $this->prospect = 0;
978 $this->fournisseur = 0;
979 $this->typent_id = 0;
980 $this->effectif_id = 0;
981 $this->forme_juridique_code = 0;
982 $this->tva_assuj = 1;
983 $this->vat_reverse_charge = 0;
984 $this->status = 1;
985
986 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
987 $this->fields['address']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
988 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
989 $this->fields['town']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
990 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
991 }
992 }
993
994
1003 public function create(User $user, $notrigger = 0)
1004 {
1005 global $langs, $conf;
1006
1007 $error = 0;
1008
1009 // Clean parameters
1010 if (empty($this->status)) {
1011 $this->status = 0;
1012 }
1013 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1014 $this->setUpperOrLowerCase();
1015 $this->nom = $this->name; // For backward compatibility
1016
1017 if (empty($this->client)) {
1018 $this->client = 0;
1019 }
1020 if (empty($this->fournisseur)) {
1021 $this->fournisseur = 0;
1022 }
1023 $this->import_key = trim((string) $this->import_key);
1024
1025 $this->code_compta_client = trim($this->code_compta_client ?? '');
1026
1027 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general ?? '');
1028 if ($this->accountancy_code_customer_general === '-1') {
1029 $this->accountancy_code_customer_general = '';
1030 }
1031 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1032 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general ?? '');
1033 if ($this->accountancy_code_supplier_general === '-1') {
1034 $this->accountancy_code_supplier_general = '';
1035 }
1036 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1037 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1038 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1039
1040 if (!empty($this->multicurrency_code)) {
1041 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1042 }
1043 if (empty($this->fk_multicurrency)) {
1044 $this->multicurrency_code = '';
1045 $this->fk_multicurrency = 0;
1046 }
1047
1048 dol_syslog(get_class($this)."::create ".$this->name);
1049
1050 $now = dol_now();
1051
1052 if (empty($this->date_creation)) {
1053 $this->date_creation = $now;
1054 }
1055
1056 $this->db->begin();
1057
1058 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1059 if ($this->code_client == -1 || $this->code_client === 'auto') {
1060 $this->get_codeclient($this, 0);
1061 }
1062 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1063 $this->get_codefournisseur($this, 1);
1064 }
1065
1066 // Check more parameters (including mandatory setup
1067 // If error, this->errors[] is filled
1068 $result = $this->verify();
1069
1070 if ($result >= 0) {
1071 $this->entity = setEntity($this);
1072
1073 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1074 $sql .= "nom";
1075 $sql .= ", name_alias";
1076 $sql .= ", entity";
1077 $sql .= ", datec";
1078 $sql .= ", fk_user_creat";
1079 $sql .= ", fk_typent";
1080 $sql .= ", canvas";
1081 $sql .= ", status";
1082 $sql .= ", ref_ext";
1083 $sql .= ", fk_stcomm";
1084 $sql .= ", fk_incoterms";
1085 $sql .= ", location_incoterms";
1086 $sql .= ", import_key";
1087 $sql .= ", fk_multicurrency";
1088 $sql .= ", multicurrency_code";
1089 $sql .= ", ip";
1090 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1091 $sql .= ", vat_reverse_charge";
1092 $sql .= ", accountancy_code_buy";
1093 $sql .= ", accountancy_code_sell";
1094 }
1095 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1096 $sql .= " '".$this->db->escape($this->name_alias)."',";
1097 $sql .= " ".((int) $this->entity).",";
1098 $sql .= " '".$this->db->idate($this->date_creation)."'";
1099 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1100 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1101 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1102 $sql .= ", ".((int) $this->status);
1103 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1104 $sql .= ", 0";
1105 $sql .= ", ".(int) $this->fk_incoterms;
1106 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1107 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1108 $sql .= ", ".(int) $this->fk_multicurrency;
1109 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1110 $sql .= ", ".(empty($this->ip) ? "null" : "'".$this->db->escape($this->ip)."'");
1111 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1112 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1113 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1114 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1115 }
1116 $sql .= ")";
1117
1118 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1119
1120 $result = $this->db->query($sql);
1121 if ($result) {
1122 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1123
1124 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1125
1126 // Addition of the assigned sales representative
1127 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1128 $this->add_commercial($user, $this->commercial_id);
1129 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1130 // If a sales representative creates a customer, they are automatically assigned to them.
1131 $this->add_commercial($user, $user->id);
1132 }
1133
1134 if ($ret >= 0) {
1135 if (! $notrigger) {
1136 // Call trigger
1137 $result = $this->call_trigger('COMPANY_CREATE', $user);
1138 if ($result < 0) {
1139 $error++;
1140 }
1141 // End call triggers
1142 }
1143 } else {
1144 $error++;
1145 }
1146
1147 if (!$error) {
1148 dol_syslog(get_class($this)."::Create success id=".$this->id);
1149 $this->db->commit();
1150 return $this->id;
1151 } else {
1152 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1153 $this->db->rollback();
1154 return -4;
1155 }
1156 } else {
1157 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1158 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1159 $result = -1;
1160 } else {
1161 $this->error = $this->db->lasterror();
1162 $result = -2;
1163 }
1164 $this->db->rollback();
1165 return $result;
1166 }
1167 } else {
1168 $this->db->rollback();
1169 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1170 return -3;
1171 }
1172 }
1173
1174
1175 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1185 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1186 {
1187 $error = 0;
1188
1189 $this->db->begin();
1190
1191 // phpcs:enable
1192 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1193 $contact = new Contact($this->db);
1194
1195 $contact->name = $this->name_bis;
1196 $contact->firstname = $this->firstname;
1197 $contact->civility_id = $this->civility_id;
1198 $contact->socid = $this->id; // fk_soc
1199 $contact->statut = 1; // deprecated
1200 $contact->status = 1;
1201 $contact->priv = 0;
1202 $contact->country_id = $this->country_id;
1203 $contact->state_id = $this->state_id;
1204 $contact->address = $this->address;
1205 $contact->email = $this->email;
1206 $contact->zip = $this->zip;
1207 $contact->town = $this->town;
1208 $this->setUpperOrLowerCase();
1209 $contact->phone_pro = $this->phone;
1210 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1211 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1212 }
1213
1214 $contactId = $contact->create($user, $notrigger);
1215 if ($contactId < 0) {
1216 $error++;
1217 $this->setErrorsFromObject($contact);
1218 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1219 }
1220
1221 if (empty($error) && is_array($tags) && !empty($tags)) {
1222 $result = $contact->setCategories($tags);
1223 if ($result < 0) {
1224 $error++;
1225 $this->setErrorsFromObject($contact);
1226 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1227 $contactId = $result;
1228 }
1229 }
1230
1231 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1232 $result = $contact->setNoEmail($no_email);
1233 if ($result < 0) {
1234 $this->setErrorsFromObject($contact);
1235 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1236 $contactId = $result;
1237 }
1238 }
1239
1240 if (empty($error)) {
1241 dol_syslog(get_class($this)."::create_individual success");
1242 $this->db->commit();
1243 } else {
1244 $this->db->rollback();
1245 }
1246
1247 return $contactId;
1248 }
1249
1256 public function verify()
1257 {
1258 global $langs, $mysoc;
1259
1260 $error = 0;
1261 $this->errors = array();
1262
1263 $result = 0;
1264 $this->name = trim($this->name);
1265 $this->nom = $this->name; // For backward compatibility
1266
1267 if (!$this->name) {
1268 $this->errors[] = 'ErrorBadThirdPartyName';
1269 $result = -2;
1270 }
1271
1272 if ($this->client) {
1273 $rescode = $this->check_codeclient();
1274 if ($rescode != 0 && $rescode != -5) {
1275 if ($rescode == -1) {
1276 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1277 } elseif ($rescode == -2) {
1278 $this->errors[] = 'ErrorCustomerCodeRequired';
1279 } elseif ($rescode == -3) {
1280 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1281 } elseif ($rescode == -4) {
1282 $this->errors[] = 'ErrorPrefixRequired';
1283 } else {
1284 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1285 }
1286
1287 $result = -3;
1288 }
1289 }
1290
1291 if ($this->fournisseur) {
1292 $rescode = $this->check_codefournisseur();
1293 if ($rescode != 0 && $rescode != -5) {
1294 if ($rescode == -1) {
1295 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1296 } elseif ($rescode == -2) {
1297 $this->errors[] = 'ErrorSupplierCodeRequired';
1298 } elseif ($rescode == -3) {
1299 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1300 } elseif ($rescode == -4) {
1301 $this->errors[] = 'ErrorPrefixRequired';
1302 } else {
1303 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1304 }
1305 $result = -3;
1306 }
1307 }
1308
1309 // Check for duplicate or mandatory fields defined into setup
1310 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'EUID', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1311 foreach ($array_to_check as $key) {
1312 $keymin = strtolower($key);
1313 $keyfield_db = $keymin;
1314 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1315 $keymin = 'code_compta_client';
1316 $keyfield_db = 'code_compta';
1317 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1318 $keymin = 'code_compta_fournisseur';
1319 $keyfield_db = 'code_compta_fournisseur';
1320 }
1321 $i = (int) preg_replace('/[^0-9]/', '', $key);
1322 $vallabel = $this->$keymin;
1323
1324 if ($i > 0) {
1325 if ($mysoc != null && $this->isACompany()) {
1326 // Check for mandatory prof id (but only if country is same than ours)
1327 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1328 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1329 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1330 $langs->load("errors");
1331 $error++;
1332 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1333 }
1334 }
1335 }
1336
1337 // Check for unicity on profid
1338 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1339 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1340 $langs->load("errors");
1341 $error++;
1342 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1343 }
1344 }
1345 } else {
1346 if ($key == 'EMAIL') {
1347 // Check for mandatory
1348 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1349 $langs->load("errors");
1350 $error++;
1351 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1352 }
1353
1354 // Check for unicity
1355 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1356 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1357 $langs->load("errors");
1358 $error++;
1359 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1360 }
1361 }
1362 } elseif ($key == 'TVA_INTRA') {
1363 // Check for unicity
1364 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1365 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1366 $langs->load("errors");
1367 $error++;
1368 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1369 }
1370 }
1371 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1372 $langs->load("errors");
1373 $error++;
1374 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1375 }
1376 } elseif ($key == 'EUID') {
1377 // Check for unicity
1378 if ($vallabel && getDolGlobalString('SOCIETE_EUID_UNIQUE')) {
1379 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1380 $langs->load("errors");
1381 $error++;
1382 $this->errors[] = $langs->trans('EUIDShort')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1383 }
1384 }
1385
1386 // Check for mandatory
1387 if (getDolGlobalString('SOCIETE_EUID_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1388 $langs->load("errors");
1389 $error++;
1390 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('EUIDShort')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1391 }
1392 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1393 // Check for unicity
1394 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1395 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1396 $langs->loadLangs(array("errors", 'compta'));
1397 $error++;
1398 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1399 }
1400 }
1401
1402 // Check for mandatory
1403 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1404 $langs->loadLangs(array("errors", 'compta'));
1405 $error++;
1406 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1407 }
1408 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1409 // Check for unicity
1410 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1411 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1412 $langs->loadLangs(array("errors", 'compta'));
1413 $error++;
1414 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1415 }
1416 }
1417
1418 // Check for mandatory
1419 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1420 $langs->loadLangs(array("errors", 'compta'));
1421 $error++;
1422 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1423 }
1424 }
1425 }
1426 }
1427
1428 if ($error) {
1429 $result = -4;
1430 }
1431
1432 return $result;
1433 }
1434
1447 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1448 {
1449 global $langs, $conf, $hookmanager;
1450
1451 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1452
1453 if (empty($id)) {
1454 $id = $this->id;
1455 }
1456 if (empty($this->country_id) && !empty($this->country_code)) {
1457 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1458 }
1459
1460 if (empty($this->country_id) && !empty($this->country_code)) {
1461 $country_id = getCountry($this->country_code, '3');
1462 $this->country_id = is_int($country_id) ? $country_id : 0;
1463 }
1464
1465 $error = 0;
1466
1467 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1468
1469 $now = dol_now();
1470
1471 // Clean parameters
1472 $this->id = $id;
1473 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1474 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1475 $this->nom = $this->name; // For backward compatibility
1476 $this->name_alias = trim((string) $this->name_alias);
1477 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1478 $this->address = trim((string) $this->address);
1479 $this->zip = trim((string) $this->zip);
1480 $this->town = trim((string) $this->town);
1481 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1482 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1483 $this->phone = trim((string) $this->phone);
1484 $this->phone = preg_replace("/\s/", "", $this->phone);
1485 $this->phone = preg_replace("/\./", "", $this->phone);
1486 $this->phone_mobile = trim((string) $this->phone_mobile);
1487 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1488 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1489 $this->fax = trim((string) $this->fax);
1490 $this->fax = preg_replace("/\s/", "", $this->fax);
1491 $this->fax = preg_replace("/\./", "", $this->fax);
1492 $this->email = trim((string) $this->email);
1493 $this->url = $this->url ? clean_url($this->url, 0) : '';
1494 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1495 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1496 $this->idprof1 = trim((string) $this->idprof1);
1497 $this->idprof2 = trim((string) $this->idprof2);
1498 $this->idprof3 = trim((string) $this->idprof3);
1499 $this->idprof4 = trim((string) $this->idprof4);
1500 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1501 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1502 $this->prefix_comm = trim((string) $this->prefix_comm);
1503 $this->outstanding_limit = price2num($this->outstanding_limit);
1504 $this->order_min_amount = price2num($this->order_min_amount);
1505 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1506 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1507 $this->tva_intra = trim((string) $this->tva_intra);
1508 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1509 $this->euid = trim((string) $this->euid);
1510
1511 if (empty($this->status)) {
1512 $this->status = 0;
1513 }
1514
1515 if (!empty($this->multicurrency_code)) {
1516 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1517 }
1518 if (empty($this->fk_multicurrency)) {
1519 $this->multicurrency_code = '';
1520 $this->fk_multicurrency = 0;
1521 }
1522
1523 // Local taxes
1524 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1525 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1526
1527 $this->localtax1_value = trim($this->localtax1_value);
1528 $this->localtax2_value = trim($this->localtax2_value);
1529
1530 $this->capital = (!is_null($this->capital) && (string) $this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1531
1532 $this->effectif_id = (int) $this->effectif_id;
1533 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1534
1535 //Gencod
1536 $this->barcode = trim((string) $this->barcode);
1537
1538 // For automatic creation
1539 if ($this->code_client == -1 || $this->code_client === 'auto') {
1540 $this->get_codeclient($this, 0);
1541 }
1542 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1543 $this->get_codefournisseur($this, 1);
1544 }
1545
1546 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1547 if ($this->accountancy_code_customer_general === '-1') {
1548 $this->accountancy_code_customer_general = '';
1549 }
1550 $this->code_compta_client = trim((string) $this->code_compta_client);
1551 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1552 if ($this->accountancy_code_supplier_general === '-1') {
1553 $this->accountancy_code_supplier_general = '';
1554 }
1555 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1556
1557 // Check parameters. More tests are done later in the ->verify()
1558 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1559 $langs->load("errors");
1560 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1561 return -1;
1562 }
1563
1564 $customer = false;
1565 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1566 // If $allowmodcodeclient is set and value is not set, we generate it
1567 if (empty($this->code_compta_client)) {
1568 $ret = $this->get_codecompta('customer');
1569 if ($ret < 0) {
1570 return -1;
1571 }
1572 }
1573
1574 $customer = true;
1575 }
1576
1577 $supplier = false;
1578 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1579 // If $allowmodcodefournisseur is set and value is not set, we generate it
1580 if (empty($this->code_compta_fournisseur)) {
1581 $ret = $this->get_codecompta('supplier');
1582 if ($ret < 0) {
1583 return -1;
1584 }
1585 }
1586
1587 $supplier = true;
1588 }
1589
1590 //Web services
1591 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1592 $this->webservices_key = trim((string) $this->webservices_key);
1593
1594 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1595 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1596
1597 //Incoterms
1598 $this->fk_incoterms = (int) $this->fk_incoterms;
1599 $this->location_incoterms = trim((string) $this->location_incoterms);
1600
1601 $this->db->begin();
1602
1603 // Check name is required and codes are ok or unique.
1604 // If error, this->errors[] is filled
1605 $result = 0;
1606 if ($action != 'add' && $action != 'merge') {
1607 // We don't check when update called during a create because verify was already done.
1608 // For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
1609 $result = $this->verify();
1610
1611 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1612 // So we can update record that were using and old numbering rule.
1613 if (is_array($this->errors)) {
1614 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1615 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1616 unset($this->errors[$key]); // Remove error message
1617 }
1618 }
1619 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1620 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1621 unset($this->errors[$key]); // Remove error message
1622 }
1623 }
1624 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1625 $result = 0;
1626 }
1627 }
1628 }
1629 $this->setUpperOrLowerCase();
1630 if ($result >= 0) {
1631 dol_syslog(get_class($this)."::update verify ok or not done");
1632
1633 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1634 $sql .= "entity = ".((int) $this->entity);
1635 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1636 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1637 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1638 $sql .= ",address = '".$this->db->escape($this->address)."'";
1639
1640 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1641 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1642
1643 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1644 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1645
1646 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1647 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1648 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1649 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1650 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1651 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1652
1653 $sql .= ",parent = ".($this->parent > 0 ? ((int) $this->parent) : "null");
1654
1655 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1656 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1657
1658 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1659 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1660 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1661 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1662 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1663 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1664
1665 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape((string) $this->tva_assuj)."'" : "null");
1666 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1667 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1668 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape((string) $this->vat_reverse_charge) . "'" : 0);
1669 }
1670 $sql .= ",euid = '".$this->db->escape($this->euid)."'";
1671 $sql .= ",status = ".((int) $this->status);
1672
1673 // Local taxes
1674 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape((string) $this->localtax1_assuj)."'" : "null");
1675 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape((string) $this->localtax2_assuj)."'" : "null");
1676 if ($this->localtax1_assuj == 1) {
1677 if ($this->localtax1_value != '') {
1678 $sql .= ", localtax1_value = ".((float) $this->localtax1_value);
1679 } else {
1680 $sql .= ", localtax1_value = 0.000";
1681 }
1682 } else {
1683 $sql .= ",localtax1_value =0.000";
1684 }
1685
1686 if ($this->localtax2_assuj == 1) {
1687 if ($this->localtax2_value != '') {
1688 $sql .= ",localtax2_value = ".((float) $this->localtax2_value);
1689 } else {
1690 $sql .= ",localtax2_value = 0.000";
1691 }
1692 } else {
1693 $sql .= ",localtax2_value = 0.000";
1694 }
1695
1696 $sql .= ",capital = ".($this->capital === null ? "null" : (float) $this->capital);
1697
1698 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1699
1700 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1701 if (isset($this->stcomm_id)) {
1702 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1703 }
1704 if (isset($this->typent_id)) {
1705 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1706 }
1707
1708 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape((string) $this->forme_juridique_code)."'" : "null");
1709 $sql .= ",birth = ".(!empty($this->birth) ? "'".$this->db->idate($this->birth)."'" : "null");
1710
1711 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null");
1712 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape((string) $this->transport_mode_id)."'" : "null");
1713 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape((string) $this->transport_mode_supplier_id)."'" : "null");
1714 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape((string) $this->shipping_method_id)."'" : "null");
1715
1716 $sql .= ",client = ".(!empty($this->client) ? ((int) $this->client) : 0);
1717 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? ((int) $this->fournisseur) : 0);
1718 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1719 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1720 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1721 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1722 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? ((float) $this->outstanding_limit) : 'null');
1723 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? ((float) $this->order_min_amount) : 'null');
1724 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? ((float) $this->supplier_order_min_amount) : 'null');
1725 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1726 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1727 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1728 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1729 $sql .= ", mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape((string) $this->mode_reglement_id)."'" : "null");
1730 $sql .= ", cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape((string) $this->cond_reglement_id)."'" : "null");
1731 $sql .= ", mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape((string) $this->mode_reglement_supplier_id)."'" : "null");
1732 $sql .= ", cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape((string) $this->cond_reglement_supplier_id)."'" : "null");
1733 $sql .= ", fk_account = ".($this->fk_account > 0 ? (int) $this->fk_account : "null");
1734 if ($customer) {
1735 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1736 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1737 }
1738
1739 if ($supplier) {
1740 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1741 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1742 }
1743 }
1744 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1745 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1746
1747 //Incoterms
1748 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1749 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1750
1751 if ($customer) {
1752 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1753 }
1754
1755 if ($supplier) {
1756 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1757 }
1758 $sql .= ", fk_user_modif = ".($user->id > 0 ? ((int) $user->id) : "null");
1759 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1760 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1761 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1762 $sql .= " WHERE rowid = ".(int) $id;
1763
1764 $resql = $this->db->query($sql);
1765 if ($resql) {
1766 if (is_object($this->oldcopy)) { // If we have information on old values
1767 if ($this->oldcopy->country_id != $this->country_id) {
1768 unset($this->country_code);
1769 unset($this->country);
1770 }
1771 if ($this->oldcopy->state_id != $this->state_id) {
1772 unset($this->state_code);
1773 unset($this->state);
1774 }
1775 } else {
1776 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1777 unset($this->country);
1778 unset($this->state_code);
1779 unset($this->state);
1780 }
1781
1782 $nbrowsaffected = $this->db->affected_rows($resql);
1783
1784 if ($nbrowsaffected) {
1785 // Update information on linked member if it is an update
1786 if (!$nosyncmember && isModEnabled('member')) {
1787 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1788
1789 dol_syslog(get_class($this)."::update update linked member");
1790
1791 $lmember = new Adherent($this->db);
1792 $result = $lmember->fetch(0, '0', $this->id);
1793
1794 if ($result > 0) {
1795 $lmember->company = $this->name;
1796 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1797 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1798 $lmember->address = $this->address;
1799 $lmember->zip = $this->zip;
1800 $lmember->town = $this->town;
1801 $lmember->email = $this->email;
1802 $lmember->socialnetworks = $this->socialnetworks;
1803 $lmember->phone = $this->phone;
1804 $lmember->state_id = $this->state_id;
1805 $lmember->country_id = $this->country_id;
1806 $lmember->default_lang = $this->default_lang;
1807
1808 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1809 if ($result < 0) {
1810 $this->setErrorsFromObject($lmember);
1811 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1812 $error++;
1813 }
1814 } elseif ($result < 0) {
1815 $this->error = $lmember->error;
1816 $error++;
1817 }
1818 }
1819 }
1820
1821 $action = 'update';
1822
1823 // update accountancy for this entity
1824 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1825 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1826
1827 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1828 $sql .= " fk_soc";
1829 $sql .= ", entity";
1830 $sql .= ", vat_reverse_charge";
1831 $sql .= ", accountancy_code_customer_general";
1832 $sql .= ", accountancy_code_customer";
1833 $sql .= ", accountancy_code_supplier_general";
1834 $sql .= ", accountancy_code_supplier";
1835 $sql .= ", accountancy_code_buy";
1836 $sql .= ", accountancy_code_sell";
1837 $sql .= ", fk_account";
1838 $sql .= ", mode_reglement";
1839 $sql .= ", cond_reglement";
1840 $sql .= ", mode_reglement_supplier";
1841 $sql .= ", cond_reglement_supplier";
1842 $sql .= ") VALUES (";
1843 $sql .= ((int) $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 .= ", ".($this->fk_account > 0 ? (int) $this->fk_account : "null");
1853 $sql .= ", ".(!empty($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null");
1854 $sql .= ", ".(!empty($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null");
1855 $sql .= ", ".(!empty($this->mode_reglement_supplier_id) ? (int) $this->mode_reglement_supplier_id : "null");
1856 $sql .= ", ".(!empty($this->cond_reglement_supplier_id) ? (int) $this->cond_reglement_supplier_id : "null");
1857 $sql .= ")";
1858 $result = $this->db->query($sql);
1859 if (!$result) {
1860 $error++;
1861 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1862 }
1863 }
1864
1865 // Actions on extra fields
1866 if (!$error) {
1867 $result = $this->insertExtraFields();
1868 if ($result < 0) {
1869 $error++;
1870 }
1871 }
1872 // Actions on extra languages
1873 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1874 $result = $this->insertExtraLanguages();
1875 if ($result < 0) {
1876 $error++;
1877 }
1878 }
1879
1880 if (!$error && $call_trigger) {
1881 // Call trigger
1882 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1883 if ($result < 0) {
1884 $error++;
1885 }
1886 // End call triggers
1887 }
1888
1889 if (!$error) {
1890 dol_syslog(get_class($this)."::Update success");
1891 $this->db->commit();
1892 return 1;
1893 } else {
1894 $this->db->rollback();
1895 return -1;
1896 }
1897 } else {
1898 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1899 // Duplicate
1900 $this->error = $langs->trans("ErrorDuplicateField");
1901 $result = -1;
1902 } else {
1903 $this->error = $this->db->lasterror();
1904 $result = -2;
1905 }
1906 $this->db->rollback();
1907 return $result;
1908 }
1909 } else {
1910 $this->db->rollback();
1911 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1912 return -3;
1913 }
1914 }
1915
1935 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1936 {
1937 global $langs;
1938 global $conf;
1939
1940 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)) {
1941 return -1;
1942 }
1943
1944 $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';
1945 $sql .= ', s.status, s.fk_warehouse';
1946 $sql .= ', s.price_level';
1947 $sql .= ', GREATEST(s.tms, sef.tms) as date_modification, s.fk_user_creat, s.fk_user_modif';
1948 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1949 $sql .= ', s.socialnetworks';
1950 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1951 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1952 $sql .= ', s.capital, s.tva_intra, s.euid';
1953 $sql .= ', s.fk_typent as typent_id';
1954 $sql .= ', s.fk_effectif as effectif_id';
1955 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1956 $sql .= ', s.birth';
1957 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1958 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1959 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1960 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1961 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1962 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1963 $sql .= ', s.mode_reglement, s.cond_reglement, s.fk_account';
1964 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier';
1965 } else {
1966 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1967 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1968 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1969 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1970 $sql .= ', spe.mode_reglement, spe.cond_reglement, spe.fk_account';
1971 $sql .= ', spe.mode_reglement_supplier, spe.cond_reglement_supplier';
1972 }
1973 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1974 $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.deposit_percent, s.transport_mode';
1975 $sql .= ', s.tva_assuj';
1976 $sql .= ', s.transport_mode_supplier';
1977 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1978 $sql .= ', s.fk_shipping_method';
1979 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1980 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1981 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1982 $sql .= ', fj.libelle as forme_juridique';
1983 $sql .= ', e.libelle as effectif';
1984 $sql .= ', c.code as country_code, c.label as country';
1985 $sql .= ', d.code_departement as state_code, d.nom as state';
1986 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1987 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1988 $sql .= ', te.code as typent_code';
1989 $sql .= ', i.libelle as label_incoterms';
1990 if (!isModEnabled('multicompany')) {
1991 $sql .= ', s.remise_client, s.remise_supplier';
1992 } else {
1993 $sql .= ', sr.remise_client, sr2.remise_supplier';
1994 }
1995 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1996 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_extrafields as sef ON sef.fk_object=s.rowid';
1997 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1998 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1999 }
2000 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
2001 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
2002 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
2003 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
2004 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
2005 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
2006 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
2007 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
2008 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
2009 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
2010 if (isModEnabled('multicompany')) {
2011 $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').'))';
2012 $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').'))';
2013 }
2014 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2015
2016 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
2017 if ($is_client) {
2018 $sql .= ' AND s.client > 0';
2019 }
2020 if ($is_supplier) {
2021 $sql .= ' AND s.fournisseur > 0';
2022 } // if both false, no test (the thirdparty can be client and/or supplier)
2023
2024 if ($rowid) {
2025 $sql .= ' AND s.rowid = '.((int) $rowid);
2026 }
2027 if ($ref) {
2028 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
2029 }
2030 if ($ref_alias) {
2031 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
2032 }
2033 if ($ref_ext) {
2034 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
2035 }
2036 if ($barcode) {
2037 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
2038 }
2039 if ($idprof1) {
2040 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2041 }
2042 if ($idprof2) {
2043 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2044 }
2045 if ($idprof3) {
2046 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2047 }
2048 if ($idprof4) {
2049 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2050 }
2051 if ($idprof5) {
2052 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2053 }
2054 if ($idprof6) {
2055 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2056 }
2057 if ($email) {
2058 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2059 }
2060
2061 $resql = $this->db->query($sql);
2062 if ($resql) {
2063 $num = $this->db->num_rows($resql);
2064 if ($num > 1) {
2065 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2066 dol_syslog($this->error, LOG_WARNING);
2067 $result = -2;
2068 } elseif ($num) { // $num = 1
2069 $obj = $this->db->fetch_object($resql);
2070
2071 $this->id = $obj->rowid;
2072 $this->entity = $obj->entity;
2073 $this->canvas = $obj->canvas;
2074
2075 $this->ref = $obj->name;
2076 $this->name = $obj->name;
2077 $this->nom = $obj->name; // deprecated
2078 $this->name_alias = $obj->name_alias;
2079 $this->ref_ext = $obj->ref_ext;
2080
2081 $this->date_creation = $this->db->jdate($obj->date_creation);
2082 $this->date_modification = $this->db->jdate($obj->date_modification);
2083 $this->user_creation_id = $obj->fk_user_creat;
2084 $this->user_modification_id = $obj->fk_user_modif;
2085
2086 $this->address = $obj->address;
2087 $this->zip = $obj->zip;
2088 $this->town = $obj->town;
2089
2090 $this->country_id = $obj->country_id;
2091 $this->country_code = $obj->country_id ? $obj->country_code : '';
2092 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2093
2094 $this->state_id = $obj->state_id;
2095 $this->state_code = $obj->state_code;
2096 $this->region_id = $obj->region_id;
2097 $this->region_code = $obj->region_code;
2098 $this->state = ($obj->state != '-' ? $obj->state : '');
2099
2100 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2101 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2102 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2103 $this->status_prospect_label = $label; // label status prospect
2104 $this->stcomm_picto = $obj->stcomm_picto; // commercial status picto
2105
2106 $this->email = $obj->email;
2107 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2108
2109 $this->url = $obj->url;
2110 $this->phone = $obj->phone;
2111 $this->phone_mobile = $obj->phone_mobile;
2112 $this->fax = $obj->fax;
2113
2114 $this->parent = $obj->parent;
2115
2116 $this->idprof1 = $obj->idprof1;
2117 $this->idprof2 = $obj->idprof2;
2118 $this->idprof3 = $obj->idprof3;
2119 $this->idprof4 = $obj->idprof4;
2120 $this->idprof5 = $obj->idprof5;
2121 $this->idprof6 = $obj->idprof6;
2122
2123 $this->capital = $obj->capital;
2124
2125 $this->code_client = $obj->code_client;
2126 $this->code_fournisseur = $obj->code_fournisseur;
2127
2128 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2129 $this->code_compta_client = $obj->code_compta;
2130 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2131 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2132
2133 $this->barcode = $obj->barcode;
2134
2135 $this->tva_assuj = $obj->tva_assuj;
2136 $this->tva_intra = $obj->tva_intra;
2137
2138 if (!empty($obj->spe_vat_reverse_charge)) {
2139 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2140 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2141 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2142 } else {
2143 $this->vat_reverse_charge = 0;
2144 }
2145 $this->euid = $obj->euid;
2146
2147 $this->status = $obj->status;
2148
2149 // Local Taxes
2150 $this->localtax1_assuj = $obj->localtax1_assuj;
2151 $this->localtax2_assuj = $obj->localtax2_assuj;
2152
2153 $this->localtax1_value = $obj->localtax1_value;
2154 $this->localtax2_value = $obj->localtax2_value;
2155
2156 $this->typent_id = $obj->typent_id;
2157 $this->typent_code = $obj->typent_code;
2158
2159 $this->effectif_id = $obj->effectif_id;
2160 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2161
2162 $this->forme_juridique_code = $obj->forme_juridique_code;
2163 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2164 $this->birth = $this->db->jdate($obj->birth);
2165
2166 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2167
2168 $this->prefix_comm = $obj->prefix_comm;
2169
2170 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2171 $this->remise_supplier_percent = $obj->remise_supplier;
2172
2173 $this->mode_reglement_id = $obj->mode_reglement;
2174 $this->cond_reglement_id = $obj->cond_reglement;
2175 $this->deposit_percent = $obj->deposit_percent;
2176 $this->transport_mode_id = $obj->transport_mode;
2177 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2178 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2179 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2180 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2181 $this->fk_account = $obj->fk_account;
2182
2183 $this->client = $obj->client;
2184 $this->fournisseur = $obj->fournisseur;
2185
2186 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2187 $this->note_private = $obj->note_private;
2188 $this->note_public = $obj->note_public;
2189 $this->model_pdf = $obj->model_pdf;
2190 $this->default_lang = $obj->default_lang;
2191 $this->logo = $obj->logo;
2192 $this->logo_squarred = $obj->logo_squarred;
2193
2194 $this->webservices_url = $obj->webservices_url;
2195 $this->webservices_key = $obj->webservices_key;
2196
2197 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2198 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2199
2200 $this->outstanding_limit = $obj->outstanding_limit;
2201 $this->order_min_amount = $obj->order_min_amount;
2202 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2203
2204 // multi price
2205 $this->price_level = $obj->price_level;
2206
2207 // warehouse
2208 $this->fk_warehouse = $obj->fk_warehouse;
2209
2210 $this->import_key = $obj->import_key;
2211
2212 //Incoterms
2213 $this->fk_incoterms = $obj->fk_incoterms;
2214 $this->location_incoterms = $obj->location_incoterms;
2215 $this->label_incoterms = $obj->label_incoterms;
2216
2217 // multicurrency
2218 $this->fk_multicurrency = $obj->fk_multicurrency;
2219 $this->multicurrency_code = $obj->multicurrency_code;
2220
2221 // pdf
2222 $this->model_pdf = $obj->model_pdf;
2223 $this->last_main_doc = $obj->last_main_doc;
2224
2225 $result = $this->id;
2226
2227 // fetch optionals attributes and labels
2228 $this->fetch_optionals();
2229 } else {
2230 $result = 0;
2231 }
2232
2233 $this->db->free($resql);
2234 } else {
2235 $this->error = $this->db->lasterror();
2236 $this->errors[] = $this->db->lasterror();
2237 $result = -3;
2238 }
2239
2240 // Use first price level if level not defined for third party
2241 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2242 $this->price_level = 1;
2243 }
2244
2245 return $result;
2246 }
2247
2258 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
2259 {
2260 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2261 return parent::setBankAccount($fk_account, $notrigger, $userused);
2262 }
2263
2264 global $conf, $user;
2265
2266 if (empty($userused)) {
2267 $userused = $user;
2268 }
2269
2270 if ($fk_account < 0) {
2271 $fk_account = 'NULL';
2272 }
2273 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2274
2275 $this->db->begin();
2276
2277 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET fk_account = ".((int) $fk_account);
2278 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2279 $resql = $this->db->query($sql);
2280 if ($resql && !$this->db->affected_rows($resql)) {
2281 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, fk_account)";
2282 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".((int) $fk_account).")";
2283 $resql = $this->db->query($sql);
2284 }
2285
2286 if (!$resql) {
2287 dol_syslog(get_class($this).'::setBankAccount Error '.$this->db->error());
2288 $this->error = $this->db->lasterror();
2289 $this->db->rollback();
2290 return -1;
2291 }
2292
2293 if (!$notrigger) {
2294 $this->context['bankaccountupdate'] = 1;
2295 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2296 if ($result < 0) {
2297 $this->db->rollback();
2298 return -1;
2299 }
2300 }
2301
2302 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
2303 $this->db->commit();
2304 return 1;
2305 }
2306
2316 public function setPaymentTerms($id, $deposit_percent = null)
2317 {
2318 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2319 return parent::setPaymentTerms($id, $deposit_percent);
2320 }
2321
2322 global $conf;
2323
2324 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.formatLogObject($deposit_percent).')');
2325
2326 $fieldname = (get_class($this) == 'Fournisseur') ? 'cond_reglement_supplier' : 'cond_reglement';
2327
2328 if (empty($deposit_percent) || $deposit_percent < 0) {
2329 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2330 }
2331 if ($deposit_percent > 100) {
2332 $deposit_percent = 100;
2333 }
2334
2335 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET deposit_percent = ".(empty($deposit_percent) ? 'NULL' : "'".$this->db->escape((string) $deposit_percent)."'");
2336 $sql .= " WHERE rowid = ".((int) $this->id);
2337 $resql = $this->db->query($sql);
2338
2339 if ($resql) {
2340 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2341 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2342 $resql = $this->db->query($sql);
2343 if ($resql && !$this->db->affected_rows($resql)) {
2344 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, ".$this->db->sanitize($fieldname).")";
2345 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL').")";
2346 $resql = $this->db->query($sql);
2347 }
2348 }
2349
2350 if (!$resql) {
2351 dol_syslog(get_class($this).'::setPaymentTerms Error '.$this->db->error());
2352 $this->error = $this->db->lasterror();
2353 return -1;
2354 }
2355
2356 $this->cond_reglement_id = $id;
2357 if (get_class($this) == 'Fournisseur') {
2358 $this->cond_reglement_supplier_id = $id;
2359 }
2360 $this->deposit_percent = $deposit_percent;
2361 return 1;
2362 }
2363
2371 public function setPaymentMethods($id)
2372 {
2373 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2374 return parent::setPaymentMethods($id);
2375 }
2376
2377 global $conf;
2378
2379 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2380
2381 $fieldname = (get_class($this) == 'Fournisseur') ? 'mode_reglement_supplier' : 'mode_reglement';
2382
2383 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2384 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2385 $resql = $this->db->query($sql);
2386 if ($resql && !$this->db->affected_rows($resql)) {
2387 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, ".$this->db->sanitize($fieldname).")";
2388 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL').")";
2389 $resql = $this->db->query($sql);
2390 }
2391
2392 if (!$resql) {
2393 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2394 $this->error = $this->db->lasterror();
2395 return -1;
2396 }
2397
2398 $this->mode_reglement_id = $id;
2399 if (get_class($this) == 'Fournisseur') {
2400 $this->mode_reglement_supplier_id = $id;
2401 }
2402 return 1;
2403 }
2404
2426 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0, $vatnumber = '')
2427 {
2428 // A rowid is known, it is a unique key so we found it
2429 if ($rowid) {
2430 return $rowid;
2431 }
2432
2433 dol_syslog(get_class($this)."::findNearest", LOG_DEBUG);
2434 $tmpthirdparty = new Societe($this->db);
2435
2436 // We try to find the thirdparty with exact matching on all fields
2437 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2438 if ($result != 0) {
2439 return $result;
2440 }
2441
2442 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2443 dol_syslog("Thirdparty not found with exact match so we try barcode search", LOG_DEBUG);
2444 if ($barcode) {
2445 $result = $tmpthirdparty->fetch(0, '', '', $barcode, '', '', '', '', '', '', '', '', $is_client, $is_supplier);
2446 if ($result != 0) {
2447 return $result;
2448 }
2449 }
2450
2451 $sqlstart = "SELECT s.rowid as id FROM ".MAIN_DB_PREFIX."societe as s";
2452 $sqlstart .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2453 if ($is_client) {
2454 $sqlstart .= ' AND s.client > 0';
2455 }
2456 if ($is_supplier) {
2457 $sqlstart .= ' AND s.fournisseur > 0';
2458 } // if both false, no test (the thirdparty can be client and/or supplier)
2459
2460 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2461 dol_syslog("Thirdparty not found with barcode search so we try profids search", LOG_DEBUG);
2462 $sqlprof = "";
2463 if ($idprof1) {
2464 $sqlprof .= " s.siren = '".$this->db->escape($idprof1)."'";
2465 }
2466 if ($idprof2) {
2467 if ($sqlprof) {
2468 $sqlprof .= " OR";
2469 }
2470 $sqlprof .= " s.siret = '".$this->db->escape($idprof2)."'";
2471 }
2472 if ($idprof3) {
2473 if ($sqlprof) {
2474 $sqlprof .= " OR";
2475 }
2476 $sqlprof .= " s.ape = '".$this->db->escape($idprof3)."'";
2477 }
2478 if ($idprof4) {
2479 if ($sqlprof) {
2480 $sqlprof .= " OR";
2481 }
2482 $sqlprof .= " s.idprof4 = '".$this->db->escape($idprof4)."'";
2483 }
2484 if ($idprof5) {
2485 if ($sqlprof) {
2486 $sqlprof .= " OR";
2487 }
2488 $sqlprof .= " s.idprof5 = '".$this->db->escape($idprof5)."'";
2489 }
2490 if ($idprof6) {
2491 if ($sqlprof) {
2492 $sqlprof .= " OR";
2493 }
2494 $sqlprof .= " s.idprof6 = '".$this->db->escape($idprof6)."'";
2495 }
2496 if ($vatnumber) {
2497 if ($sqlprof) {
2498 $sqlprof .= " OR";
2499 }
2500 $sqlprof .= " s.tva_intra = '".$this->db->escape($vatnumber)."'";
2501 }
2502
2503 if ($sqlprof) {
2504 $sqlprofquery = $sqlstart . " AND (".$sqlprof." )";
2505 $resql = $this->db->query($sqlprofquery);
2506 if ($resql) {
2507 $num = $this->db->num_rows($resql);
2508 if ($num > 1) {
2509 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2510 dol_syslog($this->error, LOG_WARNING);
2511 $result = -2;
2512 } elseif ($num) {
2513 $obj = $this->db->fetch_object($resql);
2514 $result = $obj->id;
2515 } else {
2516 $result = 0;
2517 }
2518 } else {
2519 $this->error = $this->db->lasterror();
2520 $this->errors[] = $this->db->lasterror();
2521 $result = -3;
2522 }
2523 if ($result != 0) {
2524 return $result;
2525 }
2526 }
2527
2528 // Then search on email (+ restriction on is_client and is_supplier)
2529 dol_syslog("Thirdparty not found with profids search so we try email search", LOG_DEBUG);
2530 if ($email) {
2531 $result = $tmpthirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email, '', $is_client, $is_supplier);
2532 if ($result != 0) {
2533 return $result;
2534 }
2535 }
2536
2537 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2538 dol_syslog("Thirdparty not found with email search so we try ref, ref_ext or ref_alias search", LOG_DEBUG);
2539 $sqlref = "";
2540 if ($ref) {
2541 $sqlref .= " s.nom = '".$this->db->escape($ref)."'";
2542 }
2543 if ($ref_alias) {
2544 if ($sqlref) {
2545 $sqlref .= " OR";
2546 }
2547 $sqlref .= " s.name_alias = '".$this->db->escape($ref_alias)."'";
2548 }
2549 if ($ref_ext) {
2550 if ($sqlref) {
2551 $sqlref .= " OR";
2552 }
2553 $sqlref .= " s.ref_ext = '".$this->db->escape($ref_ext)."'";
2554 }
2555
2556 if ($sqlref) {
2557 $sqlrefquery = $sqlstart . " AND (".$sqlref." )";
2558 $resql = $this->db->query($sqlrefquery);
2559 if ($resql) {
2560 $num = $this->db->num_rows($resql);
2561 if ($num > 1) {
2562 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2563 dol_syslog($this->error, LOG_WARNING);
2564 $result = -2;
2565 } elseif ($num) {
2566 $obj = $this->db->fetch_object($resql);
2567 $result = $obj->id;
2568 } else {
2569 $result = 0;
2570 }
2571 } else {
2572 $this->error = $this->db->lasterror();
2573 $this->errors[] = $this->db->lasterror();
2574 $result = -3;
2575 }
2576 }
2577 return $result;
2578 }
2579
2588 public function delete($id, $fuser = null, $call_trigger = 1)
2589 {
2590 global $conf, $user;
2591
2592 if (empty($fuser)) {
2593 $fuser = $user;
2594 }
2595
2596 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2597
2598 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2599
2600 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2601 $error = 0;
2602
2603 // Test if child exists
2604 $objectisused = $this->isObjectUsed($id);
2605 if (empty($objectisused)) {
2606 $this->db->begin();
2607
2608 // User is mandatory for trigger call
2609 if ($call_trigger) {
2610 // Call trigger
2611 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2612 if ($result < 0) {
2613 $error++;
2614 }
2615 // End call triggers
2616 }
2617
2618 if (!$error) {
2619 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2620 $static_cat = new Categorie($this->db);
2621 $toute_categs = array();
2622
2623 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2624 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2625 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2626
2627 // Remove each "Categorie"
2628 foreach ($toute_categs as $type => $categs_type) {
2629 foreach ($categs_type as $cat) {
2630 $cat->del_type($this, $type);
2631 }
2632 }
2633 }
2634
2635 if (!$error) {
2636 foreach ($this->childtablesoncascade as $tabletodelete) {
2637 $deleteFromObject = explode(':', $tabletodelete, 4);
2638 if (count($deleteFromObject) >= 2) {
2639 $className = str_replace('@', '', $deleteFromObject[0]);
2640 $filepath = $deleteFromObject[1];
2641 $columnName = $deleteFromObject[2];
2642 if (dol_include_once($filepath)) {
2643 $child_object = new $className($this->db);
2644 '@phan-var-force CommonObject $child_object';
2645 $result = $child_object->deleteByParentField($id, $columnName);
2646 if ($result < 0) {
2647 $error++;
2648 $this->errors[] = $child_object->error;
2649 break;
2650 }
2651 } else {
2652 $error++;
2653 $this->errors[] = 'Cannot include child class file '.$filepath;
2654 break;
2655 }
2656 } else {
2657 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2658 $sql .= " WHERE fk_soc = ".((int) $id);
2659 if (!$this->db->query($sql)) {
2660 $error++;
2661 $this->errors[] = $this->db->lasterror();
2662 break;
2663 }
2664 }
2665 }
2666 }
2667
2668 // Removed extrafields
2669 if (!$error) {
2670 $result = $this->deleteExtraFields();
2671 if ($result < 0) {
2672 $error++;
2673 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2674 }
2675 }
2676
2677 // Remove links to subsidiaries companies
2678 if (!$error) {
2679 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2680 $sql .= " SET parent = NULL";
2681 $sql .= " WHERE parent = ".((int) $id);
2682 if (!$this->db->query($sql)) {
2683 $error++;
2684 $this->errors[] = $this->db->lasterror();
2685 }
2686 }
2687
2688 // Remove third party
2689 if (!$error) {
2690 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2691 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2692 $sql .= " WHERE fk_soc = ".((int) $id);
2693 if (!$this->db->query($sql)) {
2694 $error++;
2695 $this->errors[] = $this->db->lasterror();
2696 }
2697 }
2698
2699 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2700 $sql .= " WHERE rowid = ".((int) $id);
2701 if (!$this->db->query($sql)) {
2702 $error++;
2703 $this->errors[] = $this->db->lasterror();
2704 }
2705 }
2706
2707 if (!$error) {
2708 $this->db->commit();
2709
2710 // Delete directory
2711 if (!empty($conf->societe->multidir_output[$entity])) {
2712 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2713 if (dol_is_dir($docdir)) {
2714 dol_delete_dir_recursive($docdir);
2715 }
2716 }
2717
2718 return 1;
2719 } else {
2720 dol_syslog($this->error, LOG_ERR);
2721 $this->db->rollback();
2722 return -1;
2723 }
2724 } else {
2725 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2726 }
2727 return 0;
2728 }
2729
2730 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2738 public function set_as_client()
2739 {
2740 // phpcs:enable
2741 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2742 return $this->setAsCustomer();
2743 }
2744
2751 public function setAsCustomer()
2752 {
2753 global $user;
2754
2755 if ($this->id) {
2756 $newclient = 1;
2757 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2758 $newclient = 3; // If prospected, we keep prospect tag
2759 }
2760 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2761 $sql .= " SET client = ".((int) $newclient);
2762 $sql .= " WHERE rowid = ".((int) $this->id);
2763
2764 $this->db->begin();
2765
2766 $resql = $this->db->query($sql);
2767 if ($resql) {
2768 $this->client = $newclient;
2769
2770 // Call trigger
2771 $result = $this->call_trigger('COMPANY_MODIFY', $user);
2772 if ($result < 0) {
2773 $this->db->rollback();
2774 return -1;
2775 }
2776 // End call triggers
2777
2778 $this->db->commit();
2779 return 1;
2780 } else {
2781 $this->db->rollback();
2782 return -1;
2783 }
2784 }
2785 return 0;
2786 }
2787
2788 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2797 public function set_remise_client($remise, $note, User $user)
2798 {
2799 // phpcs:enable
2800 global $conf, $langs;
2801
2802 // Parameter cleaning
2803 $note = trim($note);
2804 if (!$note) {
2805 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2806 return -2;
2807 }
2808
2809 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2810
2811 if ($this->id) {
2812 $this->db->begin();
2813
2814 $now = dol_now();
2815
2816 // Position current discount
2817 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2818 $sql .= " SET remise_client = '".$this->db->escape((string) $remise)."'";
2819 $sql .= " WHERE rowid = ".((int) $this->id);
2820 $resql = $this->db->query($sql);
2821 if (!$resql) {
2822 $this->db->rollback();
2823 $this->error = $this->db->error();
2824 return -1;
2825 }
2826
2827 // Writes trace in discount history
2828 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2829 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2830 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape((string) $remise)."',";
2831 $sql .= " '".$this->db->escape($note)."',";
2832 $sql .= " ".((int) $user->id);
2833 $sql .= ")";
2834
2835 $resql = $this->db->query($sql);
2836 if (!$resql) {
2837 $this->db->rollback();
2838 $this->error = $this->db->lasterror();
2839 return -1;
2840 }
2841
2842 $this->db->commit();
2843
2844 return 1;
2845 }
2846 return -1;
2847 }
2848
2849 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2858 public function set_remise_supplier($remise, $note, User $user)
2859 {
2860 // phpcs:enable
2861 global $conf, $langs;
2862
2863 // Parameter cleaning
2864 $note = trim($note);
2865 if (!$note) {
2866 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2867 return -2;
2868 }
2869
2870 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2871
2872 if ($this->id) {
2873 $this->db->begin();
2874
2875 $now = dol_now();
2876
2877 // Position current discount
2878 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2879 $sql .= " SET remise_supplier = ".((float) $remise);
2880 $sql .= " WHERE rowid = ".((int) $this->id);
2881 $resql = $this->db->query($sql);
2882 if (!$resql) {
2883 $this->db->rollback();
2884 $this->error = $this->db->error();
2885 return -1;
2886 }
2887
2888 // Writes trace in discount history
2889 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2890 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2891 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((float) $remise).",";
2892 $sql .= " '".$this->db->escape($note)."',";
2893 $sql .= " ".((int) $user->id);
2894 $sql .= ")";
2895
2896 $resql = $this->db->query($sql);
2897 if (!$resql) {
2898 $this->db->rollback();
2899 $this->error = $this->db->lasterror();
2900 return -1;
2901 }
2902
2903 $this->db->commit();
2904 return 1;
2905 }
2906
2907 return -1;
2908 }
2909
2910 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2922 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2923 {
2924 // phpcs:enable
2925 global $langs, $mysoc;
2926
2927 // Clean parameters
2928 $remise = (float) price2num($remise);
2929 $desc = trim($desc);
2930
2931 // Check parameters
2932 if (!($remise > 0)) {
2933 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2934 return -1;
2935 }
2936 if (!$desc) {
2937 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2938 return -2;
2939 }
2940
2941 if ($this->id > 0) {
2942 // Separate VAT code from VAT rate string
2943 // Discount type determines who is buyer and seller
2944 $taxes = getTaxesFromId($vatrate, ($discount_type == 0 ? $this : $mysoc), ($discount_type == 0 ? $mysoc : $this), 0);
2945 $reg = array();
2946 $vat_src_code = '';
2947 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2948 $vat_src_code = $reg[1];
2949 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2950 }
2951
2952 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2953
2954 $discount = new DiscountAbsolute($this->db);
2955 $discount->fk_soc = $this->id;
2956 $discount->socid = $this->id;
2957
2958 $discount->discount_type = $discount_type;
2959 $discount->multicurrency_code = $this->multicurrency_code;
2960
2961 $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2962 $this->fk_multicurrency = $tmparray[0];
2963 $this->multicurrency_tx = $tmparray[1];
2964
2965 $discount->multicurrency_tx = $this->multicurrency_tx;
2966
2967 $vat_tx = (float) price2num($vatrate);
2968
2969 $discount->generateFromAmount($remise, ($price_base_type == 'TTC' ? 1 : 0), $vat_tx, $taxes['localtax1'], $taxes['localtax2'], (int) $taxes['localtax1_type'], (int) $taxes['localtax2_type']);
2970
2971 $discount->vat_src_code = $vat_src_code;
2972
2973 $discount->description = $desc;
2974
2975 $result = $discount->create($user);
2976 if ($result > 0) {
2977 return $result;
2978 } else {
2979 $this->error = $discount->error;
2980 return -3;
2981 }
2982 } else {
2983 return 0;
2984 }
2985 }
2986
2996 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2997 {
2998 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2999
3000 $discountstatic = new DiscountAbsolute($this->db);
3001 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
3002 if ($result >= 0) {
3003 return $result;
3004 } else {
3005 $this->error = $discountstatic->error;
3006 return -1;
3007 }
3008 }
3009
3010
3017 public function getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type = 0)
3018 {
3019 global $conf;
3020
3021 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ttc) as amount, SUM(f.multicurrency_total_ttc) as multicurrency_amount";
3022 if (!empty($discount_type)) {
3023 $sql .= " FROM ".$this->db->prefix()."facture_fourn as f";
3024 } else {
3025 $sql .= " FROM ".$this->db->prefix()."facture as f";
3026 }
3027 $sql .= " WHERE f.entity = ".((int) $conf->entity);
3028 $sql .= " AND paye = 0 AND fk_statut = 1";
3029 $sql .= " AND f.type = ".CommonInvoice::TYPE_CREDIT_NOTE;
3030 $sql .= " AND NOT EXISTS (SELECT rowid FROM ".$this->db->prefix()."societe_remise_except as rc";
3031 $sql .= " WHERE rc.discount_type = ".((int) $discount_type);
3032 if (!empty($discount_type)) {
3033 $sql .= " AND rc.fk_invoice_supplier = f.rowid";
3034 } else {
3035 $sql .= " AND rc.fk_facture = f.rowid";
3036 }
3037 $sql .= " AND rc.fk_soc = ".((int) $this->id);
3038 $sql .= ")";
3039 $sql .= " AND f.fk_soc = ".((int) $this->id);
3040
3041 $resql = $this->db->query($sql);
3042 if ($resql) {
3043 $obj = $this->db->fetch_object($resql);
3044
3045 return $obj->nb;
3046 }
3047
3048 return -1;
3049 }
3050
3051
3061 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
3062 {
3063 global $conf;
3064
3065 $reparray = array();
3066
3067 $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";
3068 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
3069 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
3070 // Condition here should be the same than into select_dolusers()
3071 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
3072 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
3073 } else {
3074 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
3075 }
3076
3077 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
3078 if (empty($sortfield)) {
3079 $sortfield = 'u.lastname,u.firstname';
3080 }
3081 if (empty($sortorder)) {
3082 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
3083 }
3084 $sql .= $this->db->order($sortfield, $sortorder);
3085
3086 $resql = $this->db->query($sql);
3087 if ($resql) {
3088 $num = $this->db->num_rows($resql);
3089 $i = 0;
3090 while ($i < $num) {
3091 $obj = $this->db->fetch_object($resql);
3092
3093 if (empty($mode)) {
3094 $reparray[$i]['id'] = (int) $obj->rowid;
3095 $reparray[$i]['lastname'] = $obj->lastname;
3096 $reparray[$i]['firstname'] = $obj->firstname;
3097 $reparray[$i]['email'] = $obj->email;
3098 $reparray[$i]['phone'] = $obj->office_phone;
3099 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
3100 $reparray[$i]['office_fax'] = $obj->office_fax;
3101 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
3102 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
3103 $reparray[$i]['job'] = $obj->job;
3104 $reparray[$i]['statut'] = $obj->status; // deprecated
3105 $reparray[$i]['status'] = $obj->status;
3106 $reparray[$i]['entity'] = $obj->entity;
3107 $reparray[$i]['login'] = $obj->login;
3108 $reparray[$i]['photo'] = $obj->photo;
3109 $reparray[$i]['gender'] = $obj->gender;
3110 } else {
3111 $reparray[] = (int) $obj->rowid;
3112 }
3113 $i++;
3114 }
3115 return $reparray;
3116 } else {
3117 dol_print_error($this->db);
3118 return -1;
3119 }
3120 }
3121
3129 public function setPriceLevel($price_level, User $user)
3130 {
3131 if ($this->id) {
3132 $now = dol_now();
3133
3134 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
3135 $sql .= " SET price_level = ".((int) $price_level);
3136 $sql .= " WHERE rowid = ".((int) $this->id);
3137
3138 if (!$this->db->query($sql)) {
3139 dol_print_error($this->db);
3140 return -1;
3141 }
3142
3143 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
3144 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
3145 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
3146
3147 if (!$this->db->query($sql)) {
3148 dol_print_error($this->db);
3149 return -1;
3150 }
3151 return 1;
3152 }
3153 return -1;
3154 }
3155
3156 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3164 public function add_commercial(User $user, $commid)
3165 {
3166 // phpcs:enable
3167 $error = 0;
3168
3169 if ($this->id > 0 && $commid > 0) {
3170 $this->db->begin();
3171
3172 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
3173 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3174
3175 $resql = $this->db->query($sql);
3176 if (!$resql) {
3177 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3178 $error++;
3179 }
3180
3181 if (!$error) {
3182 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
3183 $sql .= " (fk_soc, fk_user)";
3184 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
3185
3186 $resql = $this->db->query($sql);
3187 if (!$resql) {
3188 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3189 $error++;
3190 }
3191 }
3192
3193 if (!$error) {
3194 $this->context = array('commercial_modified' => $commid);
3195
3196 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3197 if ($result < 0) {
3198 $error++;
3199 }
3200 }
3201
3202 if (!$error) {
3203 $this->db->commit();
3204 return 1;
3205 } else {
3206 $this->db->rollback();
3207 return -1;
3208 }
3209 }
3210
3211 return 0;
3212 }
3213
3214 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3222 public function del_commercial(User $user, $commid)
3223 {
3224 // phpcs:enable
3225 $error = 0;
3226 $this->context = array('commercial_modified' => $commid);
3227
3228 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3229 if ($result < 0) {
3230 $error++;
3231 }
3232
3233 if ($this->id > 0 && $commid > 0) {
3234 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3235 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3236
3237 if (!$this->db->query($sql)) {
3238 $error++;
3239 dol_syslog(get_class($this)."::del_commercial Erreur");
3240 }
3241 }
3242
3243 if ($error) {
3244 return -1;
3245 } else {
3246 return 1;
3247 }
3248 }
3249
3257 public function getTooltipContentArray($params)
3258 {
3259 global $conf, $langs, $user;
3260
3261 $langs->loadLangs(['companies', 'commercial']);
3262
3263 $datas = array();
3264
3265 $option = $params['option'] ?? '';
3266 $nofetch = !empty($params['nofetch']);
3267
3268 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3269
3270 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3271 return ['optimize' => $langs->trans("ShowCompany")];
3272 }
3273
3274 if (!empty($this->logo) && class_exists('Form')) {
3275 $photo = '<div class="photointooltip floatright">';
3276 $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.
3277 $photo .= '</div>';
3278 $datas['photo'] = $photo;
3279 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3280 /*$label.= '<div class="photointooltip">';
3281 $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.
3282 $label.= '</div><div style="clear: both;"></div>';*/
3283 // }
3284
3285 $datas['divopen'] = '<div class="centpercent">';
3286
3287 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3288 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3289 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3290 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3291 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3292 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3293 } elseif ($option == 'agenda') {
3294 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3295 } elseif ($option == 'project') {
3296 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3297 } elseif ($option == 'margin') {
3298 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3299 } elseif ($option == 'contact') {
3300 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3301 } elseif ($option == 'ban') {
3302 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3303 }
3304
3305 // By default
3306 if (empty($datas['picto'])) {
3307 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3308 }
3309 if (isset($this->status)) {
3310 $datas['status'] = ' '.$this->getLibStatut(5);
3311 }
3312 if (isset($this->client) && isset($this->fournisseur)) {
3313 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3314 }
3315 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3316 if (!empty($this->name_alias) && empty($noaliasinname)) {
3317 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3318 }
3319 if (!empty($this->email)) {
3320 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3321 }
3322 if (!empty($this->url)) {
3323 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3324 }
3325 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3326 $phonelist = array();
3327 if ($this->phone) {
3328 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3329 }
3330 // deliberately not making new list because fax uses same list as phone
3331 if ($this->phone_mobile) {
3332 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3333 }
3334 if ($this->fax) {
3335 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3336 }
3337 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3338 }
3339
3340 if (!empty($this->address)) {
3341 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3342 } elseif (!empty($this->country_code)) {
3343 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3344 }
3345 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3346 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3347 }
3348
3349 if (!empty($this->euid) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'euid') !== false)) {
3350 $datas['euid'] = '<br><b>'.$langs->trans('EUIDShort').':</b> '.dol_escape_htmltag($this->euid);
3351 }
3352
3353 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3354 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3355 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3356 }
3357 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3358 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3359 }
3360 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3361 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3362 }
3363 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3364 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3365 }
3366 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3367 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3368 }
3369 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3370 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3371 }
3372 }
3373
3374 $datas['separator'] = '<br>';
3375
3376 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3377 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3378 }
3379 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3380 $langs->load('compta');
3381 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3382 }
3383 // show categories for this record only in ajax to not overload lists
3384 if (!$nofetch && isModEnabled('category') && $this->client) {
3385 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3386 $form = new Form($this->db);
3387 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3388 }
3389 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3390 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3391 }
3392 if (isModEnabled('accounting') && $this->fournisseur) {
3393 $langs->load('compta');
3394 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3395 }
3396 // show categories for this record only in ajax to not overload lists
3397 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3398 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3399 $form = new Form($this->db);
3400 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3401 }
3402
3403 $datas['divclose'] = '</div>';
3404
3405 return $datas;
3406 }
3407
3421 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = 'valignmiddle')
3422 {
3423 global $conf, $langs, $hookmanager, $user;
3424
3425 if (!empty($conf->dol_no_mouse_hover)) {
3426 $notooltip = 1; // Force disable tooltips
3427 }
3428
3429 $name = $this->name ? $this->name : $this->nom;
3430
3431 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3432 if (empty($option) && $this->client > 0) {
3433 $option = 'customer';
3434 }
3435 if (empty($option) && $this->fournisseur > 0) {
3436 $option = 'supplier';
3437 }
3438 }
3439
3440 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3441 $code = '';
3442 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3443 $code = $this->code_client.' - ';
3444 }
3445
3446 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3447 $code .= $this->code_fournisseur.' - ';
3448 }
3449
3450 if ($code) {
3451 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3452 $name = $code.' '.$name;
3453 } else {
3454 $name = $code;
3455 }
3456 }
3457 }
3458
3459 if (!empty($this->name_alias) && empty($noaliasinname)) {
3460 $name .= ' ('.$this->name_alias.')';
3461 }
3462
3463 $result = '';
3464 $params = [
3465 'id' => $this->id,
3466 'objecttype' => $this->element,
3467 'option' => $option,
3468 'nofetch' => 1,
3469 ];
3470 $classfortooltip = 'classfortooltip';
3471 $dataparams = '';
3472 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3473 $classfortooltip = 'classforajaxtooltip';
3474 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3475 $label = '';
3476 } else {
3477 $label = implode($this->getTooltipContentArray($params));
3478 }
3479
3480 $linkstart = '';
3481 $linkend = '';
3482
3483 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3484 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3485 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3486 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3487 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3488 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3489 } elseif ($option == 'agenda') {
3490 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3491 } elseif ($option == 'project') {
3492 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3493 } elseif ($option == 'margin') {
3494 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3495 } elseif ($option == 'contact') {
3496 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3497 } elseif ($option == 'ban') {
3498 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3499 }
3500
3501 // By default
3502 if (empty($linkstart)) {
3503 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3504 }
3505
3506 // Add type of canvas
3507 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3508 // Add param to save lastsearch_values or not
3509 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3510 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3511 $add_save_lastsearch_values = 1;
3512 }
3513 if ($add_save_lastsearch_values) {
3514 $linkstart .= '&save_lastsearch_values=1';
3515 }
3516 $linkstart .= '"';
3517
3518 $linkclose = '';
3519 if (empty($notooltip)) {
3520 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3521 $label = $langs->trans("ShowCompany");
3522 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3523 }
3524 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3525 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl'.($withpicto ? ' valignmiddle' : '').'"';
3526 $target_value = array('_self', '_blank', '_parent', '_top');
3527 if (in_array($target, $target_value)) {
3528 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3529 }
3530 } else {
3531 $linkclose .= ' class="'.($morecss ? ' '.$morecss : '').'"';
3532 }
3533 $linkstart .= $linkclose.'>';
3534 $linkend = '</a>';
3535
3536 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3537 $linkstart = '';
3538 $linkend = '';
3539 }
3540
3541 $result .= $linkstart;
3542 if ($withpicto) {
3543 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3544 }
3545 if ($withpicto != 2) {
3546 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3547 }
3548 $result .= $linkend;
3549
3550 global $action;
3551 $hookmanager->initHooks(array('thirdpartydao'));
3552 $parameters = array(
3553 'id' => $this->id,
3554 'getnomurl' => &$result,
3555 'withpicto ' => $withpicto,
3556 'option' => $option,
3557 'maxlen' => $maxlen,
3558 'notooltip' => $notooltip,
3559 'save_lastsearch_value' => $save_lastsearch_value
3560 );
3561 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3562 if ($reshook > 0) {
3563 $result = $hookmanager->resPrint;
3564 } else {
3565 $result .= $hookmanager->resPrint;
3566 }
3567
3568 return $result;
3569 }
3570
3580 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3581 {
3582 global $langs;
3583
3584 $s = '';
3585 if (empty($option) || preg_match('/prospect/', $option)) {
3586 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3587 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3588 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3589 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3590 }
3591 }
3592 if (empty($option) || preg_match('/customer/', $option)) {
3593 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3594 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3595 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3596 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3597 }
3598 }
3599 if (empty($option) || preg_match('/supplier/', $option)) {
3600 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3601 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3602 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3603 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3604 }
3605 }
3606
3607 return $s;
3608 }
3609
3610
3617 public function getLibStatut($mode = 0)
3618 {
3619 return $this->LibStatut($this->status, $mode);
3620 }
3621
3622 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3630 public function LibStatut($status, $mode = 0)
3631 {
3632 // phpcs:enable
3633 global $langs;
3634 $langs->load('companies');
3635
3636 $statusType = 'status4';
3637 if ($status == 0) {
3638 $statusType = 'status6';
3639 }
3640
3641 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3642 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3643 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3644 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3645 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3646 }
3647
3648 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3649 }
3650
3651 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3658 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3659 {
3660 // phpcs:enable
3661 global $langs;
3662
3663 $contact_emails = $this->contact_property_array('email', 1);
3664
3665 if ($this->email && $addthirdparty) {
3666 if (empty($this->name)) {
3667 $this->name = $this->nom;
3668 }
3669 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3670 }
3671
3672 //var_dump($contact_emails)
3673 return $contact_emails;
3674 }
3675
3676 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3683 {
3684 // phpcs:enable
3685 global $langs;
3686
3687 $contact_phone = $this->contact_property_array('mobile');
3688
3689 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3690 if (empty($this->name)) {
3691 $this->name = $this->nom;
3692 }
3693 // TODO: Test if phone is not already present in contact array
3694 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3695 }
3696 return $contact_phone;
3697 }
3698
3699 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3707 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3708 {
3709 // phpcs:enable
3710 global $langs;
3711
3712 $contact_property = array();
3713
3714
3715 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3716 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3717 $sql .= " WHERE fk_soc = ".((int) $this->id);
3718 $sql .= " AND entity IN (".getEntity($this->element).")";
3719 $sql .= " ORDER BY lastname, firstname";
3720
3721 $resql = $this->db->query($sql);
3722 if ($resql) {
3723 $nump = $this->db->num_rows($resql);
3724 if ($nump) {
3725 $sepa = "(";
3726 $sepb = ")";
3727 if ($mode == 'email') {
3728 //$sepa="&lt;"; $sepb="&gt;";
3729 $sepa = "<";
3730 $sepb = ">";
3731 }
3732 $i = 0;
3733 while ($i < $nump) {
3734 $obj = $this->db->fetch_object($resql);
3735 if ($mode == 'email') {
3736 $property = $obj->email;
3737 } elseif ($mode == 'mobile') {
3738 $property = $obj->phone_mobile;
3739 } else {
3740 $property = $obj->$mode;
3741 }
3742
3743 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3744 if ($obj->status == 1 || empty($hidedisabled)) {
3745 if (empty($property)) {
3746 if ($mode == 'email') {
3747 $property = $langs->transnoentitiesnoconv("NoEMail");
3748 } elseif ($mode == 'mobile') {
3749 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3750 }
3751 }
3752
3753 if (!empty($obj->poste)) {
3754 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3755 } else {
3756 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3757 }
3758 }
3759 $i++;
3760 }
3761 }
3762 } else {
3763 dol_print_error($this->db);
3764 }
3765 return $contact_property;
3766 }
3767
3768
3769 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3775 public function contact_array()
3776 {
3777 // phpcs:enable
3778 $contacts = array();
3779
3780 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3781 $resql = $this->db->query($sql);
3782 if ($resql) {
3783 $nump = $this->db->num_rows($resql);
3784 if ($nump) {
3785 $i = 0;
3786 while ($i < $nump) {
3787 $obj = $this->db->fetch_object($resql);
3788 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3789 $i++;
3790 }
3791 }
3792 } else {
3793 dol_print_error($this->db);
3794 }
3795 return $contacts;
3796 }
3797
3798 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3804 public function contact_array_objects()
3805 {
3806 // phpcs:enable
3807 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3808 $contacts = array();
3809
3810 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3811 $resql = $this->db->query($sql);
3812 if ($resql) {
3813 $nump = $this->db->num_rows($resql);
3814 if ($nump) {
3815 $i = 0;
3816 while ($i < $nump) {
3817 $obj = $this->db->fetch_object($resql);
3818 $contact = new Contact($this->db);
3819 $contact->fetch($obj->rowid);
3820 $contacts[] = $contact;
3821 $i++;
3822 }
3823 }
3824 } else {
3825 dol_print_error($this->db);
3826 }
3827 return $contacts;
3828 }
3829
3830 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3838 public function contact_get_property($rowid, $mode)
3839 {
3840 // phpcs:enable
3841 $contact_property = '';
3842
3843 if (empty($rowid)) {
3844 return '';
3845 }
3846
3847 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3848 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3849 $sql .= " WHERE rowid = ".((int) $rowid);
3850
3851 $resql = $this->db->query($sql);
3852 if ($resql) {
3853 $nump = $this->db->num_rows($resql);
3854
3855 if ($nump) {
3856 $obj = $this->db->fetch_object($resql);
3857
3858 if ($mode == 'email') {
3859 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3860 } elseif ($mode == 'mobile') {
3861 $contact_property = $obj->phone_mobile;
3862 }
3863 }
3864 return $contact_property;
3865 } else {
3866 dol_print_error($this->db);
3867 }
3868
3869 return '';
3870 }
3871
3872
3873 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3880 public function display_rib($mode = 'label')
3881 {
3882 // phpcs:enable
3883 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3884
3885 $bac = new CompanyBankAccount($this->db);
3886 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3887 $bac->fetch(0, '', $this->id);
3888
3889 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3890 if ($mode == 'label') {
3891 return $bac->getRibLabel(true);
3892 } elseif ($mode == 'rum') {
3893 if (empty($bac->rum)) {
3894 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3895 $prelevement = new BonPrelevement($this->db);
3896 $bac->fetch_thirdparty();
3897 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3898 }
3899 return $bac->rum;
3900 } elseif ($mode == 'format') {
3901 return $bac->frstrecur;
3902 } else {
3903 return 'BadParameterToFunctionDisplayRib';
3904 }
3905 } else {
3906 return '';
3907 }
3908 }
3909
3910 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3916 public function get_all_rib()
3917 {
3918 // phpcs:enable
3919 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3920 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3921 $result = $this->db->query($sql);
3922 if (!$result) {
3923 $this->error = $this->db->lasterror();
3924 $this->errors[] = $this->db->lasterror();
3925 return 0;
3926 } else {
3927 $num_rows = $this->db->num_rows($result);
3928 $rib_array = array();
3929 if ($num_rows) {
3930 while ($obj = $this->db->fetch_object($result)) {
3931 $rib = new CompanyBankAccount($this->db);
3932 $rib->fetch($obj->rowid);
3933 $rib_array[] = $rib;
3934 }
3935 }
3936 return $rib_array;
3937 }
3938 }
3939
3943 public function getDefaultRib()
3944 {
3945 // phpcs:enable
3946 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3947 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3948 $resql = $this->db->query($sql);
3949 if (!$resql) {
3950 $this->error = $this->db->lasterror();
3951 $this->errors[] = $this->db->lasterror();
3952 return -1;
3953 } else {
3954 $num_rows = $this->db->num_rows($resql);
3955 $rib_array = array();
3956 if ($num_rows) {
3957 while ($obj = $this->db->fetch_object($resql)) {
3958 return $obj->rowid;
3959 }
3960 }
3961 return 0;
3962 }
3963 }
3964
3965
3966 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3975 public function get_codeclient($objsoc = null, $type = 0)
3976 {
3977 // phpcs:enable
3978 global $conf;
3979 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3980 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3981
3982 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3983 foreach ($dirsociete as $dirroot) {
3984 $res = dol_include_once($dirroot.$module.'.php');
3985 if ($res) {
3986 break;
3987 }
3988 }
3990 $mod = new $module($this->db);
3991 '@phan-var-force ModeleThirdPartyCode $mod';
3992
3993 $this->code_client = $mod->getNextValue($objsoc, $type);
3994 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3995
3996 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3997 }
3998 }
3999
4000 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4009 public function get_codefournisseur($objsoc = null, $type = 1)
4010 {
4011 // phpcs:enable
4012 global $conf;
4013 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4014 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4015
4016 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4017 foreach ($dirsociete as $dirroot) {
4018 $res = dol_include_once($dirroot.$module.'.php');
4019 if ($res) {
4020 break;
4021 }
4022 }
4024 $mod = new $module($this->db);
4025 '@phan-var-force ModeleThirdPartyCode $mod';
4026
4027 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
4028
4029 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4030 }
4031 }
4032
4033 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4040 public function codeclient_modifiable()
4041 {
4042 // phpcs:enable
4043 global $conf;
4044 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4045 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4046
4047 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4048 foreach ($dirsociete as $dirroot) {
4049 $res = dol_include_once($dirroot.$module.'.php');
4050 if ($res) {
4051 break;
4052 }
4053 }
4054
4055 $mod = new $module($this->db);
4056 '@phan-var-force ModeleThirdPartyCode $mod';
4057
4058 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
4059 if ($mod->code_modifiable_null && !$this->code_client) {
4060 return 1;
4061 }
4062 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
4063 return 1;
4064 }
4065 if ($mod->code_modifiable) {
4066 return 1; // To be put last
4067 }
4068 return 0;
4069 } else {
4070 return 0;
4071 }
4072 }
4073
4074
4075 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4082 {
4083 // phpcs:enable
4084 global $conf;
4085 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4086 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4087
4088 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4089 foreach ($dirsociete as $dirroot) {
4090 $res = dol_include_once($dirroot.$module.'.php');
4091 if ($res) {
4092 break;
4093 }
4094 }
4095
4096 $mod = new $module($this->db);
4097 '@phan-var-force ModeleThirdPartyCode $mod';
4098
4099 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
4100 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
4101 return 1;
4102 }
4103 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
4104 return 1;
4105 }
4106 if ($mod->code_modifiable) {
4107 return 1; // To be put last
4108 }
4109 return 0;
4110 } else {
4111 return 0;
4112 }
4113 }
4114
4115
4116 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4128 public function check_codeclient()
4129 {
4130 // phpcs:enable
4131 global $conf;
4132 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4133 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4134
4135 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4136 foreach ($dirsociete as $dirroot) {
4137 $res = dol_include_once($dirroot.$module.'.php');
4138 if ($res) {
4139 break;
4140 }
4141 }
4142
4143 $mod = new $module($this->db);
4144 '@phan-var-force ModeleThirdPartyCode $mod';
4145
4146 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
4147 $result = $mod->verif($this->db, $this->code_client, $this, 0);
4148 if ($result) { // If error
4149 $this->error = $mod->error;
4150 $this->errors = $mod->errors;
4151 }
4152 return $result;
4153 } else {
4154 return 0;
4155 }
4156 }
4157
4158 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4170 public function check_codefournisseur()
4171 {
4172 // phpcs:enable
4173 global $conf;
4174 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4175 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4176
4177 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4178 foreach ($dirsociete as $dirroot) {
4179 $res = dol_include_once($dirroot.$module.'.php');
4180 if ($res) {
4181 break;
4182 }
4183 }
4184
4185 $mod = new $module($this->db);
4186 '@phan-var-force ModeleThirdPartyCode $mod';
4187
4188 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4189 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
4190 if ($result) { // If error
4191 $this->error = $mod->error;
4192 $this->errors = $mod->errors;
4193 }
4194 return $result;
4195 } else {
4196 return 0;
4197 }
4198 }
4199
4200 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4209 public function get_codecompta($type)
4210 {
4211 // phpcs:enable
4212 global $conf;
4213
4214 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
4215 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
4216 $res = false;
4217 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4218 foreach ($dirsociete as $dirroot) {
4219 $res = dol_include_once($dirroot.$module.'.php');
4220 if ($res) {
4221 break;
4222 }
4223 }
4224
4225 if ($res) {
4226 $mod = new $module();
4227 '@phan-var-force ModeleAccountancyCode $mod';
4228
4229 // Set code count in $mod->code
4230 $result = $mod->get_code($this->db, $this, $type);
4231
4232 if ($type == 'customer') {
4233 $this->code_compta_client = $mod->code;
4234 } elseif ($type == 'supplier') {
4235 $this->code_compta_fournisseur = $mod->code;
4236 }
4237
4238 return $result;
4239 } else {
4240 $this->error = 'ErrorAccountancyCodeNotDefined';
4241 return -1;
4242 }
4243 } else {
4244 if ($type == 'customer') {
4245 $this->code_compta_client = '';
4246 } elseif ($type == 'supplier') {
4247 $this->code_compta_fournisseur = '';
4248 }
4249
4250 return 0;
4251 }
4252 }
4253
4260 public function setParent($id)
4261 {
4262 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4263
4264 if ($this->id) {
4265 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4266 if ($id > 0) {
4267 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4268 if ($sameparent < 0) {
4269 return -1;
4270 }
4271 if ($sameparent == 1) {
4272 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4273 return -1;
4274 }
4275 }
4276
4277 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? ((int) $id) : 'null').' WHERE rowid = '.((int) $this->id);
4278
4279 $resql = $this->db->query($sql);
4280 if ($resql) {
4281 $this->parent = $id;
4282 return 1;
4283 } else {
4284 return -1;
4285 }
4286 }
4287
4288 return -1;
4289 }
4290
4299 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4300 {
4301 if ($counter > 100) {
4302 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4303 }
4304
4305 $sql = 'SELECT s.parent';
4306 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4307 $sql .= ' WHERE rowid = '.((int) $idparent);
4308 $resql = $this->db->query($sql);
4309 if ($resql) {
4310 $obj = $this->db->fetch_object($resql);
4311
4312 if ($obj->parent == '') {
4313 return 0;
4314 } elseif ($obj->parent == $idchild) {
4315 return 1;
4316 } else {
4317 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4318 }
4319 return $sameparent;
4320 } else {
4321 return -1;
4322 }
4323 }
4324
4332 public function getParentsForCompany($company_id, $parents = array())
4333 {
4334 global $langs;
4335
4336 if ($company_id > 0) {
4337 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4338 $resql = $this->db->query($sql);
4339 if ($resql) {
4340 if ($obj = $this->db->fetch_object($resql)) {
4341 $parent = $obj->parent;
4342 if ($parent > 0 && !in_array($parent, $parents)) {
4343 $parents[] = $parent;
4344 return $this->getParentsForCompany($parent, $parents);
4345 } else {
4346 return $parents;
4347 }
4348 }
4349 $this->db->free($resql);
4350 } else {
4351 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4352 }
4353 }
4354 // Return a default value when $company_id is not greater than 0
4355 return array();
4356 }
4357
4364 public function getChildrenForCompany($company_id)
4365 {
4366 global $langs;
4367
4368 $children = array();
4369 if ($company_id > 0) {
4370 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "societe WHERE parent = ".((int) $company_id);
4371 $resql = $this->db->query($sql);
4372 if ($resql) {
4373 while ($obj = $this->db->fetch_object($resql)) {
4374 $child = $obj->rowid;
4375 if ($child > 0 && !in_array($child, $children)) {
4376 $children[] = $child;
4377 }
4378 }
4379 $this->db->free($resql);
4380 } else {
4381 setEventMessage($this->db->lasterror(), 'errors');
4382 }
4383 }
4384 // Return a default value when $company_id is not greater than 0
4385 return $children;
4386 }
4387
4388 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4395 public function id_prof_verifiable($idprof)
4396 {
4397 // phpcs:enable
4398 global $conf;
4399
4400 switch ($idprof) {
4401 case 1:
4402 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4403 break;
4404 case 2:
4405 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4406 break;
4407 case 3:
4408 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4409 break;
4410 case 4:
4411 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4412 break;
4413 case 5:
4414 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4415 break;
4416 case 6:
4417 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4418 break;
4419 default:
4420 $ret = false;
4421 }
4422
4423 return $ret;
4424 }
4425
4426 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4435 public function id_prof_exists($idprof, $value, $socid = 0)
4436 {
4437 // phpcs:enable
4438 $field = $idprof;
4439
4440 switch ($idprof) { // For backward compatibility
4441 case '1':
4442 case 'idprof1':
4443 $field = "siren";
4444 break;
4445 case '2':
4446 case 'idprof2':
4447 $field = "siret";
4448 break;
4449 case '3':
4450 case 'idprof3':
4451 $field = "ape";
4452 break;
4453 case '4':
4454 case 'idprof4':
4455 $field = "idprof4";
4456 break;
4457 case '5':
4458 $field = "idprof5";
4459 break;
4460 case '6':
4461 $field = "idprof6";
4462 break;
4463 }
4464
4465 //Verify duplicate entries
4466 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4467 if ($socid) {
4468 $sql .= " AND rowid <> ".((int) $socid);
4469 }
4470 $resql = $this->db->query($sql);
4471 if ($resql) {
4472 $obj = $this->db->fetch_object($resql);
4473 $count = $obj->nb;
4474 } else {
4475 $count = 0;
4476 print $this->db->error();
4477 }
4478 $this->db->free($resql);
4479
4480 if ($count > 0) {
4481 return true;
4482 } else {
4483 return false;
4484 }
4485 }
4486
4487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4494 public function id_prof_check($idprof)
4495 {
4496 // phpcs:enable
4497
4498 // Load the library necessary to check the professional identifiers
4499 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4500
4501 return isValidProfIds($idprof, $this);
4502 }
4503
4504 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4513 public function id_prof_url($idprof, $thirdparty)
4514 {
4515 // phpcs:enable
4516 global $langs, $hookmanager;
4517
4518 $url = '';
4519 $action = '';
4520
4521 $hookmanager->initHooks(array('idprofurl'));
4522 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4523 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4524 if (empty($reshook)) {
4525 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4526 return '';
4527 }
4528
4529 // TODO Move links to validate professional ID into the dictionary table "country" + column "linkidprof1"
4530 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4531 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4532 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.urlencode($strippedIdProf1); // See also http://avis-situation-sirene.insee.fr/
4533 }
4534 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4535 $url = 'https://beta.companieshouse.gov.uk/company/'.urlencode($strippedIdProf1);
4536 }
4537 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4538 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.urlencode($strippedIdProf1);
4539 }
4540 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4541 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.urlencode($strippedIdProf1).';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4542 }
4543 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4544 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.urlencode($strippedIdProf1);
4545 }
4546 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4547 $url = 'http://www.nif.pt/'.urlencode($strippedIdProf1);
4548 }
4549
4550 if ($url) {
4551 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4552 }
4553 } else {
4554 return $hookmanager->resPrint;
4555 }
4556
4557 return '';
4558 }
4559
4560 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4566 public function has_projects()
4567 {
4568 // phpcs:enable
4569 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4570 $resql = $this->db->query($sql);
4571 if ($resql) {
4572 $obj = $this->db->fetch_object($resql);
4573 $count = $obj->numproj;
4574 } else {
4575 $count = 0;
4576 print $this->db->error();
4577 }
4578 $this->db->free($resql);
4579 return ($count > 0);
4580 }
4581
4582
4589 public function info($id)
4590 {
4591 $sql = "SELECT s.rowid, s.nom as name, s.datec, GREATEST(s.tms, sef.tms) as datem,";
4592 $sql .= " fk_user_creat, fk_user_modif";
4593 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4594 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as sef ON sef.fk_object=s.rowid";
4595 $sql .= " WHERE s.rowid = ".((int) $id);
4596
4597 $result = $this->db->query($sql);
4598 if ($result) {
4599 if ($this->db->num_rows($result)) {
4600 $obj = $this->db->fetch_object($result);
4601
4602 $this->id = $obj->rowid;
4603
4604 $this->user_creation_id = $obj->fk_user_creat;
4605 $this->user_modification_id = $obj->fk_user_modif;
4606 $this->date_creation = $this->db->jdate($obj->datec);
4607 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4608
4609 $this->ref = $obj->name;
4610 }
4611
4612 $this->db->free($result);
4613 } else {
4614 dol_print_error($this->db);
4615 }
4616 }
4617
4623 public function isACompany()
4624 {
4625 // Define if third party is treated as company (or not) when nature is unknown
4626 //$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
4627 $defaultvalue = 0;
4628 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', $defaultvalue);
4629
4630 // Now try to guess using different tips
4631 if (!empty($this->tva_intra)) {
4632 $isACompany = 2;
4633 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6) || !empty($this->euid)) {
4634 $isACompany = 3;
4635 } else {
4636 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4637 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4638 $isACompany = 0;
4639 }
4640 } else {
4641 $isACompany = 4;
4642 }
4643 }
4644
4645 return $isACompany;
4646 }
4647
4653 public function isInEEC()
4654 {
4655 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4656 return isInEEC($this);
4657 }
4658
4664 public function isInSEPA()
4665 {
4666 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4667 return isInSEPA($this);
4668 }
4669
4670 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4676 public function LoadSupplierCateg()
4677 {
4678 // phpcs:enable
4679 $this->SupplierCategories = array();
4680 $sql = "SELECT rowid, label";
4681 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4682 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4683
4684 $resql = $this->db->query($sql);
4685 if ($resql) {
4686 while ($obj = $this->db->fetch_object($resql)) {
4687 $this->SupplierCategories[$obj->rowid] = $obj->label;
4688 }
4689 return 0;
4690 } else {
4691 return -1;
4692 }
4693 }
4694
4695 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4702 public function AddFournisseurInCategory($categorie_id)
4703 {
4704 // phpcs:enable
4705 if ($categorie_id > 0 && $this->id > 0) {
4706 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4707 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4708
4709 if ($resql = $this->db->query($sql)) {
4710 return 0;
4711 }
4712 } else {
4713 return 0;
4714 }
4715 return -1;
4716 }
4717
4723 public function getNbOfEMailings()
4724 {
4725 $sql = "SELECT count(mc.email) as nb";
4726 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4727 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4728 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4729
4730 $resql = $this->db->query($sql);
4731 if ($resql) {
4732 $obj = $this->db->fetch_object($resql);
4733 $nb = (int) $obj->nb;
4734
4735 $this->db->free($resql);
4736 return $nb;
4737 } else {
4738 $this->error = $this->db->error();
4739 return -1;
4740 }
4741 }
4742
4750 public function setNoEmail($no_email, $unsubscribegroup = '')
4751 {
4752 $error = 0;
4753
4754 // Update mass emailing flag into table mailing_unsubscribe
4755 if ($this->email) {
4756 $this->db->begin();
4757
4758 if ($no_email) {
4759 // TODO Add $unsubscribegroup
4760 $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)."'";
4761 $resql = $this->db->query($sql);
4762 if ($resql) {
4763 $obj = $this->db->fetch_object($resql);
4764 $noemail = $obj->nb;
4765 if (empty($noemail)) {
4766 // TODO Add $unsubscribegroup
4767 $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())."')";
4768 $resql = $this->db->query($sql);
4769 if (!$resql) {
4770 $error++;
4771 $this->error = $this->db->lasterror();
4772 $this->errors[] = $this->error;
4773 }
4774 }
4775 } else {
4776 $error++;
4777 $this->error = $this->db->lasterror();
4778 $this->errors[] = $this->error;
4779 }
4780 } else {
4781 // TODO Add $unsubscribegroup
4782 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4783 $resql = $this->db->query($sql);
4784 if (!$resql) {
4785 $error++;
4786 $this->error = $this->db->lasterror();
4787 $this->errors[] = $this->error;
4788 }
4789 }
4790
4791 if (empty($error)) {
4792 $this->no_email = $no_email;
4793 $this->db->commit();
4794 return 1;
4795 } else {
4796 $this->db->rollback();
4797 return $error * -1;
4798 }
4799 }
4800
4801 return 0;
4802 }
4803
4810 public function getNoEmail()
4811 {
4812 if ($this->email) {
4813 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4814 $resql = $this->db->query($sql);
4815 if ($resql) {
4816 $obj = $this->db->fetch_object($resql);
4817 $this->no_email = $obj->nb;
4818 return 1;
4819 } else {
4820 $this->error = $this->db->lasterror();
4821 $this->errors[] = $this->error;
4822 return -1;
4823 }
4824 }
4825 return 0;
4826 }
4827
4828 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4838 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4839 {
4840 // phpcs:enable
4841 global $user, $langs;
4842
4843 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4844 $fullname = $member->getFullName($langs);
4845
4846 if ($member->morphy == 'mor') {
4847 if (empty($socname)) {
4848 $socname = $member->company ? $member->company : $member->societe;
4849 }
4850 if (!empty($fullname) && empty($socalias)) {
4851 $socalias = $fullname;
4852 }
4853 } elseif (empty($socname) && $member->morphy == 'phy') {
4854 if (empty($socname)) {
4855 $socname = $fullname;
4856 }
4857 if (!empty($member->company) && empty($socalias)) {
4858 $socalias = $member->company;
4859 }
4860 }
4861
4862 $name = (string) $socname;
4863 $alias = $socalias ? $socalias : '';
4864
4865 // Positionne parameters
4866 $this->nom = $name; // TODO deprecated
4867 $this->name = $name;
4868 $this->name_alias = $alias;
4869 $this->address = $member->address;
4870 $this->zip = $member->zip;
4871 $this->town = $member->town;
4872 $this->country_code = $member->country_code;
4873 $this->country_id = $member->country_id;
4874 $this->phone = $member->phone; // Prof phone
4875 $this->email = $member->email;
4876 $this->socialnetworks = $member->socialnetworks;
4877 $this->entity = $member->entity;
4878
4879 $this->client = 1; // A member is a customer by default
4880 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4881 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4882 } else {
4883 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4884 }
4885 $this->code_fournisseur = '-1';
4886 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4887 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4888
4889 $this->db->begin();
4890
4891 // Creates and positions $this->id
4892 $result = $this->create($user);
4893
4894 if ($result >= 0) {
4895 // Auto-create contact on thirdparty creation
4896 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4897 // Fill fields needed by contact
4898 $this->name_bis = $member->lastname;
4899 $this->firstname = $member->firstname;
4900 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4901 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4902
4903 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4904 $result = $this->create_individual($user);
4905
4906 if ($result < 0) {
4907 setEventMessages($this->error, $this->errors, 'errors');
4908 $this->db->rollback();
4909 return -1;
4910 }
4911 }
4912
4913 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4914 $sql .= " SET fk_soc = ".((int) $this->id);
4915 $sql .= " WHERE rowid = ".((int) $member->id);
4916
4917 $resql = $this->db->query($sql);
4918 if ($resql) {
4919 $this->db->commit();
4920 return $this->id;
4921 } else {
4922 $this->error = $this->db->error();
4923
4924 $this->db->rollback();
4925 return -1;
4926 }
4927 } else {
4928 // $this->error already positioned
4929 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4930
4931 $this->db->rollback();
4932 return $result;
4933 }
4934 }
4935
4942 public function setMysoc(Conf $conf)
4943 {
4944 global $langs;
4945
4946 $this->id = 0;
4947 $this->entity = $conf->entity;
4948 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4949 $this->nom = $this->name; // deprecated
4950 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4951 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4952 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4953 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4954
4955 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4956
4957 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4958
4959 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4960
4961 // We define country_id, country_code and country
4962 $country_id = 0;
4963 $country_code = $country_label = '';
4964 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4965 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4966 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4967 if (!empty($tmp[1]) && !empty($tmp[2])) { // MAIN_INFO_SOCIETE_COUNTRY is the canonical "id:code:label"
4968 $country_code = $tmp[1];
4969 $country_label = $tmp[2];
4970 } elseif ($country_id > 0) {
4971 // For backward compatibility. The value is "id" only, or a legacy "id:label" where the
4972 // second token is a country label (e.g. 'Suisse') and not an ISO code. In both cases we
4973 // must not keep a label in country_code (it would break code-based lookups like VAT rates),
4974 // so we rebuild code and label from the authoritative country id.
4975 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4976 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4977 $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
4978 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4979 }
4980 }
4981 $this->country_id = $country_id;
4982 $this->country_code = $country_code;
4983 $this->country = $country_label;
4984 if (is_object($langs)) {
4985 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4986 }
4987
4988 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4989 // We define state_id, state_code and state
4990 $state_id = 0;
4991 $state_code = '';
4992 $state_label = '';
4993 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4994 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4995 $state_id = (int) $tmp[0];
4996 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4997 $state_code = $tmp[1];
4998 $state_label = $tmp[2];
4999 } else { // For backward compatibility
5000 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);
5001 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
5002 $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
5003 $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
5004 }
5005 }
5006 $this->state_id = $state_id;
5007 $this->state_code = $state_code;
5008 $this->state = $state_label;
5009 if (is_object($langs)) {
5010 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
5011 }
5012
5013 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
5014 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
5015 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
5016 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
5017
5018 // Social networks
5019 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
5020 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
5021 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
5022 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
5023 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
5024 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
5025 $this->socialnetworks = array();
5026 if (!empty($facebook_url)) {
5027 $this->socialnetworks['facebook'] = $facebook_url;
5028 }
5029 if (!empty($twitter_url)) {
5030 $this->socialnetworks['twitter'] = $twitter_url;
5031 }
5032 if (!empty($linkedin_url)) {
5033 $this->socialnetworks['linkedin'] = $linkedin_url;
5034 }
5035 if (!empty($instagram_url)) {
5036 $this->socialnetworks['instagram'] = $instagram_url;
5037 }
5038 if (!empty($youtube_url)) {
5039 $this->socialnetworks['youtube'] = $youtube_url;
5040 }
5041 if (!empty($github_url)) {
5042 $this->socialnetworks['github'] = $github_url;
5043 }
5044
5045 // Id prof generic
5046 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
5047 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
5048 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
5049 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
5050 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
5051 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
5052 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
5053 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
5054 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
5055 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
5056 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
5057 $this->euid = getDolGlobalString('MAIN_INFO_EUID');
5058 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
5059 $this->capital = is_numeric(price2num(getDolGlobalString('MAIN_INFO_CAPITAL'))) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : null;
5060 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
5061 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
5062 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
5063 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
5064 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
5065 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
5066 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
5067 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
5068 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
5069
5070 // Define if company use vat or not
5071 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
5072
5073 // Define if company use local taxes
5074 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
5075 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
5076
5077 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
5078 }
5079
5087 public function initAsSpecimen()
5088 {
5089 $now = dol_now();
5090
5091 // Initialize parameters
5092 $this->id = 0;
5093 $this->entity = 1;
5094 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
5095 $this->ref_ext = 'Ref ext';
5096 $this->specimen = 1;
5097 $this->address = '21 jump street';
5098 $this->zip = '99999';
5099 $this->town = 'MyTown';
5100 $this->state_id = 1;
5101 $this->state_code = 'AA';
5102 $this->state = 'MyState';
5103 $this->country_id = 1;
5104 $this->country_code = 'FR';
5105 $this->email = 'specimen@specimen.com';
5106 $this->socialnetworks = array(
5107 'skype' => 'skypepseudo',
5108 'twitter' => 'twitterpseudo',
5109 'facebook' => 'facebookpseudo',
5110 'linkedin' => 'linkedinpseudo',
5111 );
5112 $this->url = 'https://www.specimen.com';
5113
5114 $this->phone = '0909090901';
5115 $this->phone_mobile = '0909090901';
5116 $this->fax = '0909090909';
5117
5118 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
5119 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
5120 $this->typent_code = 'TE_OTHER';
5121 $this->capital = 10000;
5122 $this->client = 1;
5123 $this->prospect = 1;
5124 $this->fournisseur = 1;
5125 $this->tva_assuj = 1;
5126 //$this->tva_intra = 'EU1234567';
5127 $this->tva_intra = 'FR1234567';
5128 $this->note_public = 'This is a comment (public)';
5129 $this->note_private = 'This is a comment (private)';
5130
5131 $this->idprof1 = 'idprof1';
5132 $this->idprof2 = 'idprof2';
5133 $this->idprof3 = 'idprof3';
5134 $this->idprof4 = 'idprof4';
5135 $this->idprof5 = 'idprof5';
5136 $this->idprof6 = 'idprof6';
5137
5138 $this->euid = 'FR-RCSXXXX-idprof1';
5139
5140 return 1;
5141 }
5142
5151 public function useLocalTax($localTaxNum = 0, $mode = 0, $thirdparty = null)
5152 {
5153 if ($mode == 1 && $thirdparty instanceof Societe) {
5154 if ($localTaxNum == -1) {
5155 return array(1 => ($thirdparty->localtax1_assuj ? true : false), 2 => ($thirdparty->localtax2_assuj ? true : false));
5156 } elseif ($localTaxNum == 1) {
5157 return $thirdparty->localtax1_assuj ? true : false;
5158 } elseif ($localTaxNum == 2) {
5159 return $thirdparty->localtax2_assuj ? true : false;
5160 }
5161 return false;
5162 } else {
5163 $sql = "SELECT t.localtax1, t.localtax2";
5164 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5165 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5166 $sql .= " AND t.active = 1";
5167 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5168 if (empty($localTaxNum) || $localTaxNum == -1) {
5169 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
5170 } elseif ($localTaxNum == 1) {
5171 $sql .= " AND t.localtax1_type <> '0'";
5172 } elseif ($localTaxNum == 2) {
5173 $sql .= " AND t.localtax2_type <> '0'";
5174 }
5175
5176 $resql = $this->db->query($sql);
5177 if ($resql) {
5178 if ($localTaxNum == -1) {
5179 $obj = $this->db->fetch_object($resql);
5180 if ($obj) {
5181 return array(1 => ($obj->localtax1 ? true : false), 2 => ($obj->localtax2 ? true : false));
5182 }
5183 return array(1 => false, 2 => false);
5184 } else {
5185 return ($this->db->num_rows($resql) > 0);
5186 }
5187 } else {
5188 return false;
5189 }
5190 }
5191 }
5192
5198 public function useNPR()
5199 {
5200 $sql = "SELECT t.rowid";
5201 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5202 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5203 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
5204 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5205
5206 dol_syslog("useNPR", LOG_DEBUG);
5207 $resql = $this->db->query($sql);
5208 if ($resql) {
5209 return ($this->db->num_rows($resql) > 0);
5210 } else {
5211 return false;
5212 }
5213 }
5214
5221 public function useRevenueStamp()
5222 {
5223 $sql = "SELECT COUNT(*) as nb";
5224 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
5225 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5226 $sql .= " AND r.active = 1";
5227
5228 dol_syslog("useRevenueStamp", LOG_DEBUG);
5229 $resql = $this->db->query($sql);
5230 if ($resql) {
5231 $obj = $this->db->fetch_object($resql);
5232 return ($obj->nb > 0);
5233 } else {
5234 $this->error = $this->db->lasterror();
5235 return false;
5236 }
5237 }
5238
5244 public function getLibProspLevel()
5245 {
5246 return $this->LibProspLevel($this->fk_prospectlevel);
5247 }
5248
5249 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5256 public function LibProspLevel($fk_prospectlevel)
5257 {
5258 // phpcs:enable
5259 global $langs;
5260
5261 $label = '';
5262 if ($fk_prospectlevel != '') {
5263 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5264 // If label is not found in language file, we get label from cache/database
5265 if ($label == "ProspectLevel".$fk_prospectlevel) {
5266 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5267 }
5268 }
5269
5270 return $label;
5271 }
5272
5280 public function getLibProspCommStatut($mode = 0, $label = '')
5281 {
5282 return $this->LibProspCommStatut((int) $this->stcomm_id, $mode, $label, $this->stcomm_picto);
5283 }
5284
5285 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5299 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5300 {
5301 // phpcs:enable
5302 global $langs;
5303
5304 $langs->load('customers');
5305
5306 if ($mode == 2) {
5307 if ($status == '-1' || $status == 'ST_NO') {
5308 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5309 } elseif ($status == '0' || $status == 'ST_NEVER') {
5310 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5311 } elseif ($status == '1' || $status == 'ST_TODO') {
5312 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5313 } elseif ($status == '2' || $status == 'ST_PEND') {
5314 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5315 } elseif ($status == '3' || $status == 'ST_DONE') {
5316 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5317 } else {
5318 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);
5319 }
5320 } elseif ($mode == 3) {
5321 if ($status == '-1' || $status == 'ST_NO') {
5322 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5323 } elseif ($status == '0' || $status == 'ST_NEVER') {
5324 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5325 } elseif ($status == '1' || $status == 'ST_TODO') {
5326 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5327 } elseif ($status == '2' || $status == 'ST_PEND') {
5328 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5329 } elseif ($status == '3' || $status == 'ST_DONE') {
5330 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5331 } else {
5332 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5333 }
5334 } elseif ($mode == 4) {
5335 if ($status == '-1' || $status == 'ST_NO') {
5336 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5337 } elseif ($status == '0' || $status == 'ST_NEVER') {
5338 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5339 } elseif ($status == '1' || $status == 'ST_TODO') {
5340 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5341 } elseif ($status == '2' || $status == 'ST_PEND') {
5342 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5343 } elseif ($status == '3' || $status == 'ST_DONE') {
5344 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5345 } else {
5346 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);
5347 }
5348 }
5349
5350 return "Error, mode/status not found";
5351 }
5352
5359 public function getOutstandingProposals($mode = 'customer')
5360 {
5361 global $hookmanager;
5362 $table = 'propal';
5363 if ($mode == 'supplier') {
5364 $table = 'supplier_proposal';
5365 }
5366
5367 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5368 $sql .= " WHERE fk_soc = ".((int) $this->id);
5369 if ($mode == 'supplier') {
5370 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5371 } else {
5372 $sql .= " AND entity IN (".getEntity('propal').")";
5373 }
5374
5375 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5376
5377 // Add where from hooks
5378 $parameters = array('mode' => $mode, 'table' => $table);
5379 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5380 $sql .= $hookmanager->resPrint;
5381
5382 $resql = $this->db->query($sql);
5383 if ($resql) {
5384 $outstandingOpened = 0;
5385 $outstandingTotal = 0;
5386 $outstandingTotalIncTax = 0;
5387 $arrayofref = array();
5388 while ($obj = $this->db->fetch_object($resql)) {
5389 $arrayofref[$obj->rowid] = $obj->ref;
5390 $outstandingTotal += $obj->total_ht;
5391 $outstandingTotalIncTax += $obj->total_ttc;
5392 if ($obj->status != 0) {
5393 // Not a draft
5394 $outstandingOpened += $obj->total_ttc;
5395 }
5396 }
5397 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5398 } else {
5399 return array();
5400 }
5401 }
5402
5409 public function getOutstandingOrders($mode = 'customer')
5410 {
5411 global $hookmanager;
5412 $table = 'commande';
5413 if ($mode == 'supplier') {
5414 $table = 'commande_fournisseur';
5415 }
5416
5417 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5418 $sql .= " WHERE fk_soc = ".((int) $this->id);
5419 if ($mode == 'supplier') {
5420 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5421 } else {
5422 $sql .= " AND entity IN (".getEntity('commande').")";
5423 }
5424
5425 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5426 // Add where from hooks
5427 $parameters = array('mode' => $mode, 'table' => $table);
5428 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5429 $sql .= $hookmanager->resPrint;
5430 $resql = $this->db->query($sql);
5431 if ($resql) {
5432 $outstandingOpened = 0;
5433 $outstandingTotal = 0;
5434 $outstandingTotalIncTax = 0;
5435 $arrayofref = array();
5436 while ($obj = $this->db->fetch_object($resql)) {
5437 $arrayofref[$obj->rowid] = $obj->ref;
5438 $outstandingTotal += $obj->total_ht;
5439 $outstandingTotalIncTax += $obj->total_ttc;
5440 if ($obj->status != 0) {
5441 // Not a draft
5442 $outstandingOpened += $obj->total_ttc;
5443 }
5444 }
5445 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5446 } else {
5447 return array();
5448 }
5449 }
5450
5458 public function getOutstandingBills($mode = 'customer', $late = 0)
5459 {
5460 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5461
5462 $table = 'facture';
5463 if ($mode == 'supplier') {
5464 $table = 'facture_fourn';
5465 }
5466
5467 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5468 $paiement = $invoice->getSommePaiement();
5469 $creditnotes=$invoice->getSumCreditNotesUsed();
5470 $deposits=$invoice->getSumDepositsUsed();
5471 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5472 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5473 */
5474 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5475
5476 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5477 $sql .= " WHERE fk_soc = ".((int) $this->id);
5478 if (!empty($late)) {
5479 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5480 }
5481 if ($mode == 'supplier') {
5482 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5483 } else {
5484 $sql .= " AND entity IN (".getEntity('invoice').")";
5485 }
5486
5487 dol_syslog("getOutstandingBills", LOG_DEBUG);
5488 $resql = $this->db->query($sql);
5489 if ($resql) {
5490 $outstandingOpened = 0;
5491 $outstandingTotal = 0;
5492 $outstandingTotalIncTax = 0;
5493 $arrayofref = array();
5494 $arrayofrefopened = array();
5495 if ($mode == 'supplier') {
5496 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5497 $tmpobject = new FactureFournisseur($this->db);
5498 } else {
5499 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5500 $tmpobject = new Facture($this->db);
5501 }
5502 while ($obj = $this->db->fetch_object($resql)) {
5503 $arrayofref[$obj->rowid] = $obj->ref;
5504 $tmpobject->id = $obj->rowid;
5505
5506 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5507 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5508 ) {
5509 $outstandingTotal += $obj->total_ht;
5510 $outstandingTotalIncTax += $obj->total_ttc;
5511 }
5512
5513 $remaintopay = 0;
5514
5515 if ($obj->paye == 0
5516 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5517 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5518 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5519 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5520 $paiement = $tmpobject->getSommePaiement();
5521 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5522 $deposits = $tmpobject->getSumDepositsUsed();
5523
5524 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5525 $outstandingOpened += $remaintopay;
5526 }
5527
5528 //if credit note is converted but not used
5529 // TODO Do this also for customer ?
5530 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5531 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5532 $remaintopay -= $remainingcreditnote;
5533 $outstandingOpened -= $remainingcreditnote;
5534 }
5535
5536 if ($remaintopay) {
5537 $arrayofrefopened[$obj->rowid] = $obj->ref;
5538 }
5539 }
5540 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'amount incl taxes' > 0
5541 } else {
5542 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5543 return array();
5544 }
5545 }
5546
5553 public function getLibCustProspStatut()
5554 {
5555 return $this->LibCustProspStatut($this->client);
5556 }
5557
5558 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5565 public function LibCustProspStatut($status)
5566 {
5567 // phpcs:enable
5568 global $langs;
5569 $langs->load('companies');
5570
5571 if ($status == 0) {
5572 return $langs->trans("NorProspectNorCustomer");
5573 } elseif ($status == 1) {
5574 return $langs->trans("Customer");
5575 } elseif ($status == 2) {
5576 return $langs->trans("Prospect");
5577 } elseif ($status == 3) {
5578 return $langs->trans("ProspectCustomer");
5579 }
5580
5581 return '';
5582 }
5583
5584
5591 public function calculateVATNumberFromProperties($thirdparty)
5592 {
5593 if ($thirdparty->country_code == 'FR' && empty($thirdparty->tva_intra) && !empty($thirdparty->tva_assuj)) {
5594 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
5595
5596 $siren = preg_replace('/\s+/', '', (string) $thirdparty->idprof1);
5597 $siret = preg_replace('/\s+/', '', (string) $thirdparty->idprof2);
5598 if (!isValidSiren($siren)) {
5599 if (!isValidSiret($siret)) {
5600 return '';
5601 }
5602
5603 $siren = substr($siret, 0, 9);
5604 }
5605 if (!empty($siren)) {
5606 // [FR + key code + SIREN number ]
5607 // Key VAT = [12 + 3 * (SIREN modulo 97)] modulo 97
5608 $cle = (12 + 3 * (((int) $siren) % 97)) % 97;
5609 $tva_intra = 'FR' . str_pad((string) $cle, 2, '0', STR_PAD_LEFT) . $siren;
5610 }
5611 }
5612
5613 return $tva_intra ?? '';
5614 }
5615
5616
5628 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5629 {
5630 global $langs;
5631
5632 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5633 $modelpath = "core/modules/bank/doc/";
5634
5635 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5636 $companybankaccount = new CompanyBankAccount($this->db);
5637 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5638 if (!$result) {
5639 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5640 }
5641 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5642 $this->last_main_doc = $companybankaccount->last_main_doc;
5643 } else {
5644 // Set the model to the name of the model to be used
5645 if (!dol_strlen($modele)) {
5646 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5647 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5648 } else {
5649 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5650 return 0;
5651 }
5652 }
5653
5654 if (!isset($this->bank_account)) {
5655 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5656 $bac = new CompanyBankAccount($this->db);
5657 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5658 $result = $bac->fetch(0, '', $this->id);
5659 if ($result > 0) {
5660 $this->bank_account = $bac;
5661 } else {
5662 $this->bank_account = '';
5663 }
5664 }
5665
5666 $modelpath = "core/modules/societe/doc/";
5667
5668 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5669 }
5670
5671 return $result;
5672 }
5673
5674
5687 public function setCategories($categories, $type_categ, $remove_existing = true)
5688 {
5689 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5690
5691 // Decode type
5692 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5693 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Nothing done.', LOG_ERR);
5694 return -1;
5695 }
5696
5697 return parent::setCategoriesCommon($categories, $type_categ, $remove_existing);
5698 }
5699
5707 public function setSalesRep($salesrep, $onlyAdd = false)
5708 {
5709 global $user;
5710
5711 // Handle single user
5712 if (!is_array($salesrep)) {
5713 $salesrep = array($salesrep);
5714 }
5715
5716 $to_del = array(); // Nothing to delete
5717 $to_add = $salesrep;
5718 if ($onlyAdd === false) {
5719 // Get current users
5720 $existing = $this->getSalesRepresentatives($user, 1);
5721
5722 // Diff
5723 if (is_array($existing)) {
5724 $to_del = array_diff($existing, $salesrep);
5725 $to_add = array_diff($salesrep, $existing);
5726 }
5727 }
5728
5729 $error = 0;
5730
5731 // Process
5732 foreach ($to_del as $del) {
5733 $this->del_commercial($user, $del);
5734 }
5735 foreach ($to_add as $add) {
5736 $result = $this->add_commercial($user, $add);
5737 if ($result < 0) {
5738 $error++;
5739 break;
5740 }
5741 }
5742
5743 return $error ? -1 : 1;
5744 }
5745
5752 public function setThirdpartyType($typent_id)
5753 {
5754 global $user;
5755
5756 dol_syslog(__METHOD__, LOG_DEBUG);
5757
5758 if ($this->id) {
5759 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5760
5761 if ($result > 0) {
5762 $this->typent_id = $typent_id;
5763 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5764 return 1;
5765 } else {
5766 return -1;
5767 }
5768 } else {
5769 return -1;
5770 }
5771 }
5772
5782 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5783 {
5784 if ($origin_id == $dest_id) {
5785 dol_syslog('Error: Try to merge a thirdparty into itself');
5786 return false;
5787 }
5788
5789 // 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.
5790 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5791 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5792 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5793 $sql .= ' SELECT fk_user ';
5794 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5795 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5796
5797 $resql = $dbs->query($sql);
5798 while ($obj = $dbs->fetch_object($resql)) {
5799 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5800 }
5801
5802 // 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.
5803 // Do not include llx_societe because it will be replaced later.
5804 $tables = array(
5805 'societe_account',
5806 'societe_commerciaux',
5807 'societe_prices',
5808 'societe_remise',
5809 'societe_remise_except',
5810 'societe_rib'
5811 );
5812
5813 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5814
5815 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5816 }
5817
5826 public function setAccountancyCode($type, $value)
5827 {
5828 global $user, $langs, $conf;
5829
5830 $this->db->begin();
5831
5832 if ($type == 'buy') {
5833 $field = 'accountancy_code_buy';
5834 } elseif ($type == 'sell') {
5835 $field = 'accountancy_code_sell';
5836 } else {
5837 return -1;
5838 }
5839
5840 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5841 $sql .= $field." = '".$this->db->escape($value)."'";
5842 $sql .= " WHERE rowid = ".((int) $this->id);
5843
5844 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5845 $resql = $this->db->query($sql);
5846
5847 if ($resql) {
5848 // Call triggers
5849 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5850 $interface = new Interfaces($this->db);
5851 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5852 if ($result < 0) {
5853 $this->errors = $interface->errors;
5854 $this->db->rollback();
5855 return -1;
5856 }
5857 // End call triggers
5858
5859 $this->$field = $value;
5860
5861 $this->db->commit();
5862 return 1;
5863 } else {
5864 $this->error = $this->db->lasterror();
5865 $this->db->rollback();
5866 return -1;
5867 }
5868 }
5869
5876 public function fetchPartnerships($mode)
5877 {
5878 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5879
5880 $this->partnerships[] = array();
5881
5882 return 1;
5883 }
5884
5892 public function getKanbanView($option = '', $arraydata = array())
5893 {
5894 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5895
5896 $out = '<div class="box-flex-item box-flex-grow-zero">';
5897 $out .= '<div class="info-box info-box-sm">';
5898 $out .= '<span class="info-box-icon bg-infobox-action">';
5899 if (!empty($this->logo) && class_exists('Form')) {
5900 $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.
5901 } else {
5902 $out .= img_picto('', $this->picto);
5903 }
5904 $out .= '</span>';
5905 $out .= '<div class="info-box-content">';
5906 $out .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">' . $this->getNomUrl(1);
5907 $out .= '</div>';
5908 if (!empty($this->phone)) {
5909 $out .= '<div class="inline-block valignmiddle">';
5910 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5911 $out .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5912 $out .= '</div>';
5913 }
5914 if (!empty($this->email)) {
5915 $out .= '<div class="inline-block valignmiddle">';
5916 $out .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5917 $out .= '</div>';
5918 }
5919 if ($selected >= 0) {
5920 $out .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5921 }
5922 if (!empty($this->code_client)) {
5923 $out .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5924 }
5925 $out .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
5926 $out .= '</div>'; // end info-box-content
5927 $out .= '</div>';
5928 $out .= '</div>';
5929
5930 return $out;
5931 }
5932
5942 public function getContacts($list = 0, $code = '', $element = '', $status = -1)
5943 {
5944 // phpcs:enable
5945 global $langs;
5946
5947 $tab = array();
5948
5949 $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
5950 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5951 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5952 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5953 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5954 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5955 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5956 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5957 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5958
5959 // Add status filter if requested
5960 if ($status >= 0) {
5961 $sql .= " AND t.statut = " . ((int) $status);
5962 }
5963 if (!empty($element)) {
5964 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5965 }
5966 if ($code) {
5967 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5968 }
5969 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5970 $sql .= " AND tc.source = 'external'";
5971 $sql .= " AND tc.active = 1";
5972
5973 $sql .= " ORDER BY t.lastname ASC";
5974
5975 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5976 $resql = $this->db->query($sql);
5977 if ($resql) {
5978 $num = $this->db->num_rows($resql);
5979 $i = 0;
5980 while ($i < $num) {
5981 $obj = $this->db->fetch_object($resql);
5982
5983 if (!$list) {
5984 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5985 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5986 $tab[$obj->id] = array(
5987 'source' => $obj->source,
5988 'socid' => (int) $obj->socid,
5989 'id' => (int) $obj->id,
5990 'nom' => $obj->lastname, // For backward compatibility
5991 'civility' => $obj->civility,
5992 'lastname' => $obj->lastname,
5993 'firstname' => $obj->firstname,
5994 'email' => $obj->email,
5995 'login' => (empty($obj->login) ? '' : $obj->login),
5996 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5997 'statuscontact' => $obj->statuscontact,
5998 'rowid' => (int) $obj->rowid,
5999 'code' => $obj->code,
6000 'element' => $obj->element,
6001 'libelle' => $label_type,
6002 'status' => $obj->statuslink,
6003 'fk_c_type_contact' => (int) $obj->fk_c_type_contact
6004 );
6005 } else {
6006 $tab[$obj->id] = (int) $obj->id;
6007 }
6008 $i++;
6009 }
6010
6011 return $tab;
6012 } else {
6013 $this->error = $this->db->lasterror();
6014 dol_print_error($this->db);
6015 return -1;
6016 }
6017 }
6018
6029 public function mergeCompany($soc_origin_id)
6030 {
6031 global $conf, $langs, $hookmanager, $user, $action;
6032
6033 $error = 0;
6034 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
6035
6036 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
6037
6038 if ($soc_origin->fetch($soc_origin_id) < 1) {
6039 $this->error = $langs->trans('ErrorRecordNotFound');
6040 $error++;
6041 }
6042
6043 if (!$error) {
6044 $this->db->begin();
6045
6046 // Recopy some data
6047 $this->client |= $soc_origin->client;
6048 $this->fournisseur |= $soc_origin->fournisseur;
6049 $listofproperties = array(
6050 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
6051 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
6052 'tva_intra', 'euid', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
6053 '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',
6054 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
6055 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
6056 );
6057 foreach ($listofproperties as $property) {
6058 if (empty($this->$property)) {
6059 $this->$property = $soc_origin->$property;
6060 }
6061 }
6062
6063 if ($this->typent_id == -1) {
6064 $this->typent_id = $soc_origin->typent_id;
6065 }
6066
6067 // Concat some data
6068 $listofproperties = array(
6069 'note_public', 'note_private'
6070 );
6071 foreach ($listofproperties as $property) {
6072 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
6073 }
6074
6075 // Merge extrafields
6076 if (is_array($soc_origin->array_options)) {
6077 foreach ($soc_origin->array_options as $key => $val) {
6078 if (empty($this->array_options[$key])) {
6079 $this->array_options[$key] = $val;
6080 }
6081 }
6082 }
6083
6084 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
6085 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
6086 $this->name_bis = $this->name;
6087 }
6088
6089 // Merge categories
6090 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6091 $static_cat = new Categorie($this->db);
6092
6093 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
6094 $custcats = $static_cat->containing($this->id, 'customer', 'id');
6095 $custcats = array_merge($custcats, $custcats_ori);
6096 $this->setCategories($custcats, 'customer');
6097
6098 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
6099 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
6100 $suppcats = array_merge($suppcats, $suppcats_ori);
6101 $this->setCategories($suppcats, 'supplier');
6102
6103 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
6104 if ($soc_origin->code_client == $this->code_client
6105 || $soc_origin->code_fournisseur == $this->code_fournisseur
6106 || $soc_origin->barcode == $this->barcode) {
6107 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
6108 $soc_origin->code_client = '';
6109 $soc_origin->code_fournisseur = '';
6110 $soc_origin->barcode = '';
6111 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
6112 }
6113
6114 // Children companies
6115 if (!getDolGlobalString('SOCIETE_DISABLE_PARENTCOMPANY')) {
6116 // Children
6117 $children_ori = $this->getChildrenForCompany($soc_origin->id);
6118 if (count($children_ori)) {
6119 foreach ($children_ori as $child_id) {
6120 $child = new Societe($this->db);
6121 $child->id = $child_id;
6122 $child->setParent($this->id);
6123 }
6124 }
6125 }
6126
6127 // Update
6128 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
6129
6130 if ($result < 0) {
6131 $error++;
6132 }
6133
6134 // Move links
6135 if (!$error) {
6136 $objects = array(
6137 'Adherent' => '/adherents/class/adherent.class.php',
6138 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
6139 'ActionComm' => '/comm/action/class/actioncomm.class.php',
6140 'Propal' => '/comm/propal/class/propal.class.php',
6141 'Commande' => '/commande/class/commande.class.php',
6142 'Facture' => '/compta/facture/class/facture.class.php',
6143 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
6144 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
6145 'Contact' => '/contact/class/contact.class.php',
6146 'Contrat' => '/contrat/class/contrat.class.php',
6147 'Expedition' => '/expedition/class/expedition.class.php',
6148 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
6149 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
6150 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
6151 'Reception' => '/reception/class/reception.class.php',
6152 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
6153 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
6154 'Product' => '/product/class/product.class.php',
6155 //'ProductThirparty' => '...', // for llx_product_thirdparty
6156 'Project' => '/projet/class/project.class.php',
6157 'User' => '/user/class/user.class.php',
6158 'Account' => '/compta/bank/class/account.class.php',
6159 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
6160 'Societe' => '/societe/class/societe.class.php',
6161 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
6162 );
6163 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'delivery')) {
6164 $objects['Delivery'] = '/delivery/class/delivery.class.php';
6165 }
6166 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'mrp_mo')) {
6167 $objects['Mo'] = '/mrp/class/mo.class.php';
6168 }
6169 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'don')) {
6170 $objects['Don'] = '/don/class/don.class.php';
6171 }
6172 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'partnership')) {
6173 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
6174 }
6175 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'fichinter')) {
6176 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
6177 }
6178 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'ticket')) {
6179 $objects['Ticket'] = '/ticket/class/ticket.class.php';
6180 }
6181
6182 //First, all core objects must update their tables
6183 foreach ($objects as $object_name => $object_file) {
6184 /* $object_file is never an array -> code commented
6185 if (is_array($object_file)) {
6186 if (empty($object_file['enabled'])) {
6187 continue;
6188 }
6189 $object_file = $object_file['file'];
6190 }
6191 */
6192
6193 require_once DOL_DOCUMENT_ROOT.$object_file;
6194
6195 if (!$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
6196 $error++;
6197 $this->error = $this->db->lasterror();
6198 break;
6199 }
6200 }
6201 }
6202
6203 // External modules should update their ones too
6204 if (!$error) {
6205 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
6206 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
6207
6208 if ($reshook < 0) {
6209 $this->error = $hookmanager->error;
6210 $this->errors = $hookmanager->errors;
6211 $error++;
6212 }
6213 }
6214
6215
6216 if (!$error) {
6217 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
6218
6219 // Call trigger
6220 $result = $this->call_trigger('COMPANY_MODIFY', $user);
6221 if ($result < 0) {
6222 $error++;
6223 }
6224 // End call triggers
6225 }
6226
6227 if (!$error) {
6228 // We finally remove the old thirdparty
6229 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
6230 $this->error = $soc_origin->error;
6231 $this->errors = $soc_origin->errors;
6232 $error++;
6233 }
6234 }
6235
6236
6237 if (!$error) {
6238 // Move files from the dir of the third party to delete into the dir of the third party to keep
6239 if (!empty($conf->societe->multidir_output[$this->entity])) {
6240 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
6241 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
6242
6243 if (dol_is_dir($srcdir)) {
6244 $dirlist = dol_dir_list($srcdir, 'files', 1);
6245 foreach ($dirlist as $filetomove) {
6246 $destfile = $destdir.'/'.$filetomove['relativename'];
6247 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
6248 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
6249 }
6250 //exit;
6251 }
6252 }
6253 }
6254
6255 if (!$error) {
6256 $this->db->commit();
6257 return 0;
6258 } else {
6259 $langs->load("errors");
6260 $this->error = $langs->trans('ErrorsThirdpartyMerge');
6261 $this->db->rollback();
6262 return -1;
6263 }
6264 }
6265
6266 return -1;
6267 }
6268}
$object ref
Definition info.php:90
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
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.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
isInSEPA()
Return if a company is inside the SEPA zone (Single Euro Payment Area)
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
useLocalTax($localTaxNum=0, $mode=0, $thirdparty=null)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
update($id, User $user, $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
const PROSPECT
Third party type is a prospect.
setPaymentMethods($id)
Change the payments methods.
create(User $user, $notrigger=0)
Create third party in database.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysoc in most ca...
id_prof_check($idprof)
Check the validity of a professional identifier according to the properties (country) of the thirdpar...
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
getContacts($list=0, $code='', $element='', $status=-1)
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='valignmiddle')
Return a link on thirdparty (with picto)
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)
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0, $vatnumber='')
Search the thirdparty that match the most the provided parameters.
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.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setNoEmail($no_email, $unsubscribegroup='')
Set "blacklist" mailing status.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type=0)
Return amount (with tax) of discounts currently available for a company, user or other criteria.
getChildrenForCompany($company_id)
Get children for company.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
calculateVATNumberFromProperties($thirdparty)
Calculate VAT intracommunity number for a thirdparty if missing, from the professional ID.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
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:169
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:665
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:65
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_now($mode='gmt')
Return date for now.
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
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.
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.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
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.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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.
div refaddress div address
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
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.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
Definition html.lib.php:99
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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...
Definition html.lib.php:172
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
isValidSiren($siren, $lengthonly=0)
Check the syntax validity of a SIREN.
isValidProfIds($idprof, $thirdparty, $lenghtonly=0)
Check the validity of a professional identifier according to the properties (country) of the company ...
isValidSiret($siret, $lengthonly=0)
Check the syntax validity of a SIRET.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:133