dolibarr 21.0.0-alpha
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 */
38
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
49
50
54class Societe extends CommonObject
55{
58 use CommonPeople;
59
63 public $module = 'societe';
64
68 public $element = 'societe';
69
73 public $table_element = 'societe';
74
78 public $fk_element = 'fk_soc';
79
83 public $fieldsforcombobox = 'nom,name_alias';
84
88 protected $childtables = array(
89 'supplier_proposal' => array('name' => 'SupplierProposal'),
90 'propal' => array('name' => 'Proposal'),
91 'commande' => array('name' => 'Order'),
92 'facture' => array('name' => 'Invoice'),
93 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
94 'contrat' => array('name' => 'Contract'),
95 'fichinter' => array('name' => 'Fichinter'),
96 'facture_fourn' => array('name' => 'SupplierInvoice'),
97 'commande_fournisseur' => array('name' => 'SupplierOrder'),
98 'projet' => array('name' => 'Project'),
99 'expedition' => array('name' => 'Shipment'),
100 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
101 );
102
107 protected $childtablesoncascade = array(
108 'societe_prices',
109 'product_fournisseur_price',
110 'product_customer_price_log',
111 'product_customer_price',
112 '@Contact:/contact/class/contact.class.php:fk_soc',
113 'adherent',
114 'societe_account',
115 'societe_rib',
116 'societe_remise',
117 'societe_remise_except',
118 'societe_commerciaux',
119 'categorie',
120 'notify',
121 'notify_def',
122 'actioncomm',
123 );
124
128 public $picto = 'company';
129
134 public $restrictiononfksoc = 1;
135
139 public $oldcopy;
140
145 public $SupplierCategories = array();
146
151 public $prefixCustomerIsRequired;
152
182 public $fields = array(
183 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
184 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
185 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
186 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
187 'nom' => array('type' => 'varchar(128)', 'length'=>128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
188 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
189 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
190 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
191 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
192 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
193 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
194 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
195 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
196 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
197 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
198 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
199 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
200 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
201 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
202 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
203 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
204 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
205 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
206 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
207 'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
208 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
209 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
210 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
211 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
212 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
213 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
214 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
215 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
216 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
217 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
218 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
219 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
220 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
221 'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
222 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
223 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
224 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
225 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
226 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
227 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
228 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
229 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
230 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
231 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
232 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
233 'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
234 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
235 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
236 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
237 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
238 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
239 'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
240 'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
241 'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
242 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
243 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
244 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
245 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
246 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
247 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
248 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
249 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES")', 'visible' => -1, 'position' => 365),
250 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
251 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
252 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
253 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
254 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
255 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
256 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
257 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
258 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
259 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
260 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
261 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
262 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
263 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
264 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
265 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
266 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
267 );
268
272 public $entity;
273
280 public $nom;
281
285 public $name;
286
291 public $name_alias;
292
296 public $particulier;
297
302 public $status = 1;
303
307 public $region_code;
308
312 public $region;
313
317 public $country_id;
318
324 public $departement_code;
325
331 public $departement;
332
338 public $pays;
339
344 public $phone;
349 public $phone_mobile;
354 public $fax;
355
360 public $email;
361
366 public $no_email;
367
373 public $skype;
374
380 public $twitter;
381
387 public $facebook;
388
394 public $linkedin;
395
400 public $url;
401
406 public $barcode;
407
408 // 6 professional id (usage depends on country)
409
414 public $idprof1;
415
421 public $siren;
422
423
428 public $idprof2;
429
435 public $siret;
436
441 public $idprof3;
442
448 public $ape;
449
454 public $idprof4;
455
460 public $idprof5;
461
466 public $idprof6;
467
472 public $idprof7;
473
478 public $idprof8;
479
484 public $idprof9;
485
490 public $idprof10;
491
496 public $socialobject;
497
501 public $prefix_comm;
502
506 public $tva_assuj = 1;
507
511 public $tva_intra;
512
516 public $vat_reverse_charge = 0;
517
518 // Local taxes
519 public $localtax1_assuj;
520 public $localtax1_value;
521 public $localtax2_assuj;
522 public $localtax2_value;
523
527 public $managers;
528
532 public $capital;
533
537 public $typent_id = 0;
538 public $typent_code;
539 public $effectif;
540 public $effectif_id = 0;
541 public $forme_juridique_code;
542 public $forme_juridique = 0;
543
544 public $remise_percent;
545 public $remise_supplier_percent;
546
547 public $mode_reglement_id;
548 public $cond_reglement_id;
549 public $deposit_percent;
550 public $mode_reglement_supplier_id;
551 public $cond_reglement_supplier_id;
552 public $transport_mode_supplier_id;
553
557 public $fk_prospectlevel;
558
562 public $name_bis;
563
569 public $user_modification;
570
576 public $user_creation;
577
582 public $client = 0;
583
588 public $prospect = 0;
589
594 public $fournisseur;
595
600 public $code_client;
601
606 public $code_fournisseur;
607
612 public $code_compta_client;
613
620 public $code_compta;
621
626 public $accountancy_code_customer;
627
632 public $code_compta_fournisseur;
633
638 public $accountancy_code_supplier;
639
644 public $code_compta_product;
645
651 public $note;
652
657 public $note_private;
658
663 public $note_public;
664
669 public $stcomm_id;
670
675 public $stcomm_picto;
676
681 public $status_prospect_label;
682
687 public $price_level;
688
692 public $outstanding_limit;
693
697 public $order_min_amount;
698
702 public $supplier_order_min_amount;
703
708 public $commercial_id;
709
714 public $parent;
715
720 public $default_lang;
721
725 public $ref;
726
732 public $ref_ext;
733
740 public $import_key;
741
746 public $webservices_url;
747
752 public $webservices_key;
753
757 public $logo;
758
762 public $logo_small;
763
767 public $logo_mini;
768
772 public $logo_squarred;
773
777 public $logo_squarred_small;
778
782 public $logo_squarred_mini;
783
787 public $accountancy_code_sell;
788
792 public $accountancy_code_buy;
793
794 // Multicurrency
798 public $fk_multicurrency;
799
800 // Warehouse
804 public $fk_warehouse;
805
809 public $multicurrency_code;
810
811 // Fields loaded by fetchPartnerships()
812
813 public $partnerships = array();
814
815
819 public $bank_account;
820
821
822 const STATUS_CEASED = 0;
823 const STATUS_INACTIVITY = 1;
824
828 const NO_CUSTOMER = 0;
829
833 const CUSTOMER = 1;
834
838 const PROSPECT = 2;
839
844
848 const NO_SUPPLIER = 0;
849
853 const SUPPLIER = 1;
854
855
861 public function __construct($db)
862 {
863 global $conf;
864
865 $this->db = $db;
866
867 $this->ismultientitymanaged = 1;
868 $this->isextrafieldmanaged = 1;
869 $this->client = 0;
870 $this->prospect = 0;
871 $this->fournisseur = 0;
872 $this->typent_id = 0;
873 $this->effectif_id = 0;
874 $this->forme_juridique_code = 0;
875 $this->tva_assuj = 1;
876 $this->vat_reverse_charge = 0;
877 $this->status = 1;
878
879 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
880 $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
881 $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
882 $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
883 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
884 }
885 }
886
887
896 public function create(User $user, $notrigger = 0)
897 {
898 global $langs, $conf;
899
900 $error = 0;
901
902 // Clean parameters
903 if (empty($this->status)) {
904 $this->status = 0;
905 }
906 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
907 $this->setUpperOrLowerCase();
908 $this->nom = $this->name; // For backward compatibility
909 if (empty($this->client)) {
910 $this->client = 0;
911 }
912 if (empty($this->fournisseur)) {
913 $this->fournisseur = 0;
914 }
915 $this->import_key = trim((string) $this->import_key);
916
917 $this->accountancy_code_customer = trim((string) $this->code_compta);
918 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
919 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
920 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
921
922 if (!empty($this->multicurrency_code)) {
923 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
924 }
925 if (empty($this->fk_multicurrency)) {
926 $this->multicurrency_code = '';
927 $this->fk_multicurrency = 0;
928 }
929
930 dol_syslog(get_class($this)."::create ".$this->name);
931
932 $now = dol_now();
933
934 if (empty($this->date_creation)) {
935 $this->date_creation = $now;
936 }
937
938 $this->db->begin();
939
940 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
941 if ($this->code_client == -1 || $this->code_client === 'auto') {
942 $this->get_codeclient($this, 0);
943 }
944 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
945 $this->get_codefournisseur($this, 1);
946 }
947
948 // Check more parameters (including mandatory setup
949 // If error, this->errors[] is filled
950 $result = $this->verify();
951
952 if ($result >= 0) {
953 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
954
955 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
956 $sql .= "nom";
957 $sql .= ", name_alias";
958 $sql .= ", entity";
959 $sql .= ", datec";
960 $sql .= ", fk_user_creat";
961 $sql .= ", fk_typent";
962 $sql .= ", canvas";
963 $sql .= ", status";
964 $sql .= ", ref_ext";
965 $sql .= ", fk_stcomm";
966 $sql .= ", fk_incoterms";
967 $sql .= ", location_incoterms";
968 $sql .= ", import_key";
969 $sql .= ", fk_multicurrency";
970 $sql .= ", multicurrency_code";
971 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
972 $sql .= ", vat_reverse_charge";
973 $sql .= ", accountancy_code_buy";
974 $sql .= ", accountancy_code_sell";
975 }
976 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
977 $sql .= " '".$this->db->escape($this->name_alias)."',";
978 $sql .= " ".((int) $this->entity).",";
979 $sql .= " '".$this->db->idate($this->date_creation)."'";
980 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
981 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
982 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
983 $sql .= ", ".((int) $this->status);
984 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
985 $sql .= ", 0";
986 $sql .= ", ".(int) $this->fk_incoterms;
987 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
988 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
989 $sql .= ", ".(int) $this->fk_multicurrency;
990 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
991 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
992 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
993 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
994 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
995 }
996 $sql .= ")";
997
998 dol_syslog(get_class($this)."::create", LOG_DEBUG);
999
1000 $result = $this->db->query($sql);
1001 if ($result) {
1002 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1003
1004 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1005
1006 // update accountancy for this entity
1007 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1008 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1009
1010 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1011 $sql .= " fk_soc";
1012 $sql .= ", entity";
1013 $sql .= ", vat_reverse_charge";
1014 $sql .= ", accountancy_code_customer";
1015 $sql .= ", accountancy_code_supplier";
1016 $sql .= ", accountancy_code_buy";
1017 $sql .= ", accountancy_code_sell";
1018 $sql .= ") VALUES (";
1019 $sql .= $this->id;
1020 $sql .= ", ".((int) $conf->entity);
1021 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1022 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1023 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1024 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1025 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1026 $sql .= ")";
1027 $result = $this->db->query($sql);
1028 if (!$result) {
1029 $error++;
1030 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1031 }
1032 }
1033
1034 // Ajout du commercial affecte
1035 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1036 $this->add_commercial($user, $this->commercial_id);
1037 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1038 // si un commercial cree un client il lui est affecte automatiquement
1039 $this->add_commercial($user, $user->id);
1040 }
1041
1042 if ($ret >= 0) {
1043 if (! $notrigger) {
1044 // Call trigger
1045 $result = $this->call_trigger('COMPANY_CREATE', $user);
1046 if ($result < 0) {
1047 $error++;
1048 }
1049 // End call triggers
1050 }
1051 } else {
1052 $error++;
1053 }
1054
1055 if (!$error) {
1056 dol_syslog(get_class($this)."::Create success id=".$this->id);
1057 $this->db->commit();
1058 return $this->id;
1059 } else {
1060 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1061 $this->db->rollback();
1062 return -4;
1063 }
1064 } else {
1065 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1066 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1067 $result = -1;
1068 } else {
1069 $this->error = $this->db->lasterror();
1070 $result = -2;
1071 }
1072 $this->db->rollback();
1073 return $result;
1074 }
1075 } else {
1076 $this->db->rollback();
1077 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1078 return -3;
1079 }
1080 }
1081
1082
1083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1093 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1094 {
1095 global $conf;
1096
1097 $error = 0;
1098
1099 $this->db->begin();
1100
1101 // phpcs:enable
1102 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1103 $contact = new Contact($this->db);
1104
1105 $contact->name = $this->name_bis;
1106 $contact->firstname = $this->firstname;
1107 $contact->civility_id = $this->civility_id;
1108 $contact->socid = $this->id; // fk_soc
1109 $contact->statut = 1; // deprecated
1110 $contact->status = 1;
1111 $contact->priv = 0;
1112 $contact->country_id = $this->country_id;
1113 $contact->state_id = $this->state_id;
1114 $contact->address = $this->address;
1115 $contact->email = $this->email;
1116 $contact->zip = $this->zip;
1117 $contact->town = $this->town;
1118 $this->setUpperOrLowerCase();
1119 $contact->phone_pro = $this->phone;
1120
1121 $contactId = $contact->create($user, $notrigger);
1122 if ($contactId < 0) {
1123 $error++;
1124 $this->error = $contact->error;
1125 $this->errors = $contact->errors;
1126 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1127 }
1128
1129 if (empty($error) && is_array($tags) && !empty($tags)) {
1130 $result = $contact->setCategories($tags);
1131 if ($result < 0) {
1132 $error++;
1133 $this->error = $contact->error;
1134 $this->errors = array_merge($this->errors, $contact->errors);
1135 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1136 $contactId = $result;
1137 }
1138 }
1139
1140 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1141 $result = $contact->setNoEmail($no_email);
1142 if ($result < 0) {
1143 $this->error = $contact->error;
1144 $this->errors = array_merge($this->errors, $contact->errors);
1145 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1146 $contactId = $result;
1147 }
1148 }
1149
1150 if (empty($error)) {
1151 dol_syslog(get_class($this)."::create_individual success");
1152 $this->db->commit();
1153 } else {
1154 $this->db->rollback();
1155 }
1156
1157 return $contactId;
1158 }
1159
1166 public function verify()
1167 {
1168 global $conf, $langs, $mysoc;
1169
1170 $error = 0;
1171 $this->errors = array();
1172
1173 $result = 0;
1174 $this->name = trim($this->name);
1175 $this->nom = $this->name; // For backward compatibility
1176
1177 if (!$this->name) {
1178 $this->errors[] = 'ErrorBadThirdPartyName';
1179 $result = -2;
1180 }
1181
1182 if ($this->client) {
1183 $rescode = $this->check_codeclient();
1184 if ($rescode != 0 && $rescode != -5) {
1185 if ($rescode == -1) {
1186 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1187 } elseif ($rescode == -2) {
1188 $this->errors[] = 'ErrorCustomerCodeRequired';
1189 } elseif ($rescode == -3) {
1190 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1191 } elseif ($rescode == -4) {
1192 $this->errors[] = 'ErrorPrefixRequired';
1193 } else {
1194 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1195 }
1196
1197 $result = -3;
1198 }
1199 }
1200
1201 if ($this->fournisseur) {
1202 $rescode = $this->check_codefournisseur();
1203 if ($rescode != 0 && $rescode != -5) {
1204 if ($rescode == -1) {
1205 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1206 } elseif ($rescode == -2) {
1207 $this->errors[] = 'ErrorSupplierCodeRequired';
1208 } elseif ($rescode == -3) {
1209 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1210 } elseif ($rescode == -4) {
1211 $this->errors[] = 'ErrorPrefixRequired';
1212 } else {
1213 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1214 }
1215 $result = -3;
1216 }
1217 }
1218
1219 // Check for duplicate or mandatory fields defined into setup
1220 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1221 foreach ($array_to_check as $key) {
1222 $keymin = strtolower($key);
1223 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1224 $keymin = 'code_compta';
1225 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1226 $keymin = 'code_compta_fournisseur';
1227 }
1228 $i = (int) preg_replace('/[^0-9]/', '', $key);
1229 $vallabel = $this->$keymin;
1230
1231 if ($i > 0) {
1232 if ($this->isACompany()) {
1233 // Check for mandatory prof id (but only if country is same than ours)
1234 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1235 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1236 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1237 $langs->load("errors");
1238 $error++;
1239 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1240 }
1241 }
1242 }
1243
1244 // Check for unicity on profid
1245 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1246 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1247 $langs->load("errors");
1248 $error++;
1249 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1250 }
1251 }
1252 } else {
1253 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1254 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1255 if ($key == 'EMAIL') {
1256 // Check for mandatory
1257 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1258 $langs->load("errors");
1259 $error++;
1260 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1261 }
1262
1263 // Check for unicity
1264 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1265 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1266 $langs->load("errors");
1267 $error++;
1268 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1269 }
1270 }
1271 } elseif ($key == 'TVA_INTRA') {
1272 // Check for unicity
1273 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1274 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1275 $langs->load("errors");
1276 $error++;
1277 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1278 }
1279 }
1280 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1281 // Check for unicity
1282 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1283 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1284 $langs->loadLangs(array("errors", 'compta'));
1285 $error++;
1286 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1287 }
1288 }
1289
1290 // Check for mandatory
1291 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1292 $langs->loadLangs(array("errors", 'compta'));
1293 $error++;
1294 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1295 }
1296 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1297 // Check for unicity
1298 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1299 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1300 $langs->loadLangs(array("errors", 'compta'));
1301 $error++;
1302 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1303 }
1304 }
1305
1306 // Check for mandatory
1307 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1308 $langs->loadLangs(array("errors", 'compta'));
1309 $error++;
1310 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1311 }
1312 }
1313 }
1314 }
1315
1316 if ($error) {
1317 $result = -4;
1318 }
1319
1320 return $result;
1321 }
1322
1335 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1336 {
1337 global $langs, $conf, $hookmanager;
1338
1339 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1340
1341 if (empty($id)) {
1342 $id = $this->id;
1343 }
1344
1345 $error = 0;
1346
1347 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1348
1349 $now = dol_now();
1350
1351 // Clean parameters
1352 $this->id = $id;
1353 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1354 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1355 $this->nom = $this->name; // For backward compatibility
1356 $this->name_alias = trim((string) $this->name_alias);
1357 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1358 $this->address = trim((string) $this->address);
1359 $this->zip = trim((string) $this->zip);
1360 $this->town = trim((string) $this->town);
1361 $this->state_id = (is_numeric($this->state_id)) ? (int) trim((string) $this->state_id) : 0;
1362 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1363 $this->phone = trim((string) $this->phone);
1364 $this->phone = preg_replace("/\s/", "", $this->phone);
1365 $this->phone = preg_replace("/\./", "", $this->phone);
1366 $this->phone_mobile = trim((string) $this->phone_mobile);
1367 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1368 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1369 $this->fax = trim((string) $this->fax);
1370 $this->fax = preg_replace("/\s/", "", $this->fax);
1371 $this->fax = preg_replace("/\./", "", $this->fax);
1372 $this->email = trim((string) $this->email);
1373 $this->url = $this->url ? clean_url($this->url, 0) : '';
1374 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1375 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1376 $this->idprof1 = trim((string) $this->idprof1);
1377 $this->idprof2 = trim((string) $this->idprof2);
1378 $this->idprof3 = trim((string) $this->idprof3);
1379 $this->idprof4 = trim((string) $this->idprof4);
1380 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1381 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1382 $this->prefix_comm = trim((string) $this->prefix_comm);
1383 $this->outstanding_limit = price2num($this->outstanding_limit);
1384 $this->order_min_amount = price2num($this->order_min_amount);
1385 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1386
1387 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1388 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1389 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1390 if (empty($this->status)) {
1391 $this->status = 0;
1392 }
1393
1394 if (!empty($this->multicurrency_code)) {
1395 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1396 }
1397 if (empty($this->fk_multicurrency)) {
1398 $this->multicurrency_code = '';
1399 $this->fk_multicurrency = 0;
1400 }
1401
1402 // Local taxes
1403 $this->localtax1_assuj = trim($this->localtax1_assuj);
1404 $this->localtax2_assuj = trim($this->localtax2_assuj);
1405
1406 $this->localtax1_value = trim($this->localtax1_value);
1407 $this->localtax2_value = trim($this->localtax2_value);
1408
1409 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1410
1411 $this->effectif_id = trim((string) $this->effectif_id);
1412 $this->forme_juridique_code = trim((string) $this->forme_juridique_code);
1413
1414 //Gencod
1415 $this->barcode = trim($this->barcode);
1416
1417 // For automatic creation
1418 if ($this->code_client == -1 || $this->code_client === 'auto') {
1419 $this->get_codeclient($this, 0);
1420 }
1421 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1422 $this->get_codefournisseur($this, 1);
1423 }
1424
1425 $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1426 $this->code_compta = $this->code_compta_client; // for backward compatibility
1427 $this->code_compta_fournisseur = (empty($this->code_compta_fournisseur) ? '' : trim($this->code_compta_fournisseur));
1428
1429 // Check parameters. More tests are done later in the ->verify()
1430 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1431 $langs->load("errors");
1432 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1433 return -1;
1434 }
1435
1436 $customer = false;
1437 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1438 // If $allowmodcodeclient is set and value is not set, we generate it
1439 if (empty($this->code_compta_client)) {
1440 $ret = $this->get_codecompta('customer');
1441 if ($ret < 0) {
1442 return -1;
1443 }
1444 }
1445
1446 $customer = true;
1447 }
1448
1449 $supplier = false;
1450 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1451 // If $allowmodcodefournisseur is set and value is not set, we generate it
1452 if (empty($this->code_compta_fournisseur)) {
1453 $ret = $this->get_codecompta('supplier');
1454 if ($ret < 0) {
1455 return -1;
1456 }
1457 }
1458
1459 $supplier = true;
1460 }
1461
1462 //Web services
1463 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1464 $this->webservices_key = trim($this->webservices_key);
1465
1466 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1467 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1468
1469 //Incoterms
1470 $this->fk_incoterms = (int) $this->fk_incoterms;
1471 $this->location_incoterms = trim($this->location_incoterms);
1472
1473 $this->db->begin();
1474
1475 // Check name is required and codes are ok or unique.
1476 // If error, this->errors[] is filled
1477 $result = 0;
1478 if ($action != 'add' && $action != 'merge') {
1479 // We don't check when update called during a create because verify was already done.
1480 // 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
1481 $result = $this->verify();
1482
1483 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1484 // So we can update record that were using and old numbering rule.
1485 if (is_array($this->errors)) {
1486 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1487 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1488 unset($this->errors[$key]); // Remove error message
1489 }
1490 }
1491 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1492 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1493 unset($this->errors[$key]); // Remove error message
1494 }
1495 }
1496 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1497 $result = 0;
1498 }
1499 }
1500 }
1501 $this->setUpperOrLowerCase();
1502 if ($result >= 0) {
1503 dol_syslog(get_class($this)."::update verify ok or not done");
1504
1505 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1506 $sql .= "entity = ".$this->db->escape($this->entity);
1507 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1508 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1509 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1510 $sql .= ",address = '".$this->db->escape($this->address)."'";
1511
1512 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1513 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1514
1515 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1516 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1517
1518 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1519 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1520 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1521 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1522 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1523 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1524
1525 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1526
1527 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1528 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1529
1530 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1531 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1532 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1533 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1534 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1535 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1536
1537 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1538 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1539 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1540 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1541 }
1542 $sql .= ",status = ".((int) $this->status);
1543
1544 // Local taxes
1545 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1546 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1547 if ($this->localtax1_assuj == 1) {
1548 if ($this->localtax1_value != '') {
1549 $sql .= ",localtax1_value =".$this->localtax1_value;
1550 } else {
1551 $sql .= ",localtax1_value =0.000";
1552 }
1553 } else {
1554 $sql .= ",localtax1_value =0.000";
1555 }
1556
1557 if ($this->localtax2_assuj == 1) {
1558 if ($this->localtax2_value != '') {
1559 $sql .= ",localtax2_value =".$this->localtax2_value;
1560 } else {
1561 $sql .= ",localtax2_value =0.000";
1562 }
1563 } else {
1564 $sql .= ",localtax2_value =0.000";
1565 }
1566
1567 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1568
1569 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1570
1571 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1572 if (isset($this->stcomm_id)) {
1573 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1574 }
1575 if (isset($this->typent_id)) {
1576 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1577 }
1578
1579 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1580
1581 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1582 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1583 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1584 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1585 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1586 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1587 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1588 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1589
1590 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1591 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1592 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1593 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1594 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1595 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1596 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1597 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1598 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1599 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1600 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1601 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1602 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1603 if ($customer) {
1604 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1605 }
1606
1607 if ($supplier) {
1608 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1609 }
1610 }
1611 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1612 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1613
1614 //Incoterms
1615 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1616 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1617
1618 if ($customer) {
1619 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1620 }
1621
1622 if ($supplier) {
1623 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1624 }
1625 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1626 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1627 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1628 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1629 $sql .= " WHERE rowid = ".(int) $id;
1630
1631 $resql = $this->db->query($sql);
1632 if ($resql) {
1633 if (is_object($this->oldcopy)) { // If we have information on old values
1634 if ($this->oldcopy->country_id != $this->country_id) {
1635 unset($this->country_code);
1636 unset($this->country);
1637 }
1638 if ($this->oldcopy->state_id != $this->state_id) {
1639 unset($this->state_code);
1640 unset($this->state);
1641 }
1642 } else {
1643 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1644 unset($this->country);
1645 unset($this->state_code);
1646 unset($this->state);
1647 }
1648
1649 $nbrowsaffected = $this->db->affected_rows($resql);
1650
1651 if (!$error && $nbrowsaffected) {
1652 // Update information on linked member if it is an update
1653 if (!$nosyncmember && isModEnabled('member')) {
1654 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1655
1656 dol_syslog(get_class($this)."::update update linked member");
1657
1658 $lmember = new Adherent($this->db);
1659 $result = $lmember->fetch(0, 0, $this->id);
1660
1661 if ($result > 0) {
1662 $lmember->company = $this->name;
1663 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1664 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1665 $lmember->address = $this->address;
1666 $lmember->zip = $this->zip;
1667 $lmember->town = $this->town;
1668 $lmember->email = $this->email;
1669 $lmember->socialnetworks = $this->socialnetworks;
1670 $lmember->phone = $this->phone;
1671 $lmember->state_id = $this->state_id;
1672 $lmember->country_id = $this->country_id;
1673 $lmember->default_lang = $this->default_lang;
1674
1675 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1676 if ($result < 0) {
1677 $this->error = $lmember->error;
1678 $this->errors = array_merge($this->errors, $lmember->errors);
1679 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1680 $error++;
1681 }
1682 } elseif ($result < 0) {
1683 $this->error = $lmember->error;
1684 $error++;
1685 }
1686 }
1687 }
1688
1689 $action = 'update';
1690
1691 // update accountancy for this entity
1692 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1693 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1694
1695 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1696 $sql .= " fk_soc";
1697 $sql .= ", entity";
1698 $sql .= ", vat_reverse_charge";
1699 $sql .= ", accountancy_code_customer";
1700 $sql .= ", accountancy_code_supplier";
1701 $sql .= ", accountancy_code_buy";
1702 $sql .= ", accountancy_code_sell";
1703 $sql .= ") VALUES (";
1704 $sql .= $this->id;
1705 $sql .= ", ".$conf->entity;
1706 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1707 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1708 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1709 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1710 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1711 $sql .= ")";
1712 $result = $this->db->query($sql);
1713 if (!$result) {
1714 $error++;
1715 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1716 }
1717 }
1718
1719 // Actions on extra fields
1720 if (!$error) {
1721 $result = $this->insertExtraFields();
1722 if ($result < 0) {
1723 $error++;
1724 }
1725 }
1726 // Actions on extra languages
1727 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1728 $result = $this->insertExtraLanguages();
1729 if ($result < 0) {
1730 $error++;
1731 }
1732 }
1733
1734 if (!$error && $call_trigger) {
1735 // Call trigger
1736 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1737 if ($result < 0) {
1738 $error++;
1739 }
1740 // End call triggers
1741 }
1742
1743 if (!$error) {
1744 dol_syslog(get_class($this)."::Update success");
1745 $this->db->commit();
1746 return 1;
1747 } else {
1748 $this->db->rollback();
1749 return -1;
1750 }
1751 } else {
1752 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1753 // Doublon
1754 $this->error = $langs->trans("ErrorDuplicateField");
1755 $result = -1;
1756 } else {
1757 $this->error = $this->db->lasterror();
1758 $result = -2;
1759 }
1760 $this->db->rollback();
1761 return $result;
1762 }
1763 } else {
1764 $this->db->rollback();
1765 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1766 return -3;
1767 }
1768 }
1769
1789 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1790 {
1791 global $langs;
1792 global $conf;
1793
1794 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)) {
1795 return -1;
1796 }
1797
1798 $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';
1799 $sql .= ', s.status, s.fk_warehouse';
1800 $sql .= ', s.price_level';
1801 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1802 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1803 $sql .= ', s.socialnetworks';
1804 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1805 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1806 $sql .= ', s.capital, s.tva_intra';
1807 $sql .= ', s.fk_typent as typent_id';
1808 $sql .= ', s.fk_effectif as effectif_id';
1809 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1810 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1811 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1812 $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1813 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1814 } else {
1815 $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1816 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1817 }
1818 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1819 $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.mode_reglement, s.cond_reglement, s.deposit_percent, s.transport_mode';
1820 $sql .= ', s.fk_account, s.tva_assuj';
1821 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1822 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1823 $sql .= ', s.fk_shipping_method';
1824 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1825 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1826 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1827 $sql .= ', fj.libelle as forme_juridique';
1828 $sql .= ', e.libelle as effectif';
1829 $sql .= ', c.code as country_code, c.label as country';
1830 $sql .= ', d.code_departement as state_code, d.nom as state';
1831 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1832 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1833 $sql .= ', te.code as typent_code';
1834 $sql .= ', i.libelle as label_incoterms';
1835 if (!isModEnabled('multicompany')) {
1836 $sql .= ', s.remise_client, s.remise_supplier';
1837 } else {
1838 $sql .= ', sr.remise_client, sr2.remise_supplier';
1839 }
1840 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1841 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1842 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1843 }
1844 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1845 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1846 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1847 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1848 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1849 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1850 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1851 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1852 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1853 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1854 if (isModEnabled('multicompany')) {
1855 $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').'))';
1856 $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').'))';
1857 }
1858 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1859
1860 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1861 if ($is_client) {
1862 $sql .= ' AND s.client > 0';
1863 }
1864 if ($is_supplier) {
1865 $sql .= ' AND s.fournisseur > 0';
1866 } // if both false, no test (the thirdparty can be client and/or supplier)
1867
1868 if ($rowid) {
1869 $sql .= ' AND s.rowid = '.((int) $rowid);
1870 }
1871 if ($ref) {
1872 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1873 }
1874 if ($ref_alias) {
1875 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1876 }
1877 if ($ref_ext) {
1878 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1879 }
1880 if ($barcode) {
1881 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1882 }
1883 if ($idprof1) {
1884 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1885 }
1886 if ($idprof2) {
1887 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1888 }
1889 if ($idprof3) {
1890 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1891 }
1892 if ($idprof4) {
1893 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1894 }
1895 if ($idprof5) {
1896 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1897 }
1898 if ($idprof6) {
1899 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1900 }
1901 if ($email) {
1902 $sql .= " AND s.email = '".$this->db->escape($email)."'";
1903 }
1904
1905 $resql = $this->db->query($sql);
1906 if ($resql) {
1907 $num = $this->db->num_rows($resql);
1908 if ($num > 1) {
1909 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1910 dol_syslog($this->error, LOG_ERR);
1911 $result = -2;
1912 } elseif ($num) { // $num = 1
1913 $obj = $this->db->fetch_object($resql);
1914
1915 $this->id = $obj->rowid;
1916 $this->entity = $obj->entity;
1917 $this->canvas = $obj->canvas;
1918
1919 $this->ref = $obj->rowid;
1920 $this->name = $obj->name;
1921 $this->nom = $obj->name; // deprecated
1922 $this->name_alias = $obj->name_alias;
1923 $this->ref_ext = $obj->ref_ext;
1924
1925 $this->date_creation = $this->db->jdate($obj->date_creation);
1926 $this->date_modification = $this->db->jdate($obj->date_modification);
1927 $this->user_creation_id = $obj->fk_user_creat;
1928 $this->user_modification_id = $obj->fk_user_modif;
1929
1930 $this->address = $obj->address;
1931 $this->zip = $obj->zip;
1932 $this->town = $obj->town;
1933
1934 $this->country_id = $obj->country_id;
1935 $this->country_code = $obj->country_id ? $obj->country_code : '';
1936 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1937
1938 $this->state_id = $obj->state_id;
1939 $this->state_code = $obj->state_code;
1940 $this->region_id = $obj->region_id;
1941 $this->region_code = $obj->region_code;
1942 $this->state = ($obj->state != '-' ? $obj->state : '');
1943
1944 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1945 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1946 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1947 $this->status_prospect_label = $label; // label status prospect
1948 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1949
1950 $this->email = $obj->email;
1951 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1952
1953 $this->url = $obj->url;
1954 $this->phone = $obj->phone;
1955 $this->phone_mobile = $obj->phone_mobile;
1956 $this->fax = $obj->fax;
1957
1958 $this->parent = $obj->parent;
1959
1960 $this->idprof1 = $obj->idprof1;
1961 $this->idprof2 = $obj->idprof2;
1962 $this->idprof3 = $obj->idprof3;
1963 $this->idprof4 = $obj->idprof4;
1964 $this->idprof5 = $obj->idprof5;
1965 $this->idprof6 = $obj->idprof6;
1966
1967 $this->capital = $obj->capital;
1968
1969 $this->code_client = $obj->code_client;
1970 $this->code_fournisseur = $obj->code_fournisseur;
1971
1972 $this->code_compta = $obj->code_compta; // For backward compatibility
1973 $this->code_compta_client = $obj->code_compta;
1974 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1975
1976 $this->barcode = $obj->barcode;
1977
1978 $this->tva_assuj = $obj->tva_assuj;
1979 $this->tva_intra = $obj->tva_intra;
1980
1981 if (!empty($obj->spe_vat_reverse_charge)) {
1982 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1983 } elseif (!empty($obj->soc_vat_reverse_charge)) {
1984 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1985 } else {
1986 $this->vat_reverse_charge = 0;
1987 }
1988
1989 $this->status = $obj->status;
1990
1991 // Local Taxes
1992 $this->localtax1_assuj = $obj->localtax1_assuj;
1993 $this->localtax2_assuj = $obj->localtax2_assuj;
1994
1995 $this->localtax1_value = $obj->localtax1_value;
1996 $this->localtax2_value = $obj->localtax2_value;
1997
1998 $this->typent_id = $obj->typent_id;
1999 $this->typent_code = $obj->typent_code;
2000
2001 $this->effectif_id = $obj->effectif_id;
2002 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2003
2004 $this->forme_juridique_code = $obj->forme_juridique_code;
2005 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2006
2007 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2008
2009 $this->prefix_comm = $obj->prefix_comm;
2010
2011 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2012 $this->remise_supplier_percent = $obj->remise_supplier;
2013
2014 $this->mode_reglement_id = $obj->mode_reglement;
2015 $this->cond_reglement_id = $obj->cond_reglement;
2016 $this->deposit_percent = $obj->deposit_percent;
2017 $this->transport_mode_id = $obj->transport_mode;
2018 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2019 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2020 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2021 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2022 $this->fk_account = $obj->fk_account;
2023
2024 $this->client = $obj->client;
2025 $this->fournisseur = $obj->fournisseur;
2026
2027 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2028 $this->note_private = $obj->note_private;
2029 $this->note_public = $obj->note_public;
2030 $this->model_pdf = $obj->model_pdf;
2031 $this->default_lang = $obj->default_lang;
2032 $this->logo = $obj->logo;
2033 $this->logo_squarred = $obj->logo_squarred;
2034
2035 $this->webservices_url = $obj->webservices_url;
2036 $this->webservices_key = $obj->webservices_key;
2037
2038 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2039 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2040
2041 $this->outstanding_limit = $obj->outstanding_limit;
2042 $this->order_min_amount = $obj->order_min_amount;
2043 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2044
2045 // multiprix
2046 $this->price_level = $obj->price_level;
2047
2048 // warehouse
2049 $this->fk_warehouse = $obj->fk_warehouse;
2050
2051 $this->import_key = $obj->import_key;
2052
2053 //Incoterms
2054 $this->fk_incoterms = $obj->fk_incoterms;
2055 $this->location_incoterms = $obj->location_incoterms;
2056 $this->label_incoterms = $obj->label_incoterms;
2057
2058 // multicurrency
2059 $this->fk_multicurrency = $obj->fk_multicurrency;
2060 $this->multicurrency_code = $obj->multicurrency_code;
2061
2062 // pdf
2063 $this->model_pdf = $obj->model_pdf;
2064 $this->last_main_doc = $obj->last_main_doc;
2065
2066 $result = 1;
2067
2068 // fetch optionals attributes and labels
2069 $this->fetch_optionals();
2070 } else {
2071 $result = 0;
2072 }
2073
2074 $this->db->free($resql);
2075 } else {
2076 $this->error = $this->db->lasterror();
2077 $this->errors[] = $this->db->lasterror();
2078 $result = -3;
2079 }
2080
2081 // Use first price level if level not defined for third party
2082 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && empty($this->price_level)) {
2083 $this->price_level = 1;
2084 }
2085
2086 return $result;
2087 }
2088
2097 public function delete($id, User $fuser = null, $call_trigger = 1)
2098 {
2099 global $conf, $user;
2100
2101 if (empty($fuser)) {
2102 $fuser = $user;
2103 }
2104
2105 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2106
2107 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2108
2109 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2110 $error = 0;
2111
2112 // Test if child exists
2113 $objectisused = $this->isObjectUsed($id);
2114 if (empty($objectisused)) {
2115 $this->db->begin();
2116
2117 // User is mandatory for trigger call
2118 if (!$error && $call_trigger) {
2119 // Call trigger
2120 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2121 if ($result < 0) {
2122 $error++;
2123 }
2124 // End call triggers
2125 }
2126
2127 if (!$error) {
2128 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2129 $static_cat = new Categorie($this->db);
2130 $toute_categs = array();
2131
2132 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2133 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2134 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2135
2136 // Remove each "Categorie"
2137 foreach ($toute_categs as $type => $categs_type) {
2138 foreach ($categs_type as $cat) {
2139 $cat->del_type($this, $type);
2140 }
2141 }
2142 }
2143
2144 if (!$error) {
2145 foreach ($this->childtablesoncascade as $tabletodelete) {
2146 $deleteFromObject = explode(':', $tabletodelete, 4);
2147 if (count($deleteFromObject) >= 2) {
2148 $className = str_replace('@', '', $deleteFromObject[0]);
2149 $filepath = $deleteFromObject[1];
2150 $columnName = $deleteFromObject[2];
2151 if (dol_include_once($filepath)) {
2152 $child_object = new $className($this->db);
2153 $result = $child_object->deleteByParentField($id, $columnName);
2154 if ($result < 0) {
2155 $error++;
2156 $this->errors[] = $child_object->error;
2157 break;
2158 }
2159 } else {
2160 $error++;
2161 $this->errors[] = 'Cannot include child class file '.$filepath;
2162 break;
2163 }
2164 } else {
2165 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2166 $sql .= " WHERE fk_soc = ".((int) $id);
2167 if (!$this->db->query($sql)) {
2168 $error++;
2169 $this->errors[] = $this->db->lasterror();
2170 break;
2171 }
2172 }
2173 }
2174 }
2175
2176 // Removed extrafields
2177 if (!$error) {
2178 $result = $this->deleteExtraFields();
2179 if ($result < 0) {
2180 $error++;
2181 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2182 }
2183 }
2184
2185 // Remove links to subsidiaries companies
2186 if (!$error) {
2187 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2188 $sql .= " SET parent = NULL";
2189 $sql .= " WHERE parent = ".((int) $id);
2190 if (!$this->db->query($sql)) {
2191 $error++;
2192 $this->errors[] = $this->db->lasterror();
2193 }
2194 }
2195
2196 // Remove third party
2197 if (!$error) {
2198 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2199 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2200 $sql .= " WHERE fk_soc = ".((int) $id);
2201 if (!$this->db->query($sql)) {
2202 $error++;
2203 $this->errors[] = $this->db->lasterror();
2204 }
2205 }
2206
2207 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2208 $sql .= " WHERE rowid = ".((int) $id);
2209 if (!$this->db->query($sql)) {
2210 $error++;
2211 $this->errors[] = $this->db->lasterror();
2212 }
2213 }
2214
2215 if (!$error) {
2216 $this->db->commit();
2217
2218 // Delete directory
2219 if (!empty($conf->societe->multidir_output[$entity])) {
2220 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2221 if (dol_is_dir($docdir)) {
2222 dol_delete_dir_recursive($docdir);
2223 }
2224 }
2225
2226 return 1;
2227 } else {
2228 dol_syslog($this->error, LOG_ERR);
2229 $this->db->rollback();
2230 return -1;
2231 }
2232 } else {
2233 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2234 }
2235 return 0;
2236 }
2237
2238 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2246 public function set_as_client()
2247 {
2248 global $conf;
2249 // phpcs:enable
2250 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2251 return $this->setAsCustomer();
2252 }
2253
2260 public function setAsCustomer()
2261 {
2262 if ($this->id) {
2263 $newclient = 1;
2264 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2265 $newclient = 3; //If prospect, we keep prospect tag
2266 }
2267 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2268 $sql .= " SET client = ".((int) $newclient);
2269 $sql .= " WHERE rowid = ".((int) $this->id);
2270
2271 $resql = $this->db->query($sql);
2272 if ($resql) {
2273 $this->client = $newclient;
2274 return 1;
2275 } else {
2276 return -1;
2277 }
2278 }
2279 return 0;
2280 }
2281
2282 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2291 public function set_remise_client($remise, $note, User $user)
2292 {
2293 // phpcs:enable
2294 global $conf, $langs;
2295
2296 // Parameter cleaning
2297 $note = trim($note);
2298 if (!$note) {
2299 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2300 return -2;
2301 }
2302
2303 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2304
2305 if ($this->id) {
2306 $this->db->begin();
2307
2308 $now = dol_now();
2309
2310 // Position current discount
2311 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2312 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2313 $sql .= " WHERE rowid = ".((int) $this->id);
2314 $resql = $this->db->query($sql);
2315 if (!$resql) {
2316 $this->db->rollback();
2317 $this->error = $this->db->error();
2318 return -1;
2319 }
2320
2321 // Writes trace in discount history
2322 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2323 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2324 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2325 $sql .= " '".$this->db->escape($note)."',";
2326 $sql .= " ".((int) $user->id);
2327 $sql .= ")";
2328
2329 $resql = $this->db->query($sql);
2330 if (!$resql) {
2331 $this->db->rollback();
2332 $this->error = $this->db->lasterror();
2333 return -1;
2334 }
2335
2336 $this->db->commit();
2337
2338 return 1;
2339 }
2340 return -1;
2341 }
2342
2343 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2352 public function set_remise_supplier($remise, $note, User $user)
2353 {
2354 // phpcs:enable
2355 global $conf, $langs;
2356
2357 // Parameter cleaning
2358 $note = trim($note);
2359 if (!$note) {
2360 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2361 return -2;
2362 }
2363
2364 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2365
2366 if ($this->id) {
2367 $this->db->begin();
2368
2369 $now = dol_now();
2370
2371 // Position current discount
2372 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2373 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2374 $sql .= " WHERE rowid = ".((int) $this->id);
2375 $resql = $this->db->query($sql);
2376 if (!$resql) {
2377 $this->db->rollback();
2378 $this->error = $this->db->error();
2379 return -1;
2380 }
2381
2382 // Writes trace in discount history
2383 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2384 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2385 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2386 $sql .= " '".$this->db->escape($note)."',";
2387 $sql .= " ".((int) $user->id);
2388 $sql .= ")";
2389
2390 $resql = $this->db->query($sql);
2391 if (!$resql) {
2392 $this->db->rollback();
2393 $this->error = $this->db->lasterror();
2394 return -1;
2395 }
2396
2397 $this->db->commit();
2398 return 1;
2399 }
2400
2401 return -1;
2402 }
2403
2404 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2416 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2417 {
2418 // phpcs:enable
2419 global $langs;
2420
2421 // Clean parameters
2422 $remise = price2num($remise);
2423 $desc = trim($desc);
2424
2425 // Check parameters
2426 if (!($remise > 0)) {
2427 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2428 return -1;
2429 }
2430 if (!$desc) {
2431 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2432 return -2;
2433 }
2434
2435 if ($this->id > 0) {
2436 // Clean vat code
2437 $reg = array();
2438 $vat_src_code = '';
2439 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2440 $vat_src_code = $reg[1];
2441 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2442 }
2443
2444 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2445
2446 $discount = new DiscountAbsolute($this->db);
2447 $discount->fk_soc = $this->id;
2448 $discount->socid = $this->id;
2449
2450 $discount->discount_type = $discount_type;
2451
2452 if ($price_base_type == 'TTC') {
2453 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2454 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2455 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2456 } else {
2457 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2458 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2459 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2460 }
2461
2462 $discount->tva_tx = (float) price2num($vatrate);
2463 $discount->vat_src_code = $vat_src_code;
2464
2465 $discount->description = $desc;
2466
2467 $result = $discount->create($user);
2468 if ($result > 0) {
2469 return $result;
2470 } else {
2471 $this->error = $discount->error;
2472 return -3;
2473 }
2474 } else {
2475 return 0;
2476 }
2477 }
2478
2488 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2489 {
2490 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2491
2492 $discountstatic = new DiscountAbsolute($this->db);
2493 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2494 if ($result >= 0) {
2495 return $result;
2496 } else {
2497 $this->error = $discountstatic->error;
2498 return -1;
2499 }
2500 }
2501
2511 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2512 {
2513 global $conf;
2514
2515 $reparray = array();
2516
2517 $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";
2518 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2519 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2520 // Condition here should be the same than into select_dolusers()
2521 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2522 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2523 } else {
2524 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2525 }
2526
2527 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2528 if (empty($sortfield) && empty($sortorder)) {
2529 $sortfield = 'u.lastname,u.firstname';
2530 $sortorder = 'ASC,ASC';
2531 }
2532 $sql .= $this->db->order($sortfield, $sortorder);
2533
2534 $resql = $this->db->query($sql);
2535 if ($resql) {
2536 $num = $this->db->num_rows($resql);
2537 $i = 0;
2538 while ($i < $num) {
2539 $obj = $this->db->fetch_object($resql);
2540
2541 if (empty($mode)) {
2542 $reparray[$i]['id'] = $obj->rowid;
2543 $reparray[$i]['lastname'] = $obj->lastname;
2544 $reparray[$i]['firstname'] = $obj->firstname;
2545 $reparray[$i]['email'] = $obj->email;
2546 $reparray[$i]['phone'] = $obj->office_phone;
2547 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2548 $reparray[$i]['office_fax'] = $obj->office_fax;
2549 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2550 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2551 $reparray[$i]['job'] = $obj->job;
2552 $reparray[$i]['statut'] = $obj->status; // deprecated
2553 $reparray[$i]['status'] = $obj->status;
2554 $reparray[$i]['entity'] = $obj->entity;
2555 $reparray[$i]['login'] = $obj->login;
2556 $reparray[$i]['photo'] = $obj->photo;
2557 $reparray[$i]['gender'] = $obj->gender;
2558 } else {
2559 $reparray[] = $obj->rowid;
2560 }
2561 $i++;
2562 }
2563 return $reparray;
2564 } else {
2565 dol_print_error($this->db);
2566 return -1;
2567 }
2568 }
2569
2577 public function setPriceLevel($price_level, User $user)
2578 {
2579 if ($this->id) {
2580 $now = dol_now();
2581
2582 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2583 $sql .= " SET price_level = ".((int) $price_level);
2584 $sql .= " WHERE rowid = ".((int) $this->id);
2585
2586 if (!$this->db->query($sql)) {
2587 dol_print_error($this->db);
2588 return -1;
2589 }
2590
2591 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2592 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2593 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2594
2595 if (!$this->db->query($sql)) {
2596 dol_print_error($this->db);
2597 return -1;
2598 }
2599 return 1;
2600 }
2601 return -1;
2602 }
2603
2604 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2612 public function add_commercial(User $user, $commid)
2613 {
2614 // phpcs:enable
2615 $error = 0;
2616
2617 if ($this->id > 0 && $commid > 0) {
2618 $this->db->begin();
2619
2620 if (!$error) {
2621 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2622 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2623
2624 $resql = $this->db->query($sql);
2625 if (!$resql) {
2626 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2627 $error++;
2628 }
2629 }
2630
2631 if (!$error) {
2632 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2633 $sql .= " (fk_soc, fk_user)";
2634 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2635
2636 $resql = $this->db->query($sql);
2637 if (!$resql) {
2638 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2639 $error++;
2640 }
2641 }
2642
2643 if (!$error) {
2644 $this->context = array('commercial_modified' => $commid);
2645
2646 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2647 if ($result < 0) {
2648 $error++;
2649 }
2650 }
2651
2652 if (!$error) {
2653 $this->db->commit();
2654 return 1;
2655 } else {
2656 $this->db->rollback();
2657 return -1;
2658 }
2659 }
2660
2661 return 0;
2662 }
2663
2664 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2672 public function del_commercial(User $user, $commid)
2673 {
2674 // phpcs:enable
2675 $error = 0;
2676 $this->context = array('commercial_modified' => $commid);
2677
2678 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2679 if ($result < 0) {
2680 $error++;
2681 }
2682
2683 if ($this->id > 0 && $commid > 0) {
2684 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2685 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2686
2687 if (!$this->db->query($sql)) {
2688 $error++;
2689 dol_syslog(get_class($this)."::del_commercial Erreur");
2690 }
2691 }
2692
2693 if ($error) {
2694 return -1;
2695 } else {
2696 return 1;
2697 }
2698 }
2699
2707 public function getTooltipContentArray($params)
2708 {
2709 global $conf, $langs, $user;
2710
2711 $langs->loadLangs(['companies', 'commercial']);
2712
2713 $datas = array();
2714
2715 $option = $params['option'] ?? '';
2716 $nofetch = !empty($params['nofetch']);
2717
2718 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2719
2720 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2721 return ['optimize' => $langs->trans("ShowCompany")];
2722 }
2723
2724 if (!empty($this->logo) && class_exists('Form')) {
2725 $photo = '<div class="photointooltip floatright">';
2726 $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.
2727 $photo .= '</div>';
2728 $datas['photo'] = $photo;
2729 } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2730 /*$label.= '<div class="photointooltip">';
2731 $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.
2732 $label.= '</div><div style="clear: both;"></div>';*/
2733 }
2734
2735 $datas['divopen'] = '<div class="centpercent">';
2736
2737 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2738 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2739 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2740 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2741 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2742 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2743 } elseif ($option == 'agenda') {
2744 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2745 } elseif ($option == 'project') {
2746 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2747 } elseif ($option == 'margin') {
2748 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2749 } elseif ($option == 'contact') {
2750 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2751 } elseif ($option == 'ban') {
2752 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2753 }
2754
2755 // By default
2756 if (empty($datas['picto'])) {
2757 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2758 }
2759 if (isset($this->status)) {
2760 $datas['status'] = ' '.$this->getLibStatut(5);
2761 }
2762 if (isset($this->client) && isset($this->fournisseur)) {
2763 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2764 }
2765 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2766 if (!empty($this->name_alias) && empty($noaliasinname)) {
2767 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2768 }
2769 if (!empty($this->email)) {
2770 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2771 }
2772 if (!empty($this->url)) {
2773 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2774 }
2775 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2776 $phonelist = array();
2777 if ($this->phone) {
2778 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2779 }
2780 // deliberately not making new list because fax uses same list as phone
2781 if ($this->phone_mobile) {
2782 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2783 }
2784 if ($this->fax) {
2785 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2786 }
2787 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2788 }
2789
2790 if (!empty($this->address)) {
2791 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2792 } elseif (!empty($this->country_code)) {
2793 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2794 }
2795 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2796 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2797 }
2798
2799 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2800 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2801 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2802 }
2803 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2804 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2805 }
2806 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2807 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2808 }
2809 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2810 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2811 }
2812 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2813 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2814 }
2815 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2816 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2817 }
2818 }
2819
2820 $datas['separator'] = '<br>';
2821
2822 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2823 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2824 }
2825 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2826 $langs->load('compta');
2827 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2828 }
2829 // show categories for this record only in ajax to not overload lists
2830 if (!$nofetch && isModEnabled('category') && $this->client) {
2831 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2832 $form = new Form($this->db);
2833 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2834 }
2835 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2836 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2837 }
2838 if (isModEnabled('accounting') && $this->fournisseur) {
2839 $langs->load('compta');
2840 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2841 }
2842 // show categories for this record only in ajax to not overload lists
2843 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2844 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2845 $form = new Form($this->db);
2846 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2847 }
2848
2849 $datas['divclose'] = '</div>';
2850
2851 return $datas;
2852 }
2853
2867 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
2868 {
2869 global $conf, $langs, $hookmanager, $user;
2870
2871 if (!empty($conf->dol_no_mouse_hover)) {
2872 $notooltip = 1; // Force disable tooltips
2873 }
2874
2875 $name = $this->name ? $this->name : $this->nom;
2876
2877 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
2878 if (empty($option) && $this->client > 0) {
2879 $option = 'customer';
2880 }
2881 if (empty($option) && $this->fournisseur > 0) {
2882 $option = 'supplier';
2883 }
2884 }
2885
2886 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
2887 $code = '';
2888 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
2889 $code = $this->code_client.' - ';
2890 }
2891
2892 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
2893 $code .= $this->code_fournisseur.' - ';
2894 }
2895
2896 if ($code) {
2897 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
2898 $name = $code.' '.$name;
2899 } else {
2900 $name = $code;
2901 }
2902 }
2903 }
2904
2905 if (!empty($this->name_alias) && empty($noaliasinname)) {
2906 $name .= ' ('.$this->name_alias.')';
2907 }
2908
2909 $result = '';
2910 $params = [
2911 'id' => $this->id,
2912 'objecttype' => $this->element,
2913 'option' => $option,
2914 'nofetch' => 1,
2915 ];
2916 $classfortooltip = 'classfortooltip';
2917 $dataparams = '';
2918 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2919 $classfortooltip = 'classforajaxtooltip';
2920 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2921 $label = '';
2922 } else {
2923 $label = implode($this->getTooltipContentArray($params));
2924 }
2925
2926 $linkstart = '';
2927 $linkend = '';
2928
2929 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2930 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2931 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2932 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2933 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2934 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2935 } elseif ($option == 'agenda') {
2936 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2937 } elseif ($option == 'project') {
2938 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2939 } elseif ($option == 'margin') {
2940 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2941 } elseif ($option == 'contact') {
2942 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2943 } elseif ($option == 'ban') {
2944 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2945 }
2946
2947 // By default
2948 if (empty($linkstart)) {
2949 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2950 }
2951
2952 // Add type of canvas
2953 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2954 // Add param to save lastsearch_values or not
2955 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2956 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2957 $add_save_lastsearch_values = 1;
2958 }
2959 if ($add_save_lastsearch_values) {
2960 $linkstart .= '&save_lastsearch_values=1';
2961 }
2962 $linkstart .= '"';
2963
2964 $linkclose = '';
2965 if (empty($notooltip)) {
2966 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2967 $label = $langs->trans("ShowCompany");
2968 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2969 }
2970 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2971 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
2972 $target_value = array('_self', '_blank', '_parent', '_top');
2973 if (in_array($target, $target_value)) {
2974 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2975 }
2976 } else {
2977 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
2978 }
2979 $linkstart .= $linkclose.'>';
2980 $linkend = '</a>';
2981
2982 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
2983 $linkstart = '';
2984 $linkend = '';
2985 }
2986
2987 $result .= $linkstart;
2988 if ($withpicto) {
2989 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2990 }
2991 if ($withpicto != 2) {
2992 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2993 }
2994 $result .= $linkend;
2995
2996 global $action;
2997 $hookmanager->initHooks(array('thirdpartydao'));
2998 $parameters = array(
2999 'id' => $this->id,
3000 'getnomurl' => &$result,
3001 'withpicto ' => $withpicto,
3002 'option' => $option,
3003 'maxlen' => $maxlen,
3004 'notooltip' => $notooltip,
3005 'save_lastsearch_value' => $save_lastsearch_value
3006 );
3007 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3008 if ($reshook > 0) {
3009 $result = $hookmanager->resPrint;
3010 } else {
3011 $result .= $hookmanager->resPrint;
3012 }
3013
3014 return $result;
3015 }
3016
3026 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3027 {
3028 global $conf, $langs;
3029
3030 $s = '';
3031 if (empty($option) || preg_match('/prospect/', $option)) {
3032 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3033 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3034 }
3035 }
3036 if (empty($option) || preg_match('/customer/', $option)) {
3037 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3038 $s .= '<'.$tag.' class="customer-back" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3039 }
3040 }
3041 if (empty($option) || preg_match('/supplier/', $option)) {
3042 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3043 $s .= '<'.$tag.' class="vendor-back" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3044 }
3045 }
3046 return $s;
3047 }
3048
3049
3056 public function getLibStatut($mode = 0)
3057 {
3058 return $this->LibStatut($this->status, $mode);
3059 }
3060
3061 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3069 public function LibStatut($status, $mode = 0)
3070 {
3071 // phpcs:enable
3072 global $langs;
3073 $langs->load('companies');
3074
3075 $statusType = 'status4';
3076 if ($status == 0) {
3077 $statusType = 'status6';
3078 }
3079
3080 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3081 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3082 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3083 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3084 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3085 }
3086
3087 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3088 }
3089
3090 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3097 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3098 {
3099 // phpcs:enable
3100 global $langs;
3101
3102 $contact_emails = $this->contact_property_array('email', 1);
3103
3104 if ($this->email && $addthirdparty) {
3105 if (empty($this->name)) {
3106 $this->name = $this->nom;
3107 }
3108 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3109 }
3110
3111 //var_dump($contact_emails)
3112 return $contact_emails;
3113 }
3114
3115 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3122 {
3123 // phpcs:enable
3124 global $langs;
3125
3126 $contact_phone = $this->contact_property_array('mobile');
3127
3128 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3129 if (empty($this->name)) {
3130 $this->name = $this->nom;
3131 }
3132 // TODO: Tester si tel non deja present dans tableau contact
3133 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3134 }
3135 return $contact_phone;
3136 }
3137
3138 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3146 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3147 {
3148 // phpcs:enable
3149 global $langs;
3150
3151 $contact_property = array();
3152
3153
3154 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3155 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3156 $sql .= " WHERE fk_soc = ".((int) $this->id);
3157 $sql .= " AND entity IN (".getEntity($this->element).")";
3158 $sql .= " ORDER BY lastname, firstname";
3159
3160 $resql = $this->db->query($sql);
3161 if ($resql) {
3162 $nump = $this->db->num_rows($resql);
3163 if ($nump) {
3164 $sepa = "(";
3165 $sepb = ")";
3166 if ($mode == 'email') {
3167 //$sepa="&lt;"; $sepb="&gt;";
3168 $sepa = "<";
3169 $sepb = ">";
3170 }
3171 $i = 0;
3172 while ($i < $nump) {
3173 $obj = $this->db->fetch_object($resql);
3174 if ($mode == 'email') {
3175 $property = $obj->email;
3176 } elseif ($mode == 'mobile') {
3177 $property = $obj->phone_mobile;
3178 } else {
3179 $property = $obj->$mode;
3180 }
3181
3182 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3183 if ($obj->status == 1 || empty($hidedisabled)) {
3184 if (empty($property)) {
3185 if ($mode == 'email') {
3186 $property = $langs->transnoentitiesnoconv("NoEMail");
3187 } elseif ($mode == 'mobile') {
3188 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3189 }
3190 }
3191
3192 if (!empty($obj->poste)) {
3193 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3194 } else {
3195 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3196 }
3197 }
3198 $i++;
3199 }
3200 }
3201 } else {
3202 dol_print_error($this->db);
3203 }
3204 return $contact_property;
3205 }
3206
3207
3208 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3214 public function contact_array()
3215 {
3216 // phpcs:enable
3217 $contacts = array();
3218
3219 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3220 $resql = $this->db->query($sql);
3221 if ($resql) {
3222 $nump = $this->db->num_rows($resql);
3223 if ($nump) {
3224 $i = 0;
3225 while ($i < $nump) {
3226 $obj = $this->db->fetch_object($resql);
3227 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3228 $i++;
3229 }
3230 }
3231 } else {
3232 dol_print_error($this->db);
3233 }
3234 return $contacts;
3235 }
3236
3237 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3243 public function contact_array_objects()
3244 {
3245 // phpcs:enable
3246 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3247 $contacts = array();
3248
3249 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3250 $resql = $this->db->query($sql);
3251 if ($resql) {
3252 $nump = $this->db->num_rows($resql);
3253 if ($nump) {
3254 $i = 0;
3255 while ($i < $nump) {
3256 $obj = $this->db->fetch_object($resql);
3257 $contact = new Contact($this->db);
3258 $contact->fetch($obj->rowid);
3259 $contacts[] = $contact;
3260 $i++;
3261 }
3262 }
3263 } else {
3264 dol_print_error($this->db);
3265 }
3266 return $contacts;
3267 }
3268
3269 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3277 public function contact_get_property($rowid, $mode)
3278 {
3279 // phpcs:enable
3280 $contact_property = '';
3281
3282 if (empty($rowid)) {
3283 return '';
3284 }
3285
3286 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3287 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3288 $sql .= " WHERE rowid = ".((int) $rowid);
3289
3290 $resql = $this->db->query($sql);
3291 if ($resql) {
3292 $nump = $this->db->num_rows($resql);
3293
3294 if ($nump) {
3295 $obj = $this->db->fetch_object($resql);
3296
3297 if ($mode == 'email') {
3298 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3299 } elseif ($mode == 'mobile') {
3300 $contact_property = $obj->phone_mobile;
3301 }
3302 }
3303 return $contact_property;
3304 } else {
3305 dol_print_error($this->db);
3306 }
3307
3308 return '';
3309 }
3310
3311
3312 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3319 public function display_rib($mode = 'label')
3320 {
3321 // phpcs:enable
3322 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3323
3324 $bac = new CompanyBankAccount($this->db);
3325 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3326 $bac->fetch(0, '', $this->id);
3327
3328 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3329 if ($mode == 'label') {
3330 return $bac->getRibLabel(true);
3331 } elseif ($mode == 'rum') {
3332 if (empty($bac->rum)) {
3333 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3334 $prelevement = new BonPrelevement($this->db);
3335 $bac->fetch_thirdparty();
3336 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3337 }
3338 return $bac->rum;
3339 } elseif ($mode == 'format') {
3340 return $bac->frstrecur;
3341 } else {
3342 return 'BadParameterToFunctionDisplayRib';
3343 }
3344 } else {
3345 return '';
3346 }
3347 }
3348
3349 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3355 public function get_all_rib()
3356 {
3357 // phpcs:enable
3358 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3359 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3360 $result = $this->db->query($sql);
3361 if (!$result) {
3362 $this->error++;
3363 $this->errors[] = $this->db->lasterror;
3364 return 0;
3365 } else {
3366 $num_rows = $this->db->num_rows($result);
3367 $rib_array = array();
3368 if ($num_rows) {
3369 while ($obj = $this->db->fetch_object($result)) {
3370 $rib = new CompanyBankAccount($this->db);
3371 $rib->fetch($obj->rowid);
3372 $rib_array[] = $rib;
3373 }
3374 }
3375 return $rib_array;
3376 }
3377 }
3378
3379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3388 public function get_codeclient($objsoc = null, $type = 0)
3389 {
3390 // phpcs:enable
3391 global $conf;
3392 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3393 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3394
3395 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3396 foreach ($dirsociete as $dirroot) {
3397 $res = dol_include_once($dirroot.$module.'.php');
3398 if ($res) {
3399 break;
3400 }
3401 }
3403 $mod = new $module($this->db);
3404
3405 $this->code_client = $mod->getNextValue($objsoc, $type);
3406 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3407
3408 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3409 }
3410 }
3411
3412 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3421 public function get_codefournisseur($objsoc = null, $type = 1)
3422 {
3423 // phpcs:enable
3424 global $conf;
3425 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3426 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3427
3428 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3429 foreach ($dirsociete as $dirroot) {
3430 $res = dol_include_once($dirroot.$module.'.php');
3431 if ($res) {
3432 break;
3433 }
3434 }
3436 $mod = new $module($this->db);
3437
3438 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3439
3440 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3441 }
3442 }
3443
3444 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3451 public function codeclient_modifiable()
3452 {
3453 // phpcs:enable
3454 global $conf;
3455 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3456 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3457
3458 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3459 foreach ($dirsociete as $dirroot) {
3460 $res = dol_include_once($dirroot.$module.'.php');
3461 if ($res) {
3462 break;
3463 }
3464 }
3465
3466 $mod = new $module($this->db);
3467
3468 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3469 if ($mod->code_modifiable_null && !$this->code_client) {
3470 return 1;
3471 }
3472 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3473 return 1;
3474 }
3475 if ($mod->code_modifiable) {
3476 return 1; // A mettre en dernier
3477 }
3478 return 0;
3479 } else {
3480 return 0;
3481 }
3482 }
3483
3484
3485 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3492 {
3493 // phpcs:enable
3494 global $conf;
3495 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3496 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3497
3498 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3499 foreach ($dirsociete as $dirroot) {
3500 $res = dol_include_once($dirroot.$module.'.php');
3501 if ($res) {
3502 break;
3503 }
3504 }
3505
3506 $mod = new $module($this->db);
3507
3508 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3509 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3510 return 1;
3511 }
3512 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3513 return 1;
3514 }
3515 if ($mod->code_modifiable) {
3516 return 1; // A mettre en dernier
3517 }
3518 return 0;
3519 } else {
3520 return 0;
3521 }
3522 }
3523
3524
3525 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3537 public function check_codeclient()
3538 {
3539 // phpcs:enable
3540 global $conf;
3541 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3542 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3543
3544 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3545 foreach ($dirsociete as $dirroot) {
3546 $res = dol_include_once($dirroot.$module.'.php');
3547 if ($res) {
3548 break;
3549 }
3550 }
3551
3552 $mod = new $module($this->db);
3553
3554 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3555 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3556 if ($result) { // If error
3557 $this->error = $mod->error;
3558 $this->errors = $mod->errors;
3559 }
3560 return $result;
3561 } else {
3562 return 0;
3563 }
3564 }
3565
3566 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3578 public function check_codefournisseur()
3579 {
3580 // phpcs:enable
3581 global $conf;
3582 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3583 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3584
3585 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3586 foreach ($dirsociete as $dirroot) {
3587 $res = dol_include_once($dirroot.$module.'.php');
3588 if ($res) {
3589 break;
3590 }
3591 }
3592
3593 $mod = new $module($this->db);
3594
3595 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3596 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3597 if ($result) { // If error
3598 $this->error = $mod->error;
3599 $this->errors = $mod->errors;
3600 }
3601 return $result;
3602 } else {
3603 return 0;
3604 }
3605 }
3606
3607 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3616 public function get_codecompta($type)
3617 {
3618 // phpcs:enable
3619 global $conf;
3620
3621 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3622 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3623 $res = false;
3624 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3625 foreach ($dirsociete as $dirroot) {
3626 $res = dol_include_once($dirroot.$module.'.php');
3627 if ($res) {
3628 break;
3629 }
3630 }
3631
3632 if ($res) {
3633 $mod = new $module();
3634
3635 // Set code count in $mod->code
3636 $result = $mod->get_code($this->db, $this, $type);
3637
3638 if ($type == 'customer') {
3639 $this->code_compta_client = $mod->code;
3640 $this->code_compta = $this->code_compta_client; // For backward compatibility
3641 } elseif ($type == 'supplier') {
3642 $this->code_compta_fournisseur = $mod->code;
3643 }
3644
3645 return $result;
3646 } else {
3647 $this->error = 'ErrorAccountancyCodeNotDefined';
3648 return -1;
3649 }
3650 } else {
3651 if ($type == 'customer') {
3652 $this->code_compta_client = '';
3653 $this->code_compta = '';
3654 } elseif ($type == 'supplier') {
3655 $this->code_compta_fournisseur = '';
3656 }
3657
3658 return 0;
3659 }
3660 }
3661
3668 public function setParent($id)
3669 {
3670 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3671
3672 if ($this->id) {
3673 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3674 if ($id > 0) {
3675 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3676 if ($sameparent < 0) {
3677 return -1;
3678 }
3679 if ($sameparent == 1) {
3680 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3681 return -1;
3682 }
3683 }
3684
3685 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3686
3687 $resql = $this->db->query($sql);
3688 if ($resql) {
3689 $this->parent = $id;
3690 return 1;
3691 } else {
3692 return -1;
3693 }
3694 }
3695
3696 return -1;
3697 }
3698
3707 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3708 {
3709 if ($counter > 100) {
3710 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3711 }
3712
3713 $sql = 'SELECT s.parent';
3714 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3715 $sql .= ' WHERE rowid = '.((int) $idparent);
3716 $resql = $this->db->query($sql);
3717 if ($resql) {
3718 $obj = $this->db->fetch_object($resql);
3719
3720 if ($obj->parent == '') {
3721 return 0;
3722 } elseif ($obj->parent == $idchild) {
3723 return 1;
3724 } else {
3725 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3726 }
3727 return $sameparent;
3728 } else {
3729 return -1;
3730 }
3731 }
3732
3740 public function getParentsForCompany($company_id, $parents = array())
3741 {
3742 global $langs;
3743
3744 if ($company_id > 0) {
3745 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3746 $resql = $this->db->query($sql);
3747 if ($resql) {
3748 if ($obj = $this->db->fetch_object($resql)) {
3749 $parent = $obj->parent;
3750 if ($parent > 0 && !in_array($parent, $parents)) {
3751 $parents[] = $parent;
3752 return $this->getParentsForCompany($parent, $parents);
3753 } else {
3754 return $parents;
3755 }
3756 }
3757 $this->db->free($resql);
3758 } else {
3759 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3760 }
3761 }
3762 // Return a default value when $company_id is not greater than 0
3763 return array();
3764 }
3765
3766 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3773 public function id_prof_verifiable($idprof)
3774 {
3775 // phpcs:enable
3776 global $conf;
3777
3778 switch ($idprof) {
3779 case 1:
3780 $ret = (!getDolGlobalString('SOCIETE_IDPROF1_UNIQUE') ? false : true);
3781 break;
3782 case 2:
3783 $ret = (!getDolGlobalString('SOCIETE_IDPROF2_UNIQUE') ? false : true);
3784 break;
3785 case 3:
3786 $ret = (!getDolGlobalString('SOCIETE_IDPROF3_UNIQUE') ? false : true);
3787 break;
3788 case 4:
3789 $ret = (!getDolGlobalString('SOCIETE_IDPROF4_UNIQUE') ? false : true);
3790 break;
3791 case 5:
3792 $ret = (!getDolGlobalString('SOCIETE_IDPROF5_UNIQUE') ? false : true);
3793 break;
3794 case 6:
3795 $ret = (!getDolGlobalString('SOCIETE_IDPROF6_UNIQUE') ? false : true);
3796 break;
3797 default:
3798 $ret = false;
3799 }
3800
3801 return $ret;
3802 }
3803
3804 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3813 public function id_prof_exists($idprof, $value, $socid = 0)
3814 {
3815 // phpcs:enable
3816 $field = $idprof;
3817
3818 switch ($idprof) { // For backward compatibility
3819 case '1':
3820 case 'idprof1':
3821 $field = "siren";
3822 break;
3823 case '2':
3824 case 'idprof2':
3825 $field = "siret";
3826 break;
3827 case '3':
3828 case 'idprof3':
3829 $field = "ape";
3830 break;
3831 case '4':
3832 case 'idprof4':
3833 $field = "idprof4";
3834 break;
3835 case '5':
3836 $field = "idprof5";
3837 break;
3838 case '6':
3839 $field = "idprof6";
3840 break;
3841 }
3842
3843 //Verify duplicate entries
3844 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3845 if ($socid) {
3846 $sql .= " AND rowid <> ".$socid;
3847 }
3848 $resql = $this->db->query($sql);
3849 if ($resql) {
3850 $obj = $this->db->fetch_object($resql);
3851 $count = $obj->nb;
3852 } else {
3853 $count = 0;
3854 print $this->db->error();
3855 }
3856 $this->db->free($resql);
3857
3858 if ($count > 0) {
3859 return true;
3860 } else {
3861 return false;
3862 }
3863 }
3864
3865 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3874 public function id_prof_check($idprof, $soc)
3875 {
3876 // phpcs:enable
3877 global $conf;
3878
3879 // load the library necessary to check the professional identifiers
3880 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
3881
3882 $ok = 1;
3883
3884 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3885 return 1;
3886 }
3887
3888 // Check SIREN
3889 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
3890 return -1;
3891 }
3892
3893 // Check SIRET
3894 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
3895 return -1;
3896 }
3897
3898 //Verify CIF/NIF/NIE if pays ES
3899 if ($idprof == 1 && $soc->country_code == 'ES') {
3900 return isValidTinForES($this->idprof1);
3901 }
3902
3903 //Verify NIF if country is PT
3904 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
3905 return -1;
3906 }
3907
3908 //Verify NIF if country is DZ
3909 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
3910 return -1;
3911 }
3912
3913 //Verify ID Prof 1 if country is BE
3914 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
3915 return -1;
3916 }
3917
3918 return $ok;
3919 }
3920
3921 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3930 public function id_prof_url($idprof, $thirdparty)
3931 {
3932 // phpcs:enable
3933 global $conf, $langs, $hookmanager;
3934
3935 $url = '';
3936 $action = '';
3937
3938 $hookmanager->initHooks(array('idprofurl'));
3939 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
3940 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3941 if (empty($reshook)) {
3942 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3943 return '';
3944 }
3945
3946 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3947 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3948 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3949 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3950 }
3951 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3952 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3953 }
3954 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3955 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3956 }
3957 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3958 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3959 }
3960 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
3961 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
3962 }
3963 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3964 $url = 'http://www.nif.pt/'.$strippedIdProf1;
3965 }
3966
3967 if ($url) {
3968 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3969 }
3970 } else {
3971 return $hookmanager->resPrint;
3972 }
3973
3974 return '';
3975 }
3976
3977 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3983 public function has_projects()
3984 {
3985 // phpcs:enable
3986 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3987 $resql = $this->db->query($sql);
3988 if ($resql) {
3989 $obj = $this->db->fetch_object($resql);
3990 $count = $obj->numproj;
3991 } else {
3992 $count = 0;
3993 print $this->db->error();
3994 }
3995 $this->db->free($resql);
3996 return ($count > 0);
3997 }
3998
3999
4006 public function info($id)
4007 {
4008 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4009 $sql .= " fk_user_creat, fk_user_modif";
4010 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4011 $sql .= " WHERE s.rowid = ".((int) $id);
4012
4013 $result = $this->db->query($sql);
4014 if ($result) {
4015 if ($this->db->num_rows($result)) {
4016 $obj = $this->db->fetch_object($result);
4017
4018 $this->id = $obj->rowid;
4019
4020 $this->user_creation_id = $obj->fk_user_creat;
4021 $this->user_modification_id = $obj->fk_user_modif;
4022 $this->date_creation = $this->db->jdate($obj->datec);
4023 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4024
4025 $this->ref = $obj->name;
4026 }
4027
4028 $this->db->free($result);
4029 } else {
4030 dol_print_error($this->db);
4031 }
4032 }
4033
4039 public function isACompany()
4040 {
4041 // Define if third party is treated as company (or not) when nature is unknown
4042 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4043
4044 // Now try to guess using different tips
4045 if (!empty($this->tva_intra)) {
4046 $isACompany = 1;
4047 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4048 $isACompany = 1;
4049 } else {
4050 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4051 // TODO Add a field is_a_company into dictionary
4052 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4053 $isACompany = 0;
4054 } else {
4055 $isACompany = 1;
4056 }
4057 } else {
4058 $isACompany = 1;
4059 }
4060 }
4061
4062 return (bool) $isACompany;
4063 }
4064
4070 public function isInEEC()
4071 {
4072 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4073 return isInEEC($this);
4074 }
4075
4076 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4082 public function LoadSupplierCateg()
4083 {
4084 // phpcs:enable
4085 $this->SupplierCategories = array();
4086 $sql = "SELECT rowid, label";
4087 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4088 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4089
4090 $resql = $this->db->query($sql);
4091 if ($resql) {
4092 while ($obj = $this->db->fetch_object($resql)) {
4093 $this->SupplierCategories[$obj->rowid] = $obj->label;
4094 }
4095 return 0;
4096 } else {
4097 return -1;
4098 }
4099 }
4100
4101 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4108 public function AddFournisseurInCategory($categorie_id)
4109 {
4110 // phpcs:enable
4111 if ($categorie_id > 0 && $this->id > 0) {
4112 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4113 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4114
4115 if ($resql = $this->db->query($sql)) {
4116 return 0;
4117 }
4118 } else {
4119 return 0;
4120 }
4121 return -1;
4122 }
4123
4129 public function getNbOfEMailings()
4130 {
4131 $sql = "SELECT count(mc.email) as nb";
4132 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4133 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4134 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4135
4136 $resql = $this->db->query($sql);
4137 if ($resql) {
4138 $obj = $this->db->fetch_object($resql);
4139 $nb = $obj->nb;
4140
4141 $this->db->free($resql);
4142 return $nb;
4143 } else {
4144 $this->error = $this->db->error();
4145 return -1;
4146 }
4147 }
4148
4155 public function setNoEmail($no_email)
4156 {
4157 $error = 0;
4158
4159 // Update mass emailing flag into table mailing_unsubscribe
4160 if ($this->email) {
4161 $this->db->begin();
4162
4163 if ($no_email) {
4164 $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)."'";
4165 $resql = $this->db->query($sql);
4166 if ($resql) {
4167 $obj = $this->db->fetch_object($resql);
4168 $noemail = $obj->nb;
4169 if (empty($noemail)) {
4170 $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())."')";
4171 $resql = $this->db->query($sql);
4172 if (!$resql) {
4173 $error++;
4174 $this->error = $this->db->lasterror();
4175 $this->errors[] = $this->error;
4176 }
4177 }
4178 } else {
4179 $error++;
4180 $this->error = $this->db->lasterror();
4181 $this->errors[] = $this->error;
4182 }
4183 } else {
4184 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4185 $resql = $this->db->query($sql);
4186 if (!$resql) {
4187 $error++;
4188 $this->error = $this->db->lasterror();
4189 $this->errors[] = $this->error;
4190 }
4191 }
4192
4193 if (empty($error)) {
4194 $this->no_email = $no_email;
4195 $this->db->commit();
4196 return 1;
4197 } else {
4198 $this->db->rollback();
4199 return $error * -1;
4200 }
4201 }
4202
4203 return 0;
4204 }
4205
4212 public function getNoEmail()
4213 {
4214 if ($this->email) {
4215 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4216 $resql = $this->db->query($sql);
4217 if ($resql) {
4218 $obj = $this->db->fetch_object($resql);
4219 $this->no_email = $obj->nb;
4220 return 1;
4221 } else {
4222 $this->error = $this->db->lasterror();
4223 $this->errors[] = $this->error;
4224 return -1;
4225 }
4226 }
4227 return 0;
4228 }
4229
4230 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4240 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4241 {
4242 // phpcs:enable
4243 global $conf, $user, $langs;
4244
4245 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4246 $fullname = $member->getFullName($langs);
4247
4248 if ($member->morphy == 'mor') {
4249 if (empty($socname)) {
4250 $socname = $member->company ? $member->company : $member->societe;
4251 }
4252 if (!empty($fullname) && empty($socalias)) {
4253 $socalias = $fullname;
4254 }
4255 } elseif (empty($socname) && $member->morphy == 'phy') {
4256 if (empty($socname)) {
4257 $socname = $fullname;
4258 }
4259 if (!empty($member->company) && empty($socalias)) {
4260 $socalias = $member->company;
4261 }
4262 }
4263
4264 $name = $socname;
4265 $alias = $socalias ? $socalias : '';
4266
4267 // Positionne parameters
4268 $this->nom = $name; // TODO deprecated
4269 $this->name = $name;
4270 $this->name_alias = $alias;
4271 $this->address = $member->address;
4272 $this->zip = $member->zip;
4273 $this->town = $member->town;
4274 $this->country_code = $member->country_code;
4275 $this->country_id = $member->country_id;
4276 $this->phone = $member->phone; // Prof phone
4277 $this->email = $member->email;
4278 $this->socialnetworks = $member->socialnetworks;
4279 $this->entity = $member->entity;
4280
4281 $this->client = 1; // A member is a customer by default
4282 $this->code_client = ($customercode ? $customercode : -1);
4283 $this->code_fournisseur = '-1';
4284 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4285 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4286
4287 $this->db->begin();
4288
4289 // Cree et positionne $this->id
4290 $result = $this->create($user);
4291
4292 if ($result >= 0) {
4293 // Auto-create contact on thirdparty creation
4294 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4295 // Fill fields needed by contact
4296 $this->name_bis = $member->lastname;
4297 $this->firstname = $member->firstname;
4298 $this->civility_id = $member->civility_id;
4299
4300 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4301 $result = $this->create_individual($user);
4302
4303 if ($result < 0) {
4304 setEventMessages($this->error, $this->errors, 'errors');
4305 $this->db->rollback();
4306 return -1;
4307 }
4308 }
4309
4310 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4311 $sql .= " SET fk_soc = ".((int) $this->id);
4312 $sql .= " WHERE rowid = ".((int) $member->id);
4313
4314 $resql = $this->db->query($sql);
4315 if ($resql) {
4316 $this->db->commit();
4317 return $this->id;
4318 } else {
4319 $this->error = $this->db->error();
4320
4321 $this->db->rollback();
4322 return -1;
4323 }
4324 } else {
4325 // $this->error deja positionne
4326 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4327
4328 $this->db->rollback();
4329 return $result;
4330 }
4331 }
4332
4339 public function setMysoc(Conf $conf)
4340 {
4341 global $langs;
4342
4343 $this->id = 0;
4344 $this->entity = $conf->entity;
4345 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4346 $this->nom = $this->name; // deprecated
4347 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4348 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4349 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4350 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4351
4352 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4353
4354 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4355
4356 // We define country_id, country_code and country
4357 $country_id = 0;
4358 $country_code = $country_label = '';
4359 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4360 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4361 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4362 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4363 $country_code = $tmp[1];
4364 $country_label = $tmp[2];
4365 } else {
4366 // For backward compatibility
4367 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4368 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4369 $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
4370 $country_label = getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4371 }
4372 }
4373 $this->country_id = $country_id;
4374 $this->country_code = $country_code;
4375 $this->country = $country_label;
4376 if (is_object($langs)) {
4377 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4378 }
4379
4380 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4381 // We define state_id, state_code and state
4382 $state_id = 0;
4383 $state_code = $state_label = '';
4384 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4385 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4386 $state_id = $tmp[0];
4387 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4388 $state_code = $tmp[1];
4389 $state_label = $tmp[2];
4390 } else { // For backward compatibility
4391 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);
4392 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4393 $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
4394 $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
4395 }
4396 }
4397 $this->state_id = $state_id;
4398 $this->state_code = $state_code;
4399 $this->state = $state_label;
4400 if (is_object($langs)) {
4401 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4402 }
4403
4404 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4405 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4406 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4407 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4408
4409 // Social networks
4410 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4411 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4412 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4413 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4414 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4415 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4416 $this->socialnetworks = array();
4417 if (!empty($facebook_url)) {
4418 $this->socialnetworks['facebook'] = $facebook_url;
4419 }
4420 if (!empty($twitter_url)) {
4421 $this->socialnetworks['twitter'] = $twitter_url;
4422 }
4423 if (!empty($linkedin_url)) {
4424 $this->socialnetworks['linkedin'] = $linkedin_url;
4425 }
4426 if (!empty($instagram_url)) {
4427 $this->socialnetworks['instagram'] = $instagram_url;
4428 }
4429 if (!empty($youtube_url)) {
4430 $this->socialnetworks['youtube'] = $youtube_url;
4431 }
4432 if (!empty($github_url)) {
4433 $this->socialnetworks['github'] = $github_url;
4434 }
4435
4436 // Id prof generiques
4437 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4438 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4439 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4440 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4441 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4442 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4443 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4444 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4445 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4446 $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4447 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4448 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4449 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4450 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4451 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4452 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4453 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4454 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4455
4456 // Define if company use vat or not
4457 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4458
4459 // Define if company use local taxes
4460 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4461 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4462 }
4463
4471 public function initAsSpecimen()
4472 {
4473 $now = dol_now();
4474
4475 // Initialize parameters
4476 $this->id = 0;
4477 $this->entity = 1;
4478 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4479 $this->nom = $this->name; // For backward compatibility
4480 $this->ref_ext = 'Ref ext';
4481 $this->specimen = 1;
4482 $this->address = '21 jump street';
4483 $this->zip = '99999';
4484 $this->town = 'MyTown';
4485 $this->state_id = 1;
4486 $this->state_code = 'AA';
4487 $this->state = 'MyState';
4488 $this->country_id = 1;
4489 $this->country_code = 'FR';
4490 $this->email = 'specimen@specimen.com';
4491 $this->socialnetworks = array(
4492 'skype' => 'skypepseudo',
4493 'twitter' => 'twitterpseudo',
4494 'facebook' => 'facebookpseudo',
4495 'linkedin' => 'linkedinpseudo',
4496 );
4497 $this->url = 'http://www.specimen.com';
4498
4499 $this->phone = '0909090901';
4500 $this->phone_mobile = '0909090901';
4501 $this->fax = '0909090909';
4502
4503 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4504 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4505 $this->typent_code = 'TE_OTHER';
4506 $this->capital = 10000;
4507 $this->client = 1;
4508 $this->prospect = 1;
4509 $this->fournisseur = 1;
4510 $this->tva_assuj = 1;
4511 $this->tva_intra = 'EU1234567';
4512 $this->note_public = 'This is a comment (public)';
4513 $this->note_private = 'This is a comment (private)';
4514
4515 $this->idprof1 = 'idprof1';
4516 $this->idprof2 = 'idprof2';
4517 $this->idprof3 = 'idprof3';
4518 $this->idprof4 = 'idprof4';
4519 $this->idprof5 = 'idprof5';
4520 $this->idprof6 = 'idprof6';
4521
4522 return 1;
4523 }
4524
4531 public function useLocalTax($localTaxNum = 0)
4532 {
4533 $sql = "SELECT t.localtax1, t.localtax2";
4534 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4535 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4536 $sql .= " AND t.active = 1";
4537 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4538 if (empty($localTaxNum)) {
4539 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4540 } elseif ($localTaxNum == 1) {
4541 $sql .= " AND t.localtax1_type <> '0'";
4542 } elseif ($localTaxNum == 2) {
4543 $sql .= " AND t.localtax2_type <> '0'";
4544 }
4545
4546 $resql = $this->db->query($sql);
4547 if ($resql) {
4548 return ($this->db->num_rows($resql) > 0);
4549 } else {
4550 return false;
4551 }
4552 }
4553
4559 public function useNPR()
4560 {
4561 $sql = "SELECT t.rowid";
4562 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4563 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4564 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4565 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4566
4567 dol_syslog("useNPR", LOG_DEBUG);
4568 $resql = $this->db->query($sql);
4569 if ($resql) {
4570 return ($this->db->num_rows($resql) > 0);
4571 } else {
4572 return false;
4573 }
4574 }
4575
4582 public function useRevenueStamp()
4583 {
4584 $sql = "SELECT COUNT(*) as nb";
4585 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4586 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4587 $sql .= " AND r.active = 1";
4588
4589 dol_syslog("useRevenueStamp", LOG_DEBUG);
4590 $resql = $this->db->query($sql);
4591 if ($resql) {
4592 $obj = $this->db->fetch_object($resql);
4593 return (($obj->nb > 0) ? true : false);
4594 } else {
4595 $this->error = $this->db->lasterror();
4596 return false;
4597 }
4598 }
4599
4605 public function getLibProspLevel()
4606 {
4607 return $this->LibProspLevel($this->fk_prospectlevel);
4608 }
4609
4610 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4617 public function LibProspLevel($fk_prospectlevel)
4618 {
4619 // phpcs:enable
4620 global $langs;
4621
4622 $label = '';
4623 if ($fk_prospectlevel != '') {
4624 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4625 // If label is not found in language file, we get label from cache/database
4626 if ($label == "ProspectLevel".$fk_prospectlevel) {
4627 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4628 }
4629 }
4630
4631 return $label;
4632 }
4633
4641 public function getLibProspCommStatut($mode = 0, $label = '')
4642 {
4643 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4644 }
4645
4646 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4660 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4661 {
4662 // phpcs:enable
4663 global $langs;
4664
4665 $langs->load('customers');
4666
4667 if ($mode == 2) {
4668 if ($status == '-1' || $status == 'ST_NO') {
4669 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4670 } elseif ($status == '0' || $status == 'ST_NEVER') {
4671 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4672 } elseif ($status == '1' || $status == 'ST_TODO') {
4673 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4674 } elseif ($status == '2' || $status == 'ST_PEND') {
4675 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4676 } elseif ($status == '3' || $status == 'ST_DONE') {
4677 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4678 } else {
4679 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);
4680 }
4681 } elseif ($mode == 3) {
4682 if ($status == '-1' || $status == 'ST_NO') {
4683 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4684 } elseif ($status == '0' || $status == 'ST_NEVER') {
4685 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4686 } elseif ($status == '1' || $status == 'ST_TODO') {
4687 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4688 } elseif ($status == '2' || $status == 'ST_PEND') {
4689 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4690 } elseif ($status == '3' || $status == 'ST_DONE') {
4691 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4692 } else {
4693 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4694 }
4695 } elseif ($mode == 4) {
4696 if ($status == '-1' || $status == 'ST_NO') {
4697 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4698 } elseif ($status == '0' || $status == 'ST_NEVER') {
4699 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4700 } elseif ($status == '1' || $status == 'ST_TODO') {
4701 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4702 } elseif ($status == '2' || $status == 'ST_PEND') {
4703 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4704 } elseif ($status == '3' || $status == 'ST_DONE') {
4705 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4706 } else {
4707 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);
4708 }
4709 }
4710
4711 return "Error, mode/status not found";
4712 }
4713
4720 public function getOutstandingProposals($mode = 'customer')
4721 {
4722 $table = 'propal';
4723 if ($mode == 'supplier') {
4724 $table = 'supplier_proposal';
4725 }
4726
4727 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4728 $sql .= " WHERE fk_soc = ".((int) $this->id);
4729 if ($mode == 'supplier') {
4730 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4731 } else {
4732 $sql .= " AND entity IN (".getEntity('propal').")";
4733 }
4734
4735 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4736
4737 $resql = $this->db->query($sql);
4738 if ($resql) {
4739 $outstandingOpened = 0;
4740 $outstandingTotal = 0;
4741 $outstandingTotalIncTax = 0;
4742 $arrayofref = array();
4743 while ($obj = $this->db->fetch_object($resql)) {
4744 $arrayofref[$obj->rowid] = $obj->ref;
4745 $outstandingTotal += $obj->total_ht;
4746 $outstandingTotalIncTax += $obj->total_ttc;
4747 if ($obj->status != 0) {
4748 // Not a draft
4749 $outstandingOpened += $obj->total_ttc;
4750 }
4751 }
4752 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4753 } else {
4754 return array();
4755 }
4756 }
4757
4764 public function getOutstandingOrders($mode = 'customer')
4765 {
4766 $table = 'commande';
4767 if ($mode == 'supplier') {
4768 $table = 'commande_fournisseur';
4769 }
4770
4771 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4772 $sql .= " WHERE fk_soc = ".((int) $this->id);
4773 if ($mode == 'supplier') {
4774 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4775 } else {
4776 $sql .= " AND entity IN (".getEntity('commande').")";
4777 }
4778
4779 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4780 $resql = $this->db->query($sql);
4781 if ($resql) {
4782 $outstandingOpened = 0;
4783 $outstandingTotal = 0;
4784 $outstandingTotalIncTax = 0;
4785 $arrayofref = array();
4786 while ($obj = $this->db->fetch_object($resql)) {
4787 $arrayofref[$obj->rowid] = $obj->ref;
4788 $outstandingTotal += $obj->total_ht;
4789 $outstandingTotalIncTax += $obj->total_ttc;
4790 if ($obj->status != 0) {
4791 // Not a draft
4792 $outstandingOpened += $obj->total_ttc;
4793 }
4794 }
4795 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4796 } else {
4797 return array();
4798 }
4799 }
4800
4808 public function getOutstandingBills($mode = 'customer', $late = 0)
4809 {
4810 $table = 'facture';
4811 if ($mode == 'supplier') {
4812 $table = 'facture_fourn';
4813 }
4814
4815 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4816 $paiement = $invoice->getSommePaiement();
4817 $creditnotes=$invoice->getSumCreditNotesUsed();
4818 $deposits=$invoice->getSumDepositsUsed();
4819 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4820 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4821 */
4822 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4823 $sql .= " WHERE fk_soc = ".((int) $this->id);
4824 if (!empty($late)) {
4825 $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4826 }
4827 if ($mode == 'supplier') {
4828 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4829 } else {
4830 $sql .= " AND entity IN (".getEntity('invoice').")";
4831 }
4832
4833 dol_syslog("getOutstandingBills", LOG_DEBUG);
4834 $resql = $this->db->query($sql);
4835 if ($resql) {
4836 $outstandingOpened = 0;
4837 $outstandingTotal = 0;
4838 $outstandingTotalIncTax = 0;
4839 $arrayofref = array();
4840 $arrayofrefopened = array();
4841 if ($mode == 'supplier') {
4842 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4843 $tmpobject = new FactureFournisseur($this->db);
4844 } else {
4845 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4846 $tmpobject = new Facture($this->db);
4847 }
4848 while ($obj = $this->db->fetch_object($resql)) {
4849 $arrayofref[$obj->rowid] = $obj->ref;
4850 $tmpobject->id = $obj->rowid;
4851
4852 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4853 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4854 ) {
4855 $outstandingTotal += $obj->total_ht;
4856 $outstandingTotalIncTax += $obj->total_ttc;
4857 }
4858
4859 $remaintopay = 0;
4860
4861 if ($obj->paye == 0
4862 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4863 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
4864 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4865 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
4866 $paiement = $tmpobject->getSommePaiement();
4867 $creditnotes = $tmpobject->getSumCreditNotesUsed();
4868 $deposits = $tmpobject->getSumDepositsUsed();
4869
4870 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4871 $outstandingOpened += $remaintopay;
4872 }
4873
4874 //if credit note is converted but not used
4875 // TODO Do this also for customer ?
4876 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4877 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4878 $remaintopay -= $remainingcreditnote;
4879 $outstandingOpened -= $remainingcreditnote;
4880 }
4881
4882 if ($remaintopay) {
4883 $arrayofrefopened[$obj->rowid] = $obj->ref;
4884 }
4885 }
4886 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
4887 } else {
4888 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4889 return array();
4890 }
4891 }
4892
4899 public function getLibCustProspStatut()
4900 {
4901 return $this->LibCustProspStatut($this->client);
4902 }
4903
4904 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4911 public function LibCustProspStatut($status)
4912 {
4913 // phpcs:enable
4914 global $langs;
4915 $langs->load('companies');
4916
4917 if ($status == 0) {
4918 return $langs->trans("NorProspectNorCustomer");
4919 } elseif ($status == 1) {
4920 return $langs->trans("Customer");
4921 } elseif ($status == 2) {
4922 return $langs->trans("Prospect");
4923 } elseif ($status == 3) {
4924 return $langs->trans("ProspectCustomer");
4925 }
4926
4927 return '';
4928 }
4929
4930
4942 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4943 {
4944 global $langs;
4945
4946 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4947 $modelpath = "core/modules/bank/doc/";
4948
4949 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4950 $companybankaccount = new CompanyBankAccount($this->db);
4951 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4952 if (!$result) {
4953 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4954 }
4955 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4956 $this->last_main_doc = $companybankaccount->last_main_doc;
4957 } else {
4958 // Positionne le modele sur le nom du modele a utiliser
4959 if (!dol_strlen($modele)) {
4960 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
4961 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
4962 } else {
4963 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4964 return 0;
4965 }
4966 }
4967
4968 if (!isset($this->bank_account)) {
4969 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4970 $bac = new CompanyBankAccount($this->db);
4971 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
4972 $result = $bac->fetch(0, '', $this->id);
4973 if ($result > 0) {
4974 $this->bank_account = $bac;
4975 } else {
4976 $this->bank_account = '';
4977 }
4978 }
4979
4980 $modelpath = "core/modules/societe/doc/";
4981
4982 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4983 }
4984
4985 return $result;
4986 }
4987
4988
5000 public function setCategories($categories, $type_categ)
5001 {
5002 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5003
5004 // Decode type
5005 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5006 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5007 return -1;
5008 }
5009
5010 return parent::setCategoriesCommon($categories, $type_categ);
5011 }
5012
5020 public function setSalesRep($salesrep, $onlyAdd = false)
5021 {
5022 global $user;
5023
5024 // Handle single user
5025 if (!is_array($salesrep)) {
5026 $salesrep = array($salesrep);
5027 }
5028
5029 $to_del = array(); // Nothing to delete
5030 $to_add = $salesrep;
5031 if ($onlyAdd === false) {
5032 // Get current users
5033 $existing = $this->getSalesRepresentatives($user, 1);
5034
5035 // Diff
5036 if (is_array($existing)) {
5037 $to_del = array_diff($existing, $salesrep);
5038 $to_add = array_diff($salesrep, $existing);
5039 }
5040 }
5041
5042 $error = 0;
5043
5044 // Process
5045 foreach ($to_del as $del) {
5046 $this->del_commercial($user, $del);
5047 }
5048 foreach ($to_add as $add) {
5049 $result = $this->add_commercial($user, $add);
5050 if ($result < 0) {
5051 $error++;
5052 break;
5053 }
5054 }
5055
5056 return $error ? -1 : 1;
5057 }
5058
5065 public function setThirdpartyType($typent_id)
5066 {
5067 global $user;
5068
5069 dol_syslog(__METHOD__, LOG_DEBUG);
5070
5071 if ($this->id) {
5072 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5073
5074 if ($result > 0) {
5075 $this->typent_id = $typent_id;
5076 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5077 return 1;
5078 } else {
5079 return -1;
5080 }
5081 } else {
5082 return -1;
5083 }
5084 }
5085
5095 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5096 {
5097 if ($origin_id == $dest_id) {
5098 dol_syslog('Error: Try to merge a thirdparty into itself');
5099 return false;
5100 }
5101
5102 // 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.
5103 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5104 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5105 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5106 $sql .= ' SELECT fk_user ';
5107 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5108 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5109
5110 $resql = $dbs->query($sql);
5111 while ($obj = $dbs->fetch_object($resql)) {
5112 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5113 }
5114
5115 // llx_societe_extrafields table must not be here because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5116 // Do not include llx_societe because it will be replaced later.
5117 $tables = array(
5118 'societe_account',
5119 'societe_commerciaux',
5120 'societe_prices',
5121 'societe_remise',
5122 'societe_remise_except',
5123 'societe_rib'
5124 );
5125
5126 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5127 }
5128
5137 public function setAccountancyCode($type, $value)
5138 {
5139 global $user, $langs, $conf;
5140
5141 $this->db->begin();
5142
5143 if ($type == 'buy') {
5144 $field = 'accountancy_code_buy';
5145 } elseif ($type == 'sell') {
5146 $field = 'accountancy_code_sell';
5147 } else {
5148 return -1;
5149 }
5150
5151 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5152 $sql .= $field." = '".$this->db->escape($value)."'";
5153 $sql .= " WHERE rowid = ".((int) $this->id);
5154
5155 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5156 $resql = $this->db->query($sql);
5157
5158 if ($resql) {
5159 // Call triggers
5160 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5161 $interface = new Interfaces($this->db);
5162 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5163 if ($result < 0) {
5164 $this->errors = $interface->errors;
5165 $this->db->rollback();
5166 return -1;
5167 }
5168 // End call triggers
5169
5170 $this->$field = $value;
5171
5172 $this->db->commit();
5173 return 1;
5174 } else {
5175 $this->error = $this->db->lasterror();
5176 $this->db->rollback();
5177 return -1;
5178 }
5179 }
5180
5187 public function fetchPartnerships($mode)
5188 {
5189 global $langs;
5190
5191 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5192
5193
5194 $this->partnerships[] = array();
5195
5196 return 1;
5197 }
5198
5206 public function getKanbanView($option = '', $arraydata = array())
5207 {
5208 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5209
5210 $return = '<div class="box-flex-item box-flex-grow-zero">';
5211 $return .= '<div class="info-box info-box-sm">';
5212 $return .= '<span class="info-box-icon bg-infobox-action">';
5213 $return .= img_picto('', $this->picto);
5214 $return .= '</span>';
5215 $return .= '<div class="info-box-content">';
5216 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5217 if ($selected >= 0) {
5218 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5219 }
5220 if (property_exists($this, 'code_client')) {
5221 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5222 }
5223 if (method_exists($this, 'getLibStatut')) {
5224 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5225 }
5226 $return .= '</div>';
5227 $return .= '</div>';
5228 $return .= '</div>';
5229
5230 return $return;
5231 }
5232
5242 public function getContacts($list = 0, $code = '', $element = '')
5243 {
5244 // phpcs:enable
5245 global $langs;
5246
5247 $tab = array();
5248
5249 $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
5250 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5251 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5252 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5253 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5254 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5255 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5256 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5257 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5258 if (!empty($element)) {
5259 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5260 }
5261 if ($code) {
5262 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5263 }
5264 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5265 $sql .= " AND tc.source = 'external'";
5266 $sql .= " AND tc.active = 1";
5267
5268 $sql .= " ORDER BY t.lastname ASC";
5269
5270 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5271 $resql = $this->db->query($sql);
5272 if ($resql) {
5273 $num = $this->db->num_rows($resql);
5274 $i = 0;
5275 while ($i < $num) {
5276 $obj = $this->db->fetch_object($resql);
5277
5278 if (!$list) {
5279 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5280 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5281 $tab[$i] = array(
5282 'source' => $obj->source,
5283 'socid' => $obj->socid,
5284 'id' => $obj->id,
5285 'nom' => $obj->lastname, // For backward compatibility
5286 'civility' => $obj->civility,
5287 'lastname' => $obj->lastname,
5288 'firstname' => $obj->firstname,
5289 'email' => $obj->email,
5290 'login' => (empty($obj->login) ? '' : $obj->login),
5291 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5292 'statuscontact' => $obj->statuscontact,
5293 'rowid' => $obj->rowid,
5294 'code' => $obj->code,
5295 'element' => $obj->element,
5296 'libelle' => $libelle_type,
5297 'status' => $obj->statuslink,
5298 'fk_c_type_contact' => $obj->fk_c_type_contact
5299 );
5300 } else {
5301 $tab[$i] = $obj->id;
5302 }
5303
5304 $i++;
5305 }
5306
5307 return $tab;
5308 } else {
5309 $this->error = $this->db->lasterror();
5310 dol_print_error($this->db);
5311 return -1;
5312 }
5313 }
5314
5325 public function mergeCompany($soc_origin_id)
5326 {
5327 global $conf, $langs, $hookmanager, $user, $action;
5328
5329 $error = 0;
5330 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5331
5332 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5333
5334 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5335 $this->error = $langs->trans('ErrorRecordNotFound');
5336 $error++;
5337 }
5338
5339 if (!$error) {
5340 $this->db->begin();
5341
5342 // Recopy some data
5343 $this->client |= $soc_origin->client;
5344 $this->fournisseur |= $soc_origin->fournisseur;
5345 $listofproperties = array(
5346 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5347 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5348 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5349 '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',
5350 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5351 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5352 );
5353 foreach ($listofproperties as $property) {
5354 if (empty($this->$property)) {
5355 $this->$property = $soc_origin->$property;
5356 }
5357 }
5358
5359 if ($this->typent_id == -1) {
5360 $this->typent_id = $soc_origin->typent_id;
5361 }
5362
5363 // Concat some data
5364 $listofproperties = array(
5365 'note_public', 'note_private'
5366 );
5367 foreach ($listofproperties as $property) {
5368 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5369 }
5370
5371 // Merge extrafields
5372 if (is_array($soc_origin->array_options)) {
5373 foreach ($soc_origin->array_options as $key => $val) {
5374 if (empty($this->array_options[$key])) {
5375 $this->array_options[$key] = $val;
5376 }
5377 }
5378 }
5379
5380 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5381 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5382 $this->name_bis = $this->name;
5383 }
5384
5385 // Merge categories
5386 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5387 $static_cat = new Categorie($this->db);
5388
5389 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5390 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5391 $custcats = array_merge($custcats, $custcats_ori);
5392 $this->setCategories($custcats, 'customer');
5393
5394 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5395 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5396 $suppcats = array_merge($suppcats, $suppcats_ori);
5397 $this->setCategories($suppcats, 'supplier');
5398
5399 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5400 if ($soc_origin->code_client == $this->code_client
5401 || $soc_origin->code_fournisseur == $this->code_fournisseur
5402 || $soc_origin->barcode == $this->barcode) {
5403 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5404 $soc_origin->code_client = '';
5405 $soc_origin->code_fournisseur = '';
5406 $soc_origin->barcode = '';
5407 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5408 }
5409
5410 // Update
5411 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5412
5413 if ($result < 0) {
5414 $error++;
5415 }
5416
5417 // Move links
5418 if (!$error) {
5419 $objects = array(
5420 'Adherent' => '/adherents/class/adherent.class.php',
5421 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5422 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5423 'Propal' => '/comm/propal/class/propal.class.php',
5424 'Commande' => '/commande/class/commande.class.php',
5425 'Facture' => '/compta/facture/class/facture.class.php',
5426 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5427 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5428 'Contact' => '/contact/class/contact.class.php',
5429 'Contrat' => '/contrat/class/contrat.class.php',
5430 'Expedition' => '/expedition/class/expedition.class.php',
5431 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5432 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5433 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5434 'Reception' => '/reception/class/reception.class.php',
5435 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5436 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5437 'Product' => '/product/class/product.class.php',
5438 //'ProductThirparty' => '...', // for llx_product_thirdparty
5439 'Project' => '/projet/class/project.class.php',
5440 'User' => '/user/class/user.class.php',
5441 'Account' => '/compta/bank/class/account.class.php',
5442 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5443 'Societe' => '/societe/class/societe.class.php',
5444 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirparty of Societe.
5445 );
5446 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5447 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5448 }
5449 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5450 $objects['Mo'] = '/mrp/class/mo.class.php';
5451 }
5452 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5453 $objects['Don'] = '/don/class/don.class.php';
5454 }
5455 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5456 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5457 }
5458 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5459 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5460 }
5461 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5462 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5463 }
5464
5465 //First, all core objects must update their tables
5466 foreach ($objects as $object_name => $object_file) {
5467 if (is_array($object_file)) {
5468 if (empty($object_file['enabled'])) {
5469 continue;
5470 }
5471 $object_file = $object_file['file'];
5472 }
5473
5474 require_once DOL_DOCUMENT_ROOT.$object_file;
5475
5476 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5477 $error++;
5478 $this->error = $this->db->lasterror();
5479 break;
5480 }
5481 }
5482 }
5483
5484 // External modules should update their ones too
5485 if (!$error) {
5486 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5487 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5488
5489 if ($reshook < 0) {
5490 $this->error = $hookmanager->error;
5491 $this->errors = $hookmanager->errors;
5492 $error++;
5493 }
5494 }
5495
5496
5497 if (!$error) {
5498 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5499
5500 // Call trigger
5501 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5502 if ($result < 0) {
5503 $error++;
5504 }
5505 // End call triggers
5506 }
5507
5508 if (!$error) {
5509 // Move files from the dir of the third party to delete into the dir of the third party to keep
5510 if (!empty($conf->societe->multidir_output[$this->entity])) {
5511 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5512 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5513
5514 if (dol_is_dir($srcdir)) {
5515 $dirlist = dol_dir_list($srcdir, 'files', 1);
5516 foreach ($dirlist as $filetomove) {
5517 $destfile = $destdir.'/'.$filetomove['relativename'];
5518 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5519 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5520 }
5521 //exit;
5522 }
5523 }
5524 }
5525
5526
5527 if (!$error) {
5528 // We finally remove the old thirdparty
5529 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5530 $this->error = $soc_origin->error;
5531 $this->errors = $soc_origin->errors;
5532 $error++;
5533 }
5534 }
5535
5536 if (!$error) {
5537 $this->db->commit();
5538 return 0;
5539 } else {
5540 $langs->load("errors");
5541 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5542 $this->db->rollback();
5543 return -1;
5544 }
5545 }
5546
5547 return -1;
5548 }
5549}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:626
$object ref
Definition info.php:79
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage bank accounts description of third parties.
Class to stock current configuration.
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
update($id, User $user, $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
const PROSPECT
Third party type is a prospect.
create(User $user, $notrigger=0)
Create third party in database.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
setCategories($categories, $type_categ)
Sets object to supplied categories.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
setNoEmail($no_email)
Set "blacklist" mailing status.
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Returns the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='')
Return a link on thirdparty (with picto)
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
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 clicable link of object (with eventually picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Returns 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.
trait CommonIncoterm
Superclass for incoterm classes.
trait CommonPeople
Support class for thirdparties, contacts, members, users or resources.
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.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='')
Format phone numbers according to country.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
isValidSiren($siren)
Check the syntax validity of a SIREN.
isValidTinForPT($str)
Check the syntax validity of a Portuguese (PT) Tax Identification Number (TIN).
isValidSiret($siret)
Check the syntax validity of a SIRET.
isValidTinForES($str)
Check the syntax validity of a Spanish (ES) Tax Identification Number (TIN), where:
isValidTinForBE($str)
Check the syntax validity of a Belgium (BE) Tax Identification Number (TIN).
isValidTinForDZ($str)
Check the syntax validity of an Algerian (DZ) Tax Identification Number (TIN).
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:142