dolibarr 20.0.0
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)', 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1),
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
564 //Log data
565
570 public $date_modification;
571
577 public $user_modification;
578
583 public $date_creation;
584
590 public $user_creation;
591
596 public $client = 0;
597
602 public $prospect = 0;
603
608 public $fournisseur;
609
614 public $code_client;
615
620 public $code_fournisseur;
621
626 public $code_compta_client;
627
634 public $code_compta;
635
640 public $accountancy_code_customer;
641
646 public $code_compta_fournisseur;
647
652 public $accountancy_code_supplier;
653
658 public $code_compta_product;
659
665 public $note;
666
671 public $note_private;
672
677 public $note_public;
678
683 public $stcomm_id;
684
689 public $stcomm_picto;
690
695 public $status_prospect_label;
696
701 public $price_level;
702
706 public $outstanding_limit;
707
711 public $order_min_amount;
712
716 public $supplier_order_min_amount;
717
722 public $commercial_id;
723
728 public $parent;
729
734 public $default_lang;
735
739 public $ref;
740
746 public $ref_ext;
747
754 public $import_key;
755
760 public $webservices_url;
761
766 public $webservices_key;
767
771 public $logo;
772
776 public $logo_small;
777
781 public $logo_mini;
782
786 public $logo_squarred;
787
791 public $logo_squarred_small;
792
796 public $logo_squarred_mini;
797
801 public $accountancy_code_sell;
802
806 public $accountancy_code_buy;
807
808 // Multicurrency
812 public $fk_multicurrency;
813
814 // Warehouse
818 public $fk_warehouse;
819
823 public $multicurrency_code;
824
825 // Fields loaded by fetchPartnerships()
826
827 public $partnerships = array();
828
829
833 public $bank_account;
834
835
836 const STATUS_CEASED = 0;
837 const STATUS_INACTIVITY = 1;
838
842 const NO_CUSTOMER = 0;
843
847 const CUSTOMER = 1;
848
852 const PROSPECT = 2;
853
858
862 const NO_SUPPLIER = 0;
863
867 const SUPPLIER = 1;
868
869
875 public function __construct($db)
876 {
877 global $conf;
878
879 $this->db = $db;
880
881 $this->ismultientitymanaged = 1;
882 $this->isextrafieldmanaged = 1;
883 $this->client = 0;
884 $this->prospect = 0;
885 $this->fournisseur = 0;
886 $this->typent_id = 0;
887 $this->effectif_id = 0;
888 $this->forme_juridique_code = 0;
889 $this->tva_assuj = 1;
890 $this->vat_reverse_charge = 0;
891 $this->status = 1;
892
893 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
894 $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
895 $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
896 $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
897 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
898 }
899 }
900
901
910 public function create(User $user, $notrigger = 0)
911 {
912 global $langs, $conf;
913
914 $error = 0;
915
916 // Clean parameters
917 if (empty($this->status)) {
918 $this->status = 0;
919 }
920 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
921 $this->setUpperOrLowerCase();
922 $this->nom = $this->name; // For backward compatibility
923 if (empty($this->client)) {
924 $this->client = 0;
925 }
926 if (empty($this->fournisseur)) {
927 $this->fournisseur = 0;
928 }
929 $this->import_key = trim((string) $this->import_key);
930
931 $this->accountancy_code_customer = trim((string) $this->code_compta);
932 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
933 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
934 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
935
936 if (!empty($this->multicurrency_code)) {
937 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
938 }
939 if (empty($this->fk_multicurrency)) {
940 $this->multicurrency_code = '';
941 $this->fk_multicurrency = 0;
942 }
943
944 dol_syslog(get_class($this)."::create ".$this->name);
945
946 $now = dol_now();
947
948 if (empty($this->date_creation)) {
949 $this->date_creation = $now;
950 }
951
952 $this->db->begin();
953
954 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
955 if ($this->code_client == -1 || $this->code_client === 'auto') {
956 $this->get_codeclient($this, 0);
957 }
958 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
959 $this->get_codefournisseur($this, 1);
960 }
961
962 // Check more parameters (including mandatory setup
963 // If error, this->errors[] is filled
964 $result = $this->verify();
965
966 if ($result >= 0) {
967 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
968
969 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
970 $sql .= "nom";
971 $sql .= ", name_alias";
972 $sql .= ", entity";
973 $sql .= ", datec";
974 $sql .= ", fk_user_creat";
975 $sql .= ", fk_typent";
976 $sql .= ", canvas";
977 $sql .= ", status";
978 $sql .= ", ref_ext";
979 $sql .= ", fk_stcomm";
980 $sql .= ", fk_incoterms";
981 $sql .= ", location_incoterms";
982 $sql .= ", import_key";
983 $sql .= ", fk_multicurrency";
984 $sql .= ", multicurrency_code";
985 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
986 $sql .= ", vat_reverse_charge";
987 $sql .= ", accountancy_code_buy";
988 $sql .= ", accountancy_code_sell";
989 }
990 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
991 $sql .= " '".$this->db->escape($this->name_alias)."',";
992 $sql .= " ".((int) $this->entity).",";
993 $sql .= " '".$this->db->idate($this->date_creation)."'";
994 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
995 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
996 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
997 $sql .= ", ".((int) $this->status);
998 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
999 $sql .= ", 0";
1000 $sql .= ", ".(int) $this->fk_incoterms;
1001 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1002 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1003 $sql .= ", ".(int) $this->fk_multicurrency;
1004 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1005 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1006 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1007 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1008 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1009 }
1010 $sql .= ")";
1011
1012 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1013
1014 $result = $this->db->query($sql);
1015 if ($result) {
1016 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1017
1018 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1019
1020 // update accountancy for this entity
1021 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1022 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1023
1024 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1025 $sql .= " fk_soc";
1026 $sql .= ", entity";
1027 $sql .= ", vat_reverse_charge";
1028 $sql .= ", accountancy_code_customer";
1029 $sql .= ", accountancy_code_supplier";
1030 $sql .= ", accountancy_code_buy";
1031 $sql .= ", accountancy_code_sell";
1032 $sql .= ") VALUES (";
1033 $sql .= $this->id;
1034 $sql .= ", ".((int) $conf->entity);
1035 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1036 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1037 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1038 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1039 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1040 $sql .= ")";
1041 $result = $this->db->query($sql);
1042 if (!$result) {
1043 $error++;
1044 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1045 }
1046 }
1047
1048 // Ajout du commercial affecte
1049 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1050 $this->add_commercial($user, $this->commercial_id);
1051 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1052 // si un commercial cree un client il lui est affecte automatiquement
1053 $this->add_commercial($user, $user->id);
1054 }
1055
1056 if ($ret >= 0) {
1057 if (! $notrigger) {
1058 // Call trigger
1059 $result = $this->call_trigger('COMPANY_CREATE', $user);
1060 if ($result < 0) {
1061 $error++;
1062 }
1063 // End call triggers
1064 }
1065 } else {
1066 $error++;
1067 }
1068
1069 if (!$error) {
1070 dol_syslog(get_class($this)."::Create success id=".$this->id);
1071 $this->db->commit();
1072 return $this->id;
1073 } else {
1074 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1075 $this->db->rollback();
1076 return -4;
1077 }
1078 } else {
1079 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1080 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1081 $result = -1;
1082 } else {
1083 $this->error = $this->db->lasterror();
1084 $result = -2;
1085 }
1086 $this->db->rollback();
1087 return $result;
1088 }
1089 } else {
1090 $this->db->rollback();
1091 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1092 return -3;
1093 }
1094 }
1095
1096
1097 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1107 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1108 {
1109 global $conf;
1110
1111 $error = 0;
1112
1113 $this->db->begin();
1114
1115 // phpcs:enable
1116 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1117 $contact = new Contact($this->db);
1118
1119 $contact->name = $this->name_bis;
1120 $contact->firstname = $this->firstname;
1121 $contact->civility_id = $this->civility_id;
1122 $contact->socid = $this->id; // fk_soc
1123 $contact->statut = 1; // deprecated
1124 $contact->status = 1;
1125 $contact->priv = 0;
1126 $contact->country_id = $this->country_id;
1127 $contact->state_id = $this->state_id;
1128 $contact->address = $this->address;
1129 $contact->email = $this->email;
1130 $contact->zip = $this->zip;
1131 $contact->town = $this->town;
1132 $this->setUpperOrLowerCase();
1133 $contact->phone_pro = $this->phone;
1134
1135 $contactId = $contact->create($user, $notrigger);
1136 if ($contactId < 0) {
1137 $error++;
1138 $this->error = $contact->error;
1139 $this->errors = $contact->errors;
1140 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1141 }
1142
1143 if (empty($error) && is_array($tags) && !empty($tags)) {
1144 $result = $contact->setCategories($tags);
1145 if ($result < 0) {
1146 $error++;
1147 $this->error = $contact->error;
1148 $this->errors = array_merge($this->errors, $contact->errors);
1149 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1150 $contactId = $result;
1151 }
1152 }
1153
1154 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1155 $result = $contact->setNoEmail($no_email);
1156 if ($result < 0) {
1157 $this->error = $contact->error;
1158 $this->errors = array_merge($this->errors, $contact->errors);
1159 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1160 $contactId = $result;
1161 }
1162 }
1163
1164 if (empty($error)) {
1165 dol_syslog(get_class($this)."::create_individual success");
1166 $this->db->commit();
1167 } else {
1168 $this->db->rollback();
1169 }
1170
1171 return $contactId;
1172 }
1173
1180 public function verify()
1181 {
1182 global $conf, $langs, $mysoc;
1183
1184 $error = 0;
1185 $this->errors = array();
1186
1187 $result = 0;
1188 $this->name = trim($this->name);
1189 $this->nom = $this->name; // For backward compatibility
1190
1191 if (!$this->name) {
1192 $this->errors[] = 'ErrorBadThirdPartyName';
1193 $result = -2;
1194 }
1195
1196 if ($this->client) {
1197 $rescode = $this->check_codeclient();
1198 if ($rescode != 0 && $rescode != -5) {
1199 if ($rescode == -1) {
1200 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1201 } elseif ($rescode == -2) {
1202 $this->errors[] = 'ErrorCustomerCodeRequired';
1203 } elseif ($rescode == -3) {
1204 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1205 } elseif ($rescode == -4) {
1206 $this->errors[] = 'ErrorPrefixRequired';
1207 } else {
1208 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1209 }
1210
1211 $result = -3;
1212 }
1213 }
1214
1215 if ($this->fournisseur) {
1216 $rescode = $this->check_codefournisseur();
1217 if ($rescode != 0 && $rescode != -5) {
1218 if ($rescode == -1) {
1219 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1220 } elseif ($rescode == -2) {
1221 $this->errors[] = 'ErrorSupplierCodeRequired';
1222 } elseif ($rescode == -3) {
1223 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1224 } elseif ($rescode == -4) {
1225 $this->errors[] = 'ErrorPrefixRequired';
1226 } else {
1227 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1228 }
1229 $result = -3;
1230 }
1231 }
1232
1233 // Check for duplicate or mandatory fields defined into setup
1234 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1235 foreach ($array_to_check as $key) {
1236 $keymin = strtolower($key);
1237 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1238 $keymin = 'code_compta';
1239 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1240 $keymin = 'code_compta_fournisseur';
1241 }
1242 $i = (int) preg_replace('/[^0-9]/', '', $key);
1243 $vallabel = $this->$keymin;
1244
1245 if ($i > 0) {
1246 if ($this->isACompany()) {
1247 // Check for mandatory prof id (but only if country is same than ours)
1248 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1249 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1250 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1251 $langs->load("errors");
1252 $error++;
1253 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1254 }
1255 }
1256 }
1257
1258 // Check for unicity on profid
1259 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1260 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1261 $langs->load("errors");
1262 $error++;
1263 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1264 }
1265 }
1266 } else {
1267 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1268 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1269 if ($key == 'EMAIL') {
1270 // Check for mandatory
1271 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1272 $langs->load("errors");
1273 $error++;
1274 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1275 }
1276
1277 // Check for unicity
1278 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1279 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1280 $langs->load("errors");
1281 $error++;
1282 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1283 }
1284 }
1285 } elseif ($key == 'TVA_INTRA') {
1286 // Check for unicity
1287 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1288 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1289 $langs->load("errors");
1290 $error++;
1291 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1292 }
1293 }
1294 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1295 // Check for unicity
1296 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1297 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1298 $langs->loadLangs(array("errors", 'compta'));
1299 $error++;
1300 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1301 }
1302 }
1303
1304 // Check for mandatory
1305 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1306 $langs->loadLangs(array("errors", 'compta'));
1307 $error++;
1308 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1309 }
1310 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1311 // Check for unicity
1312 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1313 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1314 $langs->loadLangs(array("errors", 'compta'));
1315 $error++;
1316 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1317 }
1318 }
1319
1320 // Check for mandatory
1321 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1322 $langs->loadLangs(array("errors", 'compta'));
1323 $error++;
1324 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1325 }
1326 }
1327 }
1328 }
1329
1330 if ($error) {
1331 $result = -4;
1332 }
1333
1334 return $result;
1335 }
1336
1349 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1350 {
1351 global $langs, $conf, $hookmanager;
1352
1353 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1354
1355 if (empty($id)) {
1356 $id = $this->id;
1357 }
1358
1359 $error = 0;
1360
1361 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1362
1363 $now = dol_now();
1364
1365 // Clean parameters
1366 $this->id = $id;
1367 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1368 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1369 $this->nom = $this->name; // For backward compatibility
1370 $this->name_alias = trim((string) $this->name_alias);
1371 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1372 $this->address = trim((string) $this->address);
1373 $this->zip = trim((string) $this->zip);
1374 $this->town = trim((string) $this->town);
1375 $this->state_id = (is_numeric($this->state_id)) ? (int) trim((string) $this->state_id) : 0;
1376 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1377 $this->phone = trim((string) $this->phone);
1378 $this->phone = preg_replace("/\s/", "", $this->phone);
1379 $this->phone = preg_replace("/\./", "", $this->phone);
1380 $this->phone_mobile = trim((string) $this->phone_mobile);
1381 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1382 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1383 $this->fax = trim((string) $this->fax);
1384 $this->fax = preg_replace("/\s/", "", $this->fax);
1385 $this->fax = preg_replace("/\./", "", $this->fax);
1386 $this->email = trim((string) $this->email);
1387 $this->url = $this->url ? clean_url($this->url, 0) : '';
1388 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1389 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1390 $this->idprof1 = trim((string) $this->idprof1);
1391 $this->idprof2 = trim((string) $this->idprof2);
1392 $this->idprof3 = trim((string) $this->idprof3);
1393 $this->idprof4 = trim((string) $this->idprof4);
1394 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1395 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1396 $this->prefix_comm = trim((string) $this->prefix_comm);
1397 $this->outstanding_limit = price2num($this->outstanding_limit);
1398 $this->order_min_amount = price2num($this->order_min_amount);
1399 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1400
1401 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1402 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1403 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1404 if (empty($this->status)) {
1405 $this->status = 0;
1406 }
1407
1408 if (!empty($this->multicurrency_code)) {
1409 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1410 }
1411 if (empty($this->fk_multicurrency)) {
1412 $this->multicurrency_code = '';
1413 $this->fk_multicurrency = 0;
1414 }
1415
1416 // Local taxes
1417 $this->localtax1_assuj = trim($this->localtax1_assuj);
1418 $this->localtax2_assuj = trim($this->localtax2_assuj);
1419
1420 $this->localtax1_value = trim($this->localtax1_value);
1421 $this->localtax2_value = trim($this->localtax2_value);
1422
1423 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1424
1425 $this->effectif_id = trim((string) $this->effectif_id);
1426 $this->forme_juridique_code = trim((string) $this->forme_juridique_code);
1427
1428 //Gencod
1429 $this->barcode = trim($this->barcode);
1430
1431 // For automatic creation
1432 if ($this->code_client == -1 || $this->code_client === 'auto') {
1433 $this->get_codeclient($this, 0);
1434 }
1435 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1436 $this->get_codefournisseur($this, 1);
1437 }
1438
1439 $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1440 $this->code_compta = $this->code_compta_client; // for backward compatibility
1441 $this->code_compta_fournisseur = (empty($this->code_compta_fournisseur) ? '' : trim($this->code_compta_fournisseur));
1442
1443 // Check parameters. More tests are done later in the ->verify()
1444 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1445 $langs->load("errors");
1446 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1447 return -1;
1448 }
1449
1450 $customer = false;
1451 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1452 // If $allowmodcodeclient is set and value is not set, we generate it
1453 if (empty($this->code_compta_client)) {
1454 $ret = $this->get_codecompta('customer');
1455 if ($ret < 0) {
1456 return -1;
1457 }
1458 }
1459
1460 $customer = true;
1461 }
1462
1463 $supplier = false;
1464 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1465 // If $allowmodcodefournisseur is set and value is not set, we generate it
1466 if (empty($this->code_compta_fournisseur)) {
1467 $ret = $this->get_codecompta('supplier');
1468 if ($ret < 0) {
1469 return -1;
1470 }
1471 }
1472
1473 $supplier = true;
1474 }
1475
1476 //Web services
1477 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1478 $this->webservices_key = trim($this->webservices_key);
1479
1480 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1481 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1482
1483 //Incoterms
1484 $this->fk_incoterms = (int) $this->fk_incoterms;
1485 $this->location_incoterms = trim($this->location_incoterms);
1486
1487 $this->db->begin();
1488
1489 // Check name is required and codes are ok or unique.
1490 // If error, this->errors[] is filled
1491 $result = 0;
1492 if ($action != 'add' && $action != 'merge') {
1493 // We don't check when update called during a create because verify was already done.
1494 // 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
1495 $result = $this->verify();
1496
1497 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1498 // So we can update record that were using and old numbering rule.
1499 if (is_array($this->errors)) {
1500 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1501 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1502 unset($this->errors[$key]); // Remove error message
1503 }
1504 }
1505 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1506 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1507 unset($this->errors[$key]); // Remove error message
1508 }
1509 }
1510 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1511 $result = 0;
1512 }
1513 }
1514 }
1515 $this->setUpperOrLowerCase();
1516 if ($result >= 0) {
1517 dol_syslog(get_class($this)."::update verify ok or not done");
1518
1519 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1520 $sql .= "entity = ".$this->db->escape($this->entity);
1521 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1522 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1523 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1524 $sql .= ",address = '".$this->db->escape($this->address)."'";
1525
1526 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1527 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1528
1529 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1530 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1531
1532 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1533 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1534 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1535 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1536 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1537 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1538
1539 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1540
1541 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1542 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1543
1544 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1545 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1546 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1547 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1548 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1549 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1550
1551 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1552 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1553 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1554 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1555 }
1556 $sql .= ",status = ".((int) $this->status);
1557
1558 // Local taxes
1559 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1560 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1561 if ($this->localtax1_assuj == 1) {
1562 if ($this->localtax1_value != '') {
1563 $sql .= ",localtax1_value =".$this->localtax1_value;
1564 } else {
1565 $sql .= ",localtax1_value =0.000";
1566 }
1567 } else {
1568 $sql .= ",localtax1_value =0.000";
1569 }
1570
1571 if ($this->localtax2_assuj == 1) {
1572 if ($this->localtax2_value != '') {
1573 $sql .= ",localtax2_value =".$this->localtax2_value;
1574 } else {
1575 $sql .= ",localtax2_value =0.000";
1576 }
1577 } else {
1578 $sql .= ",localtax2_value =0.000";
1579 }
1580
1581 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1582
1583 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1584
1585 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1586 if (isset($this->stcomm_id)) {
1587 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1588 }
1589 if (isset($this->typent_id)) {
1590 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1591 }
1592
1593 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1594
1595 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1596 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1597 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1598 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1599 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1600 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1601 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1602 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1603
1604 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1605 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1606 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1607 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1608 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1609 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1610 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1611 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1612 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1613 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1614 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1615 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1616 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1617 if ($customer) {
1618 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1619 }
1620
1621 if ($supplier) {
1622 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1623 }
1624 }
1625 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1626 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1627
1628 //Incoterms
1629 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1630 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1631
1632 if ($customer) {
1633 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1634 }
1635
1636 if ($supplier) {
1637 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1638 }
1639 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1640 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1641 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1642 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1643 $sql .= " WHERE rowid = ".(int) $id;
1644
1645 $resql = $this->db->query($sql);
1646 if ($resql) {
1647 if (is_object($this->oldcopy)) { // If we have information on old values
1648 if ($this->oldcopy->country_id != $this->country_id) {
1649 unset($this->country_code);
1650 unset($this->country);
1651 }
1652 if ($this->oldcopy->state_id != $this->state_id) {
1653 unset($this->state_code);
1654 unset($this->state);
1655 }
1656 } else {
1657 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1658 unset($this->country);
1659 unset($this->state_code);
1660 unset($this->state);
1661 }
1662
1663 $nbrowsaffected = $this->db->affected_rows($resql);
1664
1665 if (!$error && $nbrowsaffected) {
1666 // Update information on linked member if it is an update
1667 if (!$nosyncmember && isModEnabled('member')) {
1668 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1669
1670 dol_syslog(get_class($this)."::update update linked member");
1671
1672 $lmember = new Adherent($this->db);
1673 $result = $lmember->fetch(0, 0, $this->id);
1674
1675 if ($result > 0) {
1676 $lmember->company = $this->name;
1677 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1678 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1679 $lmember->address = $this->address;
1680 $lmember->zip = $this->zip;
1681 $lmember->town = $this->town;
1682 $lmember->email = $this->email;
1683 $lmember->socialnetworks = $this->socialnetworks;
1684 $lmember->phone = $this->phone;
1685 $lmember->state_id = $this->state_id;
1686 $lmember->country_id = $this->country_id;
1687 $lmember->default_lang = $this->default_lang;
1688
1689 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1690 if ($result < 0) {
1691 $this->error = $lmember->error;
1692 $this->errors = array_merge($this->errors, $lmember->errors);
1693 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1694 $error++;
1695 }
1696 } elseif ($result < 0) {
1697 $this->error = $lmember->error;
1698 $error++;
1699 }
1700 }
1701 }
1702
1703 $action = 'update';
1704
1705 // update accountancy for this entity
1706 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1707 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1708
1709 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1710 $sql .= " fk_soc";
1711 $sql .= ", entity";
1712 $sql .= ", vat_reverse_charge";
1713 $sql .= ", accountancy_code_customer";
1714 $sql .= ", accountancy_code_supplier";
1715 $sql .= ", accountancy_code_buy";
1716 $sql .= ", accountancy_code_sell";
1717 $sql .= ") VALUES (";
1718 $sql .= $this->id;
1719 $sql .= ", ".$conf->entity;
1720 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1721 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1722 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1723 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1724 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1725 $sql .= ")";
1726 $result = $this->db->query($sql);
1727 if (!$result) {
1728 $error++;
1729 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1730 }
1731 }
1732
1733 // Actions on extra fields
1734 if (!$error) {
1735 $result = $this->insertExtraFields();
1736 if ($result < 0) {
1737 $error++;
1738 }
1739 }
1740 // Actions on extra languages
1741 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1742 $result = $this->insertExtraLanguages();
1743 if ($result < 0) {
1744 $error++;
1745 }
1746 }
1747
1748 if (!$error && $call_trigger) {
1749 // Call trigger
1750 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1751 if ($result < 0) {
1752 $error++;
1753 }
1754 // End call triggers
1755 }
1756
1757 if (!$error) {
1758 dol_syslog(get_class($this)."::Update success");
1759 $this->db->commit();
1760 return 1;
1761 } else {
1762 $this->db->rollback();
1763 return -1;
1764 }
1765 } else {
1766 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1767 // Doublon
1768 $this->error = $langs->trans("ErrorDuplicateField");
1769 $result = -1;
1770 } else {
1771 $this->error = $this->db->lasterror();
1772 $result = -2;
1773 }
1774 $this->db->rollback();
1775 return $result;
1776 }
1777 } else {
1778 $this->db->rollback();
1779 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1780 return -3;
1781 }
1782 }
1783
1803 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1804 {
1805 global $langs;
1806 global $conf;
1807
1808 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)) {
1809 return -1;
1810 }
1811
1812 $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';
1813 $sql .= ', s.status, s.fk_warehouse';
1814 $sql .= ', s.price_level';
1815 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1816 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1817 $sql .= ', s.socialnetworks';
1818 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1819 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1820 $sql .= ', s.capital, s.tva_intra';
1821 $sql .= ', s.fk_typent as typent_id';
1822 $sql .= ', s.fk_effectif as effectif_id';
1823 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1824 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1825 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1826 $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1827 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1828 } else {
1829 $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1830 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1831 }
1832 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1833 $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';
1834 $sql .= ', s.fk_account, s.tva_assuj';
1835 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1836 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1837 $sql .= ', s.fk_shipping_method';
1838 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1839 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1840 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1841 $sql .= ', fj.libelle as forme_juridique';
1842 $sql .= ', e.libelle as effectif';
1843 $sql .= ', c.code as country_code, c.label as country';
1844 $sql .= ', d.code_departement as state_code, d.nom as state';
1845 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1846 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1847 $sql .= ', te.code as typent_code';
1848 $sql .= ', i.libelle as label_incoterms';
1849 if (!isModEnabled('multicompany')) {
1850 $sql .= ', s.remise_client, s.remise_supplier';
1851 } else {
1852 $sql .= ', sr.remise_client, sr2.remise_supplier';
1853 }
1854 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1855 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1856 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1857 }
1858 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1859 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1860 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1861 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1862 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1863 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1864 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1865 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1866 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1867 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1868 if (isModEnabled('multicompany')) {
1869 $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').'))';
1870 $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').'))';
1871 }
1872 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1873
1874 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1875 if ($is_client) {
1876 $sql .= ' AND s.client > 0';
1877 }
1878 if ($is_supplier) {
1879 $sql .= ' AND s.fournisseur > 0';
1880 } // if both false, no test (the thirdparty can be client and/or supplier)
1881
1882 if ($rowid) {
1883 $sql .= ' AND s.rowid = '.((int) $rowid);
1884 }
1885 if ($ref) {
1886 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1887 }
1888 if ($ref_alias) {
1889 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1890 }
1891 if ($ref_ext) {
1892 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1893 }
1894 if ($barcode) {
1895 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1896 }
1897 if ($idprof1) {
1898 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1899 }
1900 if ($idprof2) {
1901 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1902 }
1903 if ($idprof3) {
1904 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1905 }
1906 if ($idprof4) {
1907 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1908 }
1909 if ($idprof5) {
1910 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1911 }
1912 if ($idprof6) {
1913 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1914 }
1915 if ($email) {
1916 $sql .= " AND s.email = '".$this->db->escape($email)."'";
1917 }
1918
1919 $resql = $this->db->query($sql);
1920 if ($resql) {
1921 $num = $this->db->num_rows($resql);
1922 if ($num > 1) {
1923 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1924 dol_syslog($this->error, LOG_ERR);
1925 $result = -2;
1926 } elseif ($num) { // $num = 1
1927 $obj = $this->db->fetch_object($resql);
1928
1929 $this->id = $obj->rowid;
1930 $this->entity = $obj->entity;
1931 $this->canvas = $obj->canvas;
1932
1933 $this->ref = $obj->rowid;
1934 $this->name = $obj->name;
1935 $this->nom = $obj->name; // deprecated
1936 $this->name_alias = $obj->name_alias;
1937 $this->ref_ext = $obj->ref_ext;
1938
1939 $this->date_creation = $this->db->jdate($obj->date_creation);
1940 $this->date_modification = $this->db->jdate($obj->date_modification);
1941 $this->user_creation_id = $obj->fk_user_creat;
1942 $this->user_modification_id = $obj->fk_user_modif;
1943
1944 $this->address = $obj->address;
1945 $this->zip = $obj->zip;
1946 $this->town = $obj->town;
1947
1948 $this->country_id = $obj->country_id;
1949 $this->country_code = $obj->country_id ? $obj->country_code : '';
1950 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1951
1952 $this->state_id = $obj->state_id;
1953 $this->state_code = $obj->state_code;
1954 $this->region_id = $obj->region_id;
1955 $this->region_code = $obj->region_code;
1956 $this->state = ($obj->state != '-' ? $obj->state : '');
1957
1958 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1959 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1960 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1961 $this->status_prospect_label = $label; // label status prospect
1962 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1963
1964 $this->email = $obj->email;
1965 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1966
1967 $this->url = $obj->url;
1968 $this->phone = $obj->phone;
1969 $this->phone_mobile = $obj->phone_mobile;
1970 $this->fax = $obj->fax;
1971
1972 $this->parent = $obj->parent;
1973
1974 $this->idprof1 = $obj->idprof1;
1975 $this->idprof2 = $obj->idprof2;
1976 $this->idprof3 = $obj->idprof3;
1977 $this->idprof4 = $obj->idprof4;
1978 $this->idprof5 = $obj->idprof5;
1979 $this->idprof6 = $obj->idprof6;
1980
1981 $this->capital = $obj->capital;
1982
1983 $this->code_client = $obj->code_client;
1984 $this->code_fournisseur = $obj->code_fournisseur;
1985
1986 $this->code_compta = $obj->code_compta; // For backward compatibility
1987 $this->code_compta_client = $obj->code_compta;
1988 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1989
1990 $this->barcode = $obj->barcode;
1991
1992 $this->tva_assuj = $obj->tva_assuj;
1993 $this->tva_intra = $obj->tva_intra;
1994
1995 if (!empty($obj->spe_vat_reverse_charge)) {
1996 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1997 } elseif (!empty($obj->soc_vat_reverse_charge)) {
1998 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1999 } else {
2000 $this->vat_reverse_charge = 0;
2001 }
2002
2003 $this->status = $obj->status;
2004
2005 // Local Taxes
2006 $this->localtax1_assuj = $obj->localtax1_assuj;
2007 $this->localtax2_assuj = $obj->localtax2_assuj;
2008
2009 $this->localtax1_value = $obj->localtax1_value;
2010 $this->localtax2_value = $obj->localtax2_value;
2011
2012 $this->typent_id = $obj->typent_id;
2013 $this->typent_code = $obj->typent_code;
2014
2015 $this->effectif_id = $obj->effectif_id;
2016 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2017
2018 $this->forme_juridique_code = $obj->forme_juridique_code;
2019 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2020
2021 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2022
2023 $this->prefix_comm = $obj->prefix_comm;
2024
2025 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2026 $this->remise_supplier_percent = $obj->remise_supplier;
2027
2028 $this->mode_reglement_id = $obj->mode_reglement;
2029 $this->cond_reglement_id = $obj->cond_reglement;
2030 $this->deposit_percent = $obj->deposit_percent;
2031 $this->transport_mode_id = $obj->transport_mode;
2032 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2033 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2034 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2035 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2036 $this->fk_account = $obj->fk_account;
2037
2038 $this->client = $obj->client;
2039 $this->fournisseur = $obj->fournisseur;
2040
2041 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2042 $this->note_private = $obj->note_private;
2043 $this->note_public = $obj->note_public;
2044 $this->model_pdf = $obj->model_pdf;
2045 $this->default_lang = $obj->default_lang;
2046 $this->logo = $obj->logo;
2047 $this->logo_squarred = $obj->logo_squarred;
2048
2049 $this->webservices_url = $obj->webservices_url;
2050 $this->webservices_key = $obj->webservices_key;
2051
2052 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2053 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2054
2055 $this->outstanding_limit = $obj->outstanding_limit;
2056 $this->order_min_amount = $obj->order_min_amount;
2057 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2058
2059 // multiprix
2060 $this->price_level = $obj->price_level;
2061
2062 // warehouse
2063 $this->fk_warehouse = $obj->fk_warehouse;
2064
2065 $this->import_key = $obj->import_key;
2066
2067 //Incoterms
2068 $this->fk_incoterms = $obj->fk_incoterms;
2069 $this->location_incoterms = $obj->location_incoterms;
2070 $this->label_incoterms = $obj->label_incoterms;
2071
2072 // multicurrency
2073 $this->fk_multicurrency = $obj->fk_multicurrency;
2074 $this->multicurrency_code = $obj->multicurrency_code;
2075
2076 // pdf
2077 $this->model_pdf = $obj->model_pdf;
2078 $this->last_main_doc = $obj->last_main_doc;
2079
2080 $result = 1;
2081
2082 // fetch optionals attributes and labels
2083 $this->fetch_optionals();
2084 } else {
2085 $result = 0;
2086 }
2087
2088 $this->db->free($resql);
2089 } else {
2090 $this->error = $this->db->lasterror();
2091 $this->errors[] = $this->db->lasterror();
2092 $result = -3;
2093 }
2094
2095 // Use first price level if level not defined for third party
2096 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && empty($this->price_level)) {
2097 $this->price_level = 1;
2098 }
2099
2100 return $result;
2101 }
2102
2123 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2124 {
2125 // A rowid is known, it is a unique key so we found it
2126 if ($rowid) {
2127 return $rowid;
2128 }
2129
2130 // We try to find the thirdparty with exact matching on all fields
2131 // TODO Replace this with step by step search
2132 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2133 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2134 // Then search on email with a OR (+ restriction on is_client and is_supplier)
2135 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2136 $tmpthirdparty = new Societe($this->db);
2137 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2138
2139 return $result;
2140 }
2141
2150 public function delete($id, User $fuser = null, $call_trigger = 1)
2151 {
2152 global $conf, $user;
2153
2154 if (empty($fuser)) {
2155 $fuser = $user;
2156 }
2157
2158 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2159
2160 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2161
2162 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2163 $error = 0;
2164
2165 // Test if child exists
2166 $objectisused = $this->isObjectUsed($id);
2167 if (empty($objectisused)) {
2168 $this->db->begin();
2169
2170 // User is mandatory for trigger call
2171 if (!$error && $call_trigger) {
2172 // Call trigger
2173 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2174 if ($result < 0) {
2175 $error++;
2176 }
2177 // End call triggers
2178 }
2179
2180 if (!$error) {
2181 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2182 $static_cat = new Categorie($this->db);
2183 $toute_categs = array();
2184
2185 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2186 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2187 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2188
2189 // Remove each "Categorie"
2190 foreach ($toute_categs as $type => $categs_type) {
2191 foreach ($categs_type as $cat) {
2192 $cat->del_type($this, $type);
2193 }
2194 }
2195 }
2196
2197 if (!$error) {
2198 foreach ($this->childtablesoncascade as $tabletodelete) {
2199 $deleteFromObject = explode(':', $tabletodelete, 4);
2200 if (count($deleteFromObject) >= 2) {
2201 $className = str_replace('@', '', $deleteFromObject[0]);
2202 $filepath = $deleteFromObject[1];
2203 $columnName = $deleteFromObject[2];
2204 if (dol_include_once($filepath)) {
2205 $child_object = new $className($this->db);
2206 $result = $child_object->deleteByParentField($id, $columnName);
2207 if ($result < 0) {
2208 $error++;
2209 $this->errors[] = $child_object->error;
2210 break;
2211 }
2212 } else {
2213 $error++;
2214 $this->errors[] = 'Cannot include child class file '.$filepath;
2215 break;
2216 }
2217 } else {
2218 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2219 $sql .= " WHERE fk_soc = ".((int) $id);
2220 if (!$this->db->query($sql)) {
2221 $error++;
2222 $this->errors[] = $this->db->lasterror();
2223 break;
2224 }
2225 }
2226 }
2227 }
2228
2229 // Removed extrafields
2230 if (!$error) {
2231 $result = $this->deleteExtraFields();
2232 if ($result < 0) {
2233 $error++;
2234 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2235 }
2236 }
2237
2238 // Remove links to subsidiaries companies
2239 if (!$error) {
2240 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2241 $sql .= " SET parent = NULL";
2242 $sql .= " WHERE parent = ".((int) $id);
2243 if (!$this->db->query($sql)) {
2244 $error++;
2245 $this->errors[] = $this->db->lasterror();
2246 }
2247 }
2248
2249 // Remove third party
2250 if (!$error) {
2251 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2252 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2253 $sql .= " WHERE fk_soc = ".((int) $id);
2254 if (!$this->db->query($sql)) {
2255 $error++;
2256 $this->errors[] = $this->db->lasterror();
2257 }
2258 }
2259
2260 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2261 $sql .= " WHERE rowid = ".((int) $id);
2262 if (!$this->db->query($sql)) {
2263 $error++;
2264 $this->errors[] = $this->db->lasterror();
2265 }
2266 }
2267
2268 if (!$error) {
2269 $this->db->commit();
2270
2271 // Delete directory
2272 if (!empty($conf->societe->multidir_output[$entity])) {
2273 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2274 if (dol_is_dir($docdir)) {
2275 dol_delete_dir_recursive($docdir);
2276 }
2277 }
2278
2279 return 1;
2280 } else {
2281 dol_syslog($this->error, LOG_ERR);
2282 $this->db->rollback();
2283 return -1;
2284 }
2285 } else {
2286 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2287 }
2288 return 0;
2289 }
2290
2291 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2299 public function set_as_client()
2300 {
2301 global $conf;
2302 // phpcs:enable
2303 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2304 return $this->setAsCustomer();
2305 }
2306
2313 public function setAsCustomer()
2314 {
2315 if ($this->id) {
2316 $newclient = 1;
2317 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2318 $newclient = 3; //If prospect, we keep prospect tag
2319 }
2320 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2321 $sql .= " SET client = ".((int) $newclient);
2322 $sql .= " WHERE rowid = ".((int) $this->id);
2323
2324 $resql = $this->db->query($sql);
2325 if ($resql) {
2326 $this->client = $newclient;
2327 return 1;
2328 } else {
2329 return -1;
2330 }
2331 }
2332 return 0;
2333 }
2334
2335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2344 public function set_remise_client($remise, $note, User $user)
2345 {
2346 // phpcs:enable
2347 global $conf, $langs;
2348
2349 // Parameter cleaning
2350 $note = trim($note);
2351 if (!$note) {
2352 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2353 return -2;
2354 }
2355
2356 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2357
2358 if ($this->id) {
2359 $this->db->begin();
2360
2361 $now = dol_now();
2362
2363 // Position current discount
2364 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2365 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2366 $sql .= " WHERE rowid = ".((int) $this->id);
2367 $resql = $this->db->query($sql);
2368 if (!$resql) {
2369 $this->db->rollback();
2370 $this->error = $this->db->error();
2371 return -1;
2372 }
2373
2374 // Writes trace in discount history
2375 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2376 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2377 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2378 $sql .= " '".$this->db->escape($note)."',";
2379 $sql .= " ".((int) $user->id);
2380 $sql .= ")";
2381
2382 $resql = $this->db->query($sql);
2383 if (!$resql) {
2384 $this->db->rollback();
2385 $this->error = $this->db->lasterror();
2386 return -1;
2387 }
2388
2389 $this->db->commit();
2390
2391 return 1;
2392 }
2393 return -1;
2394 }
2395
2396 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2405 public function set_remise_supplier($remise, $note, User $user)
2406 {
2407 // phpcs:enable
2408 global $conf, $langs;
2409
2410 // Parameter cleaning
2411 $note = trim($note);
2412 if (!$note) {
2413 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2414 return -2;
2415 }
2416
2417 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2418
2419 if ($this->id) {
2420 $this->db->begin();
2421
2422 $now = dol_now();
2423
2424 // Position current discount
2425 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2426 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2427 $sql .= " WHERE rowid = ".((int) $this->id);
2428 $resql = $this->db->query($sql);
2429 if (!$resql) {
2430 $this->db->rollback();
2431 $this->error = $this->db->error();
2432 return -1;
2433 }
2434
2435 // Writes trace in discount history
2436 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2437 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2438 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2439 $sql .= " '".$this->db->escape($note)."',";
2440 $sql .= " ".((int) $user->id);
2441 $sql .= ")";
2442
2443 $resql = $this->db->query($sql);
2444 if (!$resql) {
2445 $this->db->rollback();
2446 $this->error = $this->db->lasterror();
2447 return -1;
2448 }
2449
2450 $this->db->commit();
2451 return 1;
2452 }
2453
2454 return -1;
2455 }
2456
2457 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2469 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2470 {
2471 // phpcs:enable
2472 global $langs;
2473
2474 // Clean parameters
2475 $remise = price2num($remise);
2476 $desc = trim($desc);
2477
2478 // Check parameters
2479 if (!($remise > 0)) {
2480 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2481 return -1;
2482 }
2483 if (!$desc) {
2484 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2485 return -2;
2486 }
2487
2488 if ($this->id > 0) {
2489 // Clean vat code
2490 $reg = array();
2491 $vat_src_code = '';
2492 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2493 $vat_src_code = $reg[1];
2494 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2495 }
2496
2497 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2498
2499 $discount = new DiscountAbsolute($this->db);
2500 $discount->fk_soc = $this->id;
2501 $discount->socid = $this->id;
2502
2503 $discount->discount_type = $discount_type;
2504
2505 if ($price_base_type == 'TTC') {
2506 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2507 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2508 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2509 } else {
2510 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2511 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2512 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2513 }
2514
2515 $discount->tva_tx = (float) price2num($vatrate);
2516 $discount->vat_src_code = $vat_src_code;
2517
2518 $discount->description = $desc;
2519
2520 $result = $discount->create($user);
2521 if ($result > 0) {
2522 return $result;
2523 } else {
2524 $this->error = $discount->error;
2525 return -3;
2526 }
2527 } else {
2528 return 0;
2529 }
2530 }
2531
2541 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2542 {
2543 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2544
2545 $discountstatic = new DiscountAbsolute($this->db);
2546 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2547 if ($result >= 0) {
2548 return $result;
2549 } else {
2550 $this->error = $discountstatic->error;
2551 return -1;
2552 }
2553 }
2554
2564 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2565 {
2566 global $conf;
2567
2568 $reparray = array();
2569
2570 $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";
2571 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2572 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2573 // Condition here should be the same than into select_dolusers()
2574 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2575 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2576 } else {
2577 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2578 }
2579
2580 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2581 if (empty($sortfield) && empty($sortorder)) {
2582 $sortfield = 'u.lastname,u.firstname';
2583 $sortorder = 'ASC,ASC';
2584 }
2585 $sql .= $this->db->order($sortfield, $sortorder);
2586
2587 $resql = $this->db->query($sql);
2588 if ($resql) {
2589 $num = $this->db->num_rows($resql);
2590 $i = 0;
2591 while ($i < $num) {
2592 $obj = $this->db->fetch_object($resql);
2593
2594 if (empty($mode)) {
2595 $reparray[$i]['id'] = $obj->rowid;
2596 $reparray[$i]['lastname'] = $obj->lastname;
2597 $reparray[$i]['firstname'] = $obj->firstname;
2598 $reparray[$i]['email'] = $obj->email;
2599 $reparray[$i]['phone'] = $obj->office_phone;
2600 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2601 $reparray[$i]['office_fax'] = $obj->office_fax;
2602 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2603 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2604 $reparray[$i]['job'] = $obj->job;
2605 $reparray[$i]['statut'] = $obj->status; // deprecated
2606 $reparray[$i]['status'] = $obj->status;
2607 $reparray[$i]['entity'] = $obj->entity;
2608 $reparray[$i]['login'] = $obj->login;
2609 $reparray[$i]['photo'] = $obj->photo;
2610 $reparray[$i]['gender'] = $obj->gender;
2611 } else {
2612 $reparray[] = $obj->rowid;
2613 }
2614 $i++;
2615 }
2616 return $reparray;
2617 } else {
2618 dol_print_error($this->db);
2619 return -1;
2620 }
2621 }
2622
2630 public function setPriceLevel($price_level, User $user)
2631 {
2632 if ($this->id) {
2633 $now = dol_now();
2634
2635 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2636 $sql .= " SET price_level = ".((int) $price_level);
2637 $sql .= " WHERE rowid = ".((int) $this->id);
2638
2639 if (!$this->db->query($sql)) {
2640 dol_print_error($this->db);
2641 return -1;
2642 }
2643
2644 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2645 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2646 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2647
2648 if (!$this->db->query($sql)) {
2649 dol_print_error($this->db);
2650 return -1;
2651 }
2652 return 1;
2653 }
2654 return -1;
2655 }
2656
2657 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2665 public function add_commercial(User $user, $commid)
2666 {
2667 // phpcs:enable
2668 $error = 0;
2669
2670 if ($this->id > 0 && $commid > 0) {
2671 $this->db->begin();
2672
2673 if (!$error) {
2674 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2675 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2676
2677 $resql = $this->db->query($sql);
2678 if (!$resql) {
2679 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2680 $error++;
2681 }
2682 }
2683
2684 if (!$error) {
2685 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2686 $sql .= " (fk_soc, fk_user)";
2687 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2688
2689 $resql = $this->db->query($sql);
2690 if (!$resql) {
2691 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2692 $error++;
2693 }
2694 }
2695
2696 if (!$error) {
2697 $this->context = array('commercial_modified' => $commid);
2698
2699 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2700 if ($result < 0) {
2701 $error++;
2702 }
2703 }
2704
2705 if (!$error) {
2706 $this->db->commit();
2707 return 1;
2708 } else {
2709 $this->db->rollback();
2710 return -1;
2711 }
2712 }
2713
2714 return 0;
2715 }
2716
2717 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2725 public function del_commercial(User $user, $commid)
2726 {
2727 // phpcs:enable
2728 $error = 0;
2729 $this->context = array('commercial_modified' => $commid);
2730
2731 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2732 if ($result < 0) {
2733 $error++;
2734 }
2735
2736 if ($this->id > 0 && $commid > 0) {
2737 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2738 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2739
2740 if (!$this->db->query($sql)) {
2741 $error++;
2742 dol_syslog(get_class($this)."::del_commercial Erreur");
2743 }
2744 }
2745
2746 if ($error) {
2747 return -1;
2748 } else {
2749 return 1;
2750 }
2751 }
2752
2760 public function getTooltipContentArray($params)
2761 {
2762 global $conf, $langs, $user;
2763
2764 $langs->loadLangs(['companies', 'commercial']);
2765
2766 $datas = array();
2767
2768 $option = $params['option'] ?? '';
2769 $nofetch = !empty($params['nofetch']);
2770
2771 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2772
2773 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2774 return ['optimize' => $langs->trans("ShowCompany")];
2775 }
2776
2777 if (!empty($this->logo) && class_exists('Form')) {
2778 $photo = '<div class="photointooltip floatright">';
2779 $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.
2780 $photo .= '</div>';
2781 $datas['photo'] = $photo;
2782 } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2783 /*$label.= '<div class="photointooltip">';
2784 $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.
2785 $label.= '</div><div style="clear: both;"></div>';*/
2786 }
2787
2788 $datas['divopen'] = '<div class="centpercent">';
2789
2790 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2791 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2792 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2793 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2794 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2795 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2796 } elseif ($option == 'agenda') {
2797 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2798 } elseif ($option == 'project') {
2799 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2800 } elseif ($option == 'margin') {
2801 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2802 } elseif ($option == 'contact') {
2803 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2804 } elseif ($option == 'ban') {
2805 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2806 }
2807
2808 // By default
2809 if (empty($datas['picto'])) {
2810 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2811 }
2812 if (isset($this->status)) {
2813 $datas['status'] = ' '.$this->getLibStatut(5);
2814 }
2815 if (isset($this->client) && isset($this->fournisseur)) {
2816 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2817 }
2818 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2819 if (!empty($this->name_alias) && empty($noaliasinname)) {
2820 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2821 }
2822 if (!empty($this->email)) {
2823 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2824 }
2825 if (!empty($this->url)) {
2826 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2827 }
2828 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2829 $phonelist = array();
2830 if ($this->phone) {
2831 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2832 }
2833 // deliberately not making new list because fax uses same list as phone
2834 if ($this->phone_mobile) {
2835 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2836 }
2837 if ($this->fax) {
2838 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2839 }
2840 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2841 }
2842
2843 if (!empty($this->address)) {
2844 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2845 } elseif (!empty($this->country_code)) {
2846 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2847 }
2848 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2849 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2850 }
2851
2852 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2853 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2854 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2855 }
2856 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2857 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2858 }
2859 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2860 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2861 }
2862 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2863 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2864 }
2865 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2866 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2867 }
2868 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2869 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2870 }
2871 }
2872
2873 $datas['separator'] = '<br>';
2874
2875 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2876 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2877 }
2878 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2879 $langs->load('compta');
2880 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2881 }
2882 // show categories for this record only in ajax to not overload lists
2883 if (!$nofetch && isModEnabled('category') && $this->client) {
2884 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2885 $form = new Form($this->db);
2886 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2887 }
2888 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2889 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2890 }
2891 if (isModEnabled('accounting') && $this->fournisseur) {
2892 $langs->load('compta');
2893 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2894 }
2895 // show categories for this record only in ajax to not overload lists
2896 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2897 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2898 $form = new Form($this->db);
2899 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2900 }
2901
2902 $datas['divclose'] = '</div>';
2903
2904 return $datas;
2905 }
2906
2920 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
2921 {
2922 global $conf, $langs, $hookmanager, $user;
2923
2924 if (!empty($conf->dol_no_mouse_hover)) {
2925 $notooltip = 1; // Force disable tooltips
2926 }
2927
2928 $name = $this->name ? $this->name : $this->nom;
2929
2930 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
2931 if (empty($option) && $this->client > 0) {
2932 $option = 'customer';
2933 }
2934 if (empty($option) && $this->fournisseur > 0) {
2935 $option = 'supplier';
2936 }
2937 }
2938
2939 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
2940 $code = '';
2941 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
2942 $code = $this->code_client.' - ';
2943 }
2944
2945 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
2946 $code .= $this->code_fournisseur.' - ';
2947 }
2948
2949 if ($code) {
2950 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
2951 $name = $code.' '.$name;
2952 } else {
2953 $name = $code;
2954 }
2955 }
2956 }
2957
2958 if (!empty($this->name_alias) && empty($noaliasinname)) {
2959 $name .= ' ('.$this->name_alias.')';
2960 }
2961
2962 $result = '';
2963 $params = [
2964 'id' => $this->id,
2965 'objecttype' => $this->element,
2966 'option' => $option,
2967 'nofetch' => 1,
2968 ];
2969 $classfortooltip = 'classfortooltip';
2970 $dataparams = '';
2971 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2972 $classfortooltip = 'classforajaxtooltip';
2973 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2974 $label = '';
2975 } else {
2976 $label = implode($this->getTooltipContentArray($params));
2977 }
2978
2979 $linkstart = '';
2980 $linkend = '';
2981
2982 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2983 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2984 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2985 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2986 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2987 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2988 } elseif ($option == 'agenda') {
2989 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2990 } elseif ($option == 'project') {
2991 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2992 } elseif ($option == 'margin') {
2993 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2994 } elseif ($option == 'contact') {
2995 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2996 } elseif ($option == 'ban') {
2997 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2998 }
2999
3000 // By default
3001 if (empty($linkstart)) {
3002 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3003 }
3004
3005 // Add type of canvas
3006 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3007 // Add param to save lastsearch_values or not
3008 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3009 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3010 $add_save_lastsearch_values = 1;
3011 }
3012 if ($add_save_lastsearch_values) {
3013 $linkstart .= '&save_lastsearch_values=1';
3014 }
3015 $linkstart .= '"';
3016
3017 $linkclose = '';
3018 if (empty($notooltip)) {
3019 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3020 $label = $langs->trans("ShowCompany");
3021 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3022 }
3023 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3024 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3025 $target_value = array('_self', '_blank', '_parent', '_top');
3026 if (in_array($target, $target_value)) {
3027 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3028 }
3029 } else {
3030 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3031 }
3032 $linkstart .= $linkclose.'>';
3033 $linkend = '</a>';
3034
3035 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3036 $linkstart = '';
3037 $linkend = '';
3038 }
3039
3040 $result .= $linkstart;
3041 if ($withpicto) {
3042 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3043 }
3044 if ($withpicto != 2) {
3045 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3046 }
3047 $result .= $linkend;
3048
3049 global $action;
3050 $hookmanager->initHooks(array('thirdpartydao'));
3051 $parameters = array(
3052 'id' => $this->id,
3053 'getnomurl' => &$result,
3054 'withpicto ' => $withpicto,
3055 'option' => $option,
3056 'maxlen' => $maxlen,
3057 'notooltip' => $notooltip,
3058 'save_lastsearch_value' => $save_lastsearch_value
3059 );
3060 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3061 if ($reshook > 0) {
3062 $result = $hookmanager->resPrint;
3063 } else {
3064 $result .= $hookmanager->resPrint;
3065 }
3066
3067 return $result;
3068 }
3069
3079 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3080 {
3081 global $conf, $langs;
3082
3083 $s = '';
3084 if (empty($option) || preg_match('/prospect/', $option)) {
3085 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3086 $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.'>';
3087 }
3088 }
3089 if (empty($option) || preg_match('/customer/', $option)) {
3090 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3091 $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.'>';
3092 }
3093 }
3094 if (empty($option) || preg_match('/supplier/', $option)) {
3095 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3096 $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.'>';
3097 }
3098 }
3099 return $s;
3100 }
3101
3102
3109 public function getLibStatut($mode = 0)
3110 {
3111 return $this->LibStatut($this->status, $mode);
3112 }
3113
3114 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3122 public function LibStatut($status, $mode = 0)
3123 {
3124 // phpcs:enable
3125 global $langs;
3126 $langs->load('companies');
3127
3128 $statusType = 'status4';
3129 if ($status == 0) {
3130 $statusType = 'status6';
3131 }
3132
3133 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3134 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3135 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3136 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3137 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3138 }
3139
3140 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3141 }
3142
3143 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3150 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3151 {
3152 // phpcs:enable
3153 global $langs;
3154
3155 $contact_emails = $this->contact_property_array('email', 1);
3156
3157 if ($this->email && $addthirdparty) {
3158 if (empty($this->name)) {
3159 $this->name = $this->nom;
3160 }
3161 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3162 }
3163
3164 //var_dump($contact_emails)
3165 return $contact_emails;
3166 }
3167
3168 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3175 {
3176 // phpcs:enable
3177 global $langs;
3178
3179 $contact_phone = $this->contact_property_array('mobile');
3180
3181 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3182 if (empty($this->name)) {
3183 $this->name = $this->nom;
3184 }
3185 // TODO: Tester si tel non deja present dans tableau contact
3186 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3187 }
3188 return $contact_phone;
3189 }
3190
3191 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3199 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3200 {
3201 // phpcs:enable
3202 global $langs;
3203
3204 $contact_property = array();
3205
3206
3207 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3208 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3209 $sql .= " WHERE fk_soc = ".((int) $this->id);
3210 $sql .= " AND entity IN (".getEntity($this->element).")";
3211 $sql .= " ORDER BY lastname, firstname";
3212
3213 $resql = $this->db->query($sql);
3214 if ($resql) {
3215 $nump = $this->db->num_rows($resql);
3216 if ($nump) {
3217 $sepa = "(";
3218 $sepb = ")";
3219 if ($mode == 'email') {
3220 //$sepa="&lt;"; $sepb="&gt;";
3221 $sepa = "<";
3222 $sepb = ">";
3223 }
3224 $i = 0;
3225 while ($i < $nump) {
3226 $obj = $this->db->fetch_object($resql);
3227 if ($mode == 'email') {
3228 $property = $obj->email;
3229 } elseif ($mode == 'mobile') {
3230 $property = $obj->phone_mobile;
3231 } else {
3232 $property = $obj->$mode;
3233 }
3234
3235 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3236 if ($obj->status == 1 || empty($hidedisabled)) {
3237 if (empty($property)) {
3238 if ($mode == 'email') {
3239 $property = $langs->transnoentitiesnoconv("NoEMail");
3240 } elseif ($mode == 'mobile') {
3241 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3242 }
3243 }
3244
3245 if (!empty($obj->poste)) {
3246 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3247 } else {
3248 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3249 }
3250 }
3251 $i++;
3252 }
3253 }
3254 } else {
3255 dol_print_error($this->db);
3256 }
3257 return $contact_property;
3258 }
3259
3260
3261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3267 public function contact_array()
3268 {
3269 // phpcs:enable
3270 $contacts = array();
3271
3272 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3273 $resql = $this->db->query($sql);
3274 if ($resql) {
3275 $nump = $this->db->num_rows($resql);
3276 if ($nump) {
3277 $i = 0;
3278 while ($i < $nump) {
3279 $obj = $this->db->fetch_object($resql);
3280 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3281 $i++;
3282 }
3283 }
3284 } else {
3285 dol_print_error($this->db);
3286 }
3287 return $contacts;
3288 }
3289
3290 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3296 public function contact_array_objects()
3297 {
3298 // phpcs:enable
3299 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3300 $contacts = array();
3301
3302 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3303 $resql = $this->db->query($sql);
3304 if ($resql) {
3305 $nump = $this->db->num_rows($resql);
3306 if ($nump) {
3307 $i = 0;
3308 while ($i < $nump) {
3309 $obj = $this->db->fetch_object($resql);
3310 $contact = new Contact($this->db);
3311 $contact->fetch($obj->rowid);
3312 $contacts[] = $contact;
3313 $i++;
3314 }
3315 }
3316 } else {
3317 dol_print_error($this->db);
3318 }
3319 return $contacts;
3320 }
3321
3322 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3330 public function contact_get_property($rowid, $mode)
3331 {
3332 // phpcs:enable
3333 $contact_property = '';
3334
3335 if (empty($rowid)) {
3336 return '';
3337 }
3338
3339 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3340 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3341 $sql .= " WHERE rowid = ".((int) $rowid);
3342
3343 $resql = $this->db->query($sql);
3344 if ($resql) {
3345 $nump = $this->db->num_rows($resql);
3346
3347 if ($nump) {
3348 $obj = $this->db->fetch_object($resql);
3349
3350 if ($mode == 'email') {
3351 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3352 } elseif ($mode == 'mobile') {
3353 $contact_property = $obj->phone_mobile;
3354 }
3355 }
3356 return $contact_property;
3357 } else {
3358 dol_print_error($this->db);
3359 }
3360
3361 return '';
3362 }
3363
3364
3365 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3372 public function display_rib($mode = 'label')
3373 {
3374 // phpcs:enable
3375 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3376
3377 $bac = new CompanyBankAccount($this->db);
3378 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3379 $bac->fetch(0, '', $this->id);
3380
3381 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3382 if ($mode == 'label') {
3383 return $bac->getRibLabel(true);
3384 } elseif ($mode == 'rum') {
3385 if (empty($bac->rum)) {
3386 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3387 $prelevement = new BonPrelevement($this->db);
3388 $bac->fetch_thirdparty();
3389 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3390 }
3391 return $bac->rum;
3392 } elseif ($mode == 'format') {
3393 return $bac->frstrecur;
3394 } else {
3395 return 'BadParameterToFunctionDisplayRib';
3396 }
3397 } else {
3398 return '';
3399 }
3400 }
3401
3402 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3408 public function get_all_rib()
3409 {
3410 // phpcs:enable
3411 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3412 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3413 $result = $this->db->query($sql);
3414 if (!$result) {
3415 $this->error++;
3416 $this->errors[] = $this->db->lasterror;
3417 return 0;
3418 } else {
3419 $num_rows = $this->db->num_rows($result);
3420 $rib_array = array();
3421 if ($num_rows) {
3422 while ($obj = $this->db->fetch_object($result)) {
3423 $rib = new CompanyBankAccount($this->db);
3424 $rib->fetch($obj->rowid);
3425 $rib_array[] = $rib;
3426 }
3427 }
3428 return $rib_array;
3429 }
3430 }
3431
3432 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3441 public function get_codeclient($objsoc = null, $type = 0)
3442 {
3443 // phpcs:enable
3444 global $conf;
3445 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3446 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3447
3448 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3449 foreach ($dirsociete as $dirroot) {
3450 $res = dol_include_once($dirroot.$module.'.php');
3451 if ($res) {
3452 break;
3453 }
3454 }
3456 $mod = new $module($this->db);
3457
3458 $this->code_client = $mod->getNextValue($objsoc, $type);
3459 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3460
3461 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3462 }
3463 }
3464
3465 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3474 public function get_codefournisseur($objsoc = null, $type = 1)
3475 {
3476 // phpcs:enable
3477 global $conf;
3478 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3479 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3480
3481 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3482 foreach ($dirsociete as $dirroot) {
3483 $res = dol_include_once($dirroot.$module.'.php');
3484 if ($res) {
3485 break;
3486 }
3487 }
3489 $mod = new $module($this->db);
3490
3491 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3492
3493 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3494 }
3495 }
3496
3497 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3504 public function codeclient_modifiable()
3505 {
3506 // phpcs:enable
3507 global $conf;
3508 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3509 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3510
3511 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3512 foreach ($dirsociete as $dirroot) {
3513 $res = dol_include_once($dirroot.$module.'.php');
3514 if ($res) {
3515 break;
3516 }
3517 }
3518
3519 $mod = new $module($this->db);
3520
3521 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3522 if ($mod->code_modifiable_null && !$this->code_client) {
3523 return 1;
3524 }
3525 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3526 return 1;
3527 }
3528 if ($mod->code_modifiable) {
3529 return 1; // A mettre en dernier
3530 }
3531 return 0;
3532 } else {
3533 return 0;
3534 }
3535 }
3536
3537
3538 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3545 {
3546 // phpcs:enable
3547 global $conf;
3548 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3549 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3550
3551 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3552 foreach ($dirsociete as $dirroot) {
3553 $res = dol_include_once($dirroot.$module.'.php');
3554 if ($res) {
3555 break;
3556 }
3557 }
3558
3559 $mod = new $module($this->db);
3560
3561 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3562 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3563 return 1;
3564 }
3565 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3566 return 1;
3567 }
3568 if ($mod->code_modifiable) {
3569 return 1; // A mettre en dernier
3570 }
3571 return 0;
3572 } else {
3573 return 0;
3574 }
3575 }
3576
3577
3578 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3590 public function check_codeclient()
3591 {
3592 // phpcs:enable
3593 global $conf;
3594 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3595 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3596
3597 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3598 foreach ($dirsociete as $dirroot) {
3599 $res = dol_include_once($dirroot.$module.'.php');
3600 if ($res) {
3601 break;
3602 }
3603 }
3604
3605 $mod = new $module($this->db);
3606
3607 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3608 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3609 if ($result) { // If error
3610 $this->error = $mod->error;
3611 $this->errors = $mod->errors;
3612 }
3613 return $result;
3614 } else {
3615 return 0;
3616 }
3617 }
3618
3619 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3631 public function check_codefournisseur()
3632 {
3633 // phpcs:enable
3634 global $conf;
3635 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3636 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3637
3638 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3639 foreach ($dirsociete as $dirroot) {
3640 $res = dol_include_once($dirroot.$module.'.php');
3641 if ($res) {
3642 break;
3643 }
3644 }
3645
3646 $mod = new $module($this->db);
3647
3648 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3649 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3650 if ($result) { // If error
3651 $this->error = $mod->error;
3652 $this->errors = $mod->errors;
3653 }
3654 return $result;
3655 } else {
3656 return 0;
3657 }
3658 }
3659
3660 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3669 public function get_codecompta($type)
3670 {
3671 // phpcs:enable
3672 global $conf;
3673
3674 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3675 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3676 $res = false;
3677 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3678 foreach ($dirsociete as $dirroot) {
3679 $res = dol_include_once($dirroot.$module.'.php');
3680 if ($res) {
3681 break;
3682 }
3683 }
3684
3685 if ($res) {
3686 $mod = new $module();
3687
3688 // Set code count in $mod->code
3689 $result = $mod->get_code($this->db, $this, $type);
3690
3691 if ($type == 'customer') {
3692 $this->code_compta_client = $mod->code;
3693 $this->code_compta = $this->code_compta_client; // For backward compatibility
3694 } elseif ($type == 'supplier') {
3695 $this->code_compta_fournisseur = $mod->code;
3696 }
3697
3698 return $result;
3699 } else {
3700 $this->error = 'ErrorAccountancyCodeNotDefined';
3701 return -1;
3702 }
3703 } else {
3704 if ($type == 'customer') {
3705 $this->code_compta_client = '';
3706 $this->code_compta = '';
3707 } elseif ($type == 'supplier') {
3708 $this->code_compta_fournisseur = '';
3709 }
3710
3711 return 0;
3712 }
3713 }
3714
3721 public function setParent($id)
3722 {
3723 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3724
3725 if ($this->id) {
3726 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3727 if ($id > 0) {
3728 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3729 if ($sameparent < 0) {
3730 return -1;
3731 }
3732 if ($sameparent == 1) {
3733 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3734 return -1;
3735 }
3736 }
3737
3738 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3739
3740 $resql = $this->db->query($sql);
3741 if ($resql) {
3742 $this->parent = $id;
3743 return 1;
3744 } else {
3745 return -1;
3746 }
3747 }
3748
3749 return -1;
3750 }
3751
3760 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3761 {
3762 if ($counter > 100) {
3763 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3764 }
3765
3766 $sql = 'SELECT s.parent';
3767 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3768 $sql .= ' WHERE rowid = '.((int) $idparent);
3769 $resql = $this->db->query($sql);
3770 if ($resql) {
3771 $obj = $this->db->fetch_object($resql);
3772
3773 if ($obj->parent == '') {
3774 return 0;
3775 } elseif ($obj->parent == $idchild) {
3776 return 1;
3777 } else {
3778 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3779 }
3780 return $sameparent;
3781 } else {
3782 return -1;
3783 }
3784 }
3785
3793 public function getParentsForCompany($company_id, $parents = array())
3794 {
3795 global $langs;
3796
3797 if ($company_id > 0) {
3798 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3799 $resql = $this->db->query($sql);
3800 if ($resql) {
3801 if ($obj = $this->db->fetch_object($resql)) {
3802 $parent = $obj->parent;
3803 if ($parent > 0 && !in_array($parent, $parents)) {
3804 $parents[] = $parent;
3805 return $this->getParentsForCompany($parent, $parents);
3806 } else {
3807 return $parents;
3808 }
3809 }
3810 $this->db->free($resql);
3811 } else {
3812 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3813 }
3814 }
3815 // Return a default value when $company_id is not greater than 0
3816 return array();
3817 }
3818
3819 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3826 public function id_prof_verifiable($idprof)
3827 {
3828 // phpcs:enable
3829 global $conf;
3830
3831 switch ($idprof) {
3832 case 1:
3833 $ret = (!getDolGlobalString('SOCIETE_IDPROF1_UNIQUE') ? false : true);
3834 break;
3835 case 2:
3836 $ret = (!getDolGlobalString('SOCIETE_IDPROF2_UNIQUE') ? false : true);
3837 break;
3838 case 3:
3839 $ret = (!getDolGlobalString('SOCIETE_IDPROF3_UNIQUE') ? false : true);
3840 break;
3841 case 4:
3842 $ret = (!getDolGlobalString('SOCIETE_IDPROF4_UNIQUE') ? false : true);
3843 break;
3844 case 5:
3845 $ret = (!getDolGlobalString('SOCIETE_IDPROF5_UNIQUE') ? false : true);
3846 break;
3847 case 6:
3848 $ret = (!getDolGlobalString('SOCIETE_IDPROF6_UNIQUE') ? false : true);
3849 break;
3850 default:
3851 $ret = false;
3852 }
3853
3854 return $ret;
3855 }
3856
3857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3866 public function id_prof_exists($idprof, $value, $socid = 0)
3867 {
3868 // phpcs:enable
3869 $field = $idprof;
3870
3871 switch ($idprof) { // For backward compatibility
3872 case '1':
3873 case 'idprof1':
3874 $field = "siren";
3875 break;
3876 case '2':
3877 case 'idprof2':
3878 $field = "siret";
3879 break;
3880 case '3':
3881 case 'idprof3':
3882 $field = "ape";
3883 break;
3884 case '4':
3885 case 'idprof4':
3886 $field = "idprof4";
3887 break;
3888 case '5':
3889 $field = "idprof5";
3890 break;
3891 case '6':
3892 $field = "idprof6";
3893 break;
3894 }
3895
3896 //Verify duplicate entries
3897 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3898 if ($socid) {
3899 $sql .= " AND rowid <> ".$socid;
3900 }
3901 $resql = $this->db->query($sql);
3902 if ($resql) {
3903 $obj = $this->db->fetch_object($resql);
3904 $count = $obj->nb;
3905 } else {
3906 $count = 0;
3907 print $this->db->error();
3908 }
3909 $this->db->free($resql);
3910
3911 if ($count > 0) {
3912 return true;
3913 } else {
3914 return false;
3915 }
3916 }
3917
3918 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3927 public function id_prof_check($idprof, $soc)
3928 {
3929 // phpcs:enable
3930 global $conf;
3931
3932 // load the library necessary to check the professional identifiers
3933 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
3934
3935 $ok = 1;
3936
3937 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3938 return 1;
3939 }
3940
3941 // Check SIREN
3942 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
3943 return -1;
3944 }
3945
3946 // Check SIRET
3947 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
3948 return -1;
3949 }
3950
3951 //Verify CIF/NIF/NIE if pays ES
3952 if ($idprof == 1 && $soc->country_code == 'ES') {
3953 return isValidTinForES($this->idprof1);
3954 }
3955
3956 //Verify NIF if country is PT
3957 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
3958 return -1;
3959 }
3960
3961 //Verify NIF if country is DZ
3962 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
3963 return -1;
3964 }
3965
3966 //Verify ID Prof 1 if country is BE
3967 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
3968 return -1;
3969 }
3970
3971 return $ok;
3972 }
3973
3974 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3983 public function id_prof_url($idprof, $thirdparty)
3984 {
3985 // phpcs:enable
3986 global $conf, $langs, $hookmanager;
3987
3988 $url = '';
3989 $action = '';
3990
3991 $hookmanager->initHooks(array('idprofurl'));
3992 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
3993 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3994 if (empty($reshook)) {
3995 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3996 return '';
3997 }
3998
3999 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4000 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4001 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4002 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4003 }
4004 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4005 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4006 }
4007 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4008 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4009 }
4010 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4011 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4012 }
4013 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4014 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4015 }
4016 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4017 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4018 }
4019
4020 if ($url) {
4021 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4022 }
4023 } else {
4024 return $hookmanager->resPrint;
4025 }
4026
4027 return '';
4028 }
4029
4030 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4036 public function has_projects()
4037 {
4038 // phpcs:enable
4039 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4040 $resql = $this->db->query($sql);
4041 if ($resql) {
4042 $obj = $this->db->fetch_object($resql);
4043 $count = $obj->numproj;
4044 } else {
4045 $count = 0;
4046 print $this->db->error();
4047 }
4048 $this->db->free($resql);
4049 return ($count > 0);
4050 }
4051
4052
4059 public function info($id)
4060 {
4061 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4062 $sql .= " fk_user_creat, fk_user_modif";
4063 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4064 $sql .= " WHERE s.rowid = ".((int) $id);
4065
4066 $result = $this->db->query($sql);
4067 if ($result) {
4068 if ($this->db->num_rows($result)) {
4069 $obj = $this->db->fetch_object($result);
4070
4071 $this->id = $obj->rowid;
4072
4073 $this->user_creation_id = $obj->fk_user_creat;
4074 $this->user_modification_id = $obj->fk_user_modif;
4075 $this->date_creation = $this->db->jdate($obj->datec);
4076 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4077
4078 $this->ref = $obj->name;
4079 }
4080
4081 $this->db->free($result);
4082 } else {
4083 dol_print_error($this->db);
4084 }
4085 }
4086
4092 public function isACompany()
4093 {
4094 // Define if third party is treated as company (or not) when nature is unknown
4095 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4096
4097 // Now try to guess using different tips
4098 if (!empty($this->tva_intra)) {
4099 $isACompany = 1;
4100 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4101 $isACompany = 1;
4102 } else {
4103 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4104 // TODO Add a field is_a_company into dictionary
4105 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4106 $isACompany = 0;
4107 } else {
4108 $isACompany = 1;
4109 }
4110 } else {
4111 $isACompany = 1;
4112 }
4113 }
4114
4115 return (bool) $isACompany;
4116 }
4117
4123 public function isInEEC()
4124 {
4125 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4126 return isInEEC($this);
4127 }
4128
4129 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4135 public function LoadSupplierCateg()
4136 {
4137 // phpcs:enable
4138 $this->SupplierCategories = array();
4139 $sql = "SELECT rowid, label";
4140 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4141 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4142
4143 $resql = $this->db->query($sql);
4144 if ($resql) {
4145 while ($obj = $this->db->fetch_object($resql)) {
4146 $this->SupplierCategories[$obj->rowid] = $obj->label;
4147 }
4148 return 0;
4149 } else {
4150 return -1;
4151 }
4152 }
4153
4154 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4161 public function AddFournisseurInCategory($categorie_id)
4162 {
4163 // phpcs:enable
4164 if ($categorie_id > 0 && $this->id > 0) {
4165 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4166 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4167
4168 if ($resql = $this->db->query($sql)) {
4169 return 0;
4170 }
4171 } else {
4172 return 0;
4173 }
4174 return -1;
4175 }
4176
4182 public function getNbOfEMailings()
4183 {
4184 $sql = "SELECT count(mc.email) as nb";
4185 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4186 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4187 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4188
4189 $resql = $this->db->query($sql);
4190 if ($resql) {
4191 $obj = $this->db->fetch_object($resql);
4192 $nb = $obj->nb;
4193
4194 $this->db->free($resql);
4195 return $nb;
4196 } else {
4197 $this->error = $this->db->error();
4198 return -1;
4199 }
4200 }
4201
4208 public function setNoEmail($no_email)
4209 {
4210 $error = 0;
4211
4212 // Update mass emailing flag into table mailing_unsubscribe
4213 if ($this->email) {
4214 $this->db->begin();
4215
4216 if ($no_email) {
4217 $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)."'";
4218 $resql = $this->db->query($sql);
4219 if ($resql) {
4220 $obj = $this->db->fetch_object($resql);
4221 $noemail = $obj->nb;
4222 if (empty($noemail)) {
4223 $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())."')";
4224 $resql = $this->db->query($sql);
4225 if (!$resql) {
4226 $error++;
4227 $this->error = $this->db->lasterror();
4228 $this->errors[] = $this->error;
4229 }
4230 }
4231 } else {
4232 $error++;
4233 $this->error = $this->db->lasterror();
4234 $this->errors[] = $this->error;
4235 }
4236 } else {
4237 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4238 $resql = $this->db->query($sql);
4239 if (!$resql) {
4240 $error++;
4241 $this->error = $this->db->lasterror();
4242 $this->errors[] = $this->error;
4243 }
4244 }
4245
4246 if (empty($error)) {
4247 $this->no_email = $no_email;
4248 $this->db->commit();
4249 return 1;
4250 } else {
4251 $this->db->rollback();
4252 return $error * -1;
4253 }
4254 }
4255
4256 return 0;
4257 }
4258
4265 public function getNoEmail()
4266 {
4267 if ($this->email) {
4268 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4269 $resql = $this->db->query($sql);
4270 if ($resql) {
4271 $obj = $this->db->fetch_object($resql);
4272 $this->no_email = $obj->nb;
4273 return 1;
4274 } else {
4275 $this->error = $this->db->lasterror();
4276 $this->errors[] = $this->error;
4277 return -1;
4278 }
4279 }
4280 return 0;
4281 }
4282
4283 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4293 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4294 {
4295 // phpcs:enable
4296 global $conf, $user, $langs;
4297
4298 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4299 $fullname = $member->getFullName($langs);
4300
4301 if ($member->morphy == 'mor') {
4302 if (empty($socname)) {
4303 $socname = $member->company ? $member->company : $member->societe;
4304 }
4305 if (!empty($fullname) && empty($socalias)) {
4306 $socalias = $fullname;
4307 }
4308 } elseif (empty($socname) && $member->morphy == 'phy') {
4309 if (empty($socname)) {
4310 $socname = $fullname;
4311 }
4312 if (!empty($member->company) && empty($socalias)) {
4313 $socalias = $member->company;
4314 }
4315 }
4316
4317 $name = $socname;
4318 $alias = $socalias ? $socalias : '';
4319
4320 // Positionne parameters
4321 $this->nom = $name; // TODO deprecated
4322 $this->name = $name;
4323 $this->name_alias = $alias;
4324 $this->address = $member->address;
4325 $this->zip = $member->zip;
4326 $this->town = $member->town;
4327 $this->country_code = $member->country_code;
4328 $this->country_id = $member->country_id;
4329 $this->phone = $member->phone; // Prof phone
4330 $this->email = $member->email;
4331 $this->socialnetworks = $member->socialnetworks;
4332 $this->entity = $member->entity;
4333
4334 $this->client = 1; // A member is a customer by default
4335 $this->code_client = ($customercode ? $customercode : -1);
4336 $this->code_fournisseur = '-1';
4337 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4338 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4339
4340 $this->db->begin();
4341
4342 // Cree et positionne $this->id
4343 $result = $this->create($user);
4344
4345 if ($result >= 0) {
4346 // Auto-create contact on thirdparty creation
4347 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4348 // Fill fields needed by contact
4349 $this->name_bis = $member->lastname;
4350 $this->firstname = $member->firstname;
4351 $this->civility_id = $member->civility_id;
4352
4353 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4354 $result = $this->create_individual($user);
4355
4356 if ($result < 0) {
4357 setEventMessages($this->error, $this->errors, 'errors');
4358 $this->db->rollback();
4359 return -1;
4360 }
4361 }
4362
4363 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4364 $sql .= " SET fk_soc = ".((int) $this->id);
4365 $sql .= " WHERE rowid = ".((int) $member->id);
4366
4367 $resql = $this->db->query($sql);
4368 if ($resql) {
4369 $this->db->commit();
4370 return $this->id;
4371 } else {
4372 $this->error = $this->db->error();
4373
4374 $this->db->rollback();
4375 return -1;
4376 }
4377 } else {
4378 // $this->error deja positionne
4379 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4380
4381 $this->db->rollback();
4382 return $result;
4383 }
4384 }
4385
4392 public function setMysoc(Conf $conf)
4393 {
4394 global $langs;
4395
4396 $this->id = 0;
4397 $this->entity = $conf->entity;
4398 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4399 $this->nom = $this->name; // deprecated
4400 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4401 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4402 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4403 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4404
4405 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4406
4407 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4408
4409 // We define country_id, country_code and country
4410 $country_id = 0;
4411 $country_code = $country_label = '';
4412 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4413 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4414 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4415 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4416 $country_code = $tmp[1];
4417 $country_label = $tmp[2];
4418 } else {
4419 // For backward compatibility
4420 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4421 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4422 $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
4423 $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
4424 }
4425 }
4426 $this->country_id = $country_id;
4427 $this->country_code = $country_code;
4428 $this->country = $country_label;
4429 if (is_object($langs)) {
4430 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4431 }
4432
4433 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4434 // We define state_id, state_code and state
4435 $state_id = 0;
4436 $state_code = $state_label = '';
4437 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4438 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4439 $state_id = $tmp[0];
4440 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4441 $state_code = $tmp[1];
4442 $state_label = $tmp[2];
4443 } else { // For backward compatibility
4444 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);
4445 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4446 $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
4447 $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
4448 }
4449 }
4450 $this->state_id = $state_id;
4451 $this->state_code = $state_code;
4452 $this->state = $state_label;
4453 if (is_object($langs)) {
4454 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4455 }
4456
4457 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4458 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4459 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4460 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4461
4462 // Social networks
4463 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4464 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4465 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4466 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4467 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4468 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4469 $this->socialnetworks = array();
4470 if (!empty($facebook_url)) {
4471 $this->socialnetworks['facebook'] = $facebook_url;
4472 }
4473 if (!empty($twitter_url)) {
4474 $this->socialnetworks['twitter'] = $twitter_url;
4475 }
4476 if (!empty($linkedin_url)) {
4477 $this->socialnetworks['linkedin'] = $linkedin_url;
4478 }
4479 if (!empty($instagram_url)) {
4480 $this->socialnetworks['instagram'] = $instagram_url;
4481 }
4482 if (!empty($youtube_url)) {
4483 $this->socialnetworks['youtube'] = $youtube_url;
4484 }
4485 if (!empty($github_url)) {
4486 $this->socialnetworks['github'] = $github_url;
4487 }
4488
4489 // Id prof generiques
4490 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4491 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4492 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4493 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4494 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4495 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4496 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4497 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4498 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4499 $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4500 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4501 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4502 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4503 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4504 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4505 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4506 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4507 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4508
4509 // Define if company use vat or not
4510 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4511
4512 // Define if company use local taxes
4513 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4514 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4515 }
4516
4524 public function initAsSpecimen()
4525 {
4526 $now = dol_now();
4527
4528 // Initialize parameters
4529 $this->id = 0;
4530 $this->entity = 1;
4531 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4532 $this->nom = $this->name; // For backward compatibility
4533 $this->ref_ext = 'Ref ext';
4534 $this->specimen = 1;
4535 $this->address = '21 jump street';
4536 $this->zip = '99999';
4537 $this->town = 'MyTown';
4538 $this->state_id = 1;
4539 $this->state_code = 'AA';
4540 $this->state = 'MyState';
4541 $this->country_id = 1;
4542 $this->country_code = 'FR';
4543 $this->email = 'specimen@specimen.com';
4544 $this->socialnetworks = array(
4545 'skype' => 'skypepseudo',
4546 'twitter' => 'twitterpseudo',
4547 'facebook' => 'facebookpseudo',
4548 'linkedin' => 'linkedinpseudo',
4549 );
4550 $this->url = 'http://www.specimen.com';
4551
4552 $this->phone = '0909090901';
4553 $this->phone_mobile = '0909090901';
4554 $this->fax = '0909090909';
4555
4556 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4557 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4558 $this->capital = 10000;
4559 $this->client = 1;
4560 $this->prospect = 1;
4561 $this->fournisseur = 1;
4562 $this->tva_assuj = 1;
4563 $this->tva_intra = 'EU1234567';
4564 $this->note_public = 'This is a comment (public)';
4565 $this->note_private = 'This is a comment (private)';
4566
4567 $this->idprof1 = 'idprof1';
4568 $this->idprof2 = 'idprof2';
4569 $this->idprof3 = 'idprof3';
4570 $this->idprof4 = 'idprof4';
4571 $this->idprof5 = 'idprof5';
4572 $this->idprof6 = 'idprof6';
4573
4574 return 1;
4575 }
4576
4583 public function useLocalTax($localTaxNum = 0)
4584 {
4585 $sql = "SELECT t.localtax1, t.localtax2";
4586 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4587 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4588 $sql .= " AND t.active = 1";
4589 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4590 if (empty($localTaxNum)) {
4591 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4592 } elseif ($localTaxNum == 1) {
4593 $sql .= " AND t.localtax1_type <> '0'";
4594 } elseif ($localTaxNum == 2) {
4595 $sql .= " AND t.localtax2_type <> '0'";
4596 }
4597
4598 $resql = $this->db->query($sql);
4599 if ($resql) {
4600 return ($this->db->num_rows($resql) > 0);
4601 } else {
4602 return false;
4603 }
4604 }
4605
4611 public function useNPR()
4612 {
4613 $sql = "SELECT t.rowid";
4614 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4615 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4616 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4617 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4618
4619 dol_syslog("useNPR", LOG_DEBUG);
4620 $resql = $this->db->query($sql);
4621 if ($resql) {
4622 return ($this->db->num_rows($resql) > 0);
4623 } else {
4624 return false;
4625 }
4626 }
4627
4634 public function useRevenueStamp()
4635 {
4636 $sql = "SELECT COUNT(*) as nb";
4637 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4638 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4639 $sql .= " AND r.active = 1";
4640
4641 dol_syslog("useRevenueStamp", LOG_DEBUG);
4642 $resql = $this->db->query($sql);
4643 if ($resql) {
4644 $obj = $this->db->fetch_object($resql);
4645 return (($obj->nb > 0) ? true : false);
4646 } else {
4647 $this->error = $this->db->lasterror();
4648 return false;
4649 }
4650 }
4651
4657 public function getLibProspLevel()
4658 {
4659 return $this->LibProspLevel($this->fk_prospectlevel);
4660 }
4661
4662 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4669 public function LibProspLevel($fk_prospectlevel)
4670 {
4671 // phpcs:enable
4672 global $langs;
4673
4674 $label = '';
4675 if ($fk_prospectlevel != '') {
4676 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4677 // If label is not found in language file, we get label from cache/database
4678 if ($label == "ProspectLevel".$fk_prospectlevel) {
4679 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4680 }
4681 }
4682
4683 return $label;
4684 }
4685
4693 public function getLibProspCommStatut($mode = 0, $label = '')
4694 {
4695 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4696 }
4697
4698 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4712 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4713 {
4714 // phpcs:enable
4715 global $langs;
4716
4717 $langs->load('customers');
4718
4719 if ($mode == 2) {
4720 if ($status == '-1' || $status == 'ST_NO') {
4721 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4722 } elseif ($status == '0' || $status == 'ST_NEVER') {
4723 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4724 } elseif ($status == '1' || $status == 'ST_TODO') {
4725 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4726 } elseif ($status == '2' || $status == 'ST_PEND') {
4727 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4728 } elseif ($status == '3' || $status == 'ST_DONE') {
4729 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4730 } else {
4731 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);
4732 }
4733 } elseif ($mode == 3) {
4734 if ($status == '-1' || $status == 'ST_NO') {
4735 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4736 } elseif ($status == '0' || $status == 'ST_NEVER') {
4737 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4738 } elseif ($status == '1' || $status == 'ST_TODO') {
4739 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4740 } elseif ($status == '2' || $status == 'ST_PEND') {
4741 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4742 } elseif ($status == '3' || $status == 'ST_DONE') {
4743 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4744 } else {
4745 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4746 }
4747 } elseif ($mode == 4) {
4748 if ($status == '-1' || $status == 'ST_NO') {
4749 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4750 } elseif ($status == '0' || $status == 'ST_NEVER') {
4751 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4752 } elseif ($status == '1' || $status == 'ST_TODO') {
4753 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4754 } elseif ($status == '2' || $status == 'ST_PEND') {
4755 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4756 } elseif ($status == '3' || $status == 'ST_DONE') {
4757 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4758 } else {
4759 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);
4760 }
4761 }
4762
4763 return "Error, mode/status not found";
4764 }
4765
4772 public function getOutstandingProposals($mode = 'customer')
4773 {
4774 $table = 'propal';
4775 if ($mode == 'supplier') {
4776 $table = 'supplier_proposal';
4777 }
4778
4779 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4780 $sql .= " WHERE fk_soc = ".((int) $this->id);
4781 if ($mode == 'supplier') {
4782 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4783 } else {
4784 $sql .= " AND entity IN (".getEntity('propal').")";
4785 }
4786
4787 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4788
4789 $resql = $this->db->query($sql);
4790 if ($resql) {
4791 $outstandingOpened = 0;
4792 $outstandingTotal = 0;
4793 $outstandingTotalIncTax = 0;
4794 $arrayofref = array();
4795 while ($obj = $this->db->fetch_object($resql)) {
4796 $arrayofref[$obj->rowid] = $obj->ref;
4797 $outstandingTotal += $obj->total_ht;
4798 $outstandingTotalIncTax += $obj->total_ttc;
4799 if ($obj->status != 0) {
4800 // Not a draft
4801 $outstandingOpened += $obj->total_ttc;
4802 }
4803 }
4804 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4805 } else {
4806 return array();
4807 }
4808 }
4809
4816 public function getOutstandingOrders($mode = 'customer')
4817 {
4818 $table = 'commande';
4819 if ($mode == 'supplier') {
4820 $table = 'commande_fournisseur';
4821 }
4822
4823 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4824 $sql .= " WHERE fk_soc = ".((int) $this->id);
4825 if ($mode == 'supplier') {
4826 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4827 } else {
4828 $sql .= " AND entity IN (".getEntity('commande').")";
4829 }
4830
4831 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4832 $resql = $this->db->query($sql);
4833 if ($resql) {
4834 $outstandingOpened = 0;
4835 $outstandingTotal = 0;
4836 $outstandingTotalIncTax = 0;
4837 $arrayofref = array();
4838 while ($obj = $this->db->fetch_object($resql)) {
4839 $arrayofref[$obj->rowid] = $obj->ref;
4840 $outstandingTotal += $obj->total_ht;
4841 $outstandingTotalIncTax += $obj->total_ttc;
4842 if ($obj->status != 0) {
4843 // Not a draft
4844 $outstandingOpened += $obj->total_ttc;
4845 }
4846 }
4847 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4848 } else {
4849 return array();
4850 }
4851 }
4852
4860 public function getOutstandingBills($mode = 'customer', $late = 0)
4861 {
4862 $table = 'facture';
4863 if ($mode == 'supplier') {
4864 $table = 'facture_fourn';
4865 }
4866
4867 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4868 $paiement = $invoice->getSommePaiement();
4869 $creditnotes=$invoice->getSumCreditNotesUsed();
4870 $deposits=$invoice->getSumDepositsUsed();
4871 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4872 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4873 */
4874 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4875 $sql .= " WHERE fk_soc = ".((int) $this->id);
4876 if (!empty($late)) {
4877 $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4878 }
4879 if ($mode == 'supplier') {
4880 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4881 } else {
4882 $sql .= " AND entity IN (".getEntity('invoice').")";
4883 }
4884
4885 dol_syslog("getOutstandingBills", LOG_DEBUG);
4886 $resql = $this->db->query($sql);
4887 if ($resql) {
4888 $outstandingOpened = 0;
4889 $outstandingTotal = 0;
4890 $outstandingTotalIncTax = 0;
4891 $arrayofref = array();
4892 $arrayofrefopened = array();
4893 if ($mode == 'supplier') {
4894 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4895 $tmpobject = new FactureFournisseur($this->db);
4896 } else {
4897 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4898 $tmpobject = new Facture($this->db);
4899 }
4900 while ($obj = $this->db->fetch_object($resql)) {
4901 $arrayofref[$obj->rowid] = $obj->ref;
4902 $tmpobject->id = $obj->rowid;
4903
4904 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4905 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4906 ) {
4907 $outstandingTotal += $obj->total_ht;
4908 $outstandingTotalIncTax += $obj->total_ttc;
4909 }
4910
4911 $remaintopay = 0;
4912
4913 if ($obj->paye == 0
4914 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4915 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
4916 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4917 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
4918 $paiement = $tmpobject->getSommePaiement();
4919 $creditnotes = $tmpobject->getSumCreditNotesUsed();
4920 $deposits = $tmpobject->getSumDepositsUsed();
4921
4922 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4923 $outstandingOpened += $remaintopay;
4924 }
4925
4926 //if credit note is converted but not used
4927 // TODO Do this also for customer ?
4928 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4929 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4930 $remaintopay -= $remainingcreditnote;
4931 $outstandingOpened -= $remainingcreditnote;
4932 }
4933
4934 if ($remaintopay) {
4935 $arrayofrefopened[$obj->rowid] = $obj->ref;
4936 }
4937 }
4938 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
4939 } else {
4940 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4941 return array();
4942 }
4943 }
4944
4951 public function getLibCustProspStatut()
4952 {
4953 return $this->LibCustProspStatut($this->client);
4954 }
4955
4956 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4963 public function LibCustProspStatut($status)
4964 {
4965 // phpcs:enable
4966 global $langs;
4967 $langs->load('companies');
4968
4969 if ($status == 0) {
4970 return $langs->trans("NorProspectNorCustomer");
4971 } elseif ($status == 1) {
4972 return $langs->trans("Customer");
4973 } elseif ($status == 2) {
4974 return $langs->trans("Prospect");
4975 } elseif ($status == 3) {
4976 return $langs->trans("ProspectCustomer");
4977 }
4978
4979 return '';
4980 }
4981
4982
4994 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4995 {
4996 global $langs;
4997
4998 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4999 $modelpath = "core/modules/bank/doc/";
5000
5001 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5002 $companybankaccount = new CompanyBankAccount($this->db);
5003 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5004 if (!$result) {
5005 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5006 }
5007 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5008 $this->last_main_doc = $companybankaccount->last_main_doc;
5009 } else {
5010 // Positionne le modele sur le nom du modele a utiliser
5011 if (!dol_strlen($modele)) {
5012 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5013 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5014 } else {
5015 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5016 return 0;
5017 }
5018 }
5019
5020 if (!isset($this->bank_account)) {
5021 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5022 $bac = new CompanyBankAccount($this->db);
5023 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5024 $result = $bac->fetch(0, '', $this->id);
5025 if ($result > 0) {
5026 $this->bank_account = $bac;
5027 } else {
5028 $this->bank_account = '';
5029 }
5030 }
5031
5032 $modelpath = "core/modules/societe/doc/";
5033
5034 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5035 }
5036
5037 return $result;
5038 }
5039
5040
5052 public function setCategories($categories, $type_categ)
5053 {
5054 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5055
5056 // Decode type
5057 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5058 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5059 return -1;
5060 }
5061
5062 return parent::setCategoriesCommon($categories, $type_categ);
5063 }
5064
5072 public function setSalesRep($salesrep, $onlyAdd = false)
5073 {
5074 global $user;
5075
5076 // Handle single user
5077 if (!is_array($salesrep)) {
5078 $salesrep = array($salesrep);
5079 }
5080
5081 $to_del = array(); // Nothing to delete
5082 $to_add = $salesrep;
5083 if ($onlyAdd === false) {
5084 // Get current users
5085 $existing = $this->getSalesRepresentatives($user, 1);
5086
5087 // Diff
5088 if (is_array($existing)) {
5089 $to_del = array_diff($existing, $salesrep);
5090 $to_add = array_diff($salesrep, $existing);
5091 }
5092 }
5093
5094 $error = 0;
5095
5096 // Process
5097 foreach ($to_del as $del) {
5098 $this->del_commercial($user, $del);
5099 }
5100 foreach ($to_add as $add) {
5101 $result = $this->add_commercial($user, $add);
5102 if ($result < 0) {
5103 $error++;
5104 break;
5105 }
5106 }
5107
5108 return $error ? -1 : 1;
5109 }
5110
5117 public function setThirdpartyType($typent_id)
5118 {
5119 global $user;
5120
5121 dol_syslog(__METHOD__, LOG_DEBUG);
5122
5123 if ($this->id) {
5124 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5125
5126 if ($result > 0) {
5127 $this->typent_id = $typent_id;
5128 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5129 return 1;
5130 } else {
5131 return -1;
5132 }
5133 } else {
5134 return -1;
5135 }
5136 }
5137
5147 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5148 {
5149 if ($origin_id == $dest_id) {
5150 dol_syslog('Error: Try to merge a thirdparty into itself');
5151 return false;
5152 }
5153
5154 // 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.
5155 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5156 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5157 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5158 $sql .= ' SELECT fk_user ';
5159 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5160 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5161
5162 $resql = $dbs->query($sql);
5163 while ($obj = $dbs->fetch_object($resql)) {
5164 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5165 }
5166
5167 // llx_societe_extrafields table must not be here because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5168 // Do not include llx_societe because it will be replaced later.
5169 $tables = array(
5170 'societe_account',
5171 'societe_commerciaux',
5172 'societe_prices',
5173 'societe_remise',
5174 'societe_remise_except',
5175 'societe_rib'
5176 );
5177
5178 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5179 }
5180
5189 public function setAccountancyCode($type, $value)
5190 {
5191 global $user, $langs, $conf;
5192
5193 $this->db->begin();
5194
5195 if ($type == 'buy') {
5196 $field = 'accountancy_code_buy';
5197 } elseif ($type == 'sell') {
5198 $field = 'accountancy_code_sell';
5199 } else {
5200 return -1;
5201 }
5202
5203 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5204 $sql .= $field." = '".$this->db->escape($value)."'";
5205 $sql .= " WHERE rowid = ".((int) $this->id);
5206
5207 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5208 $resql = $this->db->query($sql);
5209
5210 if ($resql) {
5211 // Call triggers
5212 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5213 $interface = new Interfaces($this->db);
5214 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5215 if ($result < 0) {
5216 $this->errors = $interface->errors;
5217 $this->db->rollback();
5218 return -1;
5219 }
5220 // End call triggers
5221
5222 $this->$field = $value;
5223
5224 $this->db->commit();
5225 return 1;
5226 } else {
5227 $this->error = $this->db->lasterror();
5228 $this->db->rollback();
5229 return -1;
5230 }
5231 }
5232
5239 public function fetchPartnerships($mode)
5240 {
5241 global $langs;
5242
5243 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5244
5245
5246 $this->partnerships[] = array();
5247
5248 return 1;
5249 }
5250
5258 public function getKanbanView($option = '', $arraydata = array())
5259 {
5260 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5261
5262 $return = '<div class="box-flex-item box-flex-grow-zero">';
5263 $return .= '<div class="info-box info-box-sm">';
5264 $return .= '<span class="info-box-icon bg-infobox-action">';
5265 $return .= img_picto('', $this->picto);
5266 $return .= '</span>';
5267 $return .= '<div class="info-box-content">';
5268 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5269 if ($selected >= 0) {
5270 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5271 }
5272 if (property_exists($this, 'code_client')) {
5273 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5274 }
5275 if (method_exists($this, 'getLibStatut')) {
5276 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5277 }
5278 $return .= '</div>';
5279 $return .= '</div>';
5280 $return .= '</div>';
5281
5282 return $return;
5283 }
5284
5294 public function getContacts($list = 0, $code = '', $element = '')
5295 {
5296 // phpcs:enable
5297 global $langs;
5298
5299 $tab = array();
5300
5301 $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
5302 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5303 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5304 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5305 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5306 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5307 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5308 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5309 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5310 if (!empty($element)) {
5311 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5312 }
5313 if ($code) {
5314 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5315 }
5316 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5317 $sql .= " AND tc.source = 'external'";
5318 $sql .= " AND tc.active = 1";
5319
5320 $sql .= " ORDER BY t.lastname ASC";
5321
5322 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5323 $resql = $this->db->query($sql);
5324 if ($resql) {
5325 $num = $this->db->num_rows($resql);
5326 $i = 0;
5327 while ($i < $num) {
5328 $obj = $this->db->fetch_object($resql);
5329
5330 if (!$list) {
5331 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5332 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5333 $tab[$i] = array(
5334 'source' => $obj->source,
5335 'socid' => $obj->socid,
5336 'id' => $obj->id,
5337 'nom' => $obj->lastname, // For backward compatibility
5338 'civility' => $obj->civility,
5339 'lastname' => $obj->lastname,
5340 'firstname' => $obj->firstname,
5341 'email' => $obj->email,
5342 'login' => (empty($obj->login) ? '' : $obj->login),
5343 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5344 'statuscontact' => $obj->statuscontact,
5345 'rowid' => $obj->rowid,
5346 'code' => $obj->code,
5347 'element' => $obj->element,
5348 'libelle' => $libelle_type,
5349 'status' => $obj->statuslink,
5350 'fk_c_type_contact' => $obj->fk_c_type_contact
5351 );
5352 } else {
5353 $tab[$i] = $obj->id;
5354 }
5355
5356 $i++;
5357 }
5358
5359 return $tab;
5360 } else {
5361 $this->error = $this->db->lasterror();
5362 dol_print_error($this->db);
5363 return -1;
5364 }
5365 }
5366
5377 public function mergeCompany($soc_origin_id)
5378 {
5379 global $conf, $langs, $hookmanager, $user, $action;
5380
5381 $error = 0;
5382 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5383
5384 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5385
5386 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5387 $this->error = $langs->trans('ErrorRecordNotFound');
5388 $error++;
5389 }
5390
5391 if (!$error) {
5392 $this->db->begin();
5393
5394 // Recopy some data
5395 $this->client |= $soc_origin->client;
5396 $this->fournisseur |= $soc_origin->fournisseur;
5397 $listofproperties = array(
5398 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5399 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5400 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5401 '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',
5402 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5403 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5404 );
5405 foreach ($listofproperties as $property) {
5406 if (empty($this->$property)) {
5407 $this->$property = $soc_origin->$property;
5408 }
5409 }
5410
5411 if ($this->typent_id == -1) {
5412 $this->typent_id = $soc_origin->typent_id;
5413 }
5414
5415 // Concat some data
5416 $listofproperties = array(
5417 'note_public', 'note_private'
5418 );
5419 foreach ($listofproperties as $property) {
5420 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5421 }
5422
5423 // Merge extrafields
5424 if (is_array($soc_origin->array_options)) {
5425 foreach ($soc_origin->array_options as $key => $val) {
5426 if (empty($this->array_options[$key])) {
5427 $this->array_options[$key] = $val;
5428 }
5429 }
5430 }
5431
5432 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5433 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5434 $this->name_bis = $this->name;
5435 }
5436
5437 // Merge categories
5438 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5439 $static_cat = new Categorie($this->db);
5440
5441 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5442 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5443 $custcats = array_merge($custcats, $custcats_ori);
5444 $this->setCategories($custcats, 'customer');
5445
5446 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5447 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5448 $suppcats = array_merge($suppcats, $suppcats_ori);
5449 $this->setCategories($suppcats, 'supplier');
5450
5451 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5452 if ($soc_origin->code_client == $this->code_client
5453 || $soc_origin->code_fournisseur == $this->code_fournisseur
5454 || $soc_origin->barcode == $this->barcode) {
5455 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5456 $soc_origin->code_client = '';
5457 $soc_origin->code_fournisseur = '';
5458 $soc_origin->barcode = '';
5459 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5460 }
5461
5462 // Update
5463 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5464
5465 if ($result < 0) {
5466 $error++;
5467 }
5468
5469 // Move links
5470 if (!$error) {
5471 $objects = array(
5472 'Adherent' => '/adherents/class/adherent.class.php',
5473 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5474 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5475 'Propal' => '/comm/propal/class/propal.class.php',
5476 'Commande' => '/commande/class/commande.class.php',
5477 'Facture' => '/compta/facture/class/facture.class.php',
5478 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5479 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5480 'Contact' => '/contact/class/contact.class.php',
5481 'Contrat' => '/contrat/class/contrat.class.php',
5482 'Expedition' => '/expedition/class/expedition.class.php',
5483 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5484 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5485 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5486 'Reception' => '/reception/class/reception.class.php',
5487 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5488 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5489 'Product' => '/product/class/product.class.php',
5490 //'ProductThirparty' => '...', // for llx_product_thirdparty
5491 'Project' => '/projet/class/project.class.php',
5492 'User' => '/user/class/user.class.php',
5493 'Account' => '/compta/bank/class/account.class.php',
5494 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5495 'Societe' => '/societe/class/societe.class.php',
5496 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirparty of Societe.
5497 );
5498 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5499 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5500 }
5501 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5502 $objects['Mo'] = '/mrp/class/mo.class.php';
5503 }
5504 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5505 $objects['Don'] = '/don/class/don.class.php';
5506 }
5507 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5508 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5509 }
5510 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5511 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5512 }
5513 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5514 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5515 }
5516
5517 //First, all core objects must update their tables
5518 foreach ($objects as $object_name => $object_file) {
5519 if (is_array($object_file)) {
5520 if (empty($object_file['enabled'])) {
5521 continue;
5522 }
5523 $object_file = $object_file['file'];
5524 }
5525
5526 require_once DOL_DOCUMENT_ROOT.$object_file;
5527
5528 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5529 $error++;
5530 $this->error = $this->db->lasterror();
5531 break;
5532 }
5533 }
5534 }
5535
5536 // External modules should update their ones too
5537 if (!$error) {
5538 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5539 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5540
5541 if ($reshook < 0) {
5542 $this->error = $hookmanager->error;
5543 $this->errors = $hookmanager->errors;
5544 $error++;
5545 }
5546 }
5547
5548
5549 if (!$error) {
5550 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5551
5552 // Call trigger
5553 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5554 if ($result < 0) {
5555 $error++;
5556 }
5557 // End call triggers
5558 }
5559
5560 if (!$error) {
5561 // Move files from the dir of the third party to delete into the dir of the third party to keep
5562 if (!empty($conf->societe->multidir_output[$this->entity])) {
5563 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5564 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5565
5566 if (dol_is_dir($srcdir)) {
5567 $dirlist = dol_dir_list($srcdir, 'files', 1);
5568 foreach ($dirlist as $filetomove) {
5569 $destfile = $destdir.'/'.$filetomove['relativename'];
5570 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5571 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5572 }
5573 //exit;
5574 }
5575 }
5576 }
5577
5578
5579 if (!$error) {
5580 // We finally remove the old thirdparty
5581 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5582 $this->error = $soc_origin->error;
5583 $this->errors = $soc_origin->errors;
5584 $error++;
5585 }
5586 }
5587
5588 if (!$error) {
5589 $this->db->commit();
5590 return 0;
5591 } else {
5592 $langs->load("errors");
5593 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5594 $this->db->rollback();
5595 return -1;
5596 }
5597 }
5598
5599 return -1;
5600 }
5601}
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:636
$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.
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Search the thirdparty that match the most the provided parameters.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
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